Initial public release
contracts-ci / Install (lockfile) → compile → full test suite (push) Waiting to run
contracts-ci / PQC known-answer tests (NIST vectors) (push) Waiting to run
contracts-ci / Coverage (scoped, with artifacts) (push) Waiting to run
contracts-ci / Install (lockfile) → compile → full test suite (push) Waiting to run
contracts-ci / PQC known-answer tests (NIST vectors) (push) Waiting to run
contracts-ci / Coverage (scoped, with artifacts) (push) Waiting to run
Aere Network public source. Everything here can be checked against the live chain (chain id 2800, https://rpc.aere.network). Scope note, stated up front rather than buried: consensus on chain 2800 is classical secp256k1 ECDSA QBFT. The post-quantum work in this repository is at the signature, precompile, account and transport layers. Nothing here makes the consensus post-quantum, and no document in it should be read as claiming so.
This commit is contained in:
commit
a13a649b77
459 files changed
+119890
No files matched your search
@@ -0,0 +1,312 @@
|
|||||||
|
# Aere Network contracts: continuous verification
|
||||||
|
#
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# WHY THIS FILE IS AT .github/workflows/ AND NOT .gitea/workflows/
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# The canonical host is our own Gitea instance at git.aere.network. Gitea Actions
|
||||||
|
# scans BOTH `.gitea/workflows/` and `.github/workflows/`, and prefers `.gitea/`
|
||||||
|
# only when both exist. GitHub Actions scans `.github/workflows/` only.
|
||||||
|
# Putting the single source of truth at `.github/workflows/ci.yml` therefore
|
||||||
|
# means the same unmodified file runs on both hosts. That is the point: a
|
||||||
|
# stranger who mirrors this repo to GitHub gets the same pipeline with zero
|
||||||
|
# edits, and can compare their run against ours.
|
||||||
|
#
|
||||||
|
# Portability notes for anyone porting this elsewhere:
|
||||||
|
# * `actions/checkout@v4`, `actions/setup-node@v4` and
|
||||||
|
# `actions/upload-artifact@v3` all resolve on Gitea Actions, which proxies
|
||||||
|
# to github.com for action resolution by default.
|
||||||
|
# * upload-artifact is pinned at v3, not v4. Gitea's artifact backend
|
||||||
|
# implements the v3 upload protocol; v4 changed it and fails on Gitea at the
|
||||||
|
# time of writing. On GitHub, v3 still runs. If you are GitHub-only, v4 is
|
||||||
|
# fine.
|
||||||
|
# * Gitea runners need a label matching `runs-on`. Ours registers
|
||||||
|
# `ubuntu-22.04`. If your runner registers only `ubuntu-latest`, change the
|
||||||
|
# three `runs-on:` lines.
|
||||||
|
#
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# HONESTY STATEMENT: DOES THIS PIPELINE CURRENTLY PASS?
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# Recorded here rather than in a README so it cannot drift away from the file it
|
||||||
|
# describes. Status as of 2026-07-20, measured on the maintainer's machine
|
||||||
|
# (Windows 11, Node v24.14.1, npm 11.11.0), not assumed:
|
||||||
|
#
|
||||||
|
# job: build-and-test .......... SEE STATUS BLOCK BELOW (filled from a real run)
|
||||||
|
# job: pqc-kat ................. SEE STATUS BLOCK BELOW
|
||||||
|
# job: coverage ................ RUNS, but produces a SCOPED number, not a
|
||||||
|
# whole-repo number. See the long comment on
|
||||||
|
# that job. This is a measured limitation of a
|
||||||
|
# 16 GB runner, not a choice to look good.
|
||||||
|
#
|
||||||
|
# What this pipeline deliberately does NOT do, because each would be a way of
|
||||||
|
# being green while being wrong:
|
||||||
|
# * no `continue-on-error` on any compile, test or KAT step;
|
||||||
|
# * no `|| true` swallowing a non-zero exit anywhere in a gating step;
|
||||||
|
# * no coverage threshold invented below the real number to manufacture a
|
||||||
|
# pass. The one threshold that exists is set AT a measured value and exists
|
||||||
|
# to catch regression;
|
||||||
|
# * no test file excluded from the suite for being inconvenient. `skipFiles`
|
||||||
|
# in .solcover.js is empty;
|
||||||
|
# * `npm ci` (not `npm install`), so the lockfile is authoritative and a
|
||||||
|
# drifting transitive dependency fails the build instead of silently
|
||||||
|
# changing what was tested.
|
||||||
|
#
|
||||||
|
# If the suite goes red, the correct response is to fix the suite. Editing this
|
||||||
|
# file to make it green again is the failure mode this file exists to prevent.
|
||||||
|
|
||||||
|
name: contracts-ci
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
# Least privilege. This pipeline reads code and writes artifacts. Nothing else.
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# THE SECRETS BOUNDARY
|
||||||
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
# This is a public CI on a public repository. It has NO access to, and must
|
||||||
|
# never be given access to:
|
||||||
|
#
|
||||||
|
# * validator signing keys for the 7 chain-2800 validators;
|
||||||
|
# * any deploy key, funded account private key, or mnemonic with a balance;
|
||||||
|
# * infrastructure credentials (SSH, Hetzner API, DNS, TLS private keys);
|
||||||
|
# * RPC admin or any authenticated write endpoint;
|
||||||
|
# * the explorer, relayer or oracle service credentials.
|
||||||
|
#
|
||||||
|
# The `env:` block below is exhaustive and contains no `secrets.*` reference.
|
||||||
|
# That is verifiable by reading this file: grep it for `secrets.` and you get
|
||||||
|
# nothing. A fork's pull request runs the identical pipeline with the identical
|
||||||
|
# (empty) credential surface.
|
||||||
|
#
|
||||||
|
# WHY A PUBLIC CI STRUCTURALLY CANNOT TOUCH THE LIVE CHAIN, beyond just not
|
||||||
|
# holding keys:
|
||||||
|
# 1. Every job runs against an in-process Hardhat EVM at chainId 31337. It
|
||||||
|
# never dials chain 2800.
|
||||||
|
# 2. The only account material anywhere in the test path is the well-known
|
||||||
|
# public Hardhat mnemonic ("test test test ... junk"), which holds nothing
|
||||||
|
# on any real network.
|
||||||
|
# 3. Writing to chain 2800 requires a signature from a funded key. No such key
|
||||||
|
# exists in this repository, in this pipeline, or in the runner
|
||||||
|
# environment, so a compromised workflow file, a malicious dependency, or a
|
||||||
|
# hostile pull request still cannot produce a valid mainnet transaction.
|
||||||
|
# 4. Deployment is a separate, human-gated, offline procedure. It is not
|
||||||
|
# automated from CI by design, and moving it into CI would be a downgrade.
|
||||||
|
#
|
||||||
|
# Naming this boundary is part of the argument, not a caveat to it. "Radical
|
||||||
|
# open source" means every number here is reproducible by a stranger; it does
|
||||||
|
# not mean the keys are open. Linux publishes all of its code and none of its
|
||||||
|
# signing keys.
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Coverage instrumentation is memory-hungry. Raise V8's old-space so the
|
||||||
|
# sharded run has room. NOTE: this bounds only the V8 old-space heap; the bulk
|
||||||
|
# of coverage's growth is Hardhat's in-process EVM state plus the
|
||||||
|
# per-statement hit maps, which live OUTSIDE this budget. Do not expect this
|
||||||
|
# setting alone to make a whole-repo run fit.
|
||||||
|
NODE_OPTIONS: --max-old-space-size=6144
|
||||||
|
# Never let a stray config or test reach a real endpoint from CI.
|
||||||
|
AERE_RPC_URL: http://127.0.0.1:0
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
# 1. THE GATE. Clean-checkout install, compile, full suite. No exceptions.
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
build-and-test:
|
||||||
|
name: Install (lockfile) → compile → full test suite
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
timeout-minutes: 90
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
# Pinned to the version the numbers in REPRODUCE.md were measured on.
|
||||||
|
node-version: '24.14.1'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Record toolchain versions
|
||||||
|
# Printed so any run can be compared against any other run. A number is
|
||||||
|
# only reproducible if you know what produced it.
|
||||||
|
run: |
|
||||||
|
echo "node: $(node --version)"
|
||||||
|
echo "npm: $(npm --version)"
|
||||||
|
echo "os: $(uname -a)"
|
||||||
|
echo "mem: $(free -g | awk '/^Mem:/{print $2" GB"}')"
|
||||||
|
echo "cores: $(nproc)"
|
||||||
|
|
||||||
|
- name: Install from the lockfile
|
||||||
|
# `npm ci` NOT `npm install`. ci deletes node_modules and installs the
|
||||||
|
# exact lockfile tree, failing if package.json and package-lock.json
|
||||||
|
# disagree. That is precisely what an outsider cloning this repo does,
|
||||||
|
# and it is the step that catches "works because of what is already on
|
||||||
|
# my machine".
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Compile contracts
|
||||||
|
run: npx hardhat compile
|
||||||
|
|
||||||
|
- name: Full test suite
|
||||||
|
# THE GATE. No continue-on-error. A single failing test fails the run.
|
||||||
|
run: npx hardhat test
|
||||||
|
|
||||||
|
- name: Upload compiled artifacts
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: build-artifacts
|
||||||
|
path: |
|
||||||
|
artifacts/
|
||||||
|
retention-days: 30
|
||||||
|
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
# 2. PQC KNOWN-ANSWER TESTS, isolated so a crypto regression is legible.
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
#
|
||||||
|
# These run inside the full suite too. They are ALSO run alone, because
|
||||||
|
# "did the post-quantum verifiers still match the official NIST vectors" is
|
||||||
|
# the single question this project is most often asked, and burying its answer
|
||||||
|
# in a 1,400-line log is a bad answer.
|
||||||
|
#
|
||||||
|
# SCOPE HONESTY, because this is the most misread part of the project:
|
||||||
|
# * These KATs exercise the SOLIDITY verifier implementations against the
|
||||||
|
# official NIST reference vectors (falcon512-KAT.rsp / falcon1024-KAT.rsp,
|
||||||
|
# FIPS 202 SHAKE256).
|
||||||
|
# * They run on the local Hardhat EVM, which has NO Aere precompiles. The
|
||||||
|
# precompile-backed verification paths (0x0AE1 to 0x0AE5 live on chain
|
||||||
|
# 2800; 0x0AE6 ML-KEM-768 and 0x0AE7 HashToPoint are TESTNET-ONLY) cannot
|
||||||
|
# be exercised here and are therefore NOT covered by this job. Verifying
|
||||||
|
# those requires a precompile-bearing devnet. Do not read a green tick
|
||||||
|
# here as evidence about the precompiles.
|
||||||
|
# * Aere consensus is CLASSICAL secp256k1 ECDSA QBFT. Post-quantum
|
||||||
|
# cryptography exists at the signature, precompile, account and transport
|
||||||
|
# layers only. Nothing in this job says anything about consensus.
|
||||||
|
pqc-kat:
|
||||||
|
name: PQC known-answer tests (NIST vectors)
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
timeout-minutes: 60
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '24.14.1'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install from the lockfile
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Compile contracts
|
||||||
|
run: npx hardhat compile
|
||||||
|
|
||||||
|
- name: Falcon / SPHINCS+ / ML-DSA known-answer tests
|
||||||
|
# No continue-on-error. A KAT mismatch is a hard failure: it means an
|
||||||
|
# implementation stopped agreeing with the NIST reference.
|
||||||
|
run: |
|
||||||
|
npx hardhat test \
|
||||||
|
test/AereFalcon512Verifier.test.js \
|
||||||
|
test/AereFalcon1024Verifier.test.js \
|
||||||
|
test/AereSphincsVerifier.test.js \
|
||||||
|
test/AerePQCMessageVerifier.test.js \
|
||||||
|
test/AereCryptoRegistry.test.js \
|
||||||
|
test/AereCryptoRegistry.agility.test.js \
|
||||||
|
test/AereCryptoRegistry.newprecompiles.test.js
|
||||||
|
|
||||||
|
- name: Upload KAT vectors used
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: pqc-kat-vectors
|
||||||
|
path: |
|
||||||
|
test/falcon512_kat0.json
|
||||||
|
test/falcon1024_kat0.json
|
||||||
|
retention-days: 90
|
||||||
|
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
# 3. COVERAGE. Read the scope statement before quoting any number from here.
|
||||||
|
# ───────────────────────────────────────────────────────────────────────────
|
||||||
|
#
|
||||||
|
# WHAT THIS JOB PRODUCES: a SCOPED coverage number over a named cluster of
|
||||||
|
# contracts, plus the raw istanbul JSON as an artifact so anyone can recompute
|
||||||
|
# it. It does NOT produce a whole-repository coverage percentage.
|
||||||
|
#
|
||||||
|
# WHY NOT, stated plainly rather than hidden behind a green tick:
|
||||||
|
# A single-process whole-repo coverage run does not fit in a standard CI
|
||||||
|
# runner's memory. Measured on a 15.78 GB / 33.78 GB-commit box, the process
|
||||||
|
# reached the entire commit limit and was killed by the OS during the TEST
|
||||||
|
# phase. The COMPILE phase is solved: all contracts instrument and compile,
|
||||||
|
# and zero contracts are excluded from instrumentation. The remaining blocker
|
||||||
|
# is memory during test execution, caused by per-statement hit maps for the
|
||||||
|
# on-chain crypto suites, which execute tens of millions of statements per
|
||||||
|
# verify.
|
||||||
|
#
|
||||||
|
# The path to a real whole-repo number is sharding: run coverage over subsets
|
||||||
|
# with --testfiles, then merge the per-shard istanbul JSONs. That merge is
|
||||||
|
# arithmetically valid because instrumentation is deterministic over identical
|
||||||
|
# sources, so every shard emits identical statement/branch/function maps and
|
||||||
|
# the per-counter arrays sum. Until that full sharded run completes end to
|
||||||
|
# end, the honest whole-repo figure is NOT MEASURED, and this pipeline says so
|
||||||
|
# rather than substituting a scoped number for it.
|
||||||
|
#
|
||||||
|
# ANY figure of the "99.8% coverage" kind that has ever been attached to this
|
||||||
|
# project was never produced by a coverage tool. It was a target written as
|
||||||
|
# though achieved. It is not a claim this repository makes. The numbers below
|
||||||
|
# are the real ones, and they are lower.
|
||||||
|
coverage:
|
||||||
|
name: Coverage (scoped, with artifacts)
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
timeout-minutes: 120
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '24.14.1'
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install from the lockfile
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Coverage over the economic-core cluster
|
||||||
|
# Scoped by TEST FILE, not by skipFiles. This matters: skipFiles would
|
||||||
|
# shrink the DENOMINATOR and inflate the percentage. --testfiles leaves
|
||||||
|
# every contract instrumented and simply runs fewer tests, so the number
|
||||||
|
# produced is an honest "what these tests reach", measured against the
|
||||||
|
# full instrumented denominator.
|
||||||
|
#
|
||||||
|
# No continue-on-error: if a test in this scope fails, coverage fails.
|
||||||
|
run: |
|
||||||
|
npx hardhat coverage \
|
||||||
|
--config hardhat.config.coverage.js \
|
||||||
|
--testfiles "{test/aere-fee-burn-vault.test.js,test/aere-sink-branch-coverage.test.js,test/saere-v2-fix.test.js,test/aeresink-conservation-invariant.test.js}"
|
||||||
|
|
||||||
|
- name: Print the measured summary
|
||||||
|
run: |
|
||||||
|
echo "── Coverage summary (istanbul) ─────────────────────────────"
|
||||||
|
cat coverage/coverage-summary.json 2>/dev/null \
|
||||||
|
|| echo "coverage-summary.json not emitted; see the artifact for coverage.json"
|
||||||
|
|
||||||
|
- name: Upload the raw coverage report
|
||||||
|
# `if: always()` is used ONLY on artifact-upload steps, so that a FAILED
|
||||||
|
# run still hands you its evidence. It is never used on a step that
|
||||||
|
# decides pass or fail. That distinction is the whole difference between
|
||||||
|
# a debuggable pipeline and a dishonest one.
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: coverage-report
|
||||||
|
path: |
|
||||||
|
coverage/
|
||||||
|
coverage.json
|
||||||
|
retention-days: 90
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// solidity-coverage config. Only `npx hardhat coverage` reads this file.
|
||||||
|
// Production `hardhat test` / `compile` / deploy never do.
|
||||||
|
//
|
||||||
|
// skipFiles is EMPTY ON PURPOSE. Every contract in this repository is
|
||||||
|
// instrumented. Nothing is excluded from the denominator to make a percentage
|
||||||
|
// look better. If you ever add an entry here, say so in the coverage report,
|
||||||
|
// because a skipFiles entry silently shrinks the denominator.
|
||||||
|
//
|
||||||
|
// Neither `irMinimum` nor `configureYulOptimizer` is set, deliberately. Either
|
||||||
|
// one makes the plugin force a GLOBAL optimizer setting that clobbers the
|
||||||
|
// per-file overrides in hardhat.config.coverage.js. See the long comment in
|
||||||
|
// that file for the plugin source line that causes this.
|
||||||
|
//
|
||||||
|
// KNOWN LIMIT, stated rather than hidden: a single-process whole-repo coverage
|
||||||
|
// run needs more memory than a standard 16 GB CI runner has. Instrumentation
|
||||||
|
// keeps a per-statement hit map for every instrumented contract, and the
|
||||||
|
// on-chain crypto suites execute enormous statement counts (one Falcon verify
|
||||||
|
// runs tens of millions of statements). The run therefore OOMs during the TEST
|
||||||
|
// phase, not the compile phase. The compile phase is solved and does complete.
|
||||||
|
//
|
||||||
|
// The supported way to get a number in CI is to SHARD: run coverage over a
|
||||||
|
// subset of test files with --testfiles, then merge the per-shard istanbul
|
||||||
|
// JSONs. Merging is arithmetically valid because instrumentation is
|
||||||
|
// deterministic over identical sources, so every shard emits identical
|
||||||
|
// statement/branch/function maps and the per-counter arrays sum. Keeping
|
||||||
|
// skipFiles empty in every shard is what guarantees those maps match.
|
||||||
|
module.exports = {
|
||||||
|
istanbulFolder: "./coverage",
|
||||||
|
skipFiles: [],
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2025 AERE Network
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# aere-contracts
|
||||||
|
|
||||||
|
Solidity smart contracts for Aere Network (chain ID 2800) and their Hardhat test suites.
|
||||||
|
|
||||||
|
This repository is part of the Aere Network "verify yourself" core. The deployed contract
|
||||||
|
bytecode is already public on-chain (readable via `eth_getCode` and the block explorer), so
|
||||||
|
publishing the source here lets anyone read, compile, and re-test the exact logic that runs on
|
||||||
|
mainnet. Nothing in this repository can move funds or impersonate the network: there are no
|
||||||
|
private keys, no mnemonics, and no deployment credentials. Every network account is supplied at
|
||||||
|
runtime through environment variables (see `hardhat.config.js`).
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `contracts/` the Solidity sources, grouped by domain (pqc, pqfinality, settlement, lending,
|
||||||
|
governance, paymaster, oracle, mpc, zkverify, and more).
|
||||||
|
- `test/` the Hardhat test suites, including unit tests, fuzz/invariant/property tests, and the
|
||||||
|
cryptographic known-answer test (KAT) vectors under `test/fixtures/` and `test/*.json`.
|
||||||
|
- `hardhat.config.js` the compiler and network configuration. Keys and RPC URLs are read from
|
||||||
|
environment variables only; the sole literal mnemonic present is the well-known public Hardhat
|
||||||
|
default (`test test ... junk`) used for local test signers.
|
||||||
|
- `package.json` the dependency manifest.
|
||||||
|
|
||||||
|
## Verify
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci # installs the exact locked dependency tree
|
||||||
|
npx hardhat compile
|
||||||
|
npx hardhat test
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `npm ci`, not `npm install`. `ci` installs the exact tree recorded in
|
||||||
|
`package-lock.json` and fails if the lockfile and `package.json` disagree, so
|
||||||
|
you are running against the same dependency versions we measured. `install` is
|
||||||
|
free to resolve newer versions and will quietly give you a different tree.
|
||||||
|
|
||||||
|
Step-by-step instructions with the expected output at each step, the measured
|
||||||
|
pass and coverage numbers, and the required tool versions are in
|
||||||
|
`REPRODUCE.md`. The same three commands run on every push through
|
||||||
|
`.github/workflows/ci.yml`.
|
||||||
|
|
||||||
|
To reproduce against the live chain, point `AERE_RPC_URL` at the public RPC
|
||||||
|
(`https://rpc.aere.network`, chain ID 2800) and compare compiled bytecode to the on-chain code.
|
||||||
|
The full reproducibility manifest lives in the `aere-docs` repository (`REPRODUCE.md`).
|
||||||
|
|
||||||
|
## What is deliberately not here
|
||||||
|
|
||||||
|
Deployment scripts, deploy keys, `.env` files, infrastructure configuration, and business or
|
||||||
|
operations material are intentionally excluded. This repository is source plus tests only.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT. See `LICENSE`.
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAppPaymaster
|
||||||
|
* @notice Generic dApp-funded paymaster. Each dApp on AERE deploys one of these
|
||||||
|
* and funds it from their own treasury. The paymaster sponsors gas only
|
||||||
|
* for UserOps calling contracts on the dApp's whitelist, and (optionally)
|
||||||
|
* only for senders on the dApp's allowlist.
|
||||||
|
*
|
||||||
|
* Use case: Bank28 deploys their own AereAppPaymaster, funds it with X AERE
|
||||||
|
* per month from their CAC budget, whitelists Bank28's contracts as sponsorship
|
||||||
|
* targets, and optionally allowlists the senders they've authenticated through
|
||||||
|
* the Bank28 app. Foundation contributes zero.
|
||||||
|
*
|
||||||
|
* Same pattern works for any dApp: NFT marketplaces, games, DeFi apps.
|
||||||
|
*/
|
||||||
|
contract AereAppPaymaster is PaymasterBase {
|
||||||
|
/// Optional sender allowlist. If enabled, only allowlisted senders can be sponsored.
|
||||||
|
bool public senderAllowlistEnabled;
|
||||||
|
mapping(address => bool) public senderAllowlist;
|
||||||
|
|
||||||
|
/// Required target whitelist. UserOps must invoke an allowed target contract.
|
||||||
|
mapping(address => bool) public targetWhitelist;
|
||||||
|
|
||||||
|
/// Per-sender lifetime sponsorship cap. 0 = unlimited.
|
||||||
|
uint256 public maxOpsPerSender;
|
||||||
|
mapping(address => uint256) public opsCountBySender;
|
||||||
|
|
||||||
|
event SenderAllowlistChanged(bool enabled);
|
||||||
|
event SenderAllowlist(address indexed sender, bool allowed);
|
||||||
|
event TargetWhitelist(address indexed target, bool allowed);
|
||||||
|
event ConfigChanged(uint256 maxOpsPerSender);
|
||||||
|
event Sponsored(address indexed sender, address indexed target, uint256 newSenderCount);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep, address _owner) PaymasterBase(_ep) {
|
||||||
|
_transferOwnership(_owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSenderAllowlist(bool enabled) external onlyOwner {
|
||||||
|
senderAllowlistEnabled = enabled;
|
||||||
|
emit SenderAllowlistChanged(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAllowedSender(address sender, bool allowed) external onlyOwner {
|
||||||
|
senderAllowlist[sender] = allowed;
|
||||||
|
emit SenderAllowlist(sender, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTargetWhitelist(address target, bool allowed) external onlyOwner {
|
||||||
|
targetWhitelist[target] = allowed;
|
||||||
|
emit TargetWhitelist(target, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMaxOpsPerSender(uint256 max) external onlyOwner {
|
||||||
|
maxOpsPerSender = max;
|
||||||
|
emit ConfigChanged(max);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /*userOpHash*/,
|
||||||
|
uint256 /*maxCost*/
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
address sender = userOp.sender;
|
||||||
|
|
||||||
|
if (senderAllowlistEnabled) {
|
||||||
|
require(senderAllowlist[sender], "AppPM: sender not allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxOpsPerSender > 0) {
|
||||||
|
require(opsCountBySender[sender] < maxOpsPerSender, "AppPM: sender quota exhausted");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode target from SimpleAccount-compatible execute(target, value, data) callData layout.
|
||||||
|
bytes calldata cd = userOp.callData;
|
||||||
|
require(cd.length >= 36, "AppPM: bad callData");
|
||||||
|
address target;
|
||||||
|
assembly {
|
||||||
|
target := shr(96, calldataload(add(cd.offset, 16)))
|
||||||
|
}
|
||||||
|
require(targetWhitelist[target], "AppPM: target not allowed");
|
||||||
|
|
||||||
|
opsCountBySender[sender] += 1;
|
||||||
|
emit Sponsored(sender, target, opsCountBySender[sender]);
|
||||||
|
return ("", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAppPaymasterFactory
|
||||||
|
* @notice One-call factory for any dApp to spin up its own AereAppPaymaster.
|
||||||
|
* The dApp's deployer ends up as owner of the new paymaster.
|
||||||
|
* No registration fee. Anyone can deploy.
|
||||||
|
*/
|
||||||
|
contract AereAppPaymasterFactory {
|
||||||
|
IEntryPoint public immutable entryPoint;
|
||||||
|
|
||||||
|
event PaymasterCreated(address indexed deployer, address indexed paymaster);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep) {
|
||||||
|
entryPoint = _ep;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPaymaster() external returns (address paymaster) {
|
||||||
|
AereAppPaymaster p = new AereAppPaymaster(entryPoint, msg.sender);
|
||||||
|
paymaster = address(p);
|
||||||
|
emit PaymasterCreated(msg.sender, paymaster);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/security/Pausable.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereBridge
|
||||||
|
* @notice Federated lock-and-release bridge for native AERE between AERE Network
|
||||||
|
* and external EVM chains (Ethereum, BSC, Polygon, etc — 75+ supported).
|
||||||
|
* @dev Lock side: users deposit AERE here; off-chain federation observes the
|
||||||
|
* Locked event and mints wrapped-AERE on the destination chain.
|
||||||
|
* Release side: the federation attests to a destination-chain burn by signing
|
||||||
|
* (nonce, recipient, amount, srcChainId). Once `threshold` signatures from
|
||||||
|
* authorized signers are presented, the bridge releases AERE on this chain.
|
||||||
|
*
|
||||||
|
* Replay protection: each (srcChainId, nonce) pair can only be released once.
|
||||||
|
* Each signer can only contribute one signature per release (enforced via
|
||||||
|
* sorted-address requirement).
|
||||||
|
*/
|
||||||
|
contract AereBridge is Ownable, ReentrancyGuard, Pausable {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
uint256 public constant MIN_DEPOSIT = 1 ether; // 1 AERE
|
||||||
|
uint256 public constant MAX_SIGNERS = 21;
|
||||||
|
|
||||||
|
address[] public signers;
|
||||||
|
mapping(address => bool) public isSigner;
|
||||||
|
uint256 public threshold;
|
||||||
|
|
||||||
|
uint256 public depositNonce;
|
||||||
|
mapping(uint256 => mapping(uint256 => bool)) public processed; // srcChainId => srcNonce => done
|
||||||
|
|
||||||
|
event SignerAdded(address indexed signer);
|
||||||
|
event SignerRemoved(address indexed signer);
|
||||||
|
event ThresholdUpdated(uint256 newThreshold);
|
||||||
|
event Locked(uint256 indexed nonce, address indexed sender, uint256 indexed dstChainId, address dstRecipient, uint256 amount);
|
||||||
|
event Released(uint256 indexed srcChainId, uint256 indexed srcNonce, address indexed recipient, uint256 amount);
|
||||||
|
|
||||||
|
constructor(address[] memory initialSigners, uint256 _threshold) {
|
||||||
|
require(initialSigners.length > 0 && initialSigners.length <= MAX_SIGNERS, "signers");
|
||||||
|
require(_threshold > 0 && _threshold <= initialSigners.length, "threshold");
|
||||||
|
for (uint256 i = 0; i < initialSigners.length; i++) {
|
||||||
|
address s = initialSigners[i];
|
||||||
|
require(s != address(0) && !isSigner[s], "bad signer");
|
||||||
|
isSigner[s] = true;
|
||||||
|
signers.push(s);
|
||||||
|
emit SignerAdded(s);
|
||||||
|
}
|
||||||
|
threshold = _threshold;
|
||||||
|
emit ThresholdUpdated(_threshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Lock (outbound) ─────────────────────────────────────────
|
||||||
|
function lock(uint256 dstChainId, address dstRecipient) external payable whenNotPaused nonReentrant {
|
||||||
|
require(msg.value >= MIN_DEPOSIT, "min");
|
||||||
|
require(dstRecipient != address(0), "recipient");
|
||||||
|
uint256 n = ++depositNonce;
|
||||||
|
emit Locked(n, msg.sender, dstChainId, dstRecipient, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Release (inbound) ───────────────────────────────────────
|
||||||
|
/**
|
||||||
|
* @param srcChainId chain ID of the source chain where the burn occurred
|
||||||
|
* @param srcNonce bridge-issued nonce on the source chain (replay key)
|
||||||
|
* @param recipient AERE Network address to receive funds
|
||||||
|
* @param amount amount of AERE to release
|
||||||
|
* @param signatures array of ECDSA signatures over the canonical message,
|
||||||
|
* ordered by signer address ascending (deduplication)
|
||||||
|
*/
|
||||||
|
function release(
|
||||||
|
uint256 srcChainId,
|
||||||
|
uint256 srcNonce,
|
||||||
|
address recipient,
|
||||||
|
uint256 amount,
|
||||||
|
bytes[] calldata signatures
|
||||||
|
) external nonReentrant whenNotPaused {
|
||||||
|
require(!processed[srcChainId][srcNonce], "processed");
|
||||||
|
require(signatures.length >= threshold, "threshold");
|
||||||
|
require(amount > 0 && recipient != address(0), "params");
|
||||||
|
require(address(this).balance >= amount, "liquidity");
|
||||||
|
|
||||||
|
bytes32 message = keccak256(
|
||||||
|
abi.encodePacked(
|
||||||
|
address(this),
|
||||||
|
block.chainid,
|
||||||
|
srcChainId,
|
||||||
|
srcNonce,
|
||||||
|
recipient,
|
||||||
|
amount
|
||||||
|
)
|
||||||
|
).toEthSignedMessageHash();
|
||||||
|
|
||||||
|
address last = address(0);
|
||||||
|
for (uint256 i = 0; i < signatures.length; i++) {
|
||||||
|
address recovered = message.recover(signatures[i]);
|
||||||
|
require(isSigner[recovered], "not signer");
|
||||||
|
require(recovered > last, "unsorted/dup");
|
||||||
|
last = recovered;
|
||||||
|
}
|
||||||
|
|
||||||
|
processed[srcChainId][srcNonce] = true;
|
||||||
|
(bool ok, ) = recipient.call{value: amount}("");
|
||||||
|
require(ok, "transfer");
|
||||||
|
emit Released(srcChainId, srcNonce, recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Federation management ───────────────────────────────────
|
||||||
|
function addSigner(address s) external onlyOwner {
|
||||||
|
require(s != address(0) && !isSigner[s], "bad");
|
||||||
|
require(signers.length < MAX_SIGNERS, "max");
|
||||||
|
isSigner[s] = true;
|
||||||
|
signers.push(s);
|
||||||
|
emit SignerAdded(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSigner(address s) external onlyOwner {
|
||||||
|
require(isSigner[s], "not signer");
|
||||||
|
isSigner[s] = false;
|
||||||
|
for (uint256 i = 0; i < signers.length; i++) {
|
||||||
|
if (signers[i] == s) {
|
||||||
|
signers[i] = signers[signers.length - 1];
|
||||||
|
signers.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (threshold > signers.length) {
|
||||||
|
threshold = signers.length;
|
||||||
|
emit ThresholdUpdated(threshold);
|
||||||
|
}
|
||||||
|
emit SignerRemoved(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setThreshold(uint256 newThreshold) external onlyOwner {
|
||||||
|
require(newThreshold > 0 && newThreshold <= signers.length, "range");
|
||||||
|
threshold = newThreshold;
|
||||||
|
emit ThresholdUpdated(newThreshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
function signerCount() external view returns (uint256) { return signers.length; }
|
||||||
|
|
||||||
|
// ── Emergency ───────────────────────────────────────────────
|
||||||
|
function pause() external onlyOwner { _pause(); }
|
||||||
|
function unpause() external onlyOwner { _unpause(); }
|
||||||
|
|
||||||
|
/// @notice Allow the foundation to seed liquidity for releases.
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.24;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCancunCanary
|
||||||
|
* @notice On-chain canary proving Cancun EVM support on AERE (chain 2800):
|
||||||
|
* - TSTORE / TLOAD (EIP-1153), including auto-reset between
|
||||||
|
* transactions and a transient reentrancy lock,
|
||||||
|
* - MCOPY (EIP-5656) round-trip verified by keccak256,
|
||||||
|
* - PUSH0 (EIP-3855), implicit in solc >=0.8.20 shanghai+ output,
|
||||||
|
* - BLOBHASH (EIP-4844) and BLOBBASEFEE (EIP-7516) opcode execution.
|
||||||
|
*
|
||||||
|
* Compiled with solc 0.8.24, evmVersion = cancun, via a per-file
|
||||||
|
* hardhat override (the repo global stays 0.8.23 / shanghai-default).
|
||||||
|
*
|
||||||
|
* The constructor self-tests every opcode, so a successful deploy,
|
||||||
|
* or even a read-only eth_estimateGas / eth_call of the creation
|
||||||
|
* bytecode, is itself proof that the live chain executes Cancun
|
||||||
|
* opcodes: any TSTORE/TLOAD/MCOPY/BLOBHASH/BLOBBASEFEE failure
|
||||||
|
* reverts deployment.
|
||||||
|
*
|
||||||
|
* PUSH0 note for verifiers: the deployed runtime bytecode contains
|
||||||
|
* genuine PUSH0 (0x5f) opcodes; the canonical solc revert stub
|
||||||
|
* `5f80fd` (PUSH0 DUP1 REVERT) appears in the runtime code. To check
|
||||||
|
* rigorously, walk the bytecode from offset 0 skipping PUSH1..PUSH32
|
||||||
|
* immediates and confirm 0x5f at an opcode position. Every
|
||||||
|
* successful call to this contract executes PUSH0 on-chain.
|
||||||
|
*
|
||||||
|
* Blob note: AERE is a QBFT L1 that does not accept blob (type-3)
|
||||||
|
* transactions, so blobhash(0) == bytes32(0) in every execution
|
||||||
|
* context. blobbasefee is whatever the node's Cancun fee market
|
||||||
|
* reports (protocol minimum is 1 wei); it is recorded, not asserted.
|
||||||
|
*/
|
||||||
|
contract AereCancunCanary {
|
||||||
|
/// @dev keccak256("aere.cancun.canary.tslot"); literal so assembly can use it.
|
||||||
|
uint256 private constant T_SLOT =
|
||||||
|
0x600b3c753bdea90810db30bcdc9015ebc00429a1e131fa35c272b23785c573b1;
|
||||||
|
|
||||||
|
/// @dev keccak256("aere.cancun.canary.lock"); literal so assembly can use it.
|
||||||
|
uint256 private constant LOCK_SLOT =
|
||||||
|
0xe4d0d997dd2753c27700e5fe7c65208afc32dd89178d805290c63adf8ca6331e;
|
||||||
|
|
||||||
|
/// @notice true iff the constructor's TSTORE/TLOAD + MCOPY + blob-opcode
|
||||||
|
/// self-test passed on the deploying chain.
|
||||||
|
bool public immutable deploySelfTest;
|
||||||
|
|
||||||
|
event TransientWithinTx(uint256 written, uint256 readBack);
|
||||||
|
event TransientCrossTx(uint256 observed);
|
||||||
|
event ReentrancyLockProbe(bool attemptedReentry, bool innerCallReverted);
|
||||||
|
event McopyChecked(uint256 dataLen, bytes32 inputHash, bytes32 copyHash, bool ok);
|
||||||
|
event BlobProbed(bytes32 blobHash0, uint256 blobBaseFee);
|
||||||
|
|
||||||
|
error TransientLockActive();
|
||||||
|
|
||||||
|
/// @dev Reentrancy guard using EIP-1153 transient storage. Costs no
|
||||||
|
/// cold-SSTORE gas and needs no post-tx cleanup guarantees beyond
|
||||||
|
/// the EVM's own end-of-transaction transient reset.
|
||||||
|
modifier transientLock() {
|
||||||
|
uint256 lockV;
|
||||||
|
assembly {
|
||||||
|
lockV := tload(LOCK_SLOT)
|
||||||
|
}
|
||||||
|
if (lockV != 0) revert TransientLockActive();
|
||||||
|
assembly {
|
||||||
|
tstore(LOCK_SLOT, 1)
|
||||||
|
}
|
||||||
|
_;
|
||||||
|
assembly {
|
||||||
|
tstore(LOCK_SLOT, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// EIP-1153 round-trip.
|
||||||
|
uint256 v;
|
||||||
|
assembly {
|
||||||
|
tstore(T_SLOT, 0xCA9A17)
|
||||||
|
v := tload(T_SLOT)
|
||||||
|
}
|
||||||
|
require(v == 0xCA9A17, "TSTORE/TLOAD failed");
|
||||||
|
assembly {
|
||||||
|
tstore(T_SLOT, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EIP-5656 round-trip.
|
||||||
|
bytes memory src = abi.encodePacked(
|
||||||
|
keccak256("aere.cancun.canary.mcopy.src"),
|
||||||
|
uint256(2800)
|
||||||
|
);
|
||||||
|
bytes memory dst = new bytes(src.length);
|
||||||
|
uint256 len = src.length;
|
||||||
|
assembly {
|
||||||
|
mcopy(add(dst, 0x20), add(src, 0x20), len)
|
||||||
|
}
|
||||||
|
require(keccak256(dst) == keccak256(src), "MCOPY failed");
|
||||||
|
|
||||||
|
// EIP-4844 / EIP-7516 opcodes must execute (no blob txs on QBFT, so
|
||||||
|
// blobhash(0) is zero; blobbasefee is recorded, not asserted).
|
||||||
|
bytes32 h;
|
||||||
|
uint256 f;
|
||||||
|
assembly {
|
||||||
|
h := blobhash(0)
|
||||||
|
f := blobbasefee()
|
||||||
|
}
|
||||||
|
require(h == bytes32(0), "unexpected blob hash");
|
||||||
|
emit BlobProbed(h, f);
|
||||||
|
|
||||||
|
deploySelfTest = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// EIP-1153 transient storage
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// @notice Method A: TSTOREs `value` and TLOADs it back within the same
|
||||||
|
/// transaction; emits both as proof.
|
||||||
|
function transientWriteAndRead(uint256 value) external returns (uint256 readBack) {
|
||||||
|
assembly {
|
||||||
|
tstore(T_SLOT, value)
|
||||||
|
readBack := tload(T_SLOT)
|
||||||
|
}
|
||||||
|
emit TransientWithinTx(value, readBack);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Method B: TLOADs the same slot in a LATER transaction. Must
|
||||||
|
/// observe 0, proving the EVM auto-resets transient storage
|
||||||
|
/// between transactions.
|
||||||
|
function transientReadOnly() external returns (uint256 observed) {
|
||||||
|
assembly {
|
||||||
|
observed := tload(T_SLOT)
|
||||||
|
}
|
||||||
|
emit TransientCrossTx(observed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice View twin of transientReadOnly for eth_call checks.
|
||||||
|
function transientPeek() external view returns (uint256 observed) {
|
||||||
|
assembly {
|
||||||
|
observed := tload(T_SLOT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Current value of the transient reentrancy lock slot (always 0
|
||||||
|
/// when read from a fresh transaction).
|
||||||
|
function lockPeek() external view returns (uint256 v) {
|
||||||
|
assembly {
|
||||||
|
v := tload(LOCK_SLOT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Transient reentrancy lock demonstration. With
|
||||||
|
/// `attemptReentry = true` the function re-enters itself via an
|
||||||
|
/// external self-call; the inner call MUST revert with
|
||||||
|
/// TransientLockActive, and `innerCallReverted` is emitted true.
|
||||||
|
/// A subsequent plain call (`attemptReentry = false`) succeeds,
|
||||||
|
/// showing the lock cleared.
|
||||||
|
function guardedEnter(bool attemptReentry)
|
||||||
|
external
|
||||||
|
transientLock
|
||||||
|
returns (bool innerCallReverted)
|
||||||
|
{
|
||||||
|
if (attemptReentry) {
|
||||||
|
(bool ok, ) = address(this).call(
|
||||||
|
abi.encodeWithSelector(this.guardedEnter.selector, false)
|
||||||
|
);
|
||||||
|
innerCallReverted = !ok;
|
||||||
|
}
|
||||||
|
emit ReentrancyLockProbe(attemptReentry, innerCallReverted);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// EIP-5656 MCOPY
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// @notice Copies `data` with assembly `mcopy` and returns keccak256 of
|
||||||
|
/// both the input and the copy; equal hashes prove a faithful
|
||||||
|
/// MCOPY round-trip.
|
||||||
|
function mcopyHash(bytes calldata data)
|
||||||
|
public
|
||||||
|
pure
|
||||||
|
returns (bytes32 inputHash, bytes32 copyHash)
|
||||||
|
{
|
||||||
|
bytes memory input = data;
|
||||||
|
inputHash = keccak256(input);
|
||||||
|
uint256 len = input.length;
|
||||||
|
bytes memory copyBuf = new bytes(len);
|
||||||
|
assembly {
|
||||||
|
mcopy(add(copyBuf, 0x20), add(input, 0x20), len)
|
||||||
|
copyHash := keccak256(add(copyBuf, 0x20), len)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Transaction variant of mcopyHash; emits the comparison so the
|
||||||
|
/// proof lives in a receipt.
|
||||||
|
function mcopyCheck(bytes calldata data) external returns (bool ok) {
|
||||||
|
(bytes32 inputHash, bytes32 copyHash) = mcopyHash(data);
|
||||||
|
ok = inputHash == copyHash;
|
||||||
|
emit McopyChecked(data.length, inputHash, copyHash, ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// EIP-4844 BLOBHASH / EIP-7516 BLOBBASEFEE
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// @notice Returns blobhash(0) and blobbasefee via assembly. On AERE
|
||||||
|
/// (QBFT, no blob transactions) blobhash(0) == bytes32(0);
|
||||||
|
/// blobbasefee is the node-reported blob base fee (min 1 wei).
|
||||||
|
function blobView() public view returns (bytes32 blobHash0, uint256 blobBaseFee) {
|
||||||
|
assembly {
|
||||||
|
blobHash0 := blobhash(0)
|
||||||
|
blobBaseFee := blobbasefee()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Transaction variant of blobView; emits the values.
|
||||||
|
function blobProbe() external returns (bytes32 blobHash0, uint256 blobBaseFee) {
|
||||||
|
(blobHash0, blobBaseFee) = blobView();
|
||||||
|
emit BlobProbed(blobHash0, blobBaseFee);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCardEscrow
|
||||||
|
* @notice Pre-auth + capture rail for Bank28 (and future card programs) on AERE.
|
||||||
|
* Settlement node calls preAuth() to lock user funds via EIP-2612 permit
|
||||||
|
* (~3s, 1 block on AERE QBFT). When the card auth resolves, the node
|
||||||
|
* calls capture() with the final amount, which transfers to the
|
||||||
|
* issuer settlement address minus protocol/program fees, and refunds
|
||||||
|
* the residual hold to the user. Expired auths are released by anyone.
|
||||||
|
*
|
||||||
|
* This is the "slower path" alternative to AereLightningChannels for
|
||||||
|
* programs that don't run a long-lived channel counterparty.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address account) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IERC2612 {
|
||||||
|
function permit(
|
||||||
|
address owner, address spender, uint256 value,
|
||||||
|
uint256 deadline, uint8 v, bytes32 r, bytes32 s
|
||||||
|
) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereIdentity {
|
||||||
|
function hasClaim(address identity, bytes32 claimType) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereCardEscrow {
|
||||||
|
// ── Auth state ─────────────────────────────────────────────────
|
||||||
|
enum Status { None, Held, Captured, Released }
|
||||||
|
|
||||||
|
struct Auth {
|
||||||
|
address user;
|
||||||
|
address asset;
|
||||||
|
uint128 amount; // amount on hold (residual after partial captures)
|
||||||
|
uint64 expiresAt;
|
||||||
|
uint64 programId; // 1 = Bank28, future programs allocated by owner
|
||||||
|
Status status;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(bytes32 => Auth) public auths; // authId => Auth
|
||||||
|
|
||||||
|
// ── Programs ───────────────────────────────────────────────────
|
||||||
|
struct Program {
|
||||||
|
address settlementNode; // authorized to call preAuth/capture for this program
|
||||||
|
address feeRecipient; // program's own fee bucket (Bank28 treasury)
|
||||||
|
uint16 programFeeBps; // program-charged bps on capture (max 1000)
|
||||||
|
bool active;
|
||||||
|
}
|
||||||
|
mapping(uint64 => Program) public programs;
|
||||||
|
uint64 public nextProgramId = 1;
|
||||||
|
|
||||||
|
// ── Globals ────────────────────────────────────────────────────
|
||||||
|
address public owner;
|
||||||
|
address public protocolTreasury;
|
||||||
|
uint16 public protocolFeeBps = 30; // 30 bps = 0.30% to AereTreasury
|
||||||
|
uint16 public constant MAX_PROGRAM_FEE_BPS = 1000;
|
||||||
|
uint16 public constant MAX_PROTOCOL_FEE_BPS = 100;
|
||||||
|
IAereIdentity public identity;
|
||||||
|
bytes32 public requiredClaim; // e.g. keccak256("KYC_TIER_2")
|
||||||
|
|
||||||
|
// ── Events ─────────────────────────────────────────────────────
|
||||||
|
event ProgramRegistered(uint64 indexed programId, address settlementNode, address feeRecipient, uint16 feeBps);
|
||||||
|
event ProgramUpdated(uint64 indexed programId, address settlementNode, address feeRecipient, uint16 feeBps, bool active);
|
||||||
|
event PreAuth(bytes32 indexed authId, uint64 indexed programId, address indexed user, address asset, uint128 amount, uint64 expiresAt);
|
||||||
|
event Captured(bytes32 indexed authId, uint128 captured, address recipient, uint128 protocolFee, uint128 programFee, uint128 refunded);
|
||||||
|
event Released(bytes32 indexed authId, uint128 refunded);
|
||||||
|
event ProtocolFeeUpdated(uint16 bps);
|
||||||
|
event RequiredClaimUpdated(bytes32 claim);
|
||||||
|
|
||||||
|
modifier onlyOwner() { require(msg.sender == owner, "owner"); _; }
|
||||||
|
|
||||||
|
constructor(address _treasury, address _identity, bytes32 _requiredClaim) {
|
||||||
|
require(_treasury != address(0), "treasury=0");
|
||||||
|
owner = msg.sender;
|
||||||
|
protocolTreasury = _treasury;
|
||||||
|
identity = IAereIdentity(_identity);
|
||||||
|
requiredClaim = _requiredClaim;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Admin ──────────────────────────────────────────────────────
|
||||||
|
function registerProgram(address settlementNode, address feeRecipient, uint16 feeBps) external onlyOwner returns (uint64 id) {
|
||||||
|
require(settlementNode != address(0) && feeRecipient != address(0), "zero");
|
||||||
|
require(feeBps <= MAX_PROGRAM_FEE_BPS, "feeBps");
|
||||||
|
id = nextProgramId++;
|
||||||
|
programs[id] = Program(settlementNode, feeRecipient, feeBps, true);
|
||||||
|
emit ProgramRegistered(id, settlementNode, feeRecipient, feeBps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateProgram(uint64 id, address settlementNode, address feeRecipient, uint16 feeBps, bool active) external onlyOwner {
|
||||||
|
require(programs[id].settlementNode != address(0), "no program");
|
||||||
|
require(feeBps <= MAX_PROGRAM_FEE_BPS, "feeBps");
|
||||||
|
programs[id] = Program(settlementNode, feeRecipient, feeBps, active);
|
||||||
|
emit ProgramUpdated(id, settlementNode, feeRecipient, feeBps, active);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setProtocolFeeBps(uint16 bps) external onlyOwner {
|
||||||
|
require(bps <= MAX_PROTOCOL_FEE_BPS, "max");
|
||||||
|
protocolFeeBps = bps;
|
||||||
|
emit ProtocolFeeUpdated(bps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setProtocolTreasury(address t) external onlyOwner { require(t != address(0)); protocolTreasury = t; }
|
||||||
|
function setIdentity(address a, bytes32 claim) external onlyOwner { identity = IAereIdentity(a); requiredClaim = claim; emit RequiredClaimUpdated(claim); }
|
||||||
|
function transferOwnership(address n) external onlyOwner { require(n != address(0)); owner = n; }
|
||||||
|
|
||||||
|
// ── Pre-auth (settlement node only) ────────────────────────────
|
||||||
|
/**
|
||||||
|
* @notice Lock user funds for an upcoming card auth.
|
||||||
|
* @dev Uses EIP-2612 permit so the user signs off-chain and the settlement
|
||||||
|
* node submits the on-chain tx (sponsored by the program's paymaster).
|
||||||
|
* authId is supplied by the caller — typically keccak256(programId, externalAuthRef)
|
||||||
|
* so the off-chain card system controls the namespace.
|
||||||
|
*/
|
||||||
|
function preAuthWithPermit(
|
||||||
|
bytes32 authId,
|
||||||
|
uint64 programId,
|
||||||
|
address user,
|
||||||
|
address asset,
|
||||||
|
uint128 amount,
|
||||||
|
uint64 expiresAt,
|
||||||
|
uint256 permitDeadline,
|
||||||
|
uint8 v, bytes32 r, bytes32 s
|
||||||
|
) external {
|
||||||
|
Program storage p = programs[programId];
|
||||||
|
require(p.active && msg.sender == p.settlementNode, "not node");
|
||||||
|
require(auths[authId].status == Status.None, "authId used");
|
||||||
|
require(amount > 0 && expiresAt > block.timestamp, "params");
|
||||||
|
if (address(identity) != address(0) && requiredClaim != bytes32(0)) {
|
||||||
|
require(identity.hasClaim(user, requiredClaim), "not eligible");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pull user funds via permit. Permit failure (e.g. already used) is OK
|
||||||
|
// if allowance is already sufficient.
|
||||||
|
try IERC2612(asset).permit(user, address(this), amount, permitDeadline, v, r, s) {} catch {}
|
||||||
|
require(IERC20(asset).transferFrom(user, address(this), amount), "transferFrom");
|
||||||
|
|
||||||
|
auths[authId] = Auth(user, asset, amount, expiresAt, programId, Status.Held);
|
||||||
|
emit PreAuth(authId, programId, user, asset, amount, expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Lock funds when the user has already approved this contract (no permit).
|
||||||
|
function preAuth(
|
||||||
|
bytes32 authId, uint64 programId, address user,
|
||||||
|
address asset, uint128 amount, uint64 expiresAt
|
||||||
|
) external {
|
||||||
|
Program storage p = programs[programId];
|
||||||
|
require(p.active && msg.sender == p.settlementNode, "not node");
|
||||||
|
require(auths[authId].status == Status.None, "authId used");
|
||||||
|
require(amount > 0 && expiresAt > block.timestamp, "params");
|
||||||
|
if (address(identity) != address(0) && requiredClaim != bytes32(0)) {
|
||||||
|
require(identity.hasClaim(user, requiredClaim), "not eligible");
|
||||||
|
}
|
||||||
|
require(IERC20(asset).transferFrom(user, address(this), amount), "transferFrom");
|
||||||
|
auths[authId] = Auth(user, asset, amount, expiresAt, programId, Status.Held);
|
||||||
|
emit PreAuth(authId, programId, user, asset, amount, expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Capture (settlement node only) ─────────────────────────────
|
||||||
|
/**
|
||||||
|
* @notice Settle a held auth. Splits funds: protocolFeeBps to AereTreasury,
|
||||||
|
* programFeeBps to program.feeRecipient, captureAmount-fees to
|
||||||
|
* issuerRecipient, residual to the user. Closes the auth.
|
||||||
|
*/
|
||||||
|
function capture(bytes32 authId, uint128 captureAmount, address issuerRecipient) external {
|
||||||
|
Auth storage a = auths[authId];
|
||||||
|
require(a.status == Status.Held, "not held");
|
||||||
|
Program storage p = programs[a.programId];
|
||||||
|
require(msg.sender == p.settlementNode, "not node");
|
||||||
|
require(captureAmount <= a.amount, "over");
|
||||||
|
require(issuerRecipient != address(0), "recipient=0");
|
||||||
|
|
||||||
|
uint128 protoFee = uint128(uint256(captureAmount) * protocolFeeBps / 10_000);
|
||||||
|
uint128 progFee = uint128(uint256(captureAmount) * p.programFeeBps / 10_000);
|
||||||
|
require(uint256(protoFee) + progFee < captureAmount, "fees>=capture");
|
||||||
|
|
||||||
|
uint128 toIssuer = captureAmount - protoFee - progFee;
|
||||||
|
uint128 toRefund = a.amount - captureAmount;
|
||||||
|
|
||||||
|
a.status = Status.Captured;
|
||||||
|
a.amount = 0;
|
||||||
|
|
||||||
|
if (protoFee > 0) require(IERC20(a.asset).transfer(protocolTreasury, protoFee), "t1");
|
||||||
|
if (progFee > 0) require(IERC20(a.asset).transfer(p.feeRecipient, progFee), "t2");
|
||||||
|
if (toIssuer > 0) require(IERC20(a.asset).transfer(issuerRecipient, toIssuer), "t3");
|
||||||
|
if (toRefund > 0) require(IERC20(a.asset).transfer(a.user, toRefund), "t4");
|
||||||
|
|
||||||
|
emit Captured(authId, captureAmount, issuerRecipient, protoFee, progFee, toRefund);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Release (anyone, after expiry) ─────────────────────────────
|
||||||
|
/// @notice Refund a held auth that wasn't captured before expiry. Permissionless.
|
||||||
|
function release(bytes32 authId) external {
|
||||||
|
Auth storage a = auths[authId];
|
||||||
|
require(a.status == Status.Held, "not held");
|
||||||
|
require(block.timestamp >= a.expiresAt, "not expired");
|
||||||
|
uint128 amt = a.amount;
|
||||||
|
a.status = Status.Released;
|
||||||
|
a.amount = 0;
|
||||||
|
require(IERC20(a.asset).transfer(a.user, amt), "refund");
|
||||||
|
emit Released(authId, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Voluntary release by the program before expiry (e.g. cardholder voided).
|
||||||
|
function voidAuth(bytes32 authId) external {
|
||||||
|
Auth storage a = auths[authId];
|
||||||
|
require(a.status == Status.Held, "not held");
|
||||||
|
Program storage p = programs[a.programId];
|
||||||
|
require(msg.sender == p.settlementNode, "not node");
|
||||||
|
uint128 amt = a.amount;
|
||||||
|
a.status = Status.Released;
|
||||||
|
a.amount = 0;
|
||||||
|
require(IERC20(a.asset).transfer(a.user, amt), "refund");
|
||||||
|
emit Released(authId, amt);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
interface IBurnVault {
|
||||||
|
function burn() external payable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCoinbaseSplitter
|
||||||
|
* @notice Routes validator coinbase rewards through an atomic split:
|
||||||
|
* burnBps to AereFeeBurnVault (default 3750 = 37.5%, matching whitepaper §3.3),
|
||||||
|
* remainder back to the validator's address.
|
||||||
|
*
|
||||||
|
* Validators (or their forwarder daemons) call `splitAndDistribute()` with
|
||||||
|
* their accumulated coinbase as msg.value. The contract atomically:
|
||||||
|
* 1. Sends burnBps/10000 of msg.value to AereFeeBurnVault.
|
||||||
|
* 2. Sends the remainder back to the validator's address.
|
||||||
|
* 3. Emits Burned + Distributed events with cumulative totals.
|
||||||
|
*
|
||||||
|
* Anyone can call this contract — there is no allowlist of "who can burn."
|
||||||
|
* The splitter is owner-configurable only for the burnBps parameter and
|
||||||
|
* the burn-vault address; it cannot hold or steal funds.
|
||||||
|
*
|
||||||
|
* Cumulative on-chain accounting allows /network-status to display a live
|
||||||
|
* burn rate, and any third-party explorer or analyst to verify the
|
||||||
|
* whitepaper §3.3 deflation claim in O(1) reads.
|
||||||
|
*/
|
||||||
|
contract AereCoinbaseSplitter is Ownable, ReentrancyGuard {
|
||||||
|
/// AereFeeBurnVault — where the burned portion goes.
|
||||||
|
address payable public burnVault;
|
||||||
|
|
||||||
|
/// Burn rate in basis points. 3750 = 37.5% (matches whitepaper §3.3).
|
||||||
|
uint256 public burnBps = 3750;
|
||||||
|
uint256 public constant BPS = 10_000;
|
||||||
|
|
||||||
|
/// Cumulative AERE burned through this splitter (lifetime).
|
||||||
|
uint256 public totalBurned;
|
||||||
|
/// Cumulative AERE distributed back to validators (lifetime).
|
||||||
|
uint256 public totalDistributed;
|
||||||
|
/// Per-validator (or per-caller) cumulative burn contribution.
|
||||||
|
mapping(address => uint256) public burnedBy;
|
||||||
|
mapping(address => uint256) public distributedTo;
|
||||||
|
|
||||||
|
event Burned(address indexed contributor, uint256 amount, uint256 newTotalBurned);
|
||||||
|
event Distributed(address indexed validator, uint256 amount, uint256 newTotalDistributed);
|
||||||
|
event BurnBpsChanged(uint256 oldBps, uint256 newBps);
|
||||||
|
event BurnVaultChanged(address oldVault, address newVault);
|
||||||
|
|
||||||
|
constructor(address payable _burnVault) {
|
||||||
|
require(_burnVault != address(0), "Splitter: zero vault");
|
||||||
|
burnVault = _burnVault;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
/// Foundation can adjust the burn rate up to a hard cap of 50% — never higher.
|
||||||
|
/// The whitepaper says "up to 37.5%" so this provides headroom but caps abuse.
|
||||||
|
function setBurnBps(uint256 _bps) external onlyOwner {
|
||||||
|
require(_bps <= 5000, "Splitter: bps too high");
|
||||||
|
emit BurnBpsChanged(burnBps, _bps);
|
||||||
|
burnBps = _bps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBurnVault(address payable _vault) external onlyOwner {
|
||||||
|
require(_vault != address(0), "Splitter: zero vault");
|
||||||
|
emit BurnVaultChanged(burnVault, _vault);
|
||||||
|
burnVault = _vault;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Core ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Split msg.value: burnBps/10000 to AereFeeBurnVault, remainder to `validator`.
|
||||||
|
* @param validator The address to receive the unburned portion. For validator-
|
||||||
|
* initiated calls this is typically tx.origin or msg.sender;
|
||||||
|
* the caller decides where their rebate goes.
|
||||||
|
*/
|
||||||
|
function splitAndDistribute(address payable validator) external payable nonReentrant {
|
||||||
|
require(msg.value > 0, "Splitter: zero amount");
|
||||||
|
require(validator != address(0), "Splitter: zero validator");
|
||||||
|
|
||||||
|
uint256 burnAmount = (msg.value * burnBps) / BPS;
|
||||||
|
uint256 distributeAmount = msg.value - burnAmount;
|
||||||
|
|
||||||
|
// Send burnAmount to AereFeeBurnVault.
|
||||||
|
if (burnAmount > 0) {
|
||||||
|
IBurnVault(burnVault).burn{ value: burnAmount }();
|
||||||
|
totalBurned += burnAmount;
|
||||||
|
burnedBy[msg.sender] += burnAmount;
|
||||||
|
emit Burned(msg.sender, burnAmount, totalBurned);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Distribute remainder back to validator.
|
||||||
|
if (distributeAmount > 0) {
|
||||||
|
(bool ok, ) = validator.call{ value: distributeAmount }("");
|
||||||
|
require(ok, "Splitter: distribute failed");
|
||||||
|
totalDistributed += distributeAmount;
|
||||||
|
distributedTo[validator] += distributeAmount;
|
||||||
|
emit Distributed(validator, distributeAmount, totalDistributed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience: validator calls this with no validator argument — distributes back to msg.sender.
|
||||||
|
function splitToSelf() external payable nonReentrant {
|
||||||
|
require(msg.value > 0, "Splitter: zero amount");
|
||||||
|
uint256 burnAmount = (msg.value * burnBps) / BPS;
|
||||||
|
uint256 distributeAmount = msg.value - burnAmount;
|
||||||
|
|
||||||
|
if (burnAmount > 0) {
|
||||||
|
IBurnVault(burnVault).burn{ value: burnAmount }();
|
||||||
|
totalBurned += burnAmount;
|
||||||
|
burnedBy[msg.sender] += burnAmount;
|
||||||
|
emit Burned(msg.sender, burnAmount, totalBurned);
|
||||||
|
}
|
||||||
|
if (distributeAmount > 0) {
|
||||||
|
(bool ok, ) = payable(msg.sender).call{ value: distributeAmount }("");
|
||||||
|
require(ok, "Splitter: distribute failed");
|
||||||
|
totalDistributed += distributeAmount;
|
||||||
|
distributedTo[msg.sender] += distributeAmount;
|
||||||
|
emit Distributed(msg.sender, distributeAmount, totalDistributed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the live cumulative burn statistics for /network-status display.
|
||||||
|
function burnStats() external view returns (
|
||||||
|
uint256 lifetimeBurned,
|
||||||
|
uint256 lifetimeDistributed,
|
||||||
|
uint256 currentBurnBps
|
||||||
|
) {
|
||||||
|
return (totalBurned, totalDistributed, burnBps);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
|
||||||
|
interface IBurnVaultV2 {
|
||||||
|
function burn() external payable;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereSinkV2 {
|
||||||
|
function flush(address token, uint256 amount) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IWAERE {
|
||||||
|
function deposit() external payable;
|
||||||
|
function approve(address guy, uint256 wad) external returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCoinbaseSplitterV2
|
||||||
|
* @notice V2 of the validator coinbase splitter. Replaces V1's 2-way split
|
||||||
|
* (burn / validator-rebate) with a 3-way split that ADDS the AereSink
|
||||||
|
* bucket so a portion of every validator reward feeds the sAERE
|
||||||
|
* flywheel.
|
||||||
|
*
|
||||||
|
* Three buckets, all in basis points, owner-configurable within hard
|
||||||
|
* caps:
|
||||||
|
* burnBps — direct burn at AereFeeBurnVault (default 3750 = 37.5%)
|
||||||
|
* sinkBps — routed through AereSink (default 1500 = 15.0%)
|
||||||
|
* rebateBps — back to validator (default 4750 = 47.5%, derived)
|
||||||
|
*
|
||||||
|
* The 3-way default lifts the protocol-level deflation rate from 37.5%
|
||||||
|
* to ~52.5% net (burn bucket plus most of the sink — see saere_architecture
|
||||||
|
* for AereSink's internal 15/40/45 split which makes 55% of sink output
|
||||||
|
* a burn).
|
||||||
|
*
|
||||||
|
* @dev Owner can adjust bps within these limits:
|
||||||
|
* - burnBps ∈ [0, 5000]
|
||||||
|
* - sinkBps ∈ [0, 3000]
|
||||||
|
* - rebateBps = 10000 - burnBps - sinkBps (auto-derived; revert if < 0)
|
||||||
|
* The sink address itself is owner-settable but rate-limited: a
|
||||||
|
* setSink call has a 7-day timelock to give validators warning before
|
||||||
|
* a sink swap.
|
||||||
|
*
|
||||||
|
* This is the "in-place upgrade" that Week-1 references. The V1
|
||||||
|
* contract stays deployed and any AERE still flowing through it
|
||||||
|
* continues to honor the V1 burn behaviour. Validators migrate to
|
||||||
|
* V2 by switching the forwarder daemon's target address (off-chain
|
||||||
|
* config). Once migration is complete, V1 burnBps can be set to 0
|
||||||
|
* and the V1 contract retired.
|
||||||
|
*
|
||||||
|
* Funds-safety: V2 cannot custody AERE across calls; every
|
||||||
|
* splitAndDistribute / splitToSelf fully dispatches msg.value.
|
||||||
|
* The sink bucket is wrapped via WAERE → IAereSink.flush() in one
|
||||||
|
* transaction; if the sink call reverts, the whole tx reverts and
|
||||||
|
* the validator can retry.
|
||||||
|
*/
|
||||||
|
contract AereCoinbaseSplitterV2 is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
/* --------------------------------- state --------------------------------- */
|
||||||
|
|
||||||
|
address payable public burnVault;
|
||||||
|
address public sink; // AereSink
|
||||||
|
address public immutable WAERE_ADDR;
|
||||||
|
|
||||||
|
uint256 public burnBps = 3750; // 37.5%
|
||||||
|
uint256 public sinkBps = 1500; // 15.0%
|
||||||
|
// rebateBps = 10000 - burnBps - sinkBps (computed live)
|
||||||
|
|
||||||
|
uint256 public constant BPS = 10_000;
|
||||||
|
uint256 public constant SINK_CHANGE_TIMELOCK = 7 days;
|
||||||
|
uint256 public constant MAX_BURN_BPS = 5000;
|
||||||
|
uint256 public constant MAX_SINK_BPS = 3000;
|
||||||
|
|
||||||
|
// Cumulative lifetime accounting.
|
||||||
|
uint256 public totalBurned;
|
||||||
|
uint256 public totalSentToSink;
|
||||||
|
uint256 public totalRebated;
|
||||||
|
|
||||||
|
mapping(address => uint256) public burnedBy;
|
||||||
|
mapping(address => uint256) public sentToSinkBy;
|
||||||
|
mapping(address => uint256) public rebatedTo;
|
||||||
|
|
||||||
|
// Sink rotation timelock.
|
||||||
|
address public pendingSink;
|
||||||
|
uint256 public pendingSinkEarliestSetTs;
|
||||||
|
|
||||||
|
/* --------------------------------- events --------------------------------- */
|
||||||
|
|
||||||
|
event Burned(address indexed contributor, uint256 amount, uint256 newTotalBurned);
|
||||||
|
event SinkRouted(address indexed contributor, uint256 amount, uint256 newTotalSentToSink);
|
||||||
|
event Rebated(address indexed validator, uint256 amount, uint256 newTotalRebated);
|
||||||
|
event BpsChanged(uint256 oldBurnBps, uint256 oldSinkBps, uint256 newBurnBps, uint256 newSinkBps);
|
||||||
|
event BurnVaultChanged(address oldVault, address newVault);
|
||||||
|
event PendingSinkProposed(address indexed newSink, uint256 earliestSet);
|
||||||
|
event SinkChanged(address oldSink, address newSink);
|
||||||
|
event PendingSinkCancelled();
|
||||||
|
|
||||||
|
/* --------------------------------- errors --------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error BpsOutOfRange();
|
||||||
|
error TimelockNotElapsed(uint256 nowTs, uint256 earliest);
|
||||||
|
error NoPendingProposal();
|
||||||
|
error DistributeFailed();
|
||||||
|
error ZeroAmount();
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ------------------------------ */
|
||||||
|
|
||||||
|
constructor(address payable _burnVault, address _waere) {
|
||||||
|
if (_burnVault == address(0) || _waere == address(0)) revert ZeroAddress();
|
||||||
|
burnVault = _burnVault;
|
||||||
|
WAERE_ADDR = _waere;
|
||||||
|
// sink starts unset — until owner calls proposeSink+acceptSink, V2
|
||||||
|
// behaves like V1 (no sink bucket; the 15% sinkBps default would
|
||||||
|
// also be skipped, with that 15% rebated instead).
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- admin (rate) ----------------------------- */
|
||||||
|
|
||||||
|
/// Owner can adjust burn/sink bps within caps. rebateBps is derived.
|
||||||
|
function setBps(uint256 _burnBps, uint256 _sinkBps) external onlyOwner {
|
||||||
|
if (_burnBps > MAX_BURN_BPS) revert BpsOutOfRange();
|
||||||
|
if (_sinkBps > MAX_SINK_BPS) revert BpsOutOfRange();
|
||||||
|
if (_burnBps + _sinkBps > BPS) revert BpsOutOfRange();
|
||||||
|
emit BpsChanged(burnBps, sinkBps, _burnBps, _sinkBps);
|
||||||
|
burnBps = _burnBps;
|
||||||
|
sinkBps = _sinkBps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBurnVault(address payable _vault) external onlyOwner {
|
||||||
|
if (_vault == address(0)) revert ZeroAddress();
|
||||||
|
emit BurnVaultChanged(burnVault, _vault);
|
||||||
|
burnVault = _vault;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- admin (sink) ----------------------------- */
|
||||||
|
|
||||||
|
function proposeSink(address _sink) external onlyOwner {
|
||||||
|
if (_sink == address(0)) revert ZeroAddress();
|
||||||
|
pendingSink = _sink;
|
||||||
|
pendingSinkEarliestSetTs = block.timestamp + SINK_CHANGE_TIMELOCK;
|
||||||
|
emit PendingSinkProposed(_sink, pendingSinkEarliestSetTs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function acceptSink() external onlyOwner {
|
||||||
|
if (pendingSink == address(0)) revert NoPendingProposal();
|
||||||
|
if (block.timestamp < pendingSinkEarliestSetTs) {
|
||||||
|
revert TimelockNotElapsed(block.timestamp, pendingSinkEarliestSetTs);
|
||||||
|
}
|
||||||
|
address old = sink;
|
||||||
|
sink = pendingSink;
|
||||||
|
delete pendingSink;
|
||||||
|
delete pendingSinkEarliestSetTs;
|
||||||
|
emit SinkChanged(old, sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelPendingSink() external onlyOwner {
|
||||||
|
if (pendingSink == address(0)) revert NoPendingProposal();
|
||||||
|
delete pendingSink;
|
||||||
|
delete pendingSinkEarliestSetTs;
|
||||||
|
emit PendingSinkCancelled();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- core --------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Split msg.value 3-ways. Anyone can call. Sink bucket is skipped
|
||||||
|
* (added to rebate) when sink is unset.
|
||||||
|
*/
|
||||||
|
function splitAndDistribute(address payable validator) external payable nonReentrant {
|
||||||
|
if (msg.value == 0) revert ZeroAmount();
|
||||||
|
if (validator == address(0)) revert ZeroAddress();
|
||||||
|
|
||||||
|
uint256 burnAmt = (msg.value * burnBps) / BPS;
|
||||||
|
uint256 sinkAmt = (sink == address(0)) ? 0 : (msg.value * sinkBps) / BPS;
|
||||||
|
uint256 rebateAmt = msg.value - burnAmt - sinkAmt;
|
||||||
|
|
||||||
|
if (burnAmt > 0) {
|
||||||
|
IBurnVaultV2(burnVault).burn{value: burnAmt}();
|
||||||
|
totalBurned += burnAmt;
|
||||||
|
burnedBy[msg.sender] += burnAmt;
|
||||||
|
emit Burned(msg.sender, burnAmt, totalBurned);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sinkAmt > 0) {
|
||||||
|
// Wrap msg.value's sink share into WAERE, then approve+flush.
|
||||||
|
IWAERE(WAERE_ADDR).deposit{value: sinkAmt}();
|
||||||
|
IWAERE(WAERE_ADDR).approve(sink, sinkAmt);
|
||||||
|
IAereSinkV2(sink).flush(WAERE_ADDR, sinkAmt);
|
||||||
|
totalSentToSink += sinkAmt;
|
||||||
|
sentToSinkBy[msg.sender] += sinkAmt;
|
||||||
|
emit SinkRouted(msg.sender, sinkAmt, totalSentToSink);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rebateAmt > 0) {
|
||||||
|
(bool ok, ) = validator.call{value: rebateAmt}("");
|
||||||
|
if (!ok) revert DistributeFailed();
|
||||||
|
totalRebated += rebateAmt;
|
||||||
|
rebatedTo[validator] += rebateAmt;
|
||||||
|
emit Rebated(validator, rebateAmt, totalRebated);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitToSelf() external payable nonReentrant {
|
||||||
|
_splitToValidator(payable(msg.sender));
|
||||||
|
}
|
||||||
|
|
||||||
|
function _splitToValidator(address payable validator) internal {
|
||||||
|
if (msg.value == 0) revert ZeroAmount();
|
||||||
|
|
||||||
|
uint256 burnAmt = (msg.value * burnBps) / BPS;
|
||||||
|
uint256 sinkAmt = (sink == address(0)) ? 0 : (msg.value * sinkBps) / BPS;
|
||||||
|
uint256 rebateAmt = msg.value - burnAmt - sinkAmt;
|
||||||
|
|
||||||
|
if (burnAmt > 0) {
|
||||||
|
IBurnVaultV2(burnVault).burn{value: burnAmt}();
|
||||||
|
totalBurned += burnAmt;
|
||||||
|
burnedBy[msg.sender] += burnAmt;
|
||||||
|
emit Burned(msg.sender, burnAmt, totalBurned);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sinkAmt > 0) {
|
||||||
|
IWAERE(WAERE_ADDR).deposit{value: sinkAmt}();
|
||||||
|
IWAERE(WAERE_ADDR).approve(sink, sinkAmt);
|
||||||
|
IAereSinkV2(sink).flush(WAERE_ADDR, sinkAmt);
|
||||||
|
totalSentToSink += sinkAmt;
|
||||||
|
sentToSinkBy[msg.sender] += sinkAmt;
|
||||||
|
emit SinkRouted(msg.sender, sinkAmt, totalSentToSink);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rebateAmt > 0) {
|
||||||
|
(bool ok, ) = validator.call{value: rebateAmt}("");
|
||||||
|
if (!ok) revert DistributeFailed();
|
||||||
|
totalRebated += rebateAmt;
|
||||||
|
rebatedTo[validator] += rebateAmt;
|
||||||
|
emit Rebated(validator, rebateAmt, totalRebated);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- views -------------------------------- */
|
||||||
|
|
||||||
|
function rebateBps() external view returns (uint256) {
|
||||||
|
return BPS - burnBps - sinkBps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitStats() external view returns (
|
||||||
|
uint256 lifetimeBurned,
|
||||||
|
uint256 lifetimeSentToSink,
|
||||||
|
uint256 lifetimeRebated,
|
||||||
|
uint256 currentBurnBps,
|
||||||
|
uint256 currentSinkBps,
|
||||||
|
uint256 currentRebateBps,
|
||||||
|
address currentSink
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
totalBurned,
|
||||||
|
totalSentToSink,
|
||||||
|
totalRebated,
|
||||||
|
burnBps,
|
||||||
|
sinkBps,
|
||||||
|
BPS - burnBps - sinkBps,
|
||||||
|
sink
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE Consensus Contract
|
||||||
|
* @dev Manages consensus mechanism and validator operations
|
||||||
|
*/
|
||||||
|
contract AereConsensus is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
struct Validator {
|
||||||
|
address validatorAddress;
|
||||||
|
uint256 stake;
|
||||||
|
uint256 votingPower;
|
||||||
|
bool isActive;
|
||||||
|
uint256 joinedAt;
|
||||||
|
uint256 rewardsEarned;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ConsensusRound {
|
||||||
|
uint256 roundNumber;
|
||||||
|
address proposer;
|
||||||
|
uint256 blockHeight;
|
||||||
|
uint256 timestamp;
|
||||||
|
bool finalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
// State variables
|
||||||
|
mapping(address => Validator) public validators;
|
||||||
|
mapping(uint256 => ConsensusRound) public consensusRounds;
|
||||||
|
address[] public validatorList;
|
||||||
|
|
||||||
|
uint256 public constant MINIMUM_STAKE = 100000 * 10**18; // 100K AERE
|
||||||
|
uint256 public constant BLOCK_TIME = 12; // 12 seconds
|
||||||
|
uint256 public currentRound = 0;
|
||||||
|
uint256 public totalStaked = 0;
|
||||||
|
|
||||||
|
// Events
|
||||||
|
event ValidatorJoined(address indexed validator, uint256 stake);
|
||||||
|
event ValidatorLeft(address indexed validator);
|
||||||
|
event ValidatorSlashed(address indexed validator, uint256 amount, string reason);
|
||||||
|
event ConsensusReached(uint256 indexed round, address indexed proposer);
|
||||||
|
event BlockProposed(uint256 indexed blockHeight, address indexed proposer);
|
||||||
|
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Join as validator with minimum stake
|
||||||
|
*/
|
||||||
|
function joinValidator() external payable nonReentrant {
|
||||||
|
require(msg.value >= MINIMUM_STAKE, "Insufficient stake");
|
||||||
|
require(!validators[msg.sender].isActive, "Already a validator");
|
||||||
|
|
||||||
|
validators[msg.sender] = Validator({
|
||||||
|
validatorAddress: msg.sender,
|
||||||
|
stake: msg.value,
|
||||||
|
votingPower: calculateVotingPower(msg.value),
|
||||||
|
isActive: true,
|
||||||
|
joinedAt: block.timestamp,
|
||||||
|
rewardsEarned: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
validatorList.push(msg.sender);
|
||||||
|
totalStaked += msg.value;
|
||||||
|
|
||||||
|
emit ValidatorJoined(msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Leave validator set and withdraw stake
|
||||||
|
*/
|
||||||
|
function leaveValidator() external nonReentrant {
|
||||||
|
require(validators[msg.sender].isActive, "Not an active validator");
|
||||||
|
|
||||||
|
Validator storage validator = validators[msg.sender];
|
||||||
|
uint256 stakeToReturn = validator.stake;
|
||||||
|
|
||||||
|
validator.isActive = false;
|
||||||
|
totalStaked -= stakeToReturn;
|
||||||
|
|
||||||
|
// Remove from validator list
|
||||||
|
for (uint i = 0; i < validatorList.length; i++) {
|
||||||
|
if (validatorList[i] == msg.sender) {
|
||||||
|
validatorList[i] = validatorList[validatorList.length - 1];
|
||||||
|
validatorList.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
payable(msg.sender).transfer(stakeToReturn);
|
||||||
|
emit ValidatorLeft(msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Propose new block (only active validators)
|
||||||
|
*/
|
||||||
|
function proposeBlock(uint256 blockHeight) external {
|
||||||
|
require(validators[msg.sender].isActive, "Not an active validator");
|
||||||
|
require(isValidProposer(msg.sender), "Not selected as proposer");
|
||||||
|
|
||||||
|
currentRound++;
|
||||||
|
consensusRounds[currentRound] = ConsensusRound({
|
||||||
|
roundNumber: currentRound,
|
||||||
|
proposer: msg.sender,
|
||||||
|
blockHeight: blockHeight,
|
||||||
|
timestamp: block.timestamp,
|
||||||
|
finalized: false
|
||||||
|
});
|
||||||
|
|
||||||
|
emit BlockProposed(blockHeight, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Finalize consensus round
|
||||||
|
*/
|
||||||
|
function finalizeRound(uint256 roundNumber) external onlyOwner {
|
||||||
|
require(consensusRounds[roundNumber].proposer != address(0), "Round does not exist");
|
||||||
|
require(!consensusRounds[roundNumber].finalized, "Round already finalized");
|
||||||
|
|
||||||
|
consensusRounds[roundNumber].finalized = true;
|
||||||
|
|
||||||
|
// Distribute rewards to proposer
|
||||||
|
address proposer = consensusRounds[roundNumber].proposer;
|
||||||
|
validators[proposer].rewardsEarned += calculateBlockReward();
|
||||||
|
|
||||||
|
emit ConsensusReached(roundNumber, proposer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Slash validator for malicious behavior
|
||||||
|
*/
|
||||||
|
function slashValidator(address validatorAddress, uint256 slashAmount, string memory reason) external onlyOwner {
|
||||||
|
require(validators[validatorAddress].isActive, "Validator not active");
|
||||||
|
require(slashAmount <= validators[validatorAddress].stake, "Slash amount too high");
|
||||||
|
|
||||||
|
validators[validatorAddress].stake -= slashAmount;
|
||||||
|
totalStaked -= slashAmount;
|
||||||
|
|
||||||
|
// If stake falls below minimum, remove validator
|
||||||
|
if (validators[validatorAddress].stake < MINIMUM_STAKE) {
|
||||||
|
validators[validatorAddress].isActive = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit ValidatorSlashed(validatorAddress, slashAmount, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Calculate voting power based on stake
|
||||||
|
*/
|
||||||
|
function calculateVotingPower(uint256 stake) public pure returns (uint256) {
|
||||||
|
return stake / (10**18); // 1 voting power per AERE
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Calculate block reward
|
||||||
|
*/
|
||||||
|
function calculateBlockReward() public view returns (uint256) {
|
||||||
|
return 16 * 10**18; // 16 AERE per block
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Check if address is valid proposer for current round
|
||||||
|
*/
|
||||||
|
function isValidProposer(address proposer) public view returns (bool) {
|
||||||
|
if (!validators[proposer].isActive) return false;
|
||||||
|
|
||||||
|
// Simple round-robin selection based on block number
|
||||||
|
uint256 proposerIndex = block.number % validatorList.length;
|
||||||
|
return validatorList[proposerIndex] == proposer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get validator info
|
||||||
|
*/
|
||||||
|
function getValidator(address validatorAddress) external view returns (Validator memory) {
|
||||||
|
return validators[validatorAddress];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get active validator count
|
||||||
|
*/
|
||||||
|
function getActiveValidatorCount() external view returns (uint256) {
|
||||||
|
uint256 count = 0;
|
||||||
|
for (uint i = 0; i < validatorList.length; i++) {
|
||||||
|
if (validators[validatorList[i]].isActive) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get consensus stats
|
||||||
|
*/
|
||||||
|
function getConsensusStats() external view returns (
|
||||||
|
uint256 _totalValidators,
|
||||||
|
uint256 _totalStaked,
|
||||||
|
uint256 _currentRound,
|
||||||
|
uint256 _blockTime
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
validatorList.length,
|
||||||
|
totalStaked,
|
||||||
|
currentRound,
|
||||||
|
BLOCK_TIME
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/// @title AereDaFraudProofVerifier
|
||||||
|
/// @notice On-chain verifier for the AERE Data Availability layer's
|
||||||
|
/// bad-encoding fraud proofs and availability samples. It recomputes,
|
||||||
|
/// entirely on-chain, the Namespaced-Merkle-Tree (NMT) commitment and
|
||||||
|
/// the 2D Reed-Solomon re-encoding used by the off-chain `aere-da`
|
||||||
|
/// Rust crate (aerenew/da), and CONVICTS a badly-encoded block while
|
||||||
|
/// REJECTING spurious challenges.
|
||||||
|
///
|
||||||
|
/// Commitment layout (Celestia-style, identical to the crate):
|
||||||
|
/// * each row and each column of the 2k x 2k extended data square is
|
||||||
|
/// committed with an NMT -> row_root / col_root;
|
||||||
|
/// * an outer NMT over row_roots ++ col_roots gives the data root.
|
||||||
|
///
|
||||||
|
/// A bad-encoding fraud proof reveals the k committed basis shares of a
|
||||||
|
/// row/column plus one committed "disputed" share. The verifier:
|
||||||
|
/// 1. checks the challenged line's root is committed under the data
|
||||||
|
/// root (outer NMT inclusion), and
|
||||||
|
/// 2. checks every revealed share is committed under that root (inner
|
||||||
|
/// NMT inclusion), and
|
||||||
|
/// 3. recomputes the RS value at the disputed position from the k
|
||||||
|
/// basis shares and CONVICTS iff it disagrees with the committed
|
||||||
|
/// disputed share (the RS-parity-break check).
|
||||||
|
/// All three must hold for a conviction; otherwise the challenge is
|
||||||
|
/// rejected.
|
||||||
|
///
|
||||||
|
/// Hash: this verifier uses the EVM `sha256` precompile (0x02) and so
|
||||||
|
/// commits to the crate's SHA-256 hasher. The crate also offers a
|
||||||
|
/// FIPS-202 SHAKE256 hasher matching AERE mainnet's live 0x0AE5
|
||||||
|
/// precompile; standard EVM exposes no SHAKE256 precompile, so the
|
||||||
|
/// SHA-256 variant is the on-chain path here. Both are hash-based and
|
||||||
|
/// carry no pairing / discrete-log assumption.
|
||||||
|
///
|
||||||
|
/// Scope: verification logic only. No block production, no economic
|
||||||
|
/// slashing, no deployment wired here. This is the settlement-side
|
||||||
|
/// adjudicator a DA dispute would call.
|
||||||
|
contract AereDaFraudProofVerifier {
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Types (mirror the crate's serialization; see aerenew/da/src/nmt.rs,
|
||||||
|
// rs2d.rs, das.rs).
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// An NMT node: the namespace range it spans and its 32-byte hash.
|
||||||
|
struct Node {
|
||||||
|
bytes8 min;
|
||||||
|
bytes8 max;
|
||||||
|
bytes32 hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single-leaf NMT inclusion proof: siblings from leaf level upward.
|
||||||
|
struct InclusionProof {
|
||||||
|
uint256 index;
|
||||||
|
Node[] siblings;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A revealed share at a line position, with its inclusion proof.
|
||||||
|
struct ShareProof {
|
||||||
|
uint256 pos;
|
||||||
|
bytes8 ns;
|
||||||
|
bytes data;
|
||||||
|
InclusionProof proof;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bad-encoding fraud proof for one row (axis 0) or column (axis 1).
|
||||||
|
struct BadEncoding {
|
||||||
|
uint8 axis; // 0 = row ('r'), 1 = column ('c')
|
||||||
|
uint256 index;
|
||||||
|
Node root;
|
||||||
|
InclusionProof outerProof;
|
||||||
|
ShareProof[] basis; // k basis shares
|
||||||
|
ShareProof disputed; // the committed share that breaks RS parity
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A verifiable availability sample (light-node path).
|
||||||
|
struct Sample {
|
||||||
|
uint256 row;
|
||||||
|
uint256 col;
|
||||||
|
bytes8 ns;
|
||||||
|
bytes data;
|
||||||
|
InclusionProof rowProof;
|
||||||
|
Node rowRoot;
|
||||||
|
InclusionProof outerProof;
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes1 private constant LEAF_PREFIX = 0x00;
|
||||||
|
bytes1 private constant NODE_PREFIX = 0x01;
|
||||||
|
|
||||||
|
/// @dev GF(2^8) exp/log tables over the AES field x^8+x^4+x^3+x^2+1 (0x11b),
|
||||||
|
/// generator 0x03. Built once in the constructor; identical to the
|
||||||
|
/// crate's `Gf256::new`. `expTable` is length 512 so multiply needs no
|
||||||
|
/// modulo.
|
||||||
|
bytes private expTable;
|
||||||
|
bytes private logTable;
|
||||||
|
|
||||||
|
event BadBlockConvicted(bytes32 indexed dataRootHash, uint8 axis, uint256 index, uint256 disputedPos);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
bytes memory e = new bytes(512);
|
||||||
|
bytes memory l = new bytes(256);
|
||||||
|
uint16 x = 1;
|
||||||
|
for (uint256 i = 0; i < 255; i++) {
|
||||||
|
e[i] = bytes1(uint8(x));
|
||||||
|
l[uint256(x)] = bytes1(uint8(i));
|
||||||
|
// multiply by generator 0x03 == x + 1: x*3 = (x<<1) ^ x
|
||||||
|
x ^= x << 1;
|
||||||
|
if (x & 0x100 != 0) {
|
||||||
|
x ^= 0x11b;
|
||||||
|
}
|
||||||
|
x &= 0xff;
|
||||||
|
}
|
||||||
|
for (uint256 i = 255; i < 512; i++) {
|
||||||
|
e[i] = e[i - 255];
|
||||||
|
}
|
||||||
|
expTable = e;
|
||||||
|
logTable = l;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// NMT recomputation (SHA-256), byte-for-byte matching aerenew/da/src/nmt.rs.
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
function _leaf(bytes8 ns, bytes memory data) internal pure returns (Node memory) {
|
||||||
|
bytes32 h = sha256(abi.encodePacked(LEAF_PREFIX, ns, data));
|
||||||
|
return Node({min: ns, max: ns, hash: h});
|
||||||
|
}
|
||||||
|
|
||||||
|
function _inner(Node memory a, Node memory b) internal pure returns (Node memory) {
|
||||||
|
bytes32 h = sha256(
|
||||||
|
abi.encodePacked(NODE_PREFIX, a.min, a.max, a.hash, b.min, b.max, b.hash)
|
||||||
|
);
|
||||||
|
return Node({min: a.min, max: b.max, hash: h});
|
||||||
|
}
|
||||||
|
|
||||||
|
function _eq(Node memory a, Node memory b) internal pure returns (bool) {
|
||||||
|
return a.min == b.min && a.max == b.max && a.hash == b.hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev outer_ns(i): 8-byte big-endian encoding of i (matches das.rs).
|
||||||
|
function _outerNs(uint256 i) internal pure returns (bytes8) {
|
||||||
|
return bytes8(uint64(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev node_bytes(node) = min || max || hash (48 bytes), the outer-tree
|
||||||
|
/// leaf payload for a row/column root.
|
||||||
|
function _nodeBytes(Node memory node) internal pure returns (bytes memory) {
|
||||||
|
return abi.encodePacked(node.min, node.max, node.hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Verify a single-leaf NMT inclusion proof against `root`.
|
||||||
|
function _verifyInclusion(
|
||||||
|
Node memory root,
|
||||||
|
InclusionProof memory proof,
|
||||||
|
bytes8 ns,
|
||||||
|
bytes memory data
|
||||||
|
) internal pure returns (bool) {
|
||||||
|
Node memory node = _leaf(ns, data);
|
||||||
|
uint256 idx = proof.index;
|
||||||
|
uint256 len = proof.siblings.length;
|
||||||
|
for (uint256 i = 0; i < len; i++) {
|
||||||
|
if (idx & 1 == 0) {
|
||||||
|
node = _inner(node, proof.siblings[i]);
|
||||||
|
} else {
|
||||||
|
node = _inner(proof.siblings[i], node);
|
||||||
|
}
|
||||||
|
idx >>= 1;
|
||||||
|
}
|
||||||
|
return _eq(node, root);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// GF(256) Reed-Solomon (matches aerenew/da/src/gf256.rs).
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
function _mul(uint8 a, uint8 b) internal view returns (uint8) {
|
||||||
|
if (a == 0 || b == 0) return 0;
|
||||||
|
uint256 idx = uint256(uint8(logTable[a])) + uint256(uint8(logTable[b]));
|
||||||
|
return uint8(expTable[idx]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _div(uint8 a, uint8 b) internal view returns (uint8) {
|
||||||
|
// Caller guarantees b != 0 (interpolation nodes are distinct).
|
||||||
|
if (a == 0) return 0;
|
||||||
|
uint256 idx = (uint256(uint8(logTable[a])) + 255 - uint256(uint8(logTable[b]))) % 255;
|
||||||
|
return uint8(expTable[idx]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Evaluate at `x` the unique degree<m polynomial through (xs[i],ys[i]),
|
||||||
|
/// via the Lagrange form. Identical to `Gf256::interpolate_eval`.
|
||||||
|
function _interp(uint8[] memory xs, uint8[] memory ys, uint8 x) internal view returns (uint8) {
|
||||||
|
uint8 acc = 0;
|
||||||
|
uint256 m = xs.length;
|
||||||
|
for (uint256 i = 0; i < m; i++) {
|
||||||
|
if (x == xs[i]) {
|
||||||
|
return ys[i];
|
||||||
|
}
|
||||||
|
uint8 num = 1;
|
||||||
|
uint8 den = 1;
|
||||||
|
for (uint256 j = 0; j < m; j++) {
|
||||||
|
if (i == j) continue;
|
||||||
|
num = _mul(num, x ^ xs[j]);
|
||||||
|
den = _mul(den, xs[i] ^ xs[j]);
|
||||||
|
}
|
||||||
|
acc ^= _mul(ys[i], _div(num, den));
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Public verification API.
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// @notice Verify a bad-encoding fraud proof. Returns true iff it is a
|
||||||
|
/// VALID proof that the committed square is badly encoded: the RS
|
||||||
|
/// re-encoding of the k committed basis shares disagrees with the
|
||||||
|
/// committed disputed share, and every revealed share carries a
|
||||||
|
/// valid inclusion proof against the committed line root, which is
|
||||||
|
/// itself committed under `dataRoot`.
|
||||||
|
/// @dev View (reads the GF tables). Pure with respect to persistent state.
|
||||||
|
function verifyBadEncoding(
|
||||||
|
Node calldata dataRoot,
|
||||||
|
uint256 k,
|
||||||
|
uint256 n,
|
||||||
|
BadEncoding calldata p
|
||||||
|
) public view returns (bool) {
|
||||||
|
if (p.basis.length != k) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// The challenged line root must be committed under the data root at the
|
||||||
|
// right outer index: row r sits at index r, column c at index n + c.
|
||||||
|
uint256 outerIdx = p.axis == 0 ? p.index : n + p.index;
|
||||||
|
if (p.outerProof.index != outerIdx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_verifyInclusion(_copyNode(dataRoot), _copyProof(p.outerProof), _outerNs(outerIdx), _nodeBytes(_copyNode(p.root)))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Node memory rootMem = _copyNode(p.root);
|
||||||
|
|
||||||
|
// Every basis share is committed under the line root at its position.
|
||||||
|
for (uint256 i = 0; i < k; i++) {
|
||||||
|
ShareProof calldata b = p.basis[i];
|
||||||
|
if (b.proof.index != b.pos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_verifyInclusion(rootMem, _copyProof(b.proof), b.ns, b.data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The disputed share is committed under the line root at its position.
|
||||||
|
ShareProof calldata d = p.disputed;
|
||||||
|
if (d.proof.index != d.pos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_verifyInclusion(rootMem, _copyProof(d.proof), d.ns, d.data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recompute the RS value at the disputed position from the k basis
|
||||||
|
// shares, symbol-wise over each byte offset. CONVICT iff any byte of the
|
||||||
|
// committed disputed share disagrees with the re-encoding.
|
||||||
|
uint256 sl = d.data.length;
|
||||||
|
uint8[] memory xs = new uint8[](k);
|
||||||
|
for (uint256 i = 0; i < k; i++) {
|
||||||
|
xs[i] = uint8(p.basis[i].pos);
|
||||||
|
}
|
||||||
|
uint8 xj = uint8(d.pos);
|
||||||
|
for (uint256 bpos = 0; bpos < sl; bpos++) {
|
||||||
|
uint8[] memory ys = new uint8[](k);
|
||||||
|
for (uint256 i = 0; i < k; i++) {
|
||||||
|
ys[i] = uint8(p.basis[i].data[bpos]);
|
||||||
|
}
|
||||||
|
uint8 rec = _interp(xs, ys, xj);
|
||||||
|
if (rec != uint8(d.data[bpos])) {
|
||||||
|
return true; // RS parity break -> badly encoded -> convict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false; // re-encoding matches -> spurious challenge -> reject
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Same as {verifyBadEncoding} but state-changing: emits
|
||||||
|
/// {BadBlockConvicted} on a genuine bad-encoding proof and reverts
|
||||||
|
/// on a spurious challenge. This is the entry point a DA slashing
|
||||||
|
/// module would call.
|
||||||
|
function challenge(
|
||||||
|
Node calldata dataRoot,
|
||||||
|
uint256 k,
|
||||||
|
uint256 n,
|
||||||
|
BadEncoding calldata p
|
||||||
|
) external returns (bool) {
|
||||||
|
require(verifyBadEncoding(dataRoot, k, n, p), "AereDA: not a valid bad-encoding fraud proof");
|
||||||
|
emit BadBlockConvicted(dataRoot.hash, p.axis, p.index, p.disputed.pos);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Verify a single availability sample against the data root: the
|
||||||
|
/// cell is committed under its row root, and the row root is
|
||||||
|
/// committed under the data root. This is the NMT-inclusion leg a
|
||||||
|
/// sampling light node checks.
|
||||||
|
function verifySample(
|
||||||
|
Node calldata dataRoot,
|
||||||
|
uint256 n,
|
||||||
|
Sample calldata s
|
||||||
|
) external pure returns (bool) {
|
||||||
|
Node memory rowRoot = _copyNode(s.rowRoot);
|
||||||
|
if (!_verifyInclusion(rowRoot, _copyProof(s.rowProof), s.ns, s.data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (s.rowProof.index != s.col) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (s.outerProof.index != s.row) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!_verifyInclusion(_copyNode(dataRoot), _copyProof(s.outerProof), _outerNs(s.row), _nodeBytes(rowRoot))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return s.row < n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Small calldata -> memory copy helpers (viaIR keeps these cheap).
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
function _copyNode(Node calldata nd) internal pure returns (Node memory) {
|
||||||
|
return Node({min: nd.min, max: nd.max, hash: nd.hash});
|
||||||
|
}
|
||||||
|
|
||||||
|
function _copyProof(InclusionProof calldata pr) internal pure returns (InclusionProof memory out) {
|
||||||
|
out.index = pr.index;
|
||||||
|
out.siblings = new Node[](pr.siblings.length);
|
||||||
|
for (uint256 i = 0; i < pr.siblings.length; i++) {
|
||||||
|
out.siblings[i] = _copyNode(pr.siblings[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereFaucet
|
||||||
|
* @notice Distributes small amounts of AERE to new users for gas.
|
||||||
|
* Cooldown per address; configurable drip and cooldown by owner.
|
||||||
|
* Funded by the foundation (or anyone) by sending AERE directly.
|
||||||
|
*/
|
||||||
|
contract AereFaucet is Ownable, ReentrancyGuard {
|
||||||
|
uint256 public dripAmount = 0.05 ether; // 0.05 AERE
|
||||||
|
uint64 public cooldown = 1 days;
|
||||||
|
mapping(address => uint64) public lastClaim;
|
||||||
|
|
||||||
|
event Dripped(address indexed to, uint256 amount);
|
||||||
|
event Funded(address indexed from, uint256 amount);
|
||||||
|
event ConfigUpdated(uint256 dripAmount, uint64 cooldown);
|
||||||
|
|
||||||
|
receive() external payable { emit Funded(msg.sender, msg.value); }
|
||||||
|
|
||||||
|
function claim() external nonReentrant {
|
||||||
|
require(block.timestamp - lastClaim[msg.sender] >= cooldown, "cooldown");
|
||||||
|
require(address(this).balance >= dripAmount, "dry");
|
||||||
|
lastClaim[msg.sender] = uint64(block.timestamp);
|
||||||
|
(bool ok, ) = msg.sender.call{value: dripAmount}("");
|
||||||
|
require(ok, "transfer");
|
||||||
|
emit Dripped(msg.sender, dripAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setConfig(uint256 _drip, uint64 _cooldown) external onlyOwner {
|
||||||
|
require(_drip > 0 && _cooldown >= 1 hours, "params");
|
||||||
|
dripAmount = _drip;
|
||||||
|
cooldown = _cooldown;
|
||||||
|
emit ConfigUpdated(_drip, _cooldown);
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextClaimAt(address user) external view returns (uint64) {
|
||||||
|
uint64 last = lastClaim[user];
|
||||||
|
if (last == 0) return uint64(block.timestamp);
|
||||||
|
return last + cooldown;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereFeeBurnVault
|
||||||
|
* @notice Permanent, on-chain burn destination for protocol fees.
|
||||||
|
*
|
||||||
|
* Whitepaper §3.3 promises that "up to 37.5% of all transaction fees are
|
||||||
|
* permanently obliterated." This contract is the burn endpoint that makes
|
||||||
|
* that claim measurable and publicly auditable.
|
||||||
|
*
|
||||||
|
* Design:
|
||||||
|
* - Stateless sink: anyone can send native AERE here via `burn()`, or any
|
||||||
|
* ERC-20 via `burnToken()`. The contract has NO withdraw function and
|
||||||
|
* NO admin escape hatch — funds that enter are permanently removed
|
||||||
|
* from circulation.
|
||||||
|
* - Counters: tracks `totalBurnedAERE` and per-token `totalBurnedToken[token]`
|
||||||
|
* so the chain's deflation can be queried in a single read.
|
||||||
|
* - Sources: protocol contracts that earn fees (AereSwapRouter, the NFT
|
||||||
|
* marketplace, future card-fee router, etc.) can route a configurable
|
||||||
|
* share to this address — but the vault doesn't care WHO sends; any
|
||||||
|
* value arriving here is burned.
|
||||||
|
*
|
||||||
|
* This contract holds no privilege over any other system. Ownable is not
|
||||||
|
* needed because there are no admin operations.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address account) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereFeeBurnVault {
|
||||||
|
/// Total native AERE that has flowed into this contract.
|
||||||
|
/// Equal to address(this).balance EXCEPT after the eventual
|
||||||
|
/// "send to zero-address" sweep — see note below.
|
||||||
|
uint256 public totalBurnedAERE;
|
||||||
|
|
||||||
|
/// Cumulative native AERE actually forwarded to address(0).
|
||||||
|
uint256 public totalSentToZero;
|
||||||
|
|
||||||
|
/// Per-ERC20 lifetime burn counter.
|
||||||
|
mapping(address => uint256) public totalBurnedToken;
|
||||||
|
|
||||||
|
event AereBurned(address indexed from, uint256 amount, uint256 newTotal);
|
||||||
|
event TokenBurned(address indexed token, address indexed from, uint256 amount, uint256 newTotal);
|
||||||
|
event AereSentToZero(uint256 amount, uint256 newTotalSentToZero);
|
||||||
|
|
||||||
|
/// Plain ETH transfer = burn.
|
||||||
|
receive() external payable {
|
||||||
|
totalBurnedAERE += msg.value;
|
||||||
|
emit AereBurned(msg.sender, msg.value, totalBurnedAERE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicit native-AERE burn (same as `receive`, but lets callers attach a tag in the event log).
|
||||||
|
function burn() external payable {
|
||||||
|
totalBurnedAERE += msg.value;
|
||||||
|
emit AereBurned(msg.sender, msg.value, totalBurnedAERE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Burn an ERC-20 by pulling it from `msg.sender` via prior approval.
|
||||||
|
/// Tokens are accepted but never sent anywhere; they stay on this contract
|
||||||
|
/// forever. Counters reflect cumulative arrivals.
|
||||||
|
function burnToken(address token, uint256 amount) external {
|
||||||
|
require(token != address(0), "BurnVault: zero token");
|
||||||
|
require(amount > 0, "BurnVault: zero amount");
|
||||||
|
require(IERC20(token).transferFrom(msg.sender, address(this), amount), "BurnVault: transferFrom failed");
|
||||||
|
totalBurnedToken[token] += amount;
|
||||||
|
emit TokenBurned(token, msg.sender, amount, totalBurnedToken[token]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Optional: forward accumulated native AERE to address(0).
|
||||||
|
/// QBFT Besu permits sending to address(0); the AERE is then unreachable.
|
||||||
|
/// Anyone can call this; it has no parameters and no admin gate. This is
|
||||||
|
/// the "obliteration" step — until called, AERE sits on this contract.
|
||||||
|
function sweepToZero() external {
|
||||||
|
uint256 bal = address(this).balance;
|
||||||
|
require(bal > 0, "BurnVault: nothing to sweep");
|
||||||
|
totalSentToZero += bal;
|
||||||
|
(bool ok, ) = address(0).call{ value: bal }("");
|
||||||
|
require(ok, "BurnVault: zero-send failed");
|
||||||
|
emit AereSentToZero(bal, totalSentToZero);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience read.
|
||||||
|
function currentAEREBalance() external view returns (uint256) {
|
||||||
|
return address(this).balance;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereFeeMonetization
|
||||||
|
* @notice Pay developers (and Foundation treasury) automatically when their contracts
|
||||||
|
* get used. Modelled on Mode Network's Sequencer Fee Sharing pattern:
|
||||||
|
*
|
||||||
|
* - Developer calls register(contractAddr, payoutAddr) and receives an
|
||||||
|
* ERC-721 NFT representing the right to collect fees from contractAddr.
|
||||||
|
* - An off-chain distributor (running on aere-infra) parses recent blocks,
|
||||||
|
* attributes gas per top-level contract, and calls distribute() with
|
||||||
|
* per-tokenId amounts.
|
||||||
|
* - NFT owner calls claim(tokenId) to withdraw accumulated AERE.
|
||||||
|
*
|
||||||
|
* The NFT is transferable, so fee streams become sellable / collateralisable.
|
||||||
|
*
|
||||||
|
* Plus: a fixed `treasuryBps` slice that always flows to AERE Foundation
|
||||||
|
* (separate from per-contract dev-share). Default 500 = 5%.
|
||||||
|
*
|
||||||
|
* Fee distribution per gas fee paid (set by Foundation governance):
|
||||||
|
* burnBps (Tier 1.8): 3750 = 37.5% (permanent burn)
|
||||||
|
* treasuryBps (this tier): 500 = 5% (always to Foundation)
|
||||||
|
* devShareBps (this tier): 2000 = 20% (to registered NFT owner, else to validator)
|
||||||
|
* validatorBps (residual): 3750 = 37.5% (to block validator)
|
||||||
|
*
|
||||||
|
* Foundation registers its own foundational contracts (AereSwapRouter,
|
||||||
|
* AereSettlement, AereMessenger, AereNFTMarketplace, etc.) so their dev-share
|
||||||
|
* flows back to Foundation. External devs register their own; their NFT owner
|
||||||
|
* collects that fee stream.
|
||||||
|
*/
|
||||||
|
contract AereFeeMonetization is ERC721, Ownable, ReentrancyGuard {
|
||||||
|
/// Treasury address. All `treasuryBps` revenue flows here.
|
||||||
|
address payable public treasury;
|
||||||
|
|
||||||
|
/// Dev-share rate in basis points (10000 = 100%). Hard cap at 3000 (30%).
|
||||||
|
uint256 public devShareBps = 2000;
|
||||||
|
/// Treasury slice in basis points. Hard cap at 1500 (15%).
|
||||||
|
uint256 public treasuryBps = 500;
|
||||||
|
uint256 public constant BPS = 10_000;
|
||||||
|
|
||||||
|
/// Authorised distributors (Foundation runs these — same trust model as Tier 1.8).
|
||||||
|
mapping(address => bool) public isDistributor;
|
||||||
|
|
||||||
|
/// Auto-incrementing tokenId.
|
||||||
|
uint256 public nextTokenId = 1;
|
||||||
|
|
||||||
|
/// tokenId → contract that earns this share.
|
||||||
|
mapping(uint256 => address) public earningContract;
|
||||||
|
/// contractAddr → tokenId (0 if not registered).
|
||||||
|
mapping(address => uint256) public tokenIdOf;
|
||||||
|
/// tokenId → unclaimed AERE balance.
|
||||||
|
mapping(uint256 => uint256) public pendingRewards;
|
||||||
|
|
||||||
|
/// Lifetime cumulative paid to each NFT and to treasury.
|
||||||
|
mapping(uint256 => uint256) public totalPaidToToken;
|
||||||
|
uint256 public totalPaidToTreasury;
|
||||||
|
|
||||||
|
event Registered(address indexed contractAddr, uint256 indexed tokenId, address indexed payout);
|
||||||
|
event Distributed(uint256 indexed tokenId, uint256 amount, uint256 newPending);
|
||||||
|
event TreasuryFunded(uint256 amount, uint256 newTotal);
|
||||||
|
event Claimed(uint256 indexed tokenId, address indexed to, uint256 amount);
|
||||||
|
event RateChanged(string what, uint256 oldValue, uint256 newValue);
|
||||||
|
event DistributorChanged(address indexed distributor, bool authorised);
|
||||||
|
event TreasuryChanged(address indexed previous, address indexed next);
|
||||||
|
|
||||||
|
modifier onlyDistributor() {
|
||||||
|
require(isDistributor[msg.sender], "FeeMon: not a distributor");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(address payable _treasury) ERC721("AERE Fee Monetization", "AERE-FM") {
|
||||||
|
require(_treasury != address(0), "FeeMon: zero treasury");
|
||||||
|
treasury = _treasury;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setTreasury(address payable _treasury) external onlyOwner {
|
||||||
|
require(_treasury != address(0), "FeeMon: zero treasury");
|
||||||
|
emit TreasuryChanged(treasury, _treasury);
|
||||||
|
treasury = _treasury;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDevShareBps(uint256 _bps) external onlyOwner {
|
||||||
|
require(_bps <= 3000, "FeeMon: devShare too high");
|
||||||
|
emit RateChanged("devShareBps", devShareBps, _bps);
|
||||||
|
devShareBps = _bps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTreasuryBps(uint256 _bps) external onlyOwner {
|
||||||
|
require(_bps <= 1500, "FeeMon: treasuryBps too high");
|
||||||
|
emit RateChanged("treasuryBps", treasuryBps, _bps);
|
||||||
|
treasuryBps = _bps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDistributor(address dist, bool ok) external onlyOwner {
|
||||||
|
isDistributor[dist] = ok;
|
||||||
|
emit DistributorChanged(dist, ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Registration ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Register a contract for fee-share. The caller becomes the initial
|
||||||
|
* NFT owner. payoutAddr is informational — the NFT owner at claim time
|
||||||
|
* is who receives the AERE.
|
||||||
|
*/
|
||||||
|
function register(address contractAddr, address payoutAddr) external returns (uint256 tokenId) {
|
||||||
|
require(contractAddr != address(0), "FeeMon: zero contract");
|
||||||
|
require(tokenIdOf[contractAddr] == 0, "FeeMon: already registered");
|
||||||
|
require(payoutAddr != address(0), "FeeMon: zero payout");
|
||||||
|
|
||||||
|
tokenId = nextTokenId++;
|
||||||
|
earningContract[tokenId] = contractAddr;
|
||||||
|
tokenIdOf[contractAddr] = tokenId;
|
||||||
|
|
||||||
|
_mint(payoutAddr, tokenId);
|
||||||
|
emit Registered(contractAddr, tokenId, payoutAddr);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience: Foundation registers in bulk.
|
||||||
|
function registerBatch(address[] calldata contractAddrs, address payoutAddr)
|
||||||
|
external onlyOwner returns (uint256[] memory tokenIds)
|
||||||
|
{
|
||||||
|
tokenIds = new uint256[](contractAddrs.length);
|
||||||
|
for (uint256 i = 0; i < contractAddrs.length; i++) {
|
||||||
|
require(tokenIdOf[contractAddrs[i]] == 0, "FeeMon: already registered");
|
||||||
|
uint256 tid = nextTokenId++;
|
||||||
|
earningContract[tid] = contractAddrs[i];
|
||||||
|
tokenIdOf[contractAddrs[i]] = tid;
|
||||||
|
_mint(payoutAddr, tid);
|
||||||
|
emit Registered(contractAddrs[i], tid, payoutAddr);
|
||||||
|
tokenIds[i] = tid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Distribution (called by Foundation distributor) ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Credit per-tokenId fee shares. The distributor sends `totalAmount`
|
||||||
|
* as msg.value. Sum of `amounts` plus the treasury slice = totalAmount.
|
||||||
|
*/
|
||||||
|
function distribute(
|
||||||
|
uint256[] calldata tokenIds,
|
||||||
|
uint256[] calldata amounts,
|
||||||
|
uint256 treasuryAmount
|
||||||
|
) external payable onlyDistributor nonReentrant {
|
||||||
|
require(tokenIds.length == amounts.length, "FeeMon: length mismatch");
|
||||||
|
uint256 sum = treasuryAmount;
|
||||||
|
for (uint256 i = 0; i < amounts.length; i++) {
|
||||||
|
sum += amounts[i];
|
||||||
|
}
|
||||||
|
require(sum == msg.value, "FeeMon: amount mismatch");
|
||||||
|
|
||||||
|
// Treasury slice
|
||||||
|
if (treasuryAmount > 0) {
|
||||||
|
(bool ok, ) = treasury.call{ value: treasuryAmount }("");
|
||||||
|
require(ok, "FeeMon: treasury transfer failed");
|
||||||
|
totalPaidToTreasury += treasuryAmount;
|
||||||
|
emit TreasuryFunded(treasuryAmount, totalPaidToTreasury);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-token shares (held in contract until claim)
|
||||||
|
for (uint256 i = 0; i < tokenIds.length; i++) {
|
||||||
|
require(earningContract[tokenIds[i]] != address(0), "FeeMon: bad tokenId");
|
||||||
|
pendingRewards[tokenIds[i]] += amounts[i];
|
||||||
|
totalPaidToToken[tokenIds[i]] += amounts[i];
|
||||||
|
emit Distributed(tokenIds[i], amounts[i], pendingRewards[tokenIds[i]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Claim ─────────────────────
|
||||||
|
|
||||||
|
function claim(uint256 tokenId) external nonReentrant returns (uint256 amount) {
|
||||||
|
require(ownerOf(tokenId) == msg.sender, "FeeMon: not NFT owner");
|
||||||
|
amount = pendingRewards[tokenId];
|
||||||
|
require(amount > 0, "FeeMon: nothing to claim");
|
||||||
|
pendingRewards[tokenId] = 0;
|
||||||
|
(bool ok, ) = payable(msg.sender).call{ value: amount }("");
|
||||||
|
require(ok, "FeeMon: claim transfer failed");
|
||||||
|
emit Claimed(tokenId, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// View: how much would the current NFT owner withdraw if they called claim() now?
|
||||||
|
function claimableFor(address holder) external view returns (uint256 total) {
|
||||||
|
// Walk via balanceOf — gas-heavy, intended for off-chain UI only.
|
||||||
|
uint256 bal = balanceOf(holder);
|
||||||
|
if (bal == 0) return 0;
|
||||||
|
// ERC-721 doesn't index tokens by owner natively in OZ basic. Caller should
|
||||||
|
// pass tokenIds explicitly via pendingRewards mapping for production reads.
|
||||||
|
// This helper is a UI-friendly shortcut for small wallets.
|
||||||
|
for (uint256 t = 1; t < nextTokenId; t++) {
|
||||||
|
if (_ownerOf(t) == holder) {
|
||||||
|
total += pendingRewards[t];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Stats ─────────────────────
|
||||||
|
|
||||||
|
function policy() external view returns (uint256 burnBps_, uint256 devShareBps_, uint256 treasuryBps_, uint256 validatorBps_) {
|
||||||
|
burnBps_ = 3750; // Tier 1.8 - documented here for clarity only; actual burn lives in AereCoinbaseSplitter
|
||||||
|
devShareBps_ = devShareBps;
|
||||||
|
treasuryBps_ = treasuryBps;
|
||||||
|
// Validator residual = BPS - burn - devShare(if registered) - treasury
|
||||||
|
validatorBps_ = BPS - 3750 - devShareBps - treasuryBps;
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
|
||||||
|
|
||||||
|
/// Minimal Ownable-style interface used to prove the caller controls a contract.
|
||||||
|
interface IOwnableProbe {
|
||||||
|
function owner() external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereFeeMonetizationV2
|
||||||
|
* @notice Bug-fix redeploy of AereFeeMonetization (V1 at
|
||||||
|
* 0x6b62DC6cC974F779354c953F41b64a7aB994dd98).
|
||||||
|
*
|
||||||
|
* Pay developers (and the Foundation treasury) automatically when their
|
||||||
|
* contracts get used. A developer registers a contract and receives an
|
||||||
|
* ERC-721 representing the right to collect that contract's dev-share of
|
||||||
|
* gas fees; a Foundation distributor credits per-tokenId amounts; the NFT
|
||||||
|
* owner claims accumulated AERE.
|
||||||
|
*
|
||||||
|
* ────────────────────────── WHY V2 (finding #1, HIGH) ──────────────────────
|
||||||
|
* V1.register(contractAddr, payout) performed NO check that msg.sender
|
||||||
|
* controls contractAddr. Anyone could "squat" a victim contract's fee stream
|
||||||
|
* by registering the victim's address and minting the NFT to themselves; the
|
||||||
|
* real developer could then NEVER register (permanent DoS, "already
|
||||||
|
* registered"), and the squatter collected every fee the distributor
|
||||||
|
* attributed to that contract. There was also no unregister / reclaim path.
|
||||||
|
*
|
||||||
|
* V2 fixes:
|
||||||
|
* (1) PERMISSIONLESS-but-AUTHENTICATED register: the caller must prove it
|
||||||
|
* controls contractAddr — either
|
||||||
|
* * msg.sender == contractAddr (the contract registers itself), OR
|
||||||
|
* * msg.sender == Ownable(contractAddr).owner() (try/catch; the
|
||||||
|
* on-chain owner registers it).
|
||||||
|
* A contract that has no owner() and is not self-registering cannot be
|
||||||
|
* registered by a third party. The permissionless-monetization intent is
|
||||||
|
* preserved: NO Foundation gatekeeping of who may register their own
|
||||||
|
* contract, it is not onlyOwner.
|
||||||
|
* (2) unregister(contractAddr): the current NFT owner (registrant) OR the
|
||||||
|
* FeeMonetization owner (Foundation, for corrections) can clear a
|
||||||
|
* mistaken/stale registration. Any pending rewards are paid to the NFT
|
||||||
|
* owner first (nothing is lost), the NFT is burned, and the contract can
|
||||||
|
* be registered again cleanly.
|
||||||
|
* (3) reassignPayout(contractAddr, newPayout): convenience wrapper that moves
|
||||||
|
* the fee-stream NFT to a new payout address (equivalent to an ERC-721
|
||||||
|
* transfer, exposed by contract address for UX).
|
||||||
|
*
|
||||||
|
* Fee-distribution, claim, treasury and policy logic are byte-for-byte
|
||||||
|
* identical to V1.
|
||||||
|
*/
|
||||||
|
contract AereFeeMonetizationV2 is ERC721, Ownable, ReentrancyGuard {
|
||||||
|
/// Treasury address. All `treasuryBps` revenue flows here.
|
||||||
|
address payable public treasury;
|
||||||
|
|
||||||
|
/// Dev-share rate in basis points (10000 = 100%). Hard cap at 3000 (30%).
|
||||||
|
uint256 public devShareBps = 2000;
|
||||||
|
/// Treasury slice in basis points. Hard cap at 1500 (15%).
|
||||||
|
uint256 public treasuryBps = 500;
|
||||||
|
uint256 public constant BPS = 10_000;
|
||||||
|
|
||||||
|
/// Authorised distributors (Foundation runs these — same trust model as Tier 1.8).
|
||||||
|
mapping(address => bool) public isDistributor;
|
||||||
|
|
||||||
|
/// Auto-incrementing tokenId.
|
||||||
|
uint256 public nextTokenId = 1;
|
||||||
|
|
||||||
|
/// tokenId → contract that earns this share.
|
||||||
|
mapping(uint256 => address) public earningContract;
|
||||||
|
/// contractAddr → tokenId (0 if not registered).
|
||||||
|
mapping(address => uint256) public tokenIdOf;
|
||||||
|
/// tokenId → unclaimed AERE balance.
|
||||||
|
mapping(uint256 => uint256) public pendingRewards;
|
||||||
|
|
||||||
|
/// Lifetime cumulative paid to each NFT and to treasury.
|
||||||
|
mapping(uint256 => uint256) public totalPaidToToken;
|
||||||
|
uint256 public totalPaidToTreasury;
|
||||||
|
|
||||||
|
event Registered(address indexed contractAddr, uint256 indexed tokenId, address indexed payout);
|
||||||
|
event Unregistered(address indexed contractAddr, uint256 indexed tokenId, address indexed to, uint256 pendingPaid);
|
||||||
|
event PayoutReassigned(address indexed contractAddr, uint256 indexed tokenId, address indexed newPayout);
|
||||||
|
event Distributed(uint256 indexed tokenId, uint256 amount, uint256 newPending);
|
||||||
|
event TreasuryFunded(uint256 amount, uint256 newTotal);
|
||||||
|
event Claimed(uint256 indexed tokenId, address indexed to, uint256 amount);
|
||||||
|
event RateChanged(string what, uint256 oldValue, uint256 newValue);
|
||||||
|
event DistributorChanged(address indexed distributor, bool authorised);
|
||||||
|
event TreasuryChanged(address indexed previous, address indexed next);
|
||||||
|
|
||||||
|
modifier onlyDistributor() {
|
||||||
|
require(isDistributor[msg.sender], "FeeMon: not a distributor");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(address payable _treasury) ERC721("AERE Fee Monetization", "AERE-FM") {
|
||||||
|
require(_treasury != address(0), "FeeMon: zero treasury");
|
||||||
|
treasury = _treasury;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setTreasury(address payable _treasury) external onlyOwner {
|
||||||
|
require(_treasury != address(0), "FeeMon: zero treasury");
|
||||||
|
emit TreasuryChanged(treasury, _treasury);
|
||||||
|
treasury = _treasury;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDevShareBps(uint256 _bps) external onlyOwner {
|
||||||
|
require(_bps <= 3000, "FeeMon: devShare too high");
|
||||||
|
emit RateChanged("devShareBps", devShareBps, _bps);
|
||||||
|
devShareBps = _bps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTreasuryBps(uint256 _bps) external onlyOwner {
|
||||||
|
require(_bps <= 1500, "FeeMon: treasuryBps too high");
|
||||||
|
emit RateChanged("treasuryBps", treasuryBps, _bps);
|
||||||
|
treasuryBps = _bps;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDistributor(address dist, bool ok) external onlyOwner {
|
||||||
|
isDistributor[dist] = ok;
|
||||||
|
emit DistributorChanged(dist, ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Registration ─────────────────────
|
||||||
|
|
||||||
|
/// @notice Returns true iff `who` provably controls `target`: either it IS
|
||||||
|
/// `target` (the contract self-registering) or it is `target`'s
|
||||||
|
/// on-chain Ownable owner. try/catch so a non-Ownable target simply
|
||||||
|
/// yields false rather than reverting.
|
||||||
|
function controlsContract(address who, address target) public view returns (bool) {
|
||||||
|
if (who == target) return true;
|
||||||
|
// No-code target (EOA): only self-registration is allowed. Guard the
|
||||||
|
// owner() probe so a call to a codeless address returns false gracefully
|
||||||
|
// instead of tripping Solidity's extcodesize check (a reasonless revert).
|
||||||
|
if (target.code.length == 0) return false;
|
||||||
|
try IOwnableProbe(target).owner() returns (address o) {
|
||||||
|
return (o != address(0) && o == who);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Register a contract for fee-share. Permissionless, but the caller
|
||||||
|
* MUST control contractAddr (self-registration or its Ownable owner).
|
||||||
|
* The NFT is minted to payoutAddr (the NFT owner at claim time is who
|
||||||
|
* receives the AERE). This closes the V1 fee-stream squat + DoS.
|
||||||
|
*/
|
||||||
|
function register(address contractAddr, address payoutAddr) external returns (uint256 tokenId) {
|
||||||
|
require(contractAddr != address(0), "FeeMon: zero contract");
|
||||||
|
require(tokenIdOf[contractAddr] == 0, "FeeMon: already registered");
|
||||||
|
require(payoutAddr != address(0), "FeeMon: zero payout");
|
||||||
|
require(controlsContract(msg.sender, contractAddr), "FeeMon: not controller");
|
||||||
|
|
||||||
|
tokenId = nextTokenId++;
|
||||||
|
earningContract[tokenId] = contractAddr;
|
||||||
|
tokenIdOf[contractAddr] = tokenId;
|
||||||
|
|
||||||
|
_mint(payoutAddr, tokenId);
|
||||||
|
emit Registered(contractAddr, tokenId, payoutAddr);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Clear a mistaken/stale registration. Callable by the current NFT
|
||||||
|
/// owner (registrant) or the FeeMonetization owner. Any pending
|
||||||
|
/// rewards are paid to the current NFT owner first (nothing lost),
|
||||||
|
/// the NFT is burned, and the contract can be registered again.
|
||||||
|
function unregister(address contractAddr) external nonReentrant {
|
||||||
|
uint256 tokenId = tokenIdOf[contractAddr];
|
||||||
|
require(tokenId != 0, "FeeMon: not registered");
|
||||||
|
address holder = ownerOf(tokenId); // reverts if already burned
|
||||||
|
require(msg.sender == holder || msg.sender == owner(), "FeeMon: not authorized");
|
||||||
|
|
||||||
|
uint256 amount = pendingRewards[tokenId];
|
||||||
|
pendingRewards[tokenId] = 0;
|
||||||
|
earningContract[tokenId] = address(0);
|
||||||
|
tokenIdOf[contractAddr] = 0;
|
||||||
|
_burn(tokenId);
|
||||||
|
|
||||||
|
if (amount > 0) {
|
||||||
|
(bool ok, ) = payable(holder).call{ value: amount }("");
|
||||||
|
require(ok, "FeeMon: payout failed");
|
||||||
|
}
|
||||||
|
emit Unregistered(contractAddr, tokenId, holder, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Move a fee-stream NFT to a new payout address. Convenience wrapper
|
||||||
|
/// over a plain ERC-721 transfer, addressed by the earning contract.
|
||||||
|
function reassignPayout(address contractAddr, address newPayout) external {
|
||||||
|
require(newPayout != address(0), "FeeMon: zero payout");
|
||||||
|
uint256 tokenId = tokenIdOf[contractAddr];
|
||||||
|
require(tokenId != 0, "FeeMon: not registered");
|
||||||
|
require(ownerOf(tokenId) == msg.sender, "FeeMon: not NFT owner");
|
||||||
|
_transfer(msg.sender, newPayout, tokenId);
|
||||||
|
emit PayoutReassigned(contractAddr, tokenId, newPayout);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience: Foundation registers its OWN protocol contracts in
|
||||||
|
/// bulk. This is an onlyOwner ADMIN bootstrap (the FeeMonetization
|
||||||
|
/// owner is the Foundation multisig) — it is NOT the permissionless
|
||||||
|
/// register() path and is NOT a squat vector: only the Foundation can
|
||||||
|
/// call it, and only for the contracts it operates.
|
||||||
|
function registerBatch(address[] calldata contractAddrs, address payoutAddr)
|
||||||
|
external onlyOwner returns (uint256[] memory tokenIds)
|
||||||
|
{
|
||||||
|
require(payoutAddr != address(0), "FeeMon: zero payout");
|
||||||
|
tokenIds = new uint256[](contractAddrs.length);
|
||||||
|
for (uint256 i = 0; i < contractAddrs.length; i++) {
|
||||||
|
require(contractAddrs[i] != address(0), "FeeMon: zero contract");
|
||||||
|
require(tokenIdOf[contractAddrs[i]] == 0, "FeeMon: already registered");
|
||||||
|
uint256 tid = nextTokenId++;
|
||||||
|
earningContract[tid] = contractAddrs[i];
|
||||||
|
tokenIdOf[contractAddrs[i]] = tid;
|
||||||
|
_mint(payoutAddr, tid);
|
||||||
|
emit Registered(contractAddrs[i], tid, payoutAddr);
|
||||||
|
tokenIds[i] = tid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Distribution (called by Foundation distributor) ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Credit per-tokenId fee shares. The distributor sends `totalAmount`
|
||||||
|
* as msg.value. Sum of `amounts` plus the treasury slice = totalAmount.
|
||||||
|
*/
|
||||||
|
function distribute(
|
||||||
|
uint256[] calldata tokenIds,
|
||||||
|
uint256[] calldata amounts,
|
||||||
|
uint256 treasuryAmount
|
||||||
|
) external payable onlyDistributor nonReentrant {
|
||||||
|
require(tokenIds.length == amounts.length, "FeeMon: length mismatch");
|
||||||
|
uint256 sum = treasuryAmount;
|
||||||
|
for (uint256 i = 0; i < amounts.length; i++) {
|
||||||
|
sum += amounts[i];
|
||||||
|
}
|
||||||
|
require(sum == msg.value, "FeeMon: amount mismatch");
|
||||||
|
|
||||||
|
// Treasury slice
|
||||||
|
if (treasuryAmount > 0) {
|
||||||
|
(bool ok, ) = treasury.call{ value: treasuryAmount }("");
|
||||||
|
require(ok, "FeeMon: treasury transfer failed");
|
||||||
|
totalPaidToTreasury += treasuryAmount;
|
||||||
|
emit TreasuryFunded(treasuryAmount, totalPaidToTreasury);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-token shares (held in contract until claim)
|
||||||
|
for (uint256 i = 0; i < tokenIds.length; i++) {
|
||||||
|
require(earningContract[tokenIds[i]] != address(0), "FeeMon: bad tokenId");
|
||||||
|
pendingRewards[tokenIds[i]] += amounts[i];
|
||||||
|
totalPaidToToken[tokenIds[i]] += amounts[i];
|
||||||
|
emit Distributed(tokenIds[i], amounts[i], pendingRewards[tokenIds[i]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Claim ─────────────────────
|
||||||
|
|
||||||
|
function claim(uint256 tokenId) external nonReentrant returns (uint256 amount) {
|
||||||
|
require(ownerOf(tokenId) == msg.sender, "FeeMon: not NFT owner");
|
||||||
|
amount = pendingRewards[tokenId];
|
||||||
|
require(amount > 0, "FeeMon: nothing to claim");
|
||||||
|
pendingRewards[tokenId] = 0;
|
||||||
|
(bool ok, ) = payable(msg.sender).call{ value: amount }("");
|
||||||
|
require(ok, "FeeMon: claim transfer failed");
|
||||||
|
emit Claimed(tokenId, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// View: how much would the current NFT owner withdraw if they called claim() now?
|
||||||
|
function claimableFor(address holder) external view returns (uint256 total) {
|
||||||
|
uint256 bal = balanceOf(holder);
|
||||||
|
if (bal == 0) return 0;
|
||||||
|
for (uint256 t = 1; t < nextTokenId; t++) {
|
||||||
|
if (_ownerOf(t) == holder) {
|
||||||
|
total += pendingRewards[t];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Stats ─────────────────────
|
||||||
|
|
||||||
|
function policy() external view returns (uint256 burnBps_, uint256 devShareBps_, uint256 treasuryBps_, uint256 validatorBps_) {
|
||||||
|
burnBps_ = 3750; // Tier 1.8 - documented here for clarity only; actual burn lives in AereCoinbaseSplitter
|
||||||
|
devShareBps_ = devShareBps;
|
||||||
|
treasuryBps_ = treasuryBps;
|
||||||
|
validatorBps_ = BPS - 3750 - devShareBps - treasuryBps;
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "./AereToken.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE Governance Contract
|
||||||
|
* @dev Manages decentralized governance and proposals
|
||||||
|
*/
|
||||||
|
contract AereGovernance is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
AereToken public aereToken;
|
||||||
|
|
||||||
|
enum ProposalStatus { Active, Passed, Failed, Executed, Cancelled }
|
||||||
|
enum VoteType { Yes, No, Abstain }
|
||||||
|
|
||||||
|
struct Proposal {
|
||||||
|
uint256 id;
|
||||||
|
string title;
|
||||||
|
string description;
|
||||||
|
address proposer;
|
||||||
|
uint256 startTime;
|
||||||
|
uint256 endTime;
|
||||||
|
uint256 yesVotes;
|
||||||
|
uint256 noVotes;
|
||||||
|
uint256 abstainVotes;
|
||||||
|
ProposalStatus status;
|
||||||
|
uint256 executionTime;
|
||||||
|
bytes executionData;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Vote {
|
||||||
|
VoteType voteType;
|
||||||
|
uint256 votingPower;
|
||||||
|
bool hasVoted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// State variables
|
||||||
|
mapping(uint256 => Proposal) public proposals;
|
||||||
|
mapping(uint256 => mapping(address => Vote)) public votes;
|
||||||
|
mapping(address => uint256) public votingPower;
|
||||||
|
|
||||||
|
uint256 public proposalCount = 0;
|
||||||
|
uint256 public constant VOTING_PERIOD = 7 days;
|
||||||
|
uint256 public constant EXECUTION_DELAY = 2 days;
|
||||||
|
uint256 public constant PROPOSAL_THRESHOLD = 100000 * 10**18; // 100K AERE
|
||||||
|
uint256 public constant QUORUM_PERCENTAGE = 20; // 20%
|
||||||
|
|
||||||
|
// Events
|
||||||
|
event ProposalCreated(uint256 indexed proposalId, address indexed proposer, string title);
|
||||||
|
event VoteCast(uint256 indexed proposalId, address indexed voter, VoteType voteType, uint256 votingPower);
|
||||||
|
event ProposalExecuted(uint256 indexed proposalId);
|
||||||
|
event ProposalCancelled(uint256 indexed proposalId);
|
||||||
|
|
||||||
|
constructor(address _aereToken) {
|
||||||
|
aereToken = AereToken(_aereToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Create new governance proposal
|
||||||
|
*/
|
||||||
|
function createProposal(
|
||||||
|
string memory title,
|
||||||
|
string memory description,
|
||||||
|
bytes memory executionData
|
||||||
|
) external returns (uint256) {
|
||||||
|
require(aereToken.balanceOf(msg.sender) >= PROPOSAL_THRESHOLD, "Insufficient tokens to propose");
|
||||||
|
|
||||||
|
proposalCount++;
|
||||||
|
uint256 proposalId = proposalCount;
|
||||||
|
|
||||||
|
proposals[proposalId] = Proposal({
|
||||||
|
id: proposalId,
|
||||||
|
title: title,
|
||||||
|
description: description,
|
||||||
|
proposer: msg.sender,
|
||||||
|
startTime: block.timestamp,
|
||||||
|
endTime: block.timestamp + VOTING_PERIOD,
|
||||||
|
yesVotes: 0,
|
||||||
|
noVotes: 0,
|
||||||
|
abstainVotes: 0,
|
||||||
|
status: ProposalStatus.Active,
|
||||||
|
executionTime: 0,
|
||||||
|
executionData: executionData
|
||||||
|
});
|
||||||
|
|
||||||
|
emit ProposalCreated(proposalId, msg.sender, title);
|
||||||
|
return proposalId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Cast vote on proposal
|
||||||
|
*/
|
||||||
|
function castVote(uint256 proposalId, VoteType voteType) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
require(block.timestamp <= proposal.endTime, "Voting period ended");
|
||||||
|
require(!votes[proposalId][msg.sender].hasVoted, "Already voted");
|
||||||
|
|
||||||
|
uint256 voterPower = aereToken.balanceOf(msg.sender);
|
||||||
|
require(voterPower > 0, "No voting power");
|
||||||
|
|
||||||
|
votes[proposalId][msg.sender] = Vote({
|
||||||
|
voteType: voteType,
|
||||||
|
votingPower: voterPower,
|
||||||
|
hasVoted: true
|
||||||
|
});
|
||||||
|
|
||||||
|
if (voteType == VoteType.Yes) {
|
||||||
|
proposal.yesVotes += voterPower;
|
||||||
|
} else if (voteType == VoteType.No) {
|
||||||
|
proposal.noVotes += voterPower;
|
||||||
|
} else {
|
||||||
|
proposal.abstainVotes += voterPower;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit VoteCast(proposalId, msg.sender, voteType, voterPower);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Finalize proposal after voting period
|
||||||
|
*/
|
||||||
|
function finalizeProposal(uint256 proposalId) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
require(block.timestamp > proposal.endTime, "Voting still active");
|
||||||
|
|
||||||
|
uint256 totalVotes = proposal.yesVotes + proposal.noVotes + proposal.abstainVotes;
|
||||||
|
uint256 quorumRequired = (aereToken.getCirculatingSupply() * QUORUM_PERCENTAGE) / 100;
|
||||||
|
|
||||||
|
if (totalVotes >= quorumRequired && proposal.yesVotes > proposal.noVotes) {
|
||||||
|
proposal.status = ProposalStatus.Passed;
|
||||||
|
proposal.executionTime = block.timestamp + EXECUTION_DELAY;
|
||||||
|
} else {
|
||||||
|
proposal.status = ProposalStatus.Failed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Execute passed proposal
|
||||||
|
*/
|
||||||
|
function executeProposal(uint256 proposalId) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Passed, "Proposal not passed");
|
||||||
|
require(block.timestamp >= proposal.executionTime, "Execution delay not met");
|
||||||
|
|
||||||
|
proposal.status = ProposalStatus.Executed;
|
||||||
|
|
||||||
|
// Execute proposal logic here
|
||||||
|
if (proposal.executionData.length > 0) {
|
||||||
|
(bool success,) = address(this).call(proposal.executionData);
|
||||||
|
require(success, "Execution failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
emit ProposalExecuted(proposalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Cancel proposal (only proposer or owner)
|
||||||
|
*/
|
||||||
|
function cancelProposal(uint256 proposalId) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(
|
||||||
|
msg.sender == proposal.proposer || msg.sender == owner(),
|
||||||
|
"Not authorized to cancel"
|
||||||
|
);
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
|
||||||
|
proposal.status = ProposalStatus.Cancelled;
|
||||||
|
emit ProposalCancelled(proposalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get proposal details
|
||||||
|
*/
|
||||||
|
function getProposal(uint256 proposalId) external view returns (Proposal memory) {
|
||||||
|
return proposals[proposalId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get vote details
|
||||||
|
*/
|
||||||
|
function getVote(uint256 proposalId, address voter) external view returns (Vote memory) {
|
||||||
|
return votes[proposalId][voter];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Check if proposal has quorum
|
||||||
|
*/
|
||||||
|
function hasQuorum(uint256 proposalId) external view returns (bool) {
|
||||||
|
Proposal memory proposal = proposals[proposalId];
|
||||||
|
uint256 totalVotes = proposal.yesVotes + proposal.noVotes + proposal.abstainVotes;
|
||||||
|
uint256 quorumRequired = (aereToken.getCirculatingSupply() * QUORUM_PERCENTAGE) / 100;
|
||||||
|
return totalVotes >= quorumRequired;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get governance statistics
|
||||||
|
*/
|
||||||
|
function getGovernanceStats() external view returns (
|
||||||
|
uint256 _totalProposals,
|
||||||
|
uint256 _activeProposals,
|
||||||
|
uint256 _totalVoters,
|
||||||
|
uint256 _quorumPercentage
|
||||||
|
) {
|
||||||
|
uint256 activeCount = 0;
|
||||||
|
for (uint256 i = 1; i <= proposalCount; i++) {
|
||||||
|
if (proposals[i].status == ProposalStatus.Active) {
|
||||||
|
activeCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
proposalCount,
|
||||||
|
activeCount,
|
||||||
|
aereToken.getCirculatingSupply() / (10**18), // Convert to readable number
|
||||||
|
QUORUM_PERCENTAGE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Minimal view interface into the already-deployed AereStaking contract.
|
||||||
|
* AereStaking exposes `validatorList`, `validatorCount`, `delegations` and
|
||||||
|
* `totalStaked` as public state — no change to AereStaking is required.
|
||||||
|
*/
|
||||||
|
interface IAereStaking {
|
||||||
|
function validatorCount() external view returns (uint256);
|
||||||
|
function validatorList(uint256 index) external view returns (address);
|
||||||
|
function delegations(address validator, address delegator)
|
||||||
|
external view returns (uint256 amount, uint256 stakedAt, uint256 lastClaimBlock);
|
||||||
|
function totalStaked() external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereGovernanceStaked
|
||||||
|
* @notice On-chain governance for AERE Network.
|
||||||
|
*
|
||||||
|
* Voting power = the total AERE a holder has STAKED via AereStaking, summed
|
||||||
|
* across every validator they delegate to. "Stake to vote": only committed
|
||||||
|
* holders govern, and the 7-day unbonding period makes vote-borrowing
|
||||||
|
* impractical. Quorum is measured against total AERE staked network-wide.
|
||||||
|
*
|
||||||
|
* Replaces the earlier AereGovernance, which read voting power from an ERC-20
|
||||||
|
* balance (only counted wrapped AERE) and depended on a getCirculatingSupply()
|
||||||
|
* method the wrapped token does not implement.
|
||||||
|
*/
|
||||||
|
contract AereGovernanceStaked is Ownable, ReentrancyGuard {
|
||||||
|
IAereStaking public immutable staking;
|
||||||
|
|
||||||
|
enum ProposalStatus { Active, Passed, Failed, Executed, Cancelled }
|
||||||
|
enum VoteType { Yes, No, Abstain }
|
||||||
|
|
||||||
|
struct Proposal {
|
||||||
|
uint256 id;
|
||||||
|
string title;
|
||||||
|
string description;
|
||||||
|
address proposer;
|
||||||
|
uint256 startTime;
|
||||||
|
uint256 endTime;
|
||||||
|
uint256 yesVotes;
|
||||||
|
uint256 noVotes;
|
||||||
|
uint256 abstainVotes;
|
||||||
|
ProposalStatus status;
|
||||||
|
uint256 executionTime;
|
||||||
|
bytes executionData;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Vote {
|
||||||
|
VoteType voteType;
|
||||||
|
uint256 votingPower;
|
||||||
|
bool hasVoted;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(uint256 => Proposal) public proposals;
|
||||||
|
mapping(uint256 => mapping(address => Vote)) public votes;
|
||||||
|
|
||||||
|
uint256 public proposalCount;
|
||||||
|
uint256 public constant VOTING_PERIOD = 7 days;
|
||||||
|
uint256 public constant EXECUTION_DELAY = 2 days;
|
||||||
|
uint256 public constant PROPOSAL_THRESHOLD = 100000 ether; // 100k staked AERE
|
||||||
|
uint256 public constant QUORUM_PERCENTAGE = 20; // 20% of total staked
|
||||||
|
|
||||||
|
event ProposalCreated(uint256 indexed proposalId, address indexed proposer, string title);
|
||||||
|
event VoteCast(uint256 indexed proposalId, address indexed voter, VoteType voteType, uint256 votingPower);
|
||||||
|
event ProposalFinalized(uint256 indexed proposalId, ProposalStatus status);
|
||||||
|
event ProposalExecuted(uint256 indexed proposalId);
|
||||||
|
event ProposalCancelled(uint256 indexed proposalId);
|
||||||
|
|
||||||
|
constructor(address _staking) {
|
||||||
|
require(_staking != address(0), "staking=0");
|
||||||
|
staking = IAereStaking(_staking);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Voting power of an account = total AERE it has delegated across
|
||||||
|
* all validators in AereStaking.
|
||||||
|
*/
|
||||||
|
function votingPowerOf(address account) public view returns (uint256 total) {
|
||||||
|
uint256 n = staking.validatorCount();
|
||||||
|
for (uint256 i = 0; i < n; i++) {
|
||||||
|
address v = staking.validatorList(i);
|
||||||
|
(uint256 amount, , ) = staking.delegations(v, account);
|
||||||
|
total += amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createProposal(
|
||||||
|
string memory title,
|
||||||
|
string memory description,
|
||||||
|
bytes memory executionData
|
||||||
|
) external returns (uint256) {
|
||||||
|
require(votingPowerOf(msg.sender) >= PROPOSAL_THRESHOLD, "Insufficient staked AERE to propose");
|
||||||
|
|
||||||
|
proposalCount++;
|
||||||
|
uint256 proposalId = proposalCount;
|
||||||
|
proposals[proposalId] = Proposal({
|
||||||
|
id: proposalId,
|
||||||
|
title: title,
|
||||||
|
description: description,
|
||||||
|
proposer: msg.sender,
|
||||||
|
startTime: block.timestamp,
|
||||||
|
endTime: block.timestamp + VOTING_PERIOD,
|
||||||
|
yesVotes: 0,
|
||||||
|
noVotes: 0,
|
||||||
|
abstainVotes: 0,
|
||||||
|
status: ProposalStatus.Active,
|
||||||
|
executionTime: 0,
|
||||||
|
executionData: executionData
|
||||||
|
});
|
||||||
|
|
||||||
|
emit ProposalCreated(proposalId, msg.sender, title);
|
||||||
|
return proposalId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function castVote(uint256 proposalId, VoteType voteType) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
require(block.timestamp <= proposal.endTime, "Voting period ended");
|
||||||
|
require(!votes[proposalId][msg.sender].hasVoted, "Already voted");
|
||||||
|
|
||||||
|
uint256 voterPower = votingPowerOf(msg.sender);
|
||||||
|
require(voterPower > 0, "No voting power - stake AERE first");
|
||||||
|
|
||||||
|
votes[proposalId][msg.sender] = Vote({
|
||||||
|
voteType: voteType,
|
||||||
|
votingPower: voterPower,
|
||||||
|
hasVoted: true
|
||||||
|
});
|
||||||
|
|
||||||
|
if (voteType == VoteType.Yes) {
|
||||||
|
proposal.yesVotes += voterPower;
|
||||||
|
} else if (voteType == VoteType.No) {
|
||||||
|
proposal.noVotes += voterPower;
|
||||||
|
} else {
|
||||||
|
proposal.abstainVotes += voterPower;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit VoteCast(proposalId, msg.sender, voteType, voterPower);
|
||||||
|
}
|
||||||
|
|
||||||
|
function finalizeProposal(uint256 proposalId) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
require(block.timestamp > proposal.endTime, "Voting still active");
|
||||||
|
|
||||||
|
uint256 totalVotes = proposal.yesVotes + proposal.noVotes + proposal.abstainVotes;
|
||||||
|
uint256 quorumRequired = (staking.totalStaked() * QUORUM_PERCENTAGE) / 100;
|
||||||
|
|
||||||
|
if (totalVotes >= quorumRequired && proposal.yesVotes > proposal.noVotes) {
|
||||||
|
proposal.status = ProposalStatus.Passed;
|
||||||
|
proposal.executionTime = block.timestamp + EXECUTION_DELAY;
|
||||||
|
} else {
|
||||||
|
proposal.status = ProposalStatus.Failed;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit ProposalFinalized(proposalId, proposal.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
function executeProposal(uint256 proposalId) external nonReentrant {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(proposal.status == ProposalStatus.Passed, "Proposal not passed");
|
||||||
|
require(block.timestamp >= proposal.executionTime, "Execution delay not met");
|
||||||
|
|
||||||
|
proposal.status = ProposalStatus.Executed;
|
||||||
|
|
||||||
|
if (proposal.executionData.length > 0) {
|
||||||
|
(bool success, ) = address(this).call(proposal.executionData);
|
||||||
|
require(success, "Execution failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
emit ProposalExecuted(proposalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelProposal(uint256 proposalId) external {
|
||||||
|
Proposal storage proposal = proposals[proposalId];
|
||||||
|
require(
|
||||||
|
msg.sender == proposal.proposer || msg.sender == owner(),
|
||||||
|
"Not authorized to cancel"
|
||||||
|
);
|
||||||
|
require(proposal.status == ProposalStatus.Active, "Proposal not active");
|
||||||
|
|
||||||
|
proposal.status = ProposalStatus.Cancelled;
|
||||||
|
emit ProposalCancelled(proposalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getProposal(uint256 proposalId) external view returns (Proposal memory) {
|
||||||
|
return proposals[proposalId];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getVote(uint256 proposalId, address voter) external view returns (Vote memory) {
|
||||||
|
return votes[proposalId][voter];
|
||||||
|
}
|
||||||
|
|
||||||
|
function quorumRequired() external view returns (uint256) {
|
||||||
|
return (staking.totalStaked() * QUORUM_PERCENTAGE) / 100;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereIdentity
|
||||||
|
* @notice Lightweight on-chain DID registry. Each address controls its own identity:
|
||||||
|
* off-chain signed credentials, profile metadata URI, and revocable claims
|
||||||
|
* issued by trusted attestors (KYC providers, employers, communities).
|
||||||
|
* @dev Compatible-in-spirit with W3C DID + ERC-1056. Profile metadata stored as a
|
||||||
|
* content-addressed URI (e.g. ipfs://...) so the chain holds only the pointer.
|
||||||
|
*/
|
||||||
|
contract AereIdentity {
|
||||||
|
// ── Profiles ────────────────────────────────────────────────
|
||||||
|
mapping(address => string) public profileURI;
|
||||||
|
mapping(address => uint64) public profileUpdatedAt;
|
||||||
|
|
||||||
|
event ProfileUpdated(address indexed identity, string uri, uint64 timestamp);
|
||||||
|
|
||||||
|
function setProfile(string calldata uri) external {
|
||||||
|
profileURI[msg.sender] = uri;
|
||||||
|
profileUpdatedAt[msg.sender] = uint64(block.timestamp);
|
||||||
|
emit ProfileUpdated(msg.sender, uri, uint64(block.timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Attestors ───────────────────────────────────────────────
|
||||||
|
mapping(address => bool) public isAttestor;
|
||||||
|
address public owner;
|
||||||
|
|
||||||
|
event AttestorAdded(address indexed attestor);
|
||||||
|
event AttestorRemoved(address indexed attestor);
|
||||||
|
|
||||||
|
constructor() { owner = msg.sender; isAttestor[msg.sender] = true; }
|
||||||
|
|
||||||
|
modifier onlyOwner() { require(msg.sender == owner, "owner"); _; }
|
||||||
|
|
||||||
|
function addAttestor(address a) external onlyOwner { isAttestor[a] = true; emit AttestorAdded(a); }
|
||||||
|
function removeAttestor(address a) external onlyOwner { isAttestor[a] = false; emit AttestorRemoved(a); }
|
||||||
|
function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; }
|
||||||
|
|
||||||
|
// ── Claims ──────────────────────────────────────────────────
|
||||||
|
/// @dev claimType examples: keccak256("KYC_TIER_1"), keccak256("EMAIL_VERIFIED"),
|
||||||
|
/// keccak256("DAO_MEMBER:ENS"), keccak256("AGE_OVER_18"), etc.
|
||||||
|
struct Claim {
|
||||||
|
address attestor;
|
||||||
|
uint64 issuedAt;
|
||||||
|
uint64 expiresAt; // 0 = never
|
||||||
|
bytes32 evidence; // optional hash of off-chain document
|
||||||
|
bool revoked;
|
||||||
|
}
|
||||||
|
|
||||||
|
// subject => claimType => attestor => Claim
|
||||||
|
mapping(address => mapping(bytes32 => mapping(address => Claim))) public claims;
|
||||||
|
|
||||||
|
event ClaimIssued(address indexed subject, bytes32 indexed claimType, address indexed attestor, uint64 expiresAt, bytes32 evidence);
|
||||||
|
event ClaimRevoked(address indexed subject, bytes32 indexed claimType, address indexed attestor);
|
||||||
|
|
||||||
|
function issueClaim(address subject, bytes32 claimType, uint64 expiresAt, bytes32 evidence) external {
|
||||||
|
require(isAttestor[msg.sender], "not attestor");
|
||||||
|
require(subject != address(0), "subject");
|
||||||
|
claims[subject][claimType][msg.sender] = Claim({
|
||||||
|
attestor: msg.sender,
|
||||||
|
issuedAt: uint64(block.timestamp),
|
||||||
|
expiresAt: expiresAt,
|
||||||
|
evidence: evidence,
|
||||||
|
revoked: false
|
||||||
|
});
|
||||||
|
emit ClaimIssued(subject, claimType, msg.sender, expiresAt, evidence);
|
||||||
|
}
|
||||||
|
|
||||||
|
function revokeClaim(address subject, bytes32 claimType) external {
|
||||||
|
Claim storage c = claims[subject][claimType][msg.sender];
|
||||||
|
require(c.attestor == msg.sender, "not issuer");
|
||||||
|
require(!c.revoked, "already");
|
||||||
|
c.revoked = true;
|
||||||
|
emit ClaimRevoked(subject, claimType, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Check if a subject has a non-expired, non-revoked claim of a given type
|
||||||
|
/// from a specific attestor.
|
||||||
|
function hasValidClaim(address subject, bytes32 claimType, address attestor) external view returns (bool) {
|
||||||
|
Claim memory c = claims[subject][claimType][attestor];
|
||||||
|
if (c.attestor == address(0) || c.revoked) return false;
|
||||||
|
if (c.expiresAt != 0 && block.timestamp > c.expiresAt) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereLockedStaking
|
||||||
|
* @notice Liquidity-lock staking with fixed terms (whitepaper §3.3).
|
||||||
|
*
|
||||||
|
* Users lock native AERE for a fixed term and earn fixed APY paid in AERE
|
||||||
|
* on maturity. Early exit forfeits all reward and returns principal only.
|
||||||
|
*
|
||||||
|
* Tiers (matched to stake-v2.html):
|
||||||
|
* 0 — 30 days · 10% APY
|
||||||
|
* 1 — 90 days · 15% APY
|
||||||
|
* 2 — 180 days · 22% APY
|
||||||
|
* 3 — 365 days · 30% APY
|
||||||
|
*
|
||||||
|
* Reward pool is seeded by the Foundation; the contract refuses to pay
|
||||||
|
* a maturity if its balance cannot cover principal + reward (so other
|
||||||
|
* stakers' principal can never be drained to pay rewards).
|
||||||
|
*/
|
||||||
|
contract AereLockedStaking is Ownable, ReentrancyGuard {
|
||||||
|
// tier => APY in basis points (10000 = 100%)
|
||||||
|
uint256[4] public APY_BPS = [1000, 1500, 2200, 3000];
|
||||||
|
// tier => lock duration in seconds
|
||||||
|
uint64[4] private DURATIONS = [30 days, 90 days, 180 days, 365 days];
|
||||||
|
|
||||||
|
uint256 public constant MIN_STAKE = 1 ether; // 1 AERE
|
||||||
|
uint256 public constant MAX_STAKE = 100_000 ether; // sanity cap per lock
|
||||||
|
|
||||||
|
struct Lock {
|
||||||
|
uint256 amount;
|
||||||
|
uint64 startedAt;
|
||||||
|
uint64 unlockAt;
|
||||||
|
uint8 tier;
|
||||||
|
bool withdrawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(address => Lock[]) private _locks;
|
||||||
|
|
||||||
|
// Total principal currently locked (excludes rewards owed). Used to
|
||||||
|
// determine how much of `address(this).balance` is the reward reserve.
|
||||||
|
uint256 public totalPrincipal;
|
||||||
|
|
||||||
|
event Staked(address indexed user, uint256 indexed lockId, uint256 amount, uint8 tier, uint64 unlockAt);
|
||||||
|
event Withdrawn(address indexed user, uint256 indexed lockId, uint256 principal, uint256 reward);
|
||||||
|
event EarlyExited(address indexed user, uint256 indexed lockId, uint256 principal);
|
||||||
|
event RewardReserveDeposited(address indexed from, uint256 amount);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Lock `msg.value` for the tier's term and earn its APY on maturity.
|
||||||
|
*/
|
||||||
|
function stake(uint8 tier) external payable nonReentrant returns (uint256 lockId) {
|
||||||
|
require(tier < 4, "AereLockedStaking: bad tier");
|
||||||
|
require(msg.value >= MIN_STAKE, "AereLockedStaking: below min");
|
||||||
|
require(msg.value <= MAX_STAKE, "AereLockedStaking: above max");
|
||||||
|
|
||||||
|
uint64 nowTs = uint64(block.timestamp);
|
||||||
|
uint64 unlockAt = nowTs + DURATIONS[tier];
|
||||||
|
|
||||||
|
lockId = _locks[msg.sender].length;
|
||||||
|
_locks[msg.sender].push(Lock({
|
||||||
|
amount: msg.value,
|
||||||
|
startedAt: nowTs,
|
||||||
|
unlockAt: unlockAt,
|
||||||
|
tier: tier,
|
||||||
|
withdrawn: false
|
||||||
|
}));
|
||||||
|
|
||||||
|
totalPrincipal += msg.value;
|
||||||
|
emit Staked(msg.sender, lockId, msg.value, tier, unlockAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Reward owed if this lock matures untouched. Returns 0 if the
|
||||||
|
* lock has already been withdrawn or early-exited.
|
||||||
|
* reward = principal * APY_BPS * duration / 365 days / 10000
|
||||||
|
*/
|
||||||
|
function rewardOf(address user, uint256 lockId) public view returns (uint256) {
|
||||||
|
if (lockId >= _locks[user].length) return 0;
|
||||||
|
Lock memory l = _locks[user][lockId];
|
||||||
|
if (l.withdrawn) return 0;
|
||||||
|
return (l.amount * APY_BPS[l.tier] * DURATIONS[l.tier]) / (365 days * 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Claim a matured lock. Pays principal + full reward.
|
||||||
|
*/
|
||||||
|
function withdraw(uint256 lockId) external nonReentrant {
|
||||||
|
Lock storage l = _locks[msg.sender][lockId];
|
||||||
|
require(!l.withdrawn, "AereLockedStaking: already withdrawn");
|
||||||
|
require(block.timestamp >= l.unlockAt, "AereLockedStaking: still locked");
|
||||||
|
|
||||||
|
l.withdrawn = true;
|
||||||
|
totalPrincipal -= l.amount;
|
||||||
|
|
||||||
|
uint256 reward = (l.amount * APY_BPS[l.tier] * DURATIONS[l.tier]) / (365 days * 10000);
|
||||||
|
uint256 total = l.amount + reward;
|
||||||
|
|
||||||
|
// Pay only if the reward reserve covers it (the principal we hold
|
||||||
|
// for other locks must never be touched).
|
||||||
|
require(address(this).balance >= total + totalPrincipal, "AereLockedStaking: reward reserve insufficient");
|
||||||
|
|
||||||
|
(bool ok, ) = msg.sender.call{value: total}("");
|
||||||
|
require(ok, "AereLockedStaking: transfer failed");
|
||||||
|
emit Withdrawn(msg.sender, lockId, l.amount, reward);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Forfeit the reward and recover principal before maturity.
|
||||||
|
*/
|
||||||
|
function earlyExit(uint256 lockId) external nonReentrant {
|
||||||
|
Lock storage l = _locks[msg.sender][lockId];
|
||||||
|
require(!l.withdrawn, "AereLockedStaking: already withdrawn");
|
||||||
|
|
||||||
|
l.withdrawn = true;
|
||||||
|
totalPrincipal -= l.amount;
|
||||||
|
|
||||||
|
(bool ok, ) = msg.sender.call{value: l.amount}("");
|
||||||
|
require(ok, "AereLockedStaking: transfer failed");
|
||||||
|
emit EarlyExited(msg.sender, lockId, l.amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Views ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function lockCount(address user) external view returns (uint256) {
|
||||||
|
return _locks[user].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLock(address user, uint256 lockId) external view returns (Lock memory) {
|
||||||
|
return _locks[user][lockId];
|
||||||
|
}
|
||||||
|
|
||||||
|
function tierDuration(uint8 tier) external view returns (uint64) {
|
||||||
|
require(tier < 4, "AereLockedStaking: bad tier");
|
||||||
|
return DURATIONS[tier];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice AERE held above outstanding principal — the actual reward reserve.
|
||||||
|
function rewardReserve() external view returns (uint256) {
|
||||||
|
uint256 bal = address(this).balance;
|
||||||
|
return bal > totalPrincipal ? bal - totalPrincipal : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Reward reserve seeding ───────────────────────────────────────────
|
||||||
|
|
||||||
|
/// @notice Foundation tops up the reward reserve. Anyone can donate.
|
||||||
|
receive() external payable {
|
||||||
|
emit RewardReserveDeposited(msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereMiningDistributor
|
||||||
|
* @notice Merkle-claim payout distributor for AireFlow / mining-subscription
|
||||||
|
* epoch rewards.
|
||||||
|
*
|
||||||
|
* Workflow each epoch (default = 30 days, matches AereMiningSubscription):
|
||||||
|
*
|
||||||
|
* 1. Foundation runs an off-chain scheduler that walks all active
|
||||||
|
* subscriptions, computes each subscriber's reward share (a function
|
||||||
|
* of tier + days-active), produces a Merkle tree of
|
||||||
|
* (subscriber, amount) leaves and a root.
|
||||||
|
* 2. Foundation funds this contract with the epoch's total AERE payout
|
||||||
|
* by plain transfer or calling `fundEpoch{value:X}()`.
|
||||||
|
* 3. Foundation calls `postEpoch(root, totalAllocated, claimDeadline)`.
|
||||||
|
* The new epoch id is returned. The root is immutable for that epoch.
|
||||||
|
* 4. Each subscriber claims via `claim(epochId, index, amount, proof)`.
|
||||||
|
* The contract pays them in native AERE.
|
||||||
|
* 5. After `claimDeadline`, Foundation may `sweepUnclaimed(epochId)`
|
||||||
|
* to recover unclaimed funds (rolled into the next epoch's bucket).
|
||||||
|
*
|
||||||
|
* Funding source: AereMiningReserve wallet (whitepaper §3.2, 1.4B AERE
|
||||||
|
* earmarked over the network's life).
|
||||||
|
*
|
||||||
|
* This is not in custody of subscribers — they pull, contract never pushes.
|
||||||
|
* Single-claim guard: bitmap per epoch indexed by leaf index.
|
||||||
|
*/
|
||||||
|
contract AereMiningDistributor is Ownable, ReentrancyGuard {
|
||||||
|
struct Epoch {
|
||||||
|
bytes32 merkleRoot;
|
||||||
|
uint256 totalAllocated; // funds reserved for this epoch's leaves
|
||||||
|
uint256 totalClaimed;
|
||||||
|
uint64 claimDeadline;
|
||||||
|
bool swept;
|
||||||
|
}
|
||||||
|
|
||||||
|
Epoch[] public epochs;
|
||||||
|
/// epochId => packed bitmap (1 bit per leaf index claimed)
|
||||||
|
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitmap;
|
||||||
|
|
||||||
|
event EpochPosted(uint256 indexed epochId, bytes32 merkleRoot, uint256 totalAllocated, uint64 claimDeadline);
|
||||||
|
event Funded(address indexed from, uint256 amount);
|
||||||
|
event Claimed(uint256 indexed epochId, uint256 indexed index, address indexed account, uint256 amount);
|
||||||
|
event Swept(uint256 indexed epochId, uint256 unclaimed);
|
||||||
|
|
||||||
|
receive() external payable { emit Funded(msg.sender, msg.value); }
|
||||||
|
function fundEpoch() external payable { emit Funded(msg.sender, msg.value); }
|
||||||
|
|
||||||
|
function epochCount() external view returns (uint256) { return epochs.length; }
|
||||||
|
|
||||||
|
function postEpoch(bytes32 merkleRoot, uint256 totalAllocated, uint64 claimDeadline)
|
||||||
|
external onlyOwner returns (uint256 epochId)
|
||||||
|
{
|
||||||
|
require(merkleRoot != bytes32(0), "MiningDist: zero root");
|
||||||
|
require(totalAllocated > 0, "MiningDist: zero total");
|
||||||
|
require(claimDeadline > block.timestamp, "MiningDist: deadline past");
|
||||||
|
require(address(this).balance >= _liveFunds() + totalAllocated, "MiningDist: underfunded");
|
||||||
|
epochs.push(Epoch({
|
||||||
|
merkleRoot: merkleRoot,
|
||||||
|
totalAllocated: totalAllocated,
|
||||||
|
totalClaimed: 0,
|
||||||
|
claimDeadline: claimDeadline,
|
||||||
|
swept: false
|
||||||
|
}));
|
||||||
|
epochId = epochs.length - 1;
|
||||||
|
emit EpochPosted(epochId, merkleRoot, totalAllocated, claimDeadline);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isClaimed(uint256 epochId, uint256 index) public view returns (bool) {
|
||||||
|
uint256 wordIndex = index / 256;
|
||||||
|
uint256 bitIndex = index % 256;
|
||||||
|
uint256 word = claimedBitmap[epochId][wordIndex];
|
||||||
|
return (word & (1 << bitIndex)) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _setClaimed(uint256 epochId, uint256 index) private {
|
||||||
|
uint256 wordIndex = index / 256;
|
||||||
|
uint256 bitIndex = index % 256;
|
||||||
|
claimedBitmap[epochId][wordIndex] |= (1 << bitIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
function claim(uint256 epochId, uint256 index, address account, uint256 amount, bytes32[] calldata proof)
|
||||||
|
external nonReentrant
|
||||||
|
{
|
||||||
|
require(epochId < epochs.length, "MiningDist: bad epoch");
|
||||||
|
Epoch storage e = epochs[epochId];
|
||||||
|
require(block.timestamp <= e.claimDeadline, "MiningDist: expired");
|
||||||
|
require(!isClaimed(epochId, index), "MiningDist: already claimed");
|
||||||
|
|
||||||
|
bytes32 leaf = keccak256(abi.encodePacked(index, account, amount));
|
||||||
|
require(_verify(proof, e.merkleRoot, leaf), "MiningDist: bad proof");
|
||||||
|
|
||||||
|
_setClaimed(epochId, index);
|
||||||
|
e.totalClaimed += amount;
|
||||||
|
require(e.totalClaimed <= e.totalAllocated, "MiningDist: over-allocated");
|
||||||
|
|
||||||
|
(bool ok, ) = account.call{ value: amount }("");
|
||||||
|
require(ok, "MiningDist: payout failed");
|
||||||
|
emit Claimed(epochId, index, account, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweepUnclaimed(uint256 epochId) external onlyOwner nonReentrant {
|
||||||
|
require(epochId < epochs.length, "MiningDist: bad epoch");
|
||||||
|
Epoch storage e = epochs[epochId];
|
||||||
|
require(!e.swept, "MiningDist: already swept");
|
||||||
|
require(block.timestamp > e.claimDeadline, "MiningDist: too early");
|
||||||
|
uint256 unclaimed = e.totalAllocated - e.totalClaimed;
|
||||||
|
e.swept = true;
|
||||||
|
if (unclaimed > 0) {
|
||||||
|
(bool ok, ) = msg.sender.call{ value: unclaimed }("");
|
||||||
|
require(ok, "MiningDist: sweep failed");
|
||||||
|
}
|
||||||
|
emit Swept(epochId, unclaimed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Funds still reserved by every un-swept epoch, INCLUDING epochs whose
|
||||||
|
/// claimDeadline has passed but that have not yet been swept. An expired
|
||||||
|
/// epoch still physically holds its unclaimed AERE (sweepUnclaimed sends
|
||||||
|
/// exactly that reserve to the owner), so it must keep reserving those
|
||||||
|
/// funds until it is actually swept — otherwise the same wei could both
|
||||||
|
/// back a freshly posted epoch AND be swept to the owner, double-counting
|
||||||
|
/// it and stranding the new epoch's honest claimants. Reservation leaves
|
||||||
|
/// _liveFunds exactly once: when sweepUnclaimed sets `swept = true`.
|
||||||
|
function _liveFunds() internal view returns (uint256 reserved) {
|
||||||
|
for (uint256 i = 0; i < epochs.length; i++) {
|
||||||
|
Epoch storage e = epochs[i];
|
||||||
|
if (!e.swept) {
|
||||||
|
reserved += e.totalAllocated - e.totalClaimed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _verify(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
|
||||||
|
bytes32 hash = leaf;
|
||||||
|
for (uint256 i = 0; i < proof.length; i++) {
|
||||||
|
bytes32 p = proof[i];
|
||||||
|
hash = hash < p ? keccak256(abi.encodePacked(hash, p)) : keccak256(abi.encodePacked(p, hash));
|
||||||
|
}
|
||||||
|
return hash == root;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereMiningSubscription (AireFlow)
|
||||||
|
* @notice Cloud mining subscriptions paid in AERE
|
||||||
|
* @dev Whitepaper §5.3 — "Revolutionary Subscription Mining Platform"
|
||||||
|
* Users pay a monthly AERE fee for guaranteed hash rate allocation,
|
||||||
|
* receive proportional block rewards distributed by the foundation.
|
||||||
|
*
|
||||||
|
* Reference whitepaper §5.3:
|
||||||
|
* AireFlow 15.0 TH/s example: $300/month → ~30 AERE/month rewards (illustrative).
|
||||||
|
*/
|
||||||
|
contract AereMiningSubscription is Ownable, ReentrancyGuard {
|
||||||
|
enum Tier { BASIC, PREMIUM, ENTERPRISE, AIREFLOW }
|
||||||
|
|
||||||
|
struct TierConfig {
|
||||||
|
uint256 monthlyPriceAere; // wei
|
||||||
|
uint256 hashRateThs; // TH/s allocated
|
||||||
|
bool active;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Subscription {
|
||||||
|
Tier tier;
|
||||||
|
uint256 startBlock;
|
||||||
|
uint256 expiresAt; // block.timestamp
|
||||||
|
uint256 totalPaid;
|
||||||
|
uint256 unclaimedRewards;
|
||||||
|
uint256 lastRewardBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(Tier => TierConfig) public tiers;
|
||||||
|
mapping(address => Subscription) public subscriptions;
|
||||||
|
address[] public subscribers;
|
||||||
|
mapping(address => uint256) private subscriberIndex;
|
||||||
|
|
||||||
|
uint256 public constant SUBSCRIPTION_PERIOD = 30 days;
|
||||||
|
uint256 public networkHashRateThs = 2500; // bootstrap value, governance-updatable
|
||||||
|
uint256 public blockReward = 1.25 ether; // matches whitepaper §5.3 (1.25 AERE/block)
|
||||||
|
uint256 public difficultyAdjustmentBps = 10750; // Dt = 1.075 example
|
||||||
|
|
||||||
|
address public foundationTreasury;
|
||||||
|
|
||||||
|
event TierConfigured(Tier indexed tier, uint256 priceAere, uint256 hashRateThs);
|
||||||
|
event Subscribed(address indexed user, Tier tier, uint256 expiresAt);
|
||||||
|
event RewardsAccrued(address indexed user, uint256 amount);
|
||||||
|
event RewardsClaimed(address indexed user, uint256 amount);
|
||||||
|
event TreasurySet(address indexed treasury);
|
||||||
|
|
||||||
|
constructor(address _foundationTreasury) {
|
||||||
|
foundationTreasury = _foundationTreasury;
|
||||||
|
|
||||||
|
// Default tier configuration (whitepaper-aligned, governance-mutable)
|
||||||
|
tiers[Tier.BASIC] = TierConfig({monthlyPriceAere: 10 ether, hashRateThs: 1, active: true});
|
||||||
|
tiers[Tier.PREMIUM] = TierConfig({monthlyPriceAere: 50 ether, hashRateThs: 6, active: true});
|
||||||
|
tiers[Tier.ENTERPRISE] = TierConfig({monthlyPriceAere: 200 ether, hashRateThs: 30, active: true});
|
||||||
|
tiers[Tier.AIREFLOW] = TierConfig({monthlyPriceAere: 100 ether, hashRateThs: 15, active: true});
|
||||||
|
}
|
||||||
|
|
||||||
|
function configureTier(Tier tier, uint256 priceAere, uint256 hashRateThs) external onlyOwner {
|
||||||
|
tiers[tier] = TierConfig({monthlyPriceAere: priceAere, hashRateThs: hashRateThs, active: true});
|
||||||
|
emit TierConfigured(tier, priceAere, hashRateThs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTreasury(address _treasury) external onlyOwner {
|
||||||
|
foundationTreasury = _treasury;
|
||||||
|
emit TreasurySet(_treasury);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setNetworkHashRate(uint256 _ths) external onlyOwner {
|
||||||
|
require(_ths > 0, "AereMining: hashrate>0");
|
||||||
|
networkHashRateThs = _ths;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Subscribe (or extend) to a mining tier. Pay msg.value in native AERE.
|
||||||
|
*/
|
||||||
|
function subscribe(Tier tier) external payable nonReentrant {
|
||||||
|
TierConfig memory cfg = tiers[tier];
|
||||||
|
require(cfg.active, "AereMining: tier inactive");
|
||||||
|
require(msg.value >= cfg.monthlyPriceAere, "AereMining: insufficient payment");
|
||||||
|
|
||||||
|
Subscription storage s = subscriptions[msg.sender];
|
||||||
|
|
||||||
|
// Settle pending rewards before changing tier/period
|
||||||
|
if (s.tier == tier && s.expiresAt > block.timestamp) {
|
||||||
|
_accrue(msg.sender);
|
||||||
|
} else {
|
||||||
|
// New tier or expired — reset rewards baseline
|
||||||
|
s.lastRewardBlock = block.number;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.expiresAt < block.timestamp) {
|
||||||
|
s.startBlock = block.number;
|
||||||
|
s.expiresAt = block.timestamp + SUBSCRIPTION_PERIOD;
|
||||||
|
} else {
|
||||||
|
s.expiresAt += SUBSCRIPTION_PERIOD;
|
||||||
|
}
|
||||||
|
s.tier = tier;
|
||||||
|
s.totalPaid += msg.value;
|
||||||
|
|
||||||
|
// Track unique subscribers
|
||||||
|
if (subscriberIndex[msg.sender] == 0) {
|
||||||
|
subscribers.push(msg.sender);
|
||||||
|
subscriberIndex[msg.sender] = subscribers.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forward payment to foundation treasury
|
||||||
|
(bool ok, ) = foundationTreasury.call{value: msg.value}("");
|
||||||
|
require(ok, "AereMining: treasury transfer failed");
|
||||||
|
|
||||||
|
emit Subscribed(msg.sender, tier, s.expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Pending rewards (in AERE wei) for a subscriber.
|
||||||
|
* @dev Formula (whitepaper §5.3):
|
||||||
|
* R = B × HR × (1 - Dt) × T
|
||||||
|
* where HR = userHashRate / networkHashRate
|
||||||
|
*/
|
||||||
|
function pendingRewards(address user) public view returns (uint256) {
|
||||||
|
Subscription memory s = subscriptions[user];
|
||||||
|
if (s.expiresAt < block.timestamp || s.lastRewardBlock == 0) return s.unclaimedRewards;
|
||||||
|
uint256 blocksElapsed = block.number - s.lastRewardBlock;
|
||||||
|
uint256 userHashRate = tiers[s.tier].hashRateThs;
|
||||||
|
// Compute (1 - Dt). difficultyAdjustmentBps is e.g. 10750 = 1.075.
|
||||||
|
// (1 - Dt) is negative if Dt > 1, but in the whitepaper formula difficulty
|
||||||
|
// damps reward, not amplifies. Use (10000 - (difficultyAdjustmentBps - 10000))
|
||||||
|
// capped to non-negative if Dt < 2.
|
||||||
|
int256 difficultyFactor = int256(20000) - int256(difficultyAdjustmentBps);
|
||||||
|
if (difficultyFactor < 0) difficultyFactor = 0;
|
||||||
|
uint256 dampedReward = (blockReward * uint256(difficultyFactor)) / 10000;
|
||||||
|
uint256 reward = (dampedReward * userHashRate * blocksElapsed) / networkHashRateThs;
|
||||||
|
return s.unclaimedRewards + reward;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _accrue(address user) internal {
|
||||||
|
uint256 reward = pendingRewards(user);
|
||||||
|
Subscription storage s = subscriptions[user];
|
||||||
|
if (reward > s.unclaimedRewards) {
|
||||||
|
s.unclaimedRewards = reward;
|
||||||
|
emit RewardsAccrued(user, reward);
|
||||||
|
}
|
||||||
|
s.lastRewardBlock = block.number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function claim() external nonReentrant {
|
||||||
|
_accrue(msg.sender);
|
||||||
|
Subscription storage s = subscriptions[msg.sender];
|
||||||
|
uint256 amount = s.unclaimedRewards;
|
||||||
|
require(amount > 0, "AereMining: nothing to claim");
|
||||||
|
s.unclaimedRewards = 0;
|
||||||
|
require(address(this).balance >= amount, "AereMining: pool insufficient - needs foundation top-up");
|
||||||
|
(bool ok, ) = msg.sender.call{value: amount}("");
|
||||||
|
require(ok, "AereMining: transfer failed");
|
||||||
|
emit RewardsClaimed(msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function subscriberCount() external view returns (uint256) {
|
||||||
|
return subscribers.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Allow foundation to top up the reward pool
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereNFT
|
||||||
|
* @notice Native ERC-721 collection for AERE Network with on-chain royalties (EIP-2981).
|
||||||
|
* @dev Permissionless minting: anyone can mint by paying the mint fee in native AERE.
|
||||||
|
* Per-token royalty (creator-set, capped at 10%) flows to the original minter.
|
||||||
|
* Designed to work with AereNFTMarketplace, but conforms to EIP-2981 for any market.
|
||||||
|
*/
|
||||||
|
contract AereNFT is ERC721URIStorage, ERC721Enumerable, Ownable, IERC2981 {
|
||||||
|
uint96 public constant MAX_ROYALTY_BPS = 1000; // 10%
|
||||||
|
uint256 public mintFee = 0.01 ether; // 0.01 AERE
|
||||||
|
|
||||||
|
address public feeRecipient;
|
||||||
|
uint256 private _nextId = 1;
|
||||||
|
|
||||||
|
struct RoyaltyInfo {
|
||||||
|
address receiver;
|
||||||
|
uint96 royaltyBps;
|
||||||
|
}
|
||||||
|
mapping(uint256 => RoyaltyInfo) private _royalties;
|
||||||
|
mapping(uint256 => address) public minterOf;
|
||||||
|
|
||||||
|
event Minted(uint256 indexed tokenId, address indexed minter, string uri, uint96 royaltyBps);
|
||||||
|
event MintFeeUpdated(uint256 newFee);
|
||||||
|
event FeeRecipientUpdated(address newRecipient);
|
||||||
|
|
||||||
|
constructor(address _feeRecipient) ERC721("AERE NFT", "AERENFT") {
|
||||||
|
feeRecipient = _feeRecipient;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mint(string calldata uri, uint96 royaltyBps) external payable returns (uint256) {
|
||||||
|
require(msg.value >= mintFee, "fee");
|
||||||
|
require(royaltyBps <= MAX_ROYALTY_BPS, "royalty too high");
|
||||||
|
uint256 id = _nextId++;
|
||||||
|
_safeMint(msg.sender, id);
|
||||||
|
_setTokenURI(id, uri);
|
||||||
|
_royalties[id] = RoyaltyInfo(msg.sender, royaltyBps);
|
||||||
|
minterOf[id] = msg.sender;
|
||||||
|
|
||||||
|
if (msg.value > 0) {
|
||||||
|
(bool ok, ) = feeRecipient.call{value: msg.value}("");
|
||||||
|
require(ok, "fee transfer");
|
||||||
|
}
|
||||||
|
emit Minted(id, msg.sender, uri, royaltyBps);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMintFee(uint256 newFee) external onlyOwner {
|
||||||
|
mintFee = newFee;
|
||||||
|
emit MintFeeUpdated(newFee);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFeeRecipient(address newRecipient) external onlyOwner {
|
||||||
|
require(newRecipient != address(0), "zero");
|
||||||
|
feeRecipient = newRecipient;
|
||||||
|
emit FeeRecipientUpdated(newRecipient);
|
||||||
|
}
|
||||||
|
|
||||||
|
// EIP-2981
|
||||||
|
function royaltyInfo(uint256 tokenId, uint256 salePrice)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
override
|
||||||
|
returns (address receiver, uint256 royaltyAmount)
|
||||||
|
{
|
||||||
|
RoyaltyInfo memory r = _royalties[tokenId];
|
||||||
|
return (r.receiver, (salePrice * r.royaltyBps) / 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Required overrides for ERC721Enumerable + ERC721URIStorage
|
||||||
|
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize)
|
||||||
|
internal
|
||||||
|
override(ERC721, ERC721Enumerable)
|
||||||
|
{
|
||||||
|
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
|
||||||
|
super._burn(tokenId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenURI(uint256 tokenId)
|
||||||
|
public
|
||||||
|
view
|
||||||
|
override(ERC721, ERC721URIStorage)
|
||||||
|
returns (string memory)
|
||||||
|
{
|
||||||
|
return super.tokenURI(tokenId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function supportsInterface(bytes4 interfaceId)
|
||||||
|
public
|
||||||
|
view
|
||||||
|
override(ERC721Enumerable, ERC721URIStorage, IERC165)
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
|
||||||
|
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereNFTMarketplace
|
||||||
|
* @notice On-chain NFT marketplace for AERE Network with EIP-2981 royalty support.
|
||||||
|
* @dev Sellers list owned ERC-721 tokens for a fixed price in native AERE.
|
||||||
|
* Buyers purchase atomically: protocol fee → fee recipient, royalty → creator,
|
||||||
|
* remainder → seller. Buyers can also place expiring offers on any token.
|
||||||
|
* Marketplace must be approved (setApprovalForAll or approve) before listing.
|
||||||
|
*/
|
||||||
|
contract AereNFTMarketplace is Ownable, ReentrancyGuard {
|
||||||
|
uint96 public constant MAX_FEE_BPS = 1000; // 10%
|
||||||
|
uint96 public protocolFeeBps = 250; // 2.5%
|
||||||
|
address public feeRecipient;
|
||||||
|
|
||||||
|
struct Listing {
|
||||||
|
address seller;
|
||||||
|
uint256 price;
|
||||||
|
uint64 expiresAt; // 0 = never
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Offer {
|
||||||
|
address buyer;
|
||||||
|
uint256 price;
|
||||||
|
uint64 expiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
// collection => tokenId => Listing
|
||||||
|
mapping(address => mapping(uint256 => Listing)) public listings;
|
||||||
|
// collection => tokenId => buyer => Offer
|
||||||
|
mapping(address => mapping(uint256 => mapping(address => Offer))) public offers;
|
||||||
|
// escrowed offer balances per buyer (refundable)
|
||||||
|
mapping(address => uint256) public pendingWithdrawals;
|
||||||
|
|
||||||
|
event Listed(address indexed collection, uint256 indexed tokenId, address indexed seller, uint256 price, uint64 expiresAt);
|
||||||
|
event ListingCancelled(address indexed collection, uint256 indexed tokenId, address indexed seller);
|
||||||
|
event Sold(address indexed collection, uint256 indexed tokenId, address seller, address indexed buyer, uint256 price);
|
||||||
|
event OfferPlaced(address indexed collection, uint256 indexed tokenId, address indexed buyer, uint256 price, uint64 expiresAt);
|
||||||
|
event OfferCancelled(address indexed collection, uint256 indexed tokenId, address indexed buyer);
|
||||||
|
event OfferAccepted(address indexed collection, uint256 indexed tokenId, address seller, address indexed buyer, uint256 price);
|
||||||
|
event ProtocolFeeUpdated(uint96 newFeeBps);
|
||||||
|
event FeeRecipientUpdated(address newRecipient);
|
||||||
|
|
||||||
|
constructor(address _feeRecipient) {
|
||||||
|
require(_feeRecipient != address(0), "zero");
|
||||||
|
feeRecipient = _feeRecipient;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Listings ────────────────────────────────────────────────
|
||||||
|
function list(address collection, uint256 tokenId, uint256 price, uint64 expiresAt) external {
|
||||||
|
require(price > 0, "price=0");
|
||||||
|
IERC721 nft = IERC721(collection);
|
||||||
|
require(nft.ownerOf(tokenId) == msg.sender, "not owner");
|
||||||
|
require(
|
||||||
|
nft.getApproved(tokenId) == address(this) || nft.isApprovedForAll(msg.sender, address(this)),
|
||||||
|
"not approved"
|
||||||
|
);
|
||||||
|
listings[collection][tokenId] = Listing(msg.sender, price, expiresAt);
|
||||||
|
emit Listed(collection, tokenId, msg.sender, price, expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelListing(address collection, uint256 tokenId) external {
|
||||||
|
Listing memory l = listings[collection][tokenId];
|
||||||
|
require(l.seller == msg.sender, "not seller");
|
||||||
|
delete listings[collection][tokenId];
|
||||||
|
emit ListingCancelled(collection, tokenId, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buy(address collection, uint256 tokenId) external payable nonReentrant {
|
||||||
|
Listing memory l = listings[collection][tokenId];
|
||||||
|
require(l.seller != address(0), "not listed");
|
||||||
|
require(l.expiresAt == 0 || block.timestamp <= l.expiresAt, "expired");
|
||||||
|
require(msg.value == l.price, "bad value");
|
||||||
|
|
||||||
|
delete listings[collection][tokenId];
|
||||||
|
_settleSale(collection, tokenId, l.seller, msg.sender, l.price);
|
||||||
|
emit Sold(collection, tokenId, l.seller, msg.sender, l.price);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Offers ──────────────────────────────────────────────────
|
||||||
|
function placeOffer(address collection, uint256 tokenId, uint64 expiresAt) external payable nonReentrant {
|
||||||
|
require(msg.value > 0, "price=0");
|
||||||
|
require(expiresAt > block.timestamp, "expired");
|
||||||
|
Offer memory existing = offers[collection][tokenId][msg.sender];
|
||||||
|
if (existing.price > 0) {
|
||||||
|
// refund prior offer to escrow
|
||||||
|
pendingWithdrawals[msg.sender] += existing.price;
|
||||||
|
}
|
||||||
|
offers[collection][tokenId][msg.sender] = Offer(msg.sender, msg.value, expiresAt);
|
||||||
|
emit OfferPlaced(collection, tokenId, msg.sender, msg.value, expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelOffer(address collection, uint256 tokenId) external nonReentrant {
|
||||||
|
Offer memory o = offers[collection][tokenId][msg.sender];
|
||||||
|
require(o.price > 0, "no offer");
|
||||||
|
delete offers[collection][tokenId][msg.sender];
|
||||||
|
pendingWithdrawals[msg.sender] += o.price;
|
||||||
|
emit OfferCancelled(collection, tokenId, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
function acceptOffer(address collection, uint256 tokenId, address buyer) external nonReentrant {
|
||||||
|
IERC721 nft = IERC721(collection);
|
||||||
|
require(nft.ownerOf(tokenId) == msg.sender, "not owner");
|
||||||
|
Offer memory o = offers[collection][tokenId][buyer];
|
||||||
|
require(o.price > 0, "no offer");
|
||||||
|
require(block.timestamp <= o.expiresAt, "expired");
|
||||||
|
|
||||||
|
delete offers[collection][tokenId][buyer];
|
||||||
|
// active listing (if any) becomes invalid after transfer; clear it
|
||||||
|
if (listings[collection][tokenId].seller == msg.sender) {
|
||||||
|
delete listings[collection][tokenId];
|
||||||
|
}
|
||||||
|
_settleSale(collection, tokenId, msg.sender, buyer, o.price);
|
||||||
|
emit OfferAccepted(collection, tokenId, msg.sender, buyer, o.price);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdraw() external nonReentrant {
|
||||||
|
uint256 amount = pendingWithdrawals[msg.sender];
|
||||||
|
require(amount > 0, "nothing");
|
||||||
|
pendingWithdrawals[msg.sender] = 0;
|
||||||
|
(bool ok, ) = msg.sender.call{value: amount}("");
|
||||||
|
require(ok, "transfer");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Internal settlement ─────────────────────────────────────
|
||||||
|
function _settleSale(address collection, uint256 tokenId, address seller, address buyer, uint256 price) internal {
|
||||||
|
IERC721(collection).safeTransferFrom(seller, buyer, tokenId);
|
||||||
|
|
||||||
|
uint256 fee = (price * protocolFeeBps) / 10000;
|
||||||
|
uint256 royalty = 0;
|
||||||
|
address royaltyReceiver = address(0);
|
||||||
|
|
||||||
|
try IERC2981(collection).royaltyInfo(tokenId, price) returns (address r, uint256 amt) {
|
||||||
|
if (r != address(0) && amt > 0 && amt + fee <= price) {
|
||||||
|
royaltyReceiver = r;
|
||||||
|
royalty = amt;
|
||||||
|
}
|
||||||
|
} catch { /* collection doesn't implement EIP-2981 */ }
|
||||||
|
|
||||||
|
uint256 sellerProceeds = price - fee - royalty;
|
||||||
|
|
||||||
|
if (fee > 0) _send(feeRecipient, fee);
|
||||||
|
if (royalty > 0) _send(royaltyReceiver, royalty);
|
||||||
|
_send(seller, sellerProceeds);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _send(address to, uint256 amount) internal {
|
||||||
|
(bool ok, ) = to.call{value: amount}("");
|
||||||
|
if (!ok) {
|
||||||
|
// fall back to escrow so a malicious receiver can't block sales
|
||||||
|
pendingWithdrawals[to] += amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Admin ───────────────────────────────────────────────────
|
||||||
|
function setProtocolFee(uint96 newFeeBps) external onlyOwner {
|
||||||
|
require(newFeeBps <= MAX_FEE_BPS, "too high");
|
||||||
|
protocolFeeBps = newFeeBps;
|
||||||
|
emit ProtocolFeeUpdated(newFeeBps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFeeRecipient(address newRecipient) external onlyOwner {
|
||||||
|
require(newRecipient != address(0), "zero");
|
||||||
|
feeRecipient = newRecipient;
|
||||||
|
emit FeeRecipientUpdated(newRecipient);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereOnboardingPaymaster
|
||||||
|
* @notice Foundation-funded paymaster for first-time AERE users.
|
||||||
|
*
|
||||||
|
* Hard-capped onboarding paymaster:
|
||||||
|
* - Each address gets exactly N sponsored UserOps (lifetime — never resets)
|
||||||
|
* - Sitewide daily UserOp cap (Sybil-attack protection)
|
||||||
|
* - Optional whitelist of contract addresses we'll sponsor calls to
|
||||||
|
* - Total balance is whatever Foundation pre-funded. When drained, paymaster
|
||||||
|
* refuses all UserOps until Foundation tops up (which requires a governance
|
||||||
|
* decision, not an automated refill).
|
||||||
|
*
|
||||||
|
* Math example: with 3 sponsored txs/address and a 100-tx/day sitewide cap,
|
||||||
|
* 100,000 unique addresses cost ~300,000 gas-paid-by-paymaster txs. Even at
|
||||||
|
* 0.001 AERE/tx that's 300 AERE total to onboard 100k users.
|
||||||
|
*/
|
||||||
|
contract AereOnboardingPaymaster is PaymasterBase {
|
||||||
|
/// Lifetime sponsored UserOp cap per sender address.
|
||||||
|
uint256 public sponsoredOpsPerSender = 3;
|
||||||
|
|
||||||
|
/// Sitewide UserOp cap per UTC day (rolling: floor(block.timestamp / 1 days)).
|
||||||
|
uint256 public dailySitewideCap = 100;
|
||||||
|
|
||||||
|
/// Set to true to limit sponsorship to specific target contracts only.
|
||||||
|
bool public targetWhitelistEnabled = false;
|
||||||
|
|
||||||
|
/// Whitelist of target contracts whose function calls we will sponsor.
|
||||||
|
mapping(address => bool) public targetWhitelist;
|
||||||
|
|
||||||
|
/// Per-sender lifetime count of UserOps the paymaster has sponsored.
|
||||||
|
mapping(address => uint256) public sponsoredCount;
|
||||||
|
|
||||||
|
/// Per-day sitewide counter (key = unix day).
|
||||||
|
mapping(uint256 => uint256) public dailyCount;
|
||||||
|
|
||||||
|
event Sponsored(address indexed sender, uint256 newSenderCount, uint256 todayCount);
|
||||||
|
event ConfigChanged(uint256 perSender, uint256 dailyCap, bool whitelistEnabled);
|
||||||
|
event TargetWhitelist(address indexed target, bool allowed);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep) PaymasterBase(_ep) {}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setLimits(uint256 _perSender, uint256 _dailyCap, bool _whitelist) external onlyOwner {
|
||||||
|
sponsoredOpsPerSender = _perSender;
|
||||||
|
dailySitewideCap = _dailyCap;
|
||||||
|
targetWhitelistEnabled = _whitelist;
|
||||||
|
emit ConfigChanged(_perSender, _dailyCap, _whitelist);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setWhitelist(address target, bool allowed) external onlyOwner {
|
||||||
|
targetWhitelist[target] = allowed;
|
||||||
|
emit TargetWhitelist(target, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Paymaster hook ─────────────────────
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /* userOpHash */,
|
||||||
|
uint256 /* maxCost */
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
address sender = userOp.sender;
|
||||||
|
|
||||||
|
// Per-sender lifetime cap
|
||||||
|
require(sponsoredCount[sender] < sponsoredOpsPerSender, "OnboardingPM: sender exhausted");
|
||||||
|
|
||||||
|
// Sitewide daily cap
|
||||||
|
uint256 today = block.timestamp / 1 days;
|
||||||
|
require(dailyCount[today] < dailySitewideCap, "OnboardingPM: daily cap reached");
|
||||||
|
|
||||||
|
// Optional target whitelist — first 4 bytes of callData are the function selector;
|
||||||
|
// the called contract is encoded in `userOp.callData` after the selector. We don't
|
||||||
|
// decode the inner call here for gas reasons; whitelist by target is enforced via
|
||||||
|
// the SmartAccount's `execute(target, value, data)` callData convention which
|
||||||
|
// places `target` at bytes 16..36 of callData (standard ERC-4337 SimpleAccount).
|
||||||
|
if (targetWhitelistEnabled) {
|
||||||
|
bytes calldata cd = userOp.callData;
|
||||||
|
require(cd.length >= 36, "OnboardingPM: bad callData");
|
||||||
|
address target;
|
||||||
|
// solhint-disable-next-line no-inline-assembly
|
||||||
|
assembly {
|
||||||
|
// callData layout: 4 bytes selector + 12 padding + 20 bytes target + ...
|
||||||
|
target := shr(96, calldataload(add(cd.offset, 16)))
|
||||||
|
}
|
||||||
|
require(targetWhitelist[target], "OnboardingPM: target not allowed");
|
||||||
|
}
|
||||||
|
|
||||||
|
sponsoredCount[sender] += 1;
|
||||||
|
dailyCount[today] += 1;
|
||||||
|
|
||||||
|
emit Sponsored(sender, sponsoredCount[sender], dailyCount[today]);
|
||||||
|
return ("", 0); // validationData=0 means: no signature, no time range, valid
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereOracle
|
||||||
|
* @notice Multi-feed price oracle with reporter quorum.
|
||||||
|
* @dev Reporters submit price updates per symbol (e.g. "AERE/USD", "BTC/USD").
|
||||||
|
* The on-chain price is the median of the latest submission from each
|
||||||
|
* authorized reporter, with staleness protection. Designed for use by
|
||||||
|
* AereSwap, AereStaking liquidations, and consumer dApps.
|
||||||
|
*/
|
||||||
|
contract AereOracle is Ownable {
|
||||||
|
uint8 public constant DECIMALS = 8;
|
||||||
|
uint64 public maxStaleness = 5 minutes;
|
||||||
|
|
||||||
|
address[] public reporters;
|
||||||
|
mapping(address => bool) public isReporter;
|
||||||
|
|
||||||
|
struct Submission {
|
||||||
|
uint128 price; // scaled to 8 decimals
|
||||||
|
uint64 timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// symbol => reporter => submission
|
||||||
|
mapping(bytes32 => mapping(address => Submission)) public submissions;
|
||||||
|
bytes32[] public symbols;
|
||||||
|
mapping(bytes32 => bool) private _knownSymbol;
|
||||||
|
|
||||||
|
event ReporterAdded(address indexed reporter);
|
||||||
|
event ReporterRemoved(address indexed reporter);
|
||||||
|
event PriceSubmitted(bytes32 indexed symbol, address indexed reporter, uint128 price, uint64 timestamp);
|
||||||
|
event SymbolAdded(bytes32 indexed symbol);
|
||||||
|
event MaxStalenessUpdated(uint64 newValue);
|
||||||
|
|
||||||
|
function addReporter(address r) external onlyOwner {
|
||||||
|
require(r != address(0) && !isReporter[r], "bad");
|
||||||
|
isReporter[r] = true;
|
||||||
|
reporters.push(r);
|
||||||
|
emit ReporterAdded(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeReporter(address r) external onlyOwner {
|
||||||
|
require(isReporter[r], "not reporter");
|
||||||
|
isReporter[r] = false;
|
||||||
|
for (uint256 i = 0; i < reporters.length; i++) {
|
||||||
|
if (reporters[i] == r) {
|
||||||
|
reporters[i] = reporters[reporters.length - 1];
|
||||||
|
reporters.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit ReporterRemoved(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMaxStaleness(uint64 v) external onlyOwner {
|
||||||
|
require(v >= 30 seconds && v <= 1 hours, "range");
|
||||||
|
maxStaleness = v;
|
||||||
|
emit MaxStalenessUpdated(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit(bytes32 symbol, uint128 price) external {
|
||||||
|
require(isReporter[msg.sender], "not reporter");
|
||||||
|
require(price > 0, "price");
|
||||||
|
if (!_knownSymbol[symbol]) { _knownSymbol[symbol] = true; symbols.push(symbol); emit SymbolAdded(symbol); }
|
||||||
|
submissions[symbol][msg.sender] = Submission(price, uint64(block.timestamp));
|
||||||
|
emit PriceSubmitted(symbol, msg.sender, price, uint64(block.timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Returns the median fresh price for a symbol and the count of contributors.
|
||||||
|
function getPrice(bytes32 symbol) external view returns (uint128 price, uint64 timestamp, uint256 contributors) {
|
||||||
|
uint256 n = reporters.length;
|
||||||
|
uint128[] memory fresh = new uint128[](n);
|
||||||
|
uint64 newest = 0;
|
||||||
|
uint256 count = 0;
|
||||||
|
|
||||||
|
for (uint256 i = 0; i < n; i++) {
|
||||||
|
Submission memory s = submissions[symbol][reporters[i]];
|
||||||
|
if (s.timestamp == 0) continue;
|
||||||
|
if (block.timestamp - s.timestamp > maxStaleness) continue;
|
||||||
|
fresh[count++] = s.price;
|
||||||
|
if (s.timestamp > newest) newest = s.timestamp;
|
||||||
|
}
|
||||||
|
require(count > 0, "no fresh data");
|
||||||
|
|
||||||
|
// insertion sort (small n in practice)
|
||||||
|
for (uint256 i = 1; i < count; i++) {
|
||||||
|
uint128 key = fresh[i];
|
||||||
|
uint256 j = i;
|
||||||
|
while (j > 0 && fresh[j - 1] > key) { fresh[j] = fresh[j - 1]; j--; }
|
||||||
|
fresh[j] = key;
|
||||||
|
}
|
||||||
|
price = (count % 2 == 1) ? fresh[count / 2] : uint128((uint256(fresh[count / 2 - 1]) + uint256(fresh[count / 2])) / 2);
|
||||||
|
return (price, newest, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
function symbolCount() external view returns (uint256) { return symbols.length; }
|
||||||
|
function reporterCount() external view returns (uint256) { return reporters.length; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereOracleV2
|
||||||
|
* @notice Bug-fix redeploy of the legacy AereOracle (V1 at
|
||||||
|
* 0xf0A13823A4bFa86358Fe30aaf1f44A36AcbCf399).
|
||||||
|
*
|
||||||
|
* Multi-feed price oracle with a reporter quorum. Reporters submit price
|
||||||
|
* updates per symbol (e.g. "AERE/USD", "BTC/USD"). The on-chain price is the
|
||||||
|
* median of the latest FRESH submission from each authorized reporter.
|
||||||
|
*
|
||||||
|
* ──────────────────────── WHY V2 (finding #11) ────────────────────────
|
||||||
|
* V1.getPrice returned the median even when only ONE reporter was fresh
|
||||||
|
* (contributors == 1). With the others stale, a single fresh reporter fully
|
||||||
|
* controlled the feed — and the live V1 ran at reporterCount == 1, so the
|
||||||
|
* median was always a single key's number. There was no on-chain minimum
|
||||||
|
* quorum and no setter to raise one.
|
||||||
|
*
|
||||||
|
* V2 fix — a QUORUM-STALENESS guard:
|
||||||
|
* getPrice reverts InsufficientQuorum unless at least `minContributors`
|
||||||
|
* reporters are BOTH authorized AND fresh (within maxStaleness). Stale
|
||||||
|
* submissions are still discarded exactly as in V1, so the quorum can only
|
||||||
|
* be met by that many independently-fresh reporters — a single fresh
|
||||||
|
* reporter (or any number below the quorum) can no longer set the price.
|
||||||
|
* `minContributors` is configurable by the owner (Foundation), floored at 1,
|
||||||
|
* and defaults to 3 for a real median.
|
||||||
|
*
|
||||||
|
* The reporter model, submit(), the getPrice return signature
|
||||||
|
* (uint128 price, uint64 timestamp, uint256 contributors), DECIMALS,
|
||||||
|
* maxStaleness and the median math are otherwise identical to V1, so V2 is a
|
||||||
|
* drop-in replacement for any consumer once the quorum is operationally met.
|
||||||
|
*/
|
||||||
|
contract AereOracleV2 is Ownable {
|
||||||
|
uint8 public constant DECIMALS = 8;
|
||||||
|
uint64 public maxStaleness = 5 minutes;
|
||||||
|
|
||||||
|
/// Minimum number of FRESH, authorized reporters required for getPrice to
|
||||||
|
/// return a price. Invariant: minContributors >= 1. Default 3.
|
||||||
|
uint256 public minContributors;
|
||||||
|
|
||||||
|
address[] public reporters;
|
||||||
|
mapping(address => bool) public isReporter;
|
||||||
|
|
||||||
|
struct Submission {
|
||||||
|
uint128 price; // scaled to 8 decimals
|
||||||
|
uint64 timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// symbol => reporter => submission
|
||||||
|
mapping(bytes32 => mapping(address => Submission)) public submissions;
|
||||||
|
bytes32[] public symbols;
|
||||||
|
mapping(bytes32 => bool) private _knownSymbol;
|
||||||
|
|
||||||
|
event ReporterAdded(address indexed reporter);
|
||||||
|
event ReporterRemoved(address indexed reporter);
|
||||||
|
event PriceSubmitted(bytes32 indexed symbol, address indexed reporter, uint128 price, uint64 timestamp);
|
||||||
|
event SymbolAdded(bytes32 indexed symbol);
|
||||||
|
event MaxStalenessUpdated(uint64 newValue);
|
||||||
|
event MinContributorsUpdated(uint256 newValue);
|
||||||
|
|
||||||
|
error InsufficientQuorum(uint256 fresh, uint256 required);
|
||||||
|
|
||||||
|
constructor(uint256 _minContributors) {
|
||||||
|
require(_minContributors >= 1, "minContributors");
|
||||||
|
minContributors = _minContributors;
|
||||||
|
emit MinContributorsUpdated(_minContributors);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addReporter(address r) external onlyOwner {
|
||||||
|
require(r != address(0) && !isReporter[r], "bad");
|
||||||
|
isReporter[r] = true;
|
||||||
|
reporters.push(r);
|
||||||
|
emit ReporterAdded(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeReporter(address r) external onlyOwner {
|
||||||
|
require(isReporter[r], "not reporter");
|
||||||
|
isReporter[r] = false;
|
||||||
|
for (uint256 i = 0; i < reporters.length; i++) {
|
||||||
|
if (reporters[i] == r) {
|
||||||
|
reporters[i] = reporters[reporters.length - 1];
|
||||||
|
reporters.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit ReporterRemoved(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMaxStaleness(uint64 v) external onlyOwner {
|
||||||
|
require(v >= 30 seconds && v <= 1 hours, "range");
|
||||||
|
maxStaleness = v;
|
||||||
|
emit MaxStalenessUpdated(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Raise/lower the required fresh-reporter quorum. Floored at 1.
|
||||||
|
/// Set this to <= the number of independently-operated reporters the
|
||||||
|
/// Foundation actually runs before repointing consumers here.
|
||||||
|
function setMinContributors(uint256 v) external onlyOwner {
|
||||||
|
require(v >= 1, "minContributors");
|
||||||
|
minContributors = v;
|
||||||
|
emit MinContributorsUpdated(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submit(bytes32 symbol, uint128 price) external {
|
||||||
|
require(isReporter[msg.sender], "not reporter");
|
||||||
|
require(price > 0, "price");
|
||||||
|
if (!_knownSymbol[symbol]) { _knownSymbol[symbol] = true; symbols.push(symbol); emit SymbolAdded(symbol); }
|
||||||
|
submissions[symbol][msg.sender] = Submission(price, uint64(block.timestamp));
|
||||||
|
emit PriceSubmitted(symbol, msg.sender, price, uint64(block.timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Returns the median fresh price for a symbol and the count of
|
||||||
|
/// contributors. Reverts InsufficientQuorum unless at least
|
||||||
|
/// `minContributors` authorized reporters are fresh.
|
||||||
|
function getPrice(bytes32 symbol) external view returns (uint128 price, uint64 timestamp, uint256 contributors) {
|
||||||
|
uint256 n = reporters.length;
|
||||||
|
uint128[] memory fresh = new uint128[](n);
|
||||||
|
uint64 newest = 0;
|
||||||
|
uint256 count = 0;
|
||||||
|
|
||||||
|
for (uint256 i = 0; i < n; i++) {
|
||||||
|
Submission memory s = submissions[symbol][reporters[i]];
|
||||||
|
if (s.timestamp == 0) continue;
|
||||||
|
if (block.timestamp - s.timestamp > maxStaleness) continue;
|
||||||
|
fresh[count++] = s.price;
|
||||||
|
if (s.timestamp > newest) newest = s.timestamp;
|
||||||
|
}
|
||||||
|
// QUORUM-STALENESS GUARD: require a real quorum of FRESH reporters. This
|
||||||
|
// is the fix over V1, which required only count > 0.
|
||||||
|
if (count < minContributors) revert InsufficientQuorum(count, minContributors);
|
||||||
|
|
||||||
|
// insertion sort (small n in practice)
|
||||||
|
for (uint256 i = 1; i < count; i++) {
|
||||||
|
uint128 key = fresh[i];
|
||||||
|
uint256 j = i;
|
||||||
|
while (j > 0 && fresh[j - 1] > key) { fresh[j] = fresh[j - 1]; j--; }
|
||||||
|
fresh[j] = key;
|
||||||
|
}
|
||||||
|
price = (count % 2 == 1) ? fresh[count / 2] : uint128((uint256(fresh[count / 2 - 1]) + uint256(fresh[count / 2])) / 2);
|
||||||
|
return (price, newest, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
function symbolCount() external view returns (uint256) { return symbols.length; }
|
||||||
|
function reporterCount() external view returns (uint256) { return reporters.length; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AerePaymentChannels
|
||||||
|
* @notice Bidirectional payment channels (L2-style state channels) for AERE Network.
|
||||||
|
* @dev Two parties open a channel by depositing AERE. Off-chain they exchange signed
|
||||||
|
* states (a, b, nonce) representing the current split of the channel balance.
|
||||||
|
* Either party closes by submitting the latest co-signed state on-chain. A
|
||||||
|
* challenge window allows the counterparty to override with a higher-nonce state.
|
||||||
|
* After the challenge window expires, funds are settled.
|
||||||
|
*
|
||||||
|
* Whitepaper alignment: "L2 layers — state channels for instant micropayments"
|
||||||
|
*/
|
||||||
|
contract AerePaymentChannels is ReentrancyGuard {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
enum Status { None, Open, Closing, Closed }
|
||||||
|
|
||||||
|
struct Channel {
|
||||||
|
address partyA;
|
||||||
|
address partyB;
|
||||||
|
uint256 balanceA;
|
||||||
|
uint256 balanceB;
|
||||||
|
uint256 nonce;
|
||||||
|
uint64 challengeDeadline; // 0 unless Closing
|
||||||
|
Status status;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint64 public constant CHALLENGE_PERIOD = 1 days;
|
||||||
|
uint256 public nextChannelId = 1;
|
||||||
|
mapping(uint256 => Channel) public channels;
|
||||||
|
|
||||||
|
event ChannelOpened(uint256 indexed id, address indexed partyA, address indexed partyB, uint256 deposit);
|
||||||
|
event ChannelFunded(uint256 indexed id, address indexed party, uint256 amount);
|
||||||
|
event ChannelClosing(uint256 indexed id, uint256 nonce, uint256 balanceA, uint256 balanceB, uint64 deadline);
|
||||||
|
event ChannelChallenged(uint256 indexed id, uint256 nonce, uint256 balanceA, uint256 balanceB);
|
||||||
|
event ChannelClosed(uint256 indexed id, uint256 finalA, uint256 finalB);
|
||||||
|
|
||||||
|
function open(address counterparty) external payable returns (uint256 id) {
|
||||||
|
require(counterparty != address(0) && counterparty != msg.sender, "bad cp");
|
||||||
|
require(msg.value > 0, "deposit");
|
||||||
|
id = nextChannelId++;
|
||||||
|
channels[id] = Channel({
|
||||||
|
partyA: msg.sender,
|
||||||
|
partyB: counterparty,
|
||||||
|
balanceA: msg.value,
|
||||||
|
balanceB: 0,
|
||||||
|
nonce: 0,
|
||||||
|
challengeDeadline: 0,
|
||||||
|
status: Status.Open
|
||||||
|
});
|
||||||
|
emit ChannelOpened(id, msg.sender, counterparty, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fund(uint256 id) external payable {
|
||||||
|
Channel storage c = channels[id];
|
||||||
|
require(c.status == Status.Open, "not open");
|
||||||
|
require(msg.value > 0, "amount");
|
||||||
|
if (msg.sender == c.partyA) c.balanceA += msg.value;
|
||||||
|
else if (msg.sender == c.partyB) c.balanceB += msg.value;
|
||||||
|
else revert("not party");
|
||||||
|
emit ChannelFunded(id, msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Initiate cooperative or unilateral close with a co-signed state.
|
||||||
|
* @param id channel id
|
||||||
|
* @param balanceA proposed final balance for partyA
|
||||||
|
* @param balanceB proposed final balance for partyB
|
||||||
|
* @param nonce state nonce (higher overrides lower during challenge)
|
||||||
|
* @param sigA partyA signature over (this, id, balanceA, balanceB, nonce)
|
||||||
|
* @param sigB partyB signature over the same digest
|
||||||
|
*/
|
||||||
|
function closeWithState(
|
||||||
|
uint256 id,
|
||||||
|
uint256 balanceA,
|
||||||
|
uint256 balanceB,
|
||||||
|
uint256 nonce,
|
||||||
|
bytes calldata sigA,
|
||||||
|
bytes calldata sigB
|
||||||
|
) external nonReentrant {
|
||||||
|
Channel storage c = channels[id];
|
||||||
|
require(c.status == Status.Open || c.status == Status.Closing, "bad status");
|
||||||
|
require(balanceA + balanceB <= c.balanceA + c.balanceB, "overspend");
|
||||||
|
if (c.status == Status.Closing) require(nonce > c.nonce, "stale nonce");
|
||||||
|
|
||||||
|
bytes32 digest = _stateDigest(id, balanceA, balanceB, nonce);
|
||||||
|
require(digest.recover(sigA) == c.partyA, "sigA");
|
||||||
|
require(digest.recover(sigB) == c.partyB, "sigB");
|
||||||
|
|
||||||
|
c.balanceA = balanceA;
|
||||||
|
c.balanceB = balanceB;
|
||||||
|
c.nonce = nonce;
|
||||||
|
|
||||||
|
if (c.status == Status.Open) {
|
||||||
|
c.status = Status.Closing;
|
||||||
|
c.challengeDeadline = uint64(block.timestamp) + CHALLENGE_PERIOD;
|
||||||
|
emit ChannelClosing(id, nonce, balanceA, balanceB, c.challengeDeadline);
|
||||||
|
} else {
|
||||||
|
emit ChannelChallenged(id, nonce, balanceA, balanceB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function settle(uint256 id) external nonReentrant {
|
||||||
|
Channel storage c = channels[id];
|
||||||
|
require(c.status == Status.Closing, "not closing");
|
||||||
|
require(block.timestamp >= c.challengeDeadline, "challenge");
|
||||||
|
c.status = Status.Closed;
|
||||||
|
uint256 a = c.balanceA;
|
||||||
|
uint256 b = c.balanceB;
|
||||||
|
c.balanceA = 0;
|
||||||
|
c.balanceB = 0;
|
||||||
|
if (a > 0) { (bool ok, ) = c.partyA.call{value: a}(""); require(ok, "A"); }
|
||||||
|
if (b > 0) { (bool ok, ) = c.partyB.call{value: b}(""); require(ok, "B"); }
|
||||||
|
emit ChannelClosed(id, a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _stateDigest(uint256 id, uint256 balanceA, uint256 balanceB, uint256 nonce) internal view returns (bytes32) {
|
||||||
|
return keccak256(
|
||||||
|
abi.encodePacked("AereChannel", address(this), block.chainid, id, balanceA, balanceB, nonce)
|
||||||
|
).toEthSignedMessageHash();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereRecoveryRegistry, on-chain attested consensus-recovery evidence for Aere Network (chain 2800)
|
||||||
|
*
|
||||||
|
* @notice An append-only, fail-closed registry that records CONSENSUS RECOVERY events on
|
||||||
|
* Aere Network and binds each one to a real Falcon-512 signature verified in full,
|
||||||
|
* on-chain, by the LIVE native precompile at 0x0AE1. A recovery event is the triple
|
||||||
|
* (halt height, resume height, fault kind) that a fault caused: a validator-set drop
|
||||||
|
* below quorum, the resulting halt, and the subsequent in-place resume. An
|
||||||
|
* independent watchtower (an off-chain observer that holds a registered Falcon-512
|
||||||
|
* key) detects the halt, waits for quorum restoration, then submits the signed record
|
||||||
|
* here. No funds are ever held by this contract.
|
||||||
|
*
|
||||||
|
* WHY THIS EXISTS. Aere's fault-tolerance is characterized off-chain (see
|
||||||
|
* docs/FAULT-TOLERANCE-CHARACTERIZATION-2026-07-14.md: 0 forks over 100 adversarial
|
||||||
|
* cycles, 100/100 self-resync at the f=2 boundary). This contract turns that evidence
|
||||||
|
* into a tamper-evident, publicly auditable on-chain trail: each recorded recovery is
|
||||||
|
* authenticated by a post-quantum signature, cannot be silently rewritten, and cannot
|
||||||
|
* be forged by any operator or admin. It is the on-chain half of the fault-injection
|
||||||
|
* evidence suite that de-risks the (separately founder-gated and audit-gated)
|
||||||
|
* post-quantum consensus flip.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. This contract records ATTESTATIONS about recovery events; it does not
|
||||||
|
* itself observe consensus, halt the chain, or restore quorum, and it does not
|
||||||
|
* activate post-quantum consensus. Blocks are still produced and signed by Besu QBFT
|
||||||
|
* validators with ECDSA (secp256k1). The novelty is that the authenticity of a
|
||||||
|
* recovery record rests on a post-quantum signature (Falcon-512, NIST FIPS 206 draft
|
||||||
|
* line) verified by the live precompile activated on mainnet 2800 at block 9,189,161.
|
||||||
|
* The consensus flip stays founder-gated and audit-gated; this only makes its
|
||||||
|
* recovery evidence honest, reproducible, and quantum-durable.
|
||||||
|
*
|
||||||
|
* @dev FALCON-512 PRECOMPILE (0x0AE1) INPUT ENCODING (exactly what the live precompile parses):
|
||||||
|
* input = pk || sm
|
||||||
|
* pk = (0x00+logn) || packed_h (897 bytes, logn=9, header byte 0x09)
|
||||||
|
* sm = sigLen(2, big-endian) || nonce(40) || message(32) || esig
|
||||||
|
* esig = 0x29 || compressedSig, sigLen == esig.length
|
||||||
|
* Output: a 32-byte word, 0x..01 valid else 0x..00. An empty / zero / short return is
|
||||||
|
* treated as INVALID (this is the pre-fork behaviour of an address with no precompile,
|
||||||
|
* so a stale caller on an un-activated chain can never record). This is FAIL-CLOSED.
|
||||||
|
*
|
||||||
|
* @dev SIGNATURE ENVELOPE handed to submitRecovery():
|
||||||
|
* signature = nonce(40) || esig (esig starts 0x29, so length is 40 + 1 + sigBytes)
|
||||||
|
* The contract supplies the 32-byte message (the record hash) itself, so the signer can
|
||||||
|
* never sign a different record than the one this contract binds and records.
|
||||||
|
*
|
||||||
|
* @dev POST-QUANTUM AUTHORSHIP. Authorship of a recovery record is the Falcon-512 signature
|
||||||
|
* alone. submitRecovery() may be relayed by any msg.sender: only the holder of the
|
||||||
|
* registered operator private key can produce a valid signature over this contract's
|
||||||
|
* per-operator, per-nonce record hash, so a relayer only pays gas and can never forge
|
||||||
|
* or replay. Binding authorship to the ECDSA tx sender would defeat the purpose, since
|
||||||
|
* secp256k1 is exactly what a quantum computer breaks.
|
||||||
|
*
|
||||||
|
* @dev APPEND-ONLY. Records live in a push-only array; recordId is the array index and is
|
||||||
|
* immutable once written. There is NO function that overwrites, deletes, or edits a
|
||||||
|
* record, and there is NO owner, admin, or privileged role anywhere in this contract.
|
||||||
|
* A strictly increasing per-operator nonce is consumed on every write, so no
|
||||||
|
* (record, signature) pair can be replayed to rewrite history.
|
||||||
|
*/
|
||||||
|
contract AereRecoveryRegistry {
|
||||||
|
// ----- Falcon-512 (the only scheme this registry attests under) -----
|
||||||
|
/// @notice Live Falcon-512 verifier precompile on chain 2800.
|
||||||
|
address public constant PRECOMPILE_FALCON512 = address(0x0AE1);
|
||||||
|
uint256 internal constant FALCON512_PK_LEN = 897;
|
||||||
|
uint8 internal constant FALCON512_PK_HEADER = 0x09; // 0x00 | logn=9
|
||||||
|
uint8 internal constant FALCON512_ESIG_HEADER = 0x29; // 0x20 | logn=9
|
||||||
|
uint256 internal constant FALCON_NONCE_LEN = 40;
|
||||||
|
|
||||||
|
// ----- fault kinds -----
|
||||||
|
uint8 public constant FAULT_CRASH = 1; // one or more validators crash / go offline
|
||||||
|
uint8 public constant FAULT_NETSPLIT = 2; // network partition, minority side halts
|
||||||
|
uint8 public constant FAULT_BYZANTINE_PROPOSER = 3; // a proposer equivocates / signs invalidly
|
||||||
|
|
||||||
|
// ----- domain separator for the record hash the operator signs -----
|
||||||
|
bytes32 public constant RECORD_DOMAIN = keccak256("AereRecoveryRegistry.v1.record");
|
||||||
|
|
||||||
|
// ----- registered operator keys -----
|
||||||
|
struct Operator {
|
||||||
|
address registrant; // address that registered the key (informational; not an authority)
|
||||||
|
uint64 nonce; // strictly increasing per-operator replay counter
|
||||||
|
bytes pubKey; // the raw Falcon-512 public key (897 bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
Operator[] private _operators; // operatorId is the index into this array
|
||||||
|
|
||||||
|
// ----- recorded recovery events (append-only) -----
|
||||||
|
struct RecoveryRecord {
|
||||||
|
uint64 haltHeight; // block height at which progress stopped
|
||||||
|
uint64 resumeHeight; // block height at which progress resumed (>= haltHeight)
|
||||||
|
uint8 faultKind; // 1=CRASH, 2=NETSPLIT, 3=BYZANTINE_PROPOSER
|
||||||
|
uint16 nValidators; // validator-set size at the event (e.g. 7)
|
||||||
|
uint16 quorum; // commit quorum at the event (e.g. 5)
|
||||||
|
uint16 aliveDuringFault; // validators still alive during the fault window
|
||||||
|
uint256 operatorId; // the attesting operator key
|
||||||
|
uint64 nonce; // the per-operator nonce this record consumed
|
||||||
|
uint64 recordedAt; // block.number at which the record was written
|
||||||
|
bytes32 recordHash; // the exact 32-byte message the Falcon-512 signature verified over
|
||||||
|
}
|
||||||
|
|
||||||
|
RecoveryRecord[] private _records; // recordId is the index; push-only, never rewritten
|
||||||
|
|
||||||
|
// ----- events -----
|
||||||
|
event OperatorRegistered(uint256 indexed operatorId, address indexed registrant, uint256 pubKeyLen);
|
||||||
|
event RecoveryAttested(
|
||||||
|
uint256 indexed recordId,
|
||||||
|
uint256 indexed operatorId,
|
||||||
|
uint8 indexed faultKind,
|
||||||
|
uint64 haltHeight,
|
||||||
|
uint64 resumeHeight,
|
||||||
|
uint16 nValidators,
|
||||||
|
uint16 quorum,
|
||||||
|
uint16 aliveDuringFault,
|
||||||
|
uint64 nonce,
|
||||||
|
bytes32 recordHash
|
||||||
|
);
|
||||||
|
|
||||||
|
// ----- errors -----
|
||||||
|
error InvalidPubKey();
|
||||||
|
error UnknownOperator(uint256 operatorId);
|
||||||
|
error InvalidFaultKind(uint8 faultKind);
|
||||||
|
error InvalidHeights(uint64 haltHeight, uint64 resumeHeight);
|
||||||
|
error InvalidValidatorSet(uint16 nValidators, uint16 quorum, uint16 aliveDuringFault);
|
||||||
|
error InvalidSignatureLength();
|
||||||
|
error PQCVerificationFailed();
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Operator registration
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Register a Falcon-512 public key as a recovery-attesting operator (e.g. a
|
||||||
|
* watchtower). Permissionless: anyone may register a key. Authorship of every
|
||||||
|
* record submitted under this operatorId is the Falcon-512 signature alone, so a
|
||||||
|
* registrant is only a label, never an authority, and registering a key grants no
|
||||||
|
* power to forge a record. Multiple keys per address are allowed.
|
||||||
|
* @param pubKey the raw Falcon-512 public key (897 bytes, header byte 0x09).
|
||||||
|
* @return operatorId the identifier assigned to this key.
|
||||||
|
*/
|
||||||
|
function registerOperator(bytes calldata pubKey) external returns (uint256 operatorId) {
|
||||||
|
if (pubKey.length != FALCON512_PK_LEN || uint8(pubKey[0]) != FALCON512_PK_HEADER) revert InvalidPubKey();
|
||||||
|
|
||||||
|
operatorId = _operators.length;
|
||||||
|
_operators.push(Operator({registrant: msg.sender, nonce: 0, pubKey: pubKey}));
|
||||||
|
|
||||||
|
emit OperatorRegistered(operatorId, msg.sender, pubKey.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Recovery attestation
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Record a consensus-recovery event, authenticated on-chain by the live Falcon-512
|
||||||
|
* precompile (0x0AE1). Verifies that `signature` is a valid Falcon-512 signature by
|
||||||
|
* the registered operator key over this contract's record hash:
|
||||||
|
*
|
||||||
|
* recordHash = keccak256(abi.encode(
|
||||||
|
* RECORD_DOMAIN, block.chainid, address(this), operatorId, nonce,
|
||||||
|
* haltHeight, resumeHeight, faultKind, nValidators, quorum, aliveDuringFault))
|
||||||
|
*
|
||||||
|
* where `nonce` is the operator's current per-operator nonce. On success the record
|
||||||
|
* is appended, the nonce is incremented, and the event is emitted. Reverts (records
|
||||||
|
* nothing, advances no nonce) on: an unknown operator, an invalid fault kind,
|
||||||
|
* inconsistent heights, an inconsistent validator set, or an invalid signature
|
||||||
|
* (FAIL-CLOSED). No admin path can bypass the signature check.
|
||||||
|
*
|
||||||
|
* @param operatorId the registered operator attesting this record.
|
||||||
|
* @param haltHeight block height at which progress stopped (>= 1).
|
||||||
|
* @param resumeHeight block height at which progress resumed (>= haltHeight, <= current block).
|
||||||
|
* @param faultKind 1=CRASH, 2=NETSPLIT, 3=BYZANTINE_PROPOSER.
|
||||||
|
* @param nValidators validator-set size at the event (e.g. 7).
|
||||||
|
* @param quorum commit quorum at the event (e.g. 5), 1 <= quorum <= nValidators.
|
||||||
|
* @param aliveDuringFault validators still alive during the fault window (<= nValidators).
|
||||||
|
* @param signature the Falcon-512 signature envelope, nonce(40) || esig.
|
||||||
|
* @return recordId the append-only id assigned to this record.
|
||||||
|
*/
|
||||||
|
function submitRecovery(
|
||||||
|
uint256 operatorId,
|
||||||
|
uint64 haltHeight,
|
||||||
|
uint64 resumeHeight,
|
||||||
|
uint8 faultKind,
|
||||||
|
uint16 nValidators,
|
||||||
|
uint16 quorum,
|
||||||
|
uint16 aliveDuringFault,
|
||||||
|
bytes calldata signature
|
||||||
|
) external returns (uint256 recordId) {
|
||||||
|
if (operatorId >= _operators.length) revert UnknownOperator(operatorId);
|
||||||
|
if (faultKind != FAULT_CRASH && faultKind != FAULT_NETSPLIT && faultKind != FAULT_BYZANTINE_PROPOSER) {
|
||||||
|
revert InvalidFaultKind(faultKind);
|
||||||
|
}
|
||||||
|
// Heights must describe a real, already-happened halt-then-resume window.
|
||||||
|
if (haltHeight == 0 || resumeHeight < haltHeight || resumeHeight > uint64(block.number)) {
|
||||||
|
revert InvalidHeights(haltHeight, resumeHeight);
|
||||||
|
}
|
||||||
|
// Validator-set context must be internally consistent.
|
||||||
|
if (
|
||||||
|
nValidators == 0 || quorum == 0 || quorum > nValidators || aliveDuringFault > nValidators
|
||||||
|
) {
|
||||||
|
revert InvalidValidatorSet(nValidators, quorum, aliveDuringFault);
|
||||||
|
}
|
||||||
|
|
||||||
|
Operator storage op = _operators[operatorId];
|
||||||
|
uint64 nonce = op.nonce;
|
||||||
|
|
||||||
|
bytes32 recordHash = recordChallenge(
|
||||||
|
operatorId, nonce, haltHeight, resumeHeight, faultKind, nValidators, quorum, aliveDuringFault
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!_verifyFalcon(op.pubKey, recordHash, signature)) revert PQCVerificationFailed();
|
||||||
|
|
||||||
|
// Effects: consume the nonce and append the record (append-only, never rewritten).
|
||||||
|
op.nonce = nonce + 1;
|
||||||
|
|
||||||
|
recordId = _records.length;
|
||||||
|
_records.push(
|
||||||
|
RecoveryRecord({
|
||||||
|
haltHeight: haltHeight,
|
||||||
|
resumeHeight: resumeHeight,
|
||||||
|
faultKind: faultKind,
|
||||||
|
nValidators: nValidators,
|
||||||
|
quorum: quorum,
|
||||||
|
aliveDuringFault: aliveDuringFault,
|
||||||
|
operatorId: operatorId,
|
||||||
|
nonce: nonce,
|
||||||
|
recordedAt: uint64(block.number),
|
||||||
|
recordHash: recordHash
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
emit RecoveryAttested(
|
||||||
|
recordId,
|
||||||
|
operatorId,
|
||||||
|
faultKind,
|
||||||
|
haltHeight,
|
||||||
|
resumeHeight,
|
||||||
|
nValidators,
|
||||||
|
quorum,
|
||||||
|
aliveDuringFault,
|
||||||
|
nonce,
|
||||||
|
recordHash
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice The exact 32-byte record hash that a signature for `operatorId` must sign at a
|
||||||
|
* given nonce. Off-chain watchtowers query this to know what to sign.
|
||||||
|
*/
|
||||||
|
function recordChallenge(
|
||||||
|
uint256 operatorId,
|
||||||
|
uint64 nonce,
|
||||||
|
uint64 haltHeight,
|
||||||
|
uint64 resumeHeight,
|
||||||
|
uint8 faultKind,
|
||||||
|
uint16 nValidators,
|
||||||
|
uint16 quorum,
|
||||||
|
uint16 aliveDuringFault
|
||||||
|
) public view returns (bytes32) {
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(
|
||||||
|
RECORD_DOMAIN,
|
||||||
|
block.chainid,
|
||||||
|
address(this),
|
||||||
|
operatorId,
|
||||||
|
nonce,
|
||||||
|
haltHeight,
|
||||||
|
resumeHeight,
|
||||||
|
faultKind,
|
||||||
|
nValidators,
|
||||||
|
quorum,
|
||||||
|
aliveDuringFault
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal verifier
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Build the exact Falcon-512 precompile input with `message` as the signed 32-byte
|
||||||
|
* message, staticcall the live precompile at 0x0AE1, and return true iff it answers
|
||||||
|
* 0x..01. Any empty / short / zero return is invalid (FAIL-CLOSED).
|
||||||
|
*/
|
||||||
|
function _verifyFalcon(bytes memory pubKey, bytes32 message, bytes memory signature)
|
||||||
|
internal
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
// signature = nonce(40) || esig
|
||||||
|
if (signature.length <= FALCON_NONCE_LEN) revert InvalidSignatureLength();
|
||||||
|
uint256 sigLen = signature.length - FALCON_NONCE_LEN; // esig length
|
||||||
|
if (sigLen < 2 || sigLen > type(uint16).max) revert InvalidSignatureLength();
|
||||||
|
|
||||||
|
bytes memory nonce = _slice(signature, 0, FALCON_NONCE_LEN);
|
||||||
|
bytes memory esig = _slice(signature, FALCON_NONCE_LEN, sigLen);
|
||||||
|
|
||||||
|
// sm = sigLen(2, big-endian) || nonce(40) || message(32) || esig
|
||||||
|
bytes memory sm = abi.encodePacked(uint16(sigLen), nonce, message, esig);
|
||||||
|
bytes memory input = abi.encodePacked(pubKey, sm);
|
||||||
|
|
||||||
|
(bool ok, bytes memory ret) = PRECOMPILE_FALCON512.staticcall(input);
|
||||||
|
return ok && ret.length >= 32 && ret[31] == 0x01;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _slice(bytes memory data, uint256 start, uint256 len) internal pure returns (bytes memory out) {
|
||||||
|
out = new bytes(len);
|
||||||
|
for (uint256 i = 0; i < len; i++) {
|
||||||
|
out[i] = data[start + i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Number of registered operators (operatorIds run 0..operatorCount-1).
|
||||||
|
function operatorCount() external view returns (uint256) {
|
||||||
|
return _operators.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a registered operator.
|
||||||
|
function getOperator(uint256 operatorId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (address registrant, uint64 nonce, bytes memory pubKey)
|
||||||
|
{
|
||||||
|
if (operatorId >= _operators.length) revert UnknownOperator(operatorId);
|
||||||
|
Operator storage op = _operators[operatorId];
|
||||||
|
return (op.registrant, op.nonce, op.pubKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The current (next unused) nonce for an operator.
|
||||||
|
function nonceOf(uint256 operatorId) external view returns (uint64) {
|
||||||
|
if (operatorId >= _operators.length) revert UnknownOperator(operatorId);
|
||||||
|
return _operators[operatorId].nonce;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Total number of recovery records (recordIds run 0..recordCount-1).
|
||||||
|
function recordCount() external view returns (uint256) {
|
||||||
|
return _records.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a recorded recovery event by its append-only id.
|
||||||
|
function getRecord(uint256 recordId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint64 haltHeight,
|
||||||
|
uint64 resumeHeight,
|
||||||
|
uint8 faultKind,
|
||||||
|
uint16 nValidators,
|
||||||
|
uint16 quorum,
|
||||||
|
uint16 aliveDuringFault,
|
||||||
|
uint256 operatorId,
|
||||||
|
uint64 nonce,
|
||||||
|
uint64 recordedAt,
|
||||||
|
bytes32 recordHash
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (recordId >= _records.length) revert UnknownOperator(recordId);
|
||||||
|
RecoveryRecord storage r = _records[recordId];
|
||||||
|
return (
|
||||||
|
r.haltHeight,
|
||||||
|
r.resumeHeight,
|
||||||
|
r.faultKind,
|
||||||
|
r.nValidators,
|
||||||
|
r.quorum,
|
||||||
|
r.aliveDuringFault,
|
||||||
|
r.operatorId,
|
||||||
|
r.nonce,
|
||||||
|
r.recordedAt,
|
||||||
|
r.recordHash
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/security/Pausable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE Security Contract
|
||||||
|
* @dev Manages security monitoring and threat detection with enhanced security
|
||||||
|
*/
|
||||||
|
contract AereSecurity is Ownable, ReentrancyGuard, Pausable {
|
||||||
|
|
||||||
|
enum ThreatLevel { Low, Medium, High, Critical }
|
||||||
|
enum AlertStatus { Active, Resolved, Investigating }
|
||||||
|
|
||||||
|
struct SecurityAlert {
|
||||||
|
uint256 id;
|
||||||
|
string alertType;
|
||||||
|
ThreatLevel severity;
|
||||||
|
string message;
|
||||||
|
address reporter;
|
||||||
|
uint256 timestamp;
|
||||||
|
AlertStatus status;
|
||||||
|
string resolution;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SecurityMetrics {
|
||||||
|
uint256 totalAlerts;
|
||||||
|
uint256 resolvedAlerts;
|
||||||
|
uint256 criticalAlerts;
|
||||||
|
uint256 lastScanTime;
|
||||||
|
bool systemHealthy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// State variables
|
||||||
|
mapping(uint256 => SecurityAlert) public alerts;
|
||||||
|
mapping(address => bool) public authorizedReporters;
|
||||||
|
mapping(address => uint256) public reputationScores;
|
||||||
|
mapping(address => uint256) public reportCounts;
|
||||||
|
mapping(address => uint256) public lastReportTime;
|
||||||
|
|
||||||
|
uint256 public alertCount = 0;
|
||||||
|
SecurityMetrics public securityMetrics;
|
||||||
|
|
||||||
|
// Security parameters
|
||||||
|
uint256 public constant RATE_LIMIT_WINDOW = 1 hours;
|
||||||
|
uint256 public constant MAX_REPORTS_PER_WINDOW = 10;
|
||||||
|
uint256 public constant MIN_REPUTATION_TO_REPORT = 50;
|
||||||
|
|
||||||
|
// Events
|
||||||
|
event SecurityAlertCreated(uint256 indexed alertId, ThreatLevel severity, string alertType, address indexed reporter);
|
||||||
|
event AlertResolved(uint256 indexed alertId, string resolution, address indexed resolver);
|
||||||
|
event ThreatDetected(address indexed source, string threatType, ThreatLevel severity, address indexed detector);
|
||||||
|
event ReputationUpdated(address indexed entity, uint256 oldScore, uint256 newScore);
|
||||||
|
event ReporterAuthorized(address indexed reporter, address indexed authorizer);
|
||||||
|
event ReporterRevoked(address indexed reporter, address indexed revoker);
|
||||||
|
|
||||||
|
modifier onlyAuthorizedReporter() {
|
||||||
|
require(authorizedReporters[msg.sender], "AereSecurity: Not authorized to report");
|
||||||
|
require(reputationScores[msg.sender] >= MIN_REPUTATION_TO_REPORT, "AereSecurity: Insufficient reputation");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier rateLimited() {
|
||||||
|
require(
|
||||||
|
reportCounts[msg.sender] < MAX_REPORTS_PER_WINDOW ||
|
||||||
|
block.timestamp > lastReportTime[msg.sender] + RATE_LIMIT_WINDOW,
|
||||||
|
"AereSecurity: Rate limit exceeded"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (block.timestamp > lastReportTime[msg.sender] + RATE_LIMIT_WINDOW) {
|
||||||
|
reportCounts[msg.sender] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
reportCounts[msg.sender]++;
|
||||||
|
lastReportTime[msg.sender] = block.timestamp;
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
securityMetrics = SecurityMetrics({
|
||||||
|
totalAlerts: 0,
|
||||||
|
resolvedAlerts: 0,
|
||||||
|
criticalAlerts: 0,
|
||||||
|
lastScanTime: block.timestamp,
|
||||||
|
systemHealthy: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Owner is authorized reporter by default with high reputation
|
||||||
|
authorizedReporters[msg.sender] = true;
|
||||||
|
reputationScores[msg.sender] = 100;
|
||||||
|
|
||||||
|
emit ReporterAuthorized(msg.sender, msg.sender);
|
||||||
|
emit ReputationUpdated(msg.sender, 0, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Add authorized security reporter with reputation check
|
||||||
|
*/
|
||||||
|
function addAuthorizedReporter(address reporter) external onlyOwner {
|
||||||
|
require(reporter != address(0), "AereSecurity: Invalid reporter address");
|
||||||
|
require(!authorizedReporters[reporter], "AereSecurity: Reporter already authorized");
|
||||||
|
|
||||||
|
authorizedReporters[reporter] = true;
|
||||||
|
if (reputationScores[reporter] == 0) {
|
||||||
|
reputationScores[reporter] = MIN_REPUTATION_TO_REPORT;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit ReporterAuthorized(reporter, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Remove authorized security reporter
|
||||||
|
*/
|
||||||
|
function removeAuthorizedReporter(address reporter) external onlyOwner {
|
||||||
|
require(reporter != msg.sender, "AereSecurity: Cannot remove self");
|
||||||
|
authorizedReporters[reporter] = false;
|
||||||
|
|
||||||
|
emit ReporterRevoked(reporter, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Report security alert with enhanced validation
|
||||||
|
*/
|
||||||
|
function reportSecurityAlert(
|
||||||
|
string memory alertType,
|
||||||
|
ThreatLevel severity,
|
||||||
|
string memory message
|
||||||
|
) external onlyAuthorizedReporter rateLimited whenNotPaused nonReentrant returns (uint256) {
|
||||||
|
require(bytes(alertType).length > 0 && bytes(alertType).length <= 100, "AereSecurity: Invalid alert type");
|
||||||
|
require(bytes(message).length > 0 && bytes(message).length <= 1000, "AereSecurity: Invalid message");
|
||||||
|
|
||||||
|
alertCount++;
|
||||||
|
uint256 alertId = alertCount;
|
||||||
|
|
||||||
|
alerts[alertId] = SecurityAlert({
|
||||||
|
id: alertId,
|
||||||
|
alertType: alertType,
|
||||||
|
severity: severity,
|
||||||
|
message: message,
|
||||||
|
reporter: msg.sender,
|
||||||
|
timestamp: block.timestamp,
|
||||||
|
status: AlertStatus.Active,
|
||||||
|
resolution: ""
|
||||||
|
});
|
||||||
|
|
||||||
|
securityMetrics.totalAlerts++;
|
||||||
|
if (severity == ThreatLevel.Critical) {
|
||||||
|
securityMetrics.criticalAlerts++;
|
||||||
|
securityMetrics.systemHealthy = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update reporter reputation (positive for reporting)
|
||||||
|
_updateReputationSafe(msg.sender, reputationScores[msg.sender] + 1);
|
||||||
|
|
||||||
|
emit SecurityAlertCreated(alertId, severity, alertType, msg.sender);
|
||||||
|
return alertId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Resolve security alert with enhanced validation
|
||||||
|
*/
|
||||||
|
function resolveAlert(uint256 alertId, string memory resolution) external onlyOwner nonReentrant {
|
||||||
|
require(alertId > 0 && alertId <= alertCount, "AereSecurity: Alert does not exist");
|
||||||
|
require(alerts[alertId].status != AlertStatus.Resolved, "AereSecurity: Alert already resolved");
|
||||||
|
require(bytes(resolution).length > 0 && bytes(resolution).length <= 1000, "AereSecurity: Invalid resolution");
|
||||||
|
|
||||||
|
alerts[alertId].status = AlertStatus.Resolved;
|
||||||
|
alerts[alertId].resolution = resolution;
|
||||||
|
|
||||||
|
securityMetrics.resolvedAlerts++;
|
||||||
|
|
||||||
|
// Update system health if all critical alerts resolved
|
||||||
|
if (alerts[alertId].severity == ThreatLevel.Critical) {
|
||||||
|
securityMetrics.criticalAlerts = securityMetrics.criticalAlerts > 0 ? securityMetrics.criticalAlerts - 1 : 0;
|
||||||
|
if (securityMetrics.criticalAlerts == 0) {
|
||||||
|
securityMetrics.systemHealthy = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emit AlertResolved(alertId, resolution, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Detect and report threat with enhanced validation
|
||||||
|
*/
|
||||||
|
function detectThreat(
|
||||||
|
address source,
|
||||||
|
string memory threatType,
|
||||||
|
ThreatLevel severity
|
||||||
|
) external onlyAuthorizedReporter rateLimited whenNotPaused nonReentrant {
|
||||||
|
require(source != address(0), "AereSecurity: Invalid source address");
|
||||||
|
require(bytes(threatType).length > 0 && bytes(threatType).length <= 100, "AereSecurity: Invalid threat type");
|
||||||
|
|
||||||
|
// Update reputation score for the source (negative impact)
|
||||||
|
if (reputationScores[source] > uint256(severity) + 1) {
|
||||||
|
_updateReputationSafe(source, reputationScores[source] - (uint256(severity) + 1));
|
||||||
|
} else {
|
||||||
|
_updateReputationSafe(source, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create alert
|
||||||
|
string memory message = string(abi.encodePacked("Threat detected from ", _addressToString(source)));
|
||||||
|
this.reportSecurityAlert(threatType, severity, message);
|
||||||
|
|
||||||
|
emit ThreatDetected(source, threatType, severity, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Update reputation score with bounds checking
|
||||||
|
*/
|
||||||
|
function updateReputation(address entity, uint256 score) external onlyOwner {
|
||||||
|
require(entity != address(0), "AereSecurity: Invalid entity address");
|
||||||
|
require(score <= 100, "AereSecurity: Score too high");
|
||||||
|
|
||||||
|
uint256 oldScore = reputationScores[entity];
|
||||||
|
_updateReputationSafe(entity, score);
|
||||||
|
|
||||||
|
emit ReputationUpdated(entity, oldScore, score);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Internal safe reputation update
|
||||||
|
*/
|
||||||
|
function _updateReputationSafe(address entity, uint256 score) internal {
|
||||||
|
uint256 oldScore = reputationScores[entity];
|
||||||
|
reputationScores[entity] = score > 100 ? 100 : score;
|
||||||
|
|
||||||
|
if (oldScore != reputationScores[entity]) {
|
||||||
|
emit ReputationUpdated(entity, oldScore, reputationScores[entity]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Perform security scan (only owner, rate limited)
|
||||||
|
*/
|
||||||
|
function performSecurityScan() external onlyOwner {
|
||||||
|
require(block.timestamp >= securityMetrics.lastScanTime + 1 hours, "AereSecurity: Scan rate limited");
|
||||||
|
|
||||||
|
securityMetrics.lastScanTime = block.timestamp;
|
||||||
|
securityMetrics.systemHealthy = (securityMetrics.criticalAlerts == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Emergency pause function
|
||||||
|
*/
|
||||||
|
function emergencyPause() external onlyOwner {
|
||||||
|
_pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Unpause function
|
||||||
|
*/
|
||||||
|
function unpause() external onlyOwner {
|
||||||
|
_unpause();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get alert details with existence check
|
||||||
|
*/
|
||||||
|
function getAlert(uint256 alertId) external view returns (SecurityAlert memory) {
|
||||||
|
require(alertId > 0 && alertId <= alertCount, "AereSecurity: Alert does not exist");
|
||||||
|
return alerts[alertId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get security metrics
|
||||||
|
*/
|
||||||
|
function getSecurityMetrics() external view returns (SecurityMetrics memory) {
|
||||||
|
return securityMetrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get reputation score
|
||||||
|
*/
|
||||||
|
function getReputationScore(address entity) external view returns (uint256) {
|
||||||
|
return reputationScores[entity];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Check if system is healthy
|
||||||
|
*/
|
||||||
|
function isSystemHealthy() external view returns (bool) {
|
||||||
|
return securityMetrics.systemHealthy && securityMetrics.criticalAlerts == 0 && !paused();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get active alerts count by severity
|
||||||
|
*/
|
||||||
|
function getActiveAlertsBySeverity(ThreatLevel severity) external view returns (uint256) {
|
||||||
|
uint256 count = 0;
|
||||||
|
for (uint256 i = 1; i <= alertCount; i++) {
|
||||||
|
if (alerts[i].severity == severity && alerts[i].status == AlertStatus.Active) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Check if address is authorized reporter
|
||||||
|
*/
|
||||||
|
function isAuthorizedReporter(address reporter) external view returns (bool) {
|
||||||
|
return authorizedReporters[reporter] && reputationScores[reporter] >= MIN_REPUTATION_TO_REPORT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Get reporter statistics
|
||||||
|
*/
|
||||||
|
function getReporterStats(address reporter) external view returns (
|
||||||
|
bool authorized,
|
||||||
|
uint256 reputation,
|
||||||
|
uint256 reportsInWindow,
|
||||||
|
uint256 lastReport
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
authorizedReporters[reporter],
|
||||||
|
reputationScores[reporter],
|
||||||
|
reportCounts[reporter],
|
||||||
|
lastReportTime[reporter]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Convert address to string
|
||||||
|
*/
|
||||||
|
function _addressToString(address account) internal pure returns (string memory) {
|
||||||
|
bytes32 value = bytes32(uint256(uint160(account)));
|
||||||
|
bytes memory alphabet = "0123456789abcdef";
|
||||||
|
bytes memory str = new bytes(42);
|
||||||
|
str[0] = '0';
|
||||||
|
str[1] = 'x';
|
||||||
|
for (uint256 i = 0; i < 20; i++) {
|
||||||
|
str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)];
|
||||||
|
str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)];
|
||||||
|
}
|
||||||
|
return string(str);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
interface IAereStaking {
|
||||||
|
function balanceOf(address user) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereLockedStaking {
|
||||||
|
function lockCount(address user) external view returns (uint256);
|
||||||
|
function getLock(address user, uint256 lockId) external view returns (
|
||||||
|
uint8 tier, uint256 amount, uint64 startTime, uint64 unlockTime, bool withdrawn
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereStakeQuotaPaymaster
|
||||||
|
* @notice "Stake AERE, get free transactions" — Tron's killer UX, brought to EVM.
|
||||||
|
*
|
||||||
|
* Reads the user's effective AERE stake (delegated AereStaking + active
|
||||||
|
* AereLockedStaking locks) and allocates a daily free-tx quota:
|
||||||
|
*
|
||||||
|
* quotaPerDay = stakedAERE * txPerKiloAere / 1000
|
||||||
|
*
|
||||||
|
* Default: stake 1 AERE → 0.02 txs/day (i.e. 1 free tx per 50 AERE staked, recommended floor)
|
||||||
|
* stake 1,000 AERE → 20 txs/day
|
||||||
|
* stake 10,000 AERE → 200 txs/day
|
||||||
|
*
|
||||||
|
* Quota resets per UTC day. Unused quota does NOT roll over.
|
||||||
|
*
|
||||||
|
* Funding: self-funding from validator-reward share (5% of block rewards routed
|
||||||
|
* here automatically). Foundation pre-funds the seed balance, then the validator
|
||||||
|
* share keeps the pool topped up.
|
||||||
|
*
|
||||||
|
* Safety: per-UserOp gas-spend cap prevents one user from draining the pool with a
|
||||||
|
* single huge transaction.
|
||||||
|
*/
|
||||||
|
contract AereStakeQuotaPaymaster is PaymasterBase {
|
||||||
|
IAereStaking public immutable staking;
|
||||||
|
IAereLockedStaking public immutable lockedStaking;
|
||||||
|
|
||||||
|
/// How many sponsored UserOps per 1000 AERE staked, per day.
|
||||||
|
/// Default 20 = 1 free tx per 50 AERE staked. Owner-tunable.
|
||||||
|
uint256 public txPerKiloAerePerDay = 20;
|
||||||
|
|
||||||
|
/// Max gas the paymaster will cover per single UserOp.
|
||||||
|
uint256 public maxSponsoredGasWei = 0.01 ether;
|
||||||
|
|
||||||
|
/// (sender, day) => sponsoredCount
|
||||||
|
mapping(bytes32 => uint256) public usedQuota;
|
||||||
|
|
||||||
|
event Sponsored(address indexed sender, uint256 dayQuota, uint256 used);
|
||||||
|
event ConfigChanged(uint256 txPerKilo, uint256 maxGasWei);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep, IAereStaking _staking, IAereLockedStaking _locked) PaymasterBase(_ep) {
|
||||||
|
staking = _staking;
|
||||||
|
lockedStaking = _locked;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setQuotaParams(uint256 _txPerKilo, uint256 _maxGasWei) external onlyOwner {
|
||||||
|
txPerKiloAerePerDay = _txPerKilo;
|
||||||
|
maxSponsoredGasWei = _maxGasWei;
|
||||||
|
emit ConfigChanged(_txPerKilo, _maxGasWei);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Quota views ─────────────────────
|
||||||
|
|
||||||
|
/// Effective AERE stake of a user = delegated + sum of active locks.
|
||||||
|
function stakedOf(address user) public view returns (uint256 total) {
|
||||||
|
try staking.balanceOf(user) returns (uint256 d) { total += d; } catch {}
|
||||||
|
try lockedStaking.lockCount(user) returns (uint256 n) {
|
||||||
|
for (uint256 i = 0; i < n; i++) {
|
||||||
|
try lockedStaking.getLock(user, i) returns (
|
||||||
|
uint8 /*tier*/, uint256 amount, uint64 /*start*/, uint64 unlockTime, bool withdrawn
|
||||||
|
) {
|
||||||
|
if (!withdrawn && block.timestamp < unlockTime) {
|
||||||
|
total += amount;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dailyQuotaOf(address user) public view returns (uint256) {
|
||||||
|
return (stakedOf(user) * txPerKiloAerePerDay) / 1000 ether;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quotaRemaining(address user) external view returns (uint256 remaining, uint256 dailyQuota) {
|
||||||
|
dailyQuota = dailyQuotaOf(user);
|
||||||
|
uint256 today = block.timestamp / 1 days;
|
||||||
|
bytes32 k = keccak256(abi.encodePacked(user, today));
|
||||||
|
uint256 used = usedQuota[k];
|
||||||
|
remaining = used >= dailyQuota ? 0 : dailyQuota - used;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Paymaster hook ─────────────────────
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /*userOpHash*/,
|
||||||
|
uint256 maxCost
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
require(maxCost <= maxSponsoredGasWei, "StakePM: tx too expensive");
|
||||||
|
|
||||||
|
address sender = userOp.sender;
|
||||||
|
uint256 dailyQuota = dailyQuotaOf(sender);
|
||||||
|
require(dailyQuota > 0, "StakePM: stake more AERE");
|
||||||
|
|
||||||
|
uint256 today = block.timestamp / 1 days;
|
||||||
|
bytes32 k = keccak256(abi.encodePacked(sender, today));
|
||||||
|
uint256 used = usedQuota[k];
|
||||||
|
require(used < dailyQuota, "StakePM: daily quota exhausted");
|
||||||
|
|
||||||
|
usedQuota[k] = used + 1;
|
||||||
|
emit Sponsored(sender, dailyQuota, used + 1);
|
||||||
|
return ("", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev CORRECTED interfaces to the REAL deployed staking contracts on chain 2800.
|
||||||
|
*
|
||||||
|
* AereStaking (0xAbDb01d9A4f41792129b2654Fb6DDB9689360DEc) does NOT expose
|
||||||
|
* balanceOf(address). A delegator's stake is stored per (validator, delegator)
|
||||||
|
* in the public `delegations` mapping, so a delegator's TOTAL delegated amount
|
||||||
|
* is the sum over every validator of delegations[validator][delegator].amount.
|
||||||
|
* A user that is itself an active validator also has validators[user].selfStake.
|
||||||
|
* There is no single-argument aggregate getter on the real contract, so we read
|
||||||
|
* the real public getters and aggregate (bounded).
|
||||||
|
*/
|
||||||
|
interface IAereStaking {
|
||||||
|
// public getter for `mapping(address => Validator) public validators`
|
||||||
|
function validators(address v) external view returns (
|
||||||
|
bool active,
|
||||||
|
uint256 selfStake,
|
||||||
|
uint256 totalDelegated,
|
||||||
|
uint256 commissionBps,
|
||||||
|
uint256 lastRewardBlock,
|
||||||
|
uint256 accumulatedRewards
|
||||||
|
);
|
||||||
|
// public getter for `mapping(address => mapping(address => Delegation)) public delegations`
|
||||||
|
function delegations(address validator, address delegator) external view returns (
|
||||||
|
uint256 amount,
|
||||||
|
uint256 stakedAt,
|
||||||
|
uint256 lastClaimBlock
|
||||||
|
);
|
||||||
|
// public getter for `address[] public validatorList`
|
||||||
|
function validatorList(uint256 index) external view returns (address);
|
||||||
|
function validatorCount() external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev CORRECTED getLock field order to match the REAL AereLockedStaking
|
||||||
|
* (0x21108c28A849b05aE6b7a3a5bc435C9Bc897E7Ad), whose Lock struct is:
|
||||||
|
* struct Lock { uint256 amount; uint64 startedAt; uint64 unlockAt; uint8 tier; bool withdrawn; }
|
||||||
|
* getLock returns the struct in THIS order (amount first). The V1 paymaster
|
||||||
|
* declared (uint8 tier, uint256 amount, ...) which mis-decodes the first word
|
||||||
|
* (amount = 1e21) as a uint8, failing the ABI validity check and reverting —
|
||||||
|
* a revert NOT swallowed by the surrounding try/catch, bricking any real locker.
|
||||||
|
*/
|
||||||
|
interface IAereLockedStaking {
|
||||||
|
function lockCount(address user) external view returns (uint256);
|
||||||
|
function getLock(address user, uint256 lockId) external view returns (
|
||||||
|
uint256 amount, uint64 startedAt, uint64 unlockAt, uint8 tier, bool withdrawn
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereStakeQuotaPaymasterV2
|
||||||
|
* @notice Bug-fix redeploy of AereStakeQuotaPaymaster (V1 at
|
||||||
|
* 0xD16C86D792444c2667A26dB62f01b90FC0DaB87b, non-functional).
|
||||||
|
*
|
||||||
|
* "Stake AERE, get free transactions" — Tron's killer UX, brought to EVM.
|
||||||
|
*
|
||||||
|
* Reads the user's effective AERE stake (delegated AereStaking + own validator
|
||||||
|
* self-stake + active AereLockedStaking locks) and allocates a daily free-tx
|
||||||
|
* quota:
|
||||||
|
*
|
||||||
|
* quotaPerDay = stakedAERE * txPerKiloAere / 1000
|
||||||
|
*
|
||||||
|
* stake 1,000 AERE → 20 txs/day (1 free tx per 50 AERE staked, default)
|
||||||
|
* stake 10,000 AERE → 200 txs/day
|
||||||
|
*
|
||||||
|
* Quota resets per UTC day. Unused quota does NOT roll over.
|
||||||
|
*
|
||||||
|
* ── Fixes over V1 ────────────────────────────────────────────────────────
|
||||||
|
* F1 (HIGH): V1 called IAereStaking.balanceOf(address), which does not exist
|
||||||
|
* on the real AereStaking → the delegated read was always caught and
|
||||||
|
* contributed 0. V2 sums the real delegations across validatorList
|
||||||
|
* plus the user's own validator self-stake.
|
||||||
|
* F2 (HIGH): V1's IAereLockedStaking.getLock field order (tier first) did not
|
||||||
|
* match the real struct (amount first) → decoding a real lock hard-
|
||||||
|
* reverted (not swallowed by try/catch), so ANY user with a real lock
|
||||||
|
* could never be sponsored. V2 matches the real field order exactly.
|
||||||
|
* F3 (MED): the lock loop was unbounded. V2 bounds both the validator scan and
|
||||||
|
* the lock scan (MAX_*_SCANNED) so a single UserOp validation cannot
|
||||||
|
* be griefed into out-of-gas.
|
||||||
|
*
|
||||||
|
* Quota logic, per-op gas cap, daily reset and try/catch tolerance are otherwise
|
||||||
|
* identical to V1.
|
||||||
|
*/
|
||||||
|
contract AereStakeQuotaPaymasterV2 is PaymasterBase {
|
||||||
|
IAereStaking public immutable staking;
|
||||||
|
IAereLockedStaking public immutable lockedStaking;
|
||||||
|
|
||||||
|
/// Bound the per-validation loops so validation can never be griefed OOG.
|
||||||
|
uint256 public constant MAX_LOCKS_SCANNED = 100;
|
||||||
|
uint256 public constant MAX_VALIDATORS_SCANNED = 100;
|
||||||
|
|
||||||
|
/// How many sponsored UserOps per 1000 AERE staked, per day.
|
||||||
|
/// Default 20 = 1 free tx per 50 AERE staked. Owner-tunable.
|
||||||
|
uint256 public txPerKiloAerePerDay = 20;
|
||||||
|
|
||||||
|
/// Max gas the paymaster will cover per single UserOp.
|
||||||
|
uint256 public maxSponsoredGasWei = 0.01 ether;
|
||||||
|
|
||||||
|
/// (sender, day) => sponsoredCount
|
||||||
|
mapping(bytes32 => uint256) public usedQuota;
|
||||||
|
|
||||||
|
event Sponsored(address indexed sender, uint256 dayQuota, uint256 used);
|
||||||
|
event ConfigChanged(uint256 txPerKilo, uint256 maxGasWei);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep, IAereStaking _staking, IAereLockedStaking _locked) PaymasterBase(_ep) {
|
||||||
|
staking = _staking;
|
||||||
|
lockedStaking = _locked;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setQuotaParams(uint256 _txPerKilo, uint256 _maxGasWei) external onlyOwner {
|
||||||
|
txPerKiloAerePerDay = _txPerKilo;
|
||||||
|
maxSponsoredGasWei = _maxGasWei;
|
||||||
|
emit ConfigChanged(_txPerKilo, _maxGasWei);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Quota views ─────────────────────
|
||||||
|
|
||||||
|
/// Effective AERE stake of a user =
|
||||||
|
/// delegated (sum over validators) + own validator self-stake + active locks.
|
||||||
|
/// Every external read is wrapped in try/catch so a misbehaving/paused source
|
||||||
|
/// degrades that user's quota to 0 rather than bricking validation. Both loops
|
||||||
|
/// are bounded by MAX_*_SCANNED.
|
||||||
|
function stakedOf(address user) public view returns (uint256 total) {
|
||||||
|
// 1. Own validator self-stake (if the user is an active validator).
|
||||||
|
try staking.validators(user) returns (
|
||||||
|
bool active, uint256 selfStake, uint256, uint256, uint256, uint256
|
||||||
|
) {
|
||||||
|
if (active) total += selfStake;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
// 2. Delegated stake, summed across the validator set (bounded).
|
||||||
|
try staking.validatorCount() returns (uint256 vn) {
|
||||||
|
uint256 vcap = vn < MAX_VALIDATORS_SCANNED ? vn : MAX_VALIDATORS_SCANNED;
|
||||||
|
for (uint256 i = 0; i < vcap; i++) {
|
||||||
|
try staking.validatorList(i) returns (address v) {
|
||||||
|
try staking.delegations(v, user) returns (uint256 amount, uint256, uint256) {
|
||||||
|
total += amount;
|
||||||
|
} catch {}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
// 3. Active locked stake (bounded).
|
||||||
|
try lockedStaking.lockCount(user) returns (uint256 n) {
|
||||||
|
uint256 lcap = n < MAX_LOCKS_SCANNED ? n : MAX_LOCKS_SCANNED;
|
||||||
|
for (uint256 i = 0; i < lcap; i++) {
|
||||||
|
try lockedStaking.getLock(user, i) returns (
|
||||||
|
uint256 amount, uint64 /*startedAt*/, uint64 unlockAt, uint8 /*tier*/, bool withdrawn
|
||||||
|
) {
|
||||||
|
if (!withdrawn && block.timestamp < unlockAt) {
|
||||||
|
total += amount;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dailyQuotaOf(address user) public view returns (uint256) {
|
||||||
|
return (stakedOf(user) * txPerKiloAerePerDay) / 1000 ether;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quotaRemaining(address user) external view returns (uint256 remaining, uint256 dailyQuota) {
|
||||||
|
dailyQuota = dailyQuotaOf(user);
|
||||||
|
uint256 today = block.timestamp / 1 days;
|
||||||
|
bytes32 k = keccak256(abi.encodePacked(user, today));
|
||||||
|
uint256 used = usedQuota[k];
|
||||||
|
remaining = used >= dailyQuota ? 0 : dailyQuota - used;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Paymaster hook ─────────────────────
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /*userOpHash*/,
|
||||||
|
uint256 maxCost
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
require(maxCost <= maxSponsoredGasWei, "StakePM: tx too expensive");
|
||||||
|
|
||||||
|
address sender = userOp.sender;
|
||||||
|
uint256 dailyQuota = dailyQuotaOf(sender);
|
||||||
|
require(dailyQuota > 0, "StakePM: stake more AERE");
|
||||||
|
|
||||||
|
uint256 today = block.timestamp / 1 days;
|
||||||
|
bytes32 k = keccak256(abi.encodePacked(sender, today));
|
||||||
|
uint256 used = usedQuota[k];
|
||||||
|
require(used < dailyQuota, "StakePM: daily quota exhausted");
|
||||||
|
|
||||||
|
usedQuota[k] = used + 1;
|
||||||
|
emit Sponsored(sender, dailyQuota, used + 1);
|
||||||
|
return ("", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereStaking
|
||||||
|
* @notice Delegated stake pool for AERE Network validators
|
||||||
|
* @dev Token holders delegate AERE to validators and earn 8% APY (matches genesis rewardRate).
|
||||||
|
* Validators earn block rewards for producing blocks; a portion is shared with delegators.
|
||||||
|
*
|
||||||
|
* Whitepaper alignment:
|
||||||
|
* - 100k AERE proposal threshold for governance (used elsewhere)
|
||||||
|
* - 7-day voting window
|
||||||
|
* - 5% slashing rate for misbehaving validators
|
||||||
|
* - 500 AERE minimum self-stake (genesis-defined)
|
||||||
|
*/
|
||||||
|
contract AereStaking is Ownable, ReentrancyGuard {
|
||||||
|
uint256 public constant MIN_VALIDATOR_SELF_STAKE = 500 ether; // 500 AERE
|
||||||
|
uint256 public constant MIN_DELEGATION = 1 ether; // 1 AERE
|
||||||
|
uint256 public constant UNBONDING_PERIOD = 7 days;
|
||||||
|
uint256 public constant ANNUAL_REWARD_RATE_BPS = 800; // 8% APY
|
||||||
|
uint256 public constant SLASH_RATE_BPS = 500; // 5%
|
||||||
|
|
||||||
|
struct Validator {
|
||||||
|
bool active;
|
||||||
|
uint256 selfStake;
|
||||||
|
uint256 totalDelegated;
|
||||||
|
uint256 commissionBps; // out of 10000
|
||||||
|
uint256 lastRewardBlock;
|
||||||
|
uint256 accumulatedRewards;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Delegation {
|
||||||
|
uint256 amount;
|
||||||
|
uint256 stakedAt;
|
||||||
|
uint256 lastClaimBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UnbondRequest {
|
||||||
|
uint256 amount;
|
||||||
|
uint256 readyAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(address => Validator) public validators;
|
||||||
|
mapping(address => mapping(address => Delegation)) public delegations; // validator => delegator => stake
|
||||||
|
mapping(address => UnbondRequest[]) public unbondQueue;
|
||||||
|
|
||||||
|
address[] public validatorList;
|
||||||
|
uint256 public totalStaked;
|
||||||
|
|
||||||
|
event ValidatorRegistered(address indexed validator, uint256 selfStake, uint256 commissionBps);
|
||||||
|
event ValidatorDeactivated(address indexed validator);
|
||||||
|
event Delegated(address indexed validator, address indexed delegator, uint256 amount);
|
||||||
|
event UnbondInitiated(address indexed validator, address indexed delegator, uint256 amount, uint256 readyAt);
|
||||||
|
event UnbondClaimed(address indexed delegator, uint256 amount);
|
||||||
|
event RewardsClaimed(address indexed delegator, uint256 amount);
|
||||||
|
event ValidatorSlashed(address indexed validator, uint256 amount, string reason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Register as a validator. Sender deposits self-stake (msg.value).
|
||||||
|
* @param commissionBps Validator's cut of delegator rewards (e.g. 1000 = 10%)
|
||||||
|
*/
|
||||||
|
function registerValidator(uint256 commissionBps) external payable nonReentrant {
|
||||||
|
require(msg.value >= MIN_VALIDATOR_SELF_STAKE, "AereStaking: insufficient self-stake");
|
||||||
|
require(commissionBps <= 5000, "AereStaking: max commission 50%");
|
||||||
|
require(!validators[msg.sender].active, "AereStaking: already registered");
|
||||||
|
|
||||||
|
validators[msg.sender] = Validator({
|
||||||
|
active: true,
|
||||||
|
selfStake: msg.value,
|
||||||
|
totalDelegated: 0,
|
||||||
|
commissionBps: commissionBps,
|
||||||
|
lastRewardBlock: block.number,
|
||||||
|
accumulatedRewards: 0
|
||||||
|
});
|
||||||
|
validatorList.push(msg.sender);
|
||||||
|
totalStaked += msg.value;
|
||||||
|
emit ValidatorRegistered(msg.sender, msg.value, commissionBps);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Delegate AERE to a validator. msg.value is the delegation amount.
|
||||||
|
*/
|
||||||
|
function delegate(address validator) external payable nonReentrant {
|
||||||
|
require(msg.value >= MIN_DELEGATION, "AereStaking: below minimum delegation");
|
||||||
|
require(validators[validator].active, "AereStaking: validator not active");
|
||||||
|
|
||||||
|
Delegation storage d = delegations[validator][msg.sender];
|
||||||
|
if (d.amount == 0) {
|
||||||
|
d.stakedAt = block.timestamp;
|
||||||
|
d.lastClaimBlock = block.number;
|
||||||
|
}
|
||||||
|
d.amount += msg.value;
|
||||||
|
validators[validator].totalDelegated += msg.value;
|
||||||
|
totalStaked += msg.value;
|
||||||
|
emit Delegated(validator, msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Initiate unbonding. Funds release after 7 days.
|
||||||
|
*/
|
||||||
|
function unbond(address validator, uint256 amount) external nonReentrant {
|
||||||
|
Delegation storage d = delegations[validator][msg.sender];
|
||||||
|
require(d.amount >= amount, "AereStaking: insufficient delegation");
|
||||||
|
|
||||||
|
d.amount -= amount;
|
||||||
|
validators[validator].totalDelegated -= amount;
|
||||||
|
totalStaked -= amount;
|
||||||
|
|
||||||
|
unbondQueue[msg.sender].push(UnbondRequest({
|
||||||
|
amount: amount,
|
||||||
|
readyAt: block.timestamp + UNBONDING_PERIOD
|
||||||
|
}));
|
||||||
|
emit UnbondInitiated(validator, msg.sender, amount, block.timestamp + UNBONDING_PERIOD);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Claim all matured unbonding requests.
|
||||||
|
*/
|
||||||
|
function claimUnbonded() external nonReentrant {
|
||||||
|
uint256 total = 0;
|
||||||
|
UnbondRequest[] storage queue = unbondQueue[msg.sender];
|
||||||
|
uint256 i = 0;
|
||||||
|
while (i < queue.length) {
|
||||||
|
if (queue[i].readyAt <= block.timestamp) {
|
||||||
|
total += queue[i].amount;
|
||||||
|
queue[i] = queue[queue.length - 1];
|
||||||
|
queue.pop();
|
||||||
|
} else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(total > 0, "AereStaking: nothing to claim");
|
||||||
|
(bool ok, ) = msg.sender.call{value: total}("");
|
||||||
|
require(ok, "AereStaking: transfer failed");
|
||||||
|
emit UnbondClaimed(msg.sender, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Pending rewards for a delegator (linear approximation: 8% APY).
|
||||||
|
*/
|
||||||
|
function pendingRewards(address validator, address delegator) public view returns (uint256) {
|
||||||
|
Delegation memory d = delegations[validator][delegator];
|
||||||
|
if (d.amount == 0) return 0;
|
||||||
|
uint256 blocksElapsed = block.number - d.lastClaimBlock;
|
||||||
|
// 100ms blocks → 315,360,000 blocks/year. Reward per block = stake * 8% / 315360000.
|
||||||
|
uint256 grossReward = (d.amount * ANNUAL_REWARD_RATE_BPS * blocksElapsed) / (315360000 * 10000);
|
||||||
|
// Subtract validator commission
|
||||||
|
uint256 commission = (grossReward * validators[validator].commissionBps) / 10000;
|
||||||
|
return grossReward - commission;
|
||||||
|
}
|
||||||
|
|
||||||
|
function claimRewards(address validator) external nonReentrant {
|
||||||
|
uint256 reward = pendingRewards(validator, msg.sender);
|
||||||
|
require(reward > 0, "AereStaking: nothing to claim");
|
||||||
|
delegations[validator][msg.sender].lastClaimBlock = block.number;
|
||||||
|
// In production, rewards come from the protocol-level mining supply (2.52B AERE).
|
||||||
|
// Until that's wired up via consensus, this contract must be funded by foundation.
|
||||||
|
require(address(this).balance >= reward, "AereStaking: pool insufficient (needs foundation top-up)");
|
||||||
|
(bool ok, ) = msg.sender.call{value: reward}("");
|
||||||
|
require(ok, "AereStaking: transfer failed");
|
||||||
|
emit RewardsClaimed(msg.sender, reward);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Slash a validator (only callable by AereConsensus or owner).
|
||||||
|
*/
|
||||||
|
function slash(address validator, string calldata reason) external onlyOwner {
|
||||||
|
Validator storage v = validators[validator];
|
||||||
|
require(v.active, "AereStaking: validator not active");
|
||||||
|
uint256 slashAmount = (v.selfStake * SLASH_RATE_BPS) / 10000;
|
||||||
|
v.selfStake -= slashAmount;
|
||||||
|
totalStaked -= slashAmount;
|
||||||
|
if (v.selfStake < MIN_VALIDATOR_SELF_STAKE) {
|
||||||
|
v.active = false;
|
||||||
|
emit ValidatorDeactivated(validator);
|
||||||
|
}
|
||||||
|
emit ValidatorSlashed(validator, slashAmount, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatorCount() external view returns (uint256) {
|
||||||
|
return validatorList.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Allow foundation to seed the reward pool
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSwap — constant-product AMM
|
||||||
|
* @notice Constant-product automated market maker for AERE Network
|
||||||
|
* @dev Implements the x*y=k constant-product invariant, the canonical EVM
|
||||||
|
* pool design. Each pair is its own contract; this factory uses a
|
||||||
|
* simple single-pool design (token0/token1 paired against WAERE).
|
||||||
|
*
|
||||||
|
* Whitepaper alignment:
|
||||||
|
* - "Ultra-High Performance DEX Engine"
|
||||||
|
* - sub-second trade execution (matches AERE 100ms blocks)
|
||||||
|
* - near-zero slippage (governed by liquidity depth, same as any AMM)
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address account) external view returns (uint256);
|
||||||
|
function approve(address spender, uint256 amount) external returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereSwapPair {
|
||||||
|
address public immutable token0;
|
||||||
|
address public immutable token1;
|
||||||
|
address public immutable factory;
|
||||||
|
|
||||||
|
uint112 private reserve0;
|
||||||
|
uint112 private reserve1;
|
||||||
|
uint32 private blockTimestampLast;
|
||||||
|
|
||||||
|
uint256 public constant MINIMUM_LIQUIDITY = 1000;
|
||||||
|
uint256 public totalSupply;
|
||||||
|
mapping(address => uint256) public balanceOf;
|
||||||
|
|
||||||
|
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
|
||||||
|
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
|
||||||
|
event Swap(
|
||||||
|
address indexed sender,
|
||||||
|
uint256 amount0In,
|
||||||
|
uint256 amount1In,
|
||||||
|
uint256 amount0Out,
|
||||||
|
uint256 amount1Out,
|
||||||
|
address indexed to
|
||||||
|
);
|
||||||
|
event Sync(uint112 reserve0, uint112 reserve1);
|
||||||
|
|
||||||
|
constructor(address _token0, address _token1) {
|
||||||
|
token0 = _token0;
|
||||||
|
token1 = _token1;
|
||||||
|
factory = msg.sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getReserves() public view returns (uint112 r0, uint112 r1, uint32 ts) {
|
||||||
|
return (reserve0, reserve1, blockTimestampLast);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _update(uint256 balance0, uint256 balance1) private {
|
||||||
|
require(balance0 <= type(uint112).max && balance1 <= type(uint112).max, "AereSwap: overflow");
|
||||||
|
reserve0 = uint112(balance0);
|
||||||
|
reserve1 = uint112(balance1);
|
||||||
|
blockTimestampLast = uint32(block.timestamp);
|
||||||
|
emit Sync(reserve0, reserve1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Mint LP tokens by depositing both tokens at the current ratio.
|
||||||
|
* @dev Caller must have already transferred tokens to this contract.
|
||||||
|
*/
|
||||||
|
function mint(address to) external returns (uint256 liquidity) {
|
||||||
|
(uint112 _r0, uint112 _r1, ) = getReserves();
|
||||||
|
uint256 balance0 = IERC20(token0).balanceOf(address(this));
|
||||||
|
uint256 balance1 = IERC20(token1).balanceOf(address(this));
|
||||||
|
uint256 amount0 = balance0 - _r0;
|
||||||
|
uint256 amount1 = balance1 - _r1;
|
||||||
|
|
||||||
|
uint256 _totalSupply = totalSupply;
|
||||||
|
if (_totalSupply == 0) {
|
||||||
|
liquidity = _sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
|
||||||
|
balanceOf[address(0)] = MINIMUM_LIQUIDITY;
|
||||||
|
totalSupply += MINIMUM_LIQUIDITY;
|
||||||
|
} else {
|
||||||
|
uint256 a = (amount0 * _totalSupply) / _r0;
|
||||||
|
uint256 b = (amount1 * _totalSupply) / _r1;
|
||||||
|
liquidity = a < b ? a : b;
|
||||||
|
}
|
||||||
|
require(liquidity > 0, "AereSwap: zero liquidity");
|
||||||
|
balanceOf[to] += liquidity;
|
||||||
|
totalSupply += liquidity;
|
||||||
|
_update(balance0, balance1);
|
||||||
|
emit Mint(msg.sender, amount0, amount1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Burn LP tokens, withdraw both tokens.
|
||||||
|
* @dev Caller must have transferred their LP tokens to this contract first.
|
||||||
|
*/
|
||||||
|
function burn(address to) external returns (uint256 amount0, uint256 amount1) {
|
||||||
|
uint256 liquidity = balanceOf[address(this)];
|
||||||
|
uint256 balance0 = IERC20(token0).balanceOf(address(this));
|
||||||
|
uint256 balance1 = IERC20(token1).balanceOf(address(this));
|
||||||
|
uint256 _totalSupply = totalSupply;
|
||||||
|
amount0 = (liquidity * balance0) / _totalSupply;
|
||||||
|
amount1 = (liquidity * balance1) / _totalSupply;
|
||||||
|
require(amount0 > 0 && amount1 > 0, "AereSwap: zero burn output");
|
||||||
|
balanceOf[address(this)] = 0;
|
||||||
|
totalSupply -= liquidity;
|
||||||
|
IERC20(token0).transfer(to, amount0);
|
||||||
|
IERC20(token1).transfer(to, amount1);
|
||||||
|
balance0 = IERC20(token0).balanceOf(address(this));
|
||||||
|
balance1 = IERC20(token1).balanceOf(address(this));
|
||||||
|
_update(balance0, balance1);
|
||||||
|
emit Burn(msg.sender, amount0, amount1, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Swap with constant-product invariant. 0.3% fee retained in pool (LP earns).
|
||||||
|
* @dev Caller must have transferred input tokens to this contract first.
|
||||||
|
*/
|
||||||
|
function swap(uint256 amount0Out, uint256 amount1Out, address to) external {
|
||||||
|
require(amount0Out > 0 || amount1Out > 0, "AereSwap: zero output");
|
||||||
|
(uint112 _r0, uint112 _r1, ) = getReserves();
|
||||||
|
require(amount0Out < _r0 && amount1Out < _r1, "AereSwap: insufficient liquidity");
|
||||||
|
|
||||||
|
if (amount0Out > 0) IERC20(token0).transfer(to, amount0Out);
|
||||||
|
if (amount1Out > 0) IERC20(token1).transfer(to, amount1Out);
|
||||||
|
|
||||||
|
uint256 balance0 = IERC20(token0).balanceOf(address(this));
|
||||||
|
uint256 balance1 = IERC20(token1).balanceOf(address(this));
|
||||||
|
uint256 amount0In = balance0 > _r0 - amount0Out ? balance0 - (_r0 - amount0Out) : 0;
|
||||||
|
uint256 amount1In = balance1 > _r1 - amount1Out ? balance1 - (_r1 - amount1Out) : 0;
|
||||||
|
require(amount0In > 0 || amount1In > 0, "AereSwap: zero input");
|
||||||
|
|
||||||
|
// Fee: 0.3% taken from input. Adjusted balances must satisfy x*y >= k.
|
||||||
|
uint256 balance0Adj = balance0 * 1000 - amount0In * 3;
|
||||||
|
uint256 balance1Adj = balance1 * 1000 - amount1In * 3;
|
||||||
|
require(balance0Adj * balance1Adj >= uint256(_r0) * _r1 * 1_000_000, "AereSwap: K invariant");
|
||||||
|
|
||||||
|
_update(balance0, balance1);
|
||||||
|
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _sqrt(uint256 x) private pure returns (uint256 r) {
|
||||||
|
if (x == 0) return 0;
|
||||||
|
uint256 z = (x + 1) / 2;
|
||||||
|
r = x;
|
||||||
|
while (z < r) { r = z; z = (x / z + z) / 2; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereSwapFactory {
|
||||||
|
address public immutable WAERE;
|
||||||
|
address public feeTo;
|
||||||
|
address public feeToSetter;
|
||||||
|
|
||||||
|
mapping(address => mapping(address => address)) public getPair;
|
||||||
|
address[] public allPairs;
|
||||||
|
|
||||||
|
event PairCreated(address indexed token0, address indexed token1, address pair, uint256 index);
|
||||||
|
|
||||||
|
constructor(address _WAERE, address _feeToSetter) {
|
||||||
|
WAERE = _WAERE;
|
||||||
|
feeToSetter = _feeToSetter;
|
||||||
|
}
|
||||||
|
|
||||||
|
function allPairsLength() external view returns (uint256) {
|
||||||
|
return allPairs.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPair(address tokenA, address tokenB) external returns (address pair) {
|
||||||
|
require(tokenA != tokenB, "AereSwap: identical tokens");
|
||||||
|
(address t0, address t1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
|
||||||
|
require(t0 != address(0), "AereSwap: zero address");
|
||||||
|
require(getPair[t0][t1] == address(0), "AereSwap: pair exists");
|
||||||
|
|
||||||
|
AereSwapPair p = new AereSwapPair(t0, t1);
|
||||||
|
pair = address(p);
|
||||||
|
getPair[t0][t1] = pair;
|
||||||
|
getPair[t1][t0] = pair;
|
||||||
|
allPairs.push(pair);
|
||||||
|
emit PairCreated(t0, t1, pair, allPairs.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFeeTo(address _feeTo) external {
|
||||||
|
require(msg.sender == feeToSetter, "AereSwap: forbidden");
|
||||||
|
feeTo = _feeTo;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSwapRouter
|
||||||
|
* @notice Periphery router for AereSwap constant-product AMM (factory + pairs
|
||||||
|
* already deployed). ABI-compatible with the canonical x*y=k router
|
||||||
|
* interface so existing wallets, aggregators, and SDKs work against
|
||||||
|
* AERE without code changes.
|
||||||
|
* Adds:
|
||||||
|
* - addLiquidity (with deadline + slippage min-amounts)
|
||||||
|
* - addLiquidityAERE (native AERE auto-wraps to WAERE)
|
||||||
|
* - removeLiquidity / removeLiquidityAERE
|
||||||
|
* - swapExactTokensForTokens
|
||||||
|
* - swapExactAEREForTokens / swapExactTokensForAERE (auto-wrap/unwrap)
|
||||||
|
* - quote / getAmountOut / getAmountIn / getAmountsOut / getAmountsIn helpers
|
||||||
|
*
|
||||||
|
* Designed to plug into the already-deployed AereSwapFactory
|
||||||
|
* at 0xf0a8df7BDc25721892475B21271e52D77B0e84DC.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address account) external view returns (uint256);
|
||||||
|
function approve(address spender, uint256 amount) external returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IWAERE {
|
||||||
|
function deposit() external payable;
|
||||||
|
function withdraw(uint256) external;
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereSwapFactory {
|
||||||
|
function getPair(address tokenA, address tokenB) external view returns (address pair);
|
||||||
|
function createPair(address tokenA, address tokenB) external returns (address pair);
|
||||||
|
function WAERE() external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereSwapPair {
|
||||||
|
function token0() external view returns (address);
|
||||||
|
function token1() external view returns (address);
|
||||||
|
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 ts);
|
||||||
|
function mint(address to) external returns (uint256 liquidity);
|
||||||
|
function burn(address to) external returns (uint256 amount0, uint256 amount1);
|
||||||
|
function swap(uint256 amount0Out, uint256 amount1Out, address to) external;
|
||||||
|
function totalSupply() external view returns (uint256);
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereSwapRouter {
|
||||||
|
address public immutable factory;
|
||||||
|
address public immutable WAERE;
|
||||||
|
|
||||||
|
modifier ensure(uint256 deadline) {
|
||||||
|
require(block.timestamp <= deadline, "AereRouter: EXPIRED");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(address _factory, address _WAERE) {
|
||||||
|
factory = _factory;
|
||||||
|
WAERE = _WAERE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow this contract to receive native AERE from WAERE.withdraw().
|
||||||
|
receive() external payable {
|
||||||
|
require(msg.sender == WAERE, "AereRouter: only WAERE");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
// LIQUIDITY
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
function _addLiquidity(
|
||||||
|
address tokenA,
|
||||||
|
address tokenB,
|
||||||
|
uint256 amountADesired,
|
||||||
|
uint256 amountBDesired,
|
||||||
|
uint256 amountAMin,
|
||||||
|
uint256 amountBMin
|
||||||
|
) internal returns (uint256 amountA, uint256 amountB) {
|
||||||
|
if (IAereSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) {
|
||||||
|
IAereSwapFactory(factory).createPair(tokenA, tokenB);
|
||||||
|
}
|
||||||
|
(uint256 rA, uint256 rB) = getReserves(factory, tokenA, tokenB);
|
||||||
|
if (rA == 0 && rB == 0) {
|
||||||
|
(amountA, amountB) = (amountADesired, amountBDesired);
|
||||||
|
} else {
|
||||||
|
uint256 amountBOptimal = quote(amountADesired, rA, rB);
|
||||||
|
if (amountBOptimal <= amountBDesired) {
|
||||||
|
require(amountBOptimal >= amountBMin, "AereRouter: INSUFFICIENT_B_AMOUNT");
|
||||||
|
(amountA, amountB) = (amountADesired, amountBOptimal);
|
||||||
|
} else {
|
||||||
|
uint256 amountAOptimal = quote(amountBDesired, rB, rA);
|
||||||
|
assert(amountAOptimal <= amountADesired);
|
||||||
|
require(amountAOptimal >= amountAMin, "AereRouter: INSUFFICIENT_A_AMOUNT");
|
||||||
|
(amountA, amountB) = (amountAOptimal, amountBDesired);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLiquidity(
|
||||||
|
address tokenA,
|
||||||
|
address tokenB,
|
||||||
|
uint256 amountADesired,
|
||||||
|
uint256 amountBDesired,
|
||||||
|
uint256 amountAMin,
|
||||||
|
uint256 amountBMin,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) external ensure(deadline) returns (uint256 amountA, uint256 amountB, uint256 liquidity) {
|
||||||
|
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
|
||||||
|
address pair = pairFor(factory, tokenA, tokenB);
|
||||||
|
_safeTransferFrom(tokenA, msg.sender, pair, amountA);
|
||||||
|
_safeTransferFrom(tokenB, msg.sender, pair, amountB);
|
||||||
|
liquidity = IAereSwapPair(pair).mint(to);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLiquidityAERE(
|
||||||
|
address token,
|
||||||
|
uint256 amountTokenDesired,
|
||||||
|
uint256 amountTokenMin,
|
||||||
|
uint256 amountAEREMin,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
)
|
||||||
|
external
|
||||||
|
payable
|
||||||
|
ensure(deadline)
|
||||||
|
returns (uint256 amountToken, uint256 amountAERE, uint256 liquidity)
|
||||||
|
{
|
||||||
|
(amountToken, amountAERE) = _addLiquidity(
|
||||||
|
token, WAERE, amountTokenDesired, msg.value, amountTokenMin, amountAEREMin
|
||||||
|
);
|
||||||
|
address pair = pairFor(factory, token, WAERE);
|
||||||
|
_safeTransferFrom(token, msg.sender, pair, amountToken);
|
||||||
|
IWAERE(WAERE).deposit{ value: amountAERE }();
|
||||||
|
require(IWAERE(WAERE).transfer(pair, amountAERE), "AereRouter: WAERE_TRANSFER_FAIL");
|
||||||
|
liquidity = IAereSwapPair(pair).mint(to);
|
||||||
|
// refund any dust
|
||||||
|
if (msg.value > amountAERE) _safeTransferAERE(msg.sender, msg.value - amountAERE);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLiquidity(
|
||||||
|
address tokenA,
|
||||||
|
address tokenB,
|
||||||
|
uint256 liquidity,
|
||||||
|
uint256 amountAMin,
|
||||||
|
uint256 amountBMin,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) public ensure(deadline) returns (uint256 amountA, uint256 amountB) {
|
||||||
|
address pair = pairFor(factory, tokenA, tokenB);
|
||||||
|
require(IAereSwapPair(pair).transferFrom(msg.sender, pair, liquidity), "AereRouter: LP_TRANSFER_FAIL");
|
||||||
|
(uint256 amount0, uint256 amount1) = IAereSwapPair(pair).burn(to);
|
||||||
|
(address t0, ) = sortTokens(tokenA, tokenB);
|
||||||
|
(amountA, amountB) = tokenA == t0 ? (amount0, amount1) : (amount1, amount0);
|
||||||
|
require(amountA >= amountAMin, "AereRouter: INSUFFICIENT_A_AMOUNT");
|
||||||
|
require(amountB >= amountBMin, "AereRouter: INSUFFICIENT_B_AMOUNT");
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLiquidityAERE(
|
||||||
|
address token,
|
||||||
|
uint256 liquidity,
|
||||||
|
uint256 amountTokenMin,
|
||||||
|
uint256 amountAEREMin,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) external ensure(deadline) returns (uint256 amountToken, uint256 amountAERE) {
|
||||||
|
(amountToken, amountAERE) = removeLiquidity(
|
||||||
|
token, WAERE, liquidity, amountTokenMin, amountAEREMin, address(this), deadline
|
||||||
|
);
|
||||||
|
_safeTransfer(token, to, amountToken);
|
||||||
|
IWAERE(WAERE).withdraw(amountAERE);
|
||||||
|
_safeTransferAERE(to, amountAERE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
// SWAPS
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
function _swap(uint256[] memory amounts, address[] memory path, address _to) internal {
|
||||||
|
for (uint256 i = 0; i < path.length - 1; i++) {
|
||||||
|
(address input, address output) = (path[i], path[i + 1]);
|
||||||
|
(address t0, ) = sortTokens(input, output);
|
||||||
|
uint256 amountOut = amounts[i + 1];
|
||||||
|
(uint256 amount0Out, uint256 amount1Out) =
|
||||||
|
input == t0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
|
||||||
|
address to = i < path.length - 2 ? pairFor(factory, output, path[i + 2]) : _to;
|
||||||
|
IAereSwapPair(pairFor(factory, input, output)).swap(amount0Out, amount1Out, to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function swapExactTokensForTokens(
|
||||||
|
uint256 amountIn,
|
||||||
|
uint256 amountOutMin,
|
||||||
|
address[] calldata path,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) external ensure(deadline) returns (uint256[] memory amounts) {
|
||||||
|
amounts = getAmountsOut(factory, amountIn, path);
|
||||||
|
require(amounts[amounts.length - 1] >= amountOutMin, "AereRouter: INSUFFICIENT_OUTPUT_AMOUNT");
|
||||||
|
_safeTransferFrom(path[0], msg.sender, pairFor(factory, path[0], path[1]), amounts[0]);
|
||||||
|
_swap(amounts, path, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
function swapExactAEREForTokens(
|
||||||
|
uint256 amountOutMin,
|
||||||
|
address[] calldata path,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) external payable ensure(deadline) returns (uint256[] memory amounts) {
|
||||||
|
require(path[0] == WAERE, "AereRouter: INVALID_PATH");
|
||||||
|
amounts = getAmountsOut(factory, msg.value, path);
|
||||||
|
require(amounts[amounts.length - 1] >= amountOutMin, "AereRouter: INSUFFICIENT_OUTPUT_AMOUNT");
|
||||||
|
IWAERE(WAERE).deposit{ value: amounts[0] }();
|
||||||
|
require(IWAERE(WAERE).transfer(pairFor(factory, path[0], path[1]), amounts[0]), "AereRouter: WAERE_FAIL");
|
||||||
|
_swap(amounts, path, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
function swapExactTokensForAERE(
|
||||||
|
uint256 amountIn,
|
||||||
|
uint256 amountOutMin,
|
||||||
|
address[] calldata path,
|
||||||
|
address to,
|
||||||
|
uint256 deadline
|
||||||
|
) external ensure(deadline) returns (uint256[] memory amounts) {
|
||||||
|
require(path[path.length - 1] == WAERE, "AereRouter: INVALID_PATH");
|
||||||
|
amounts = getAmountsOut(factory, amountIn, path);
|
||||||
|
require(amounts[amounts.length - 1] >= amountOutMin, "AereRouter: INSUFFICIENT_OUTPUT_AMOUNT");
|
||||||
|
_safeTransferFrom(path[0], msg.sender, pairFor(factory, path[0], path[1]), amounts[0]);
|
||||||
|
_swap(amounts, path, address(this));
|
||||||
|
IWAERE(WAERE).withdraw(amounts[amounts.length - 1]);
|
||||||
|
_safeTransferAERE(to, amounts[amounts.length - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
// LIBRARY (constant-product AMM math, inlined)
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
function sortTokens(address tokenA, address tokenB) public pure returns (address token0, address token1) {
|
||||||
|
require(tokenA != tokenB, "AereRouter: IDENTICAL_ADDRESSES");
|
||||||
|
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
|
||||||
|
require(token0 != address(0), "AereRouter: ZERO_ADDRESS");
|
||||||
|
}
|
||||||
|
|
||||||
|
function pairFor(address _factory, address tokenA, address tokenB) public view returns (address pair) {
|
||||||
|
pair = IAereSwapFactory(_factory).getPair(tokenA, tokenB);
|
||||||
|
require(pair != address(0), "AereRouter: PAIR_NOT_EXISTS");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getReserves(address _factory, address tokenA, address tokenB)
|
||||||
|
public view returns (uint256 reserveA, uint256 reserveB)
|
||||||
|
{
|
||||||
|
(address t0, ) = sortTokens(tokenA, tokenB);
|
||||||
|
(uint112 r0, uint112 r1, ) = IAereSwapPair(pairFor(_factory, tokenA, tokenB)).getReserves();
|
||||||
|
(reserveA, reserveB) = tokenA == t0 ? (uint256(r0), uint256(r1)) : (uint256(r1), uint256(r0));
|
||||||
|
}
|
||||||
|
|
||||||
|
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) public pure returns (uint256 amountB) {
|
||||||
|
require(amountA > 0, "AereRouter: INSUFFICIENT_AMOUNT");
|
||||||
|
require(reserveA > 0 && reserveB > 0, "AereRouter: INSUFFICIENT_LIQUIDITY");
|
||||||
|
amountB = (amountA * reserveB) / reserveA;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0.3% fee — matches AereSwapPair.swap() math (1000-3 = 997 numerator).
|
||||||
|
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public pure returns (uint256 amountOut) {
|
||||||
|
require(amountIn > 0, "AereRouter: INSUFFICIENT_INPUT");
|
||||||
|
require(reserveIn > 0 && reserveOut > 0, "AereRouter: INSUFFICIENT_LIQUIDITY");
|
||||||
|
uint256 amountInWithFee = amountIn * 997;
|
||||||
|
uint256 numerator = amountInWithFee * reserveOut;
|
||||||
|
uint256 denominator = reserveIn * 1000 + amountInWithFee;
|
||||||
|
amountOut = numerator / denominator;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) public pure returns (uint256 amountIn) {
|
||||||
|
require(amountOut > 0, "AereRouter: INSUFFICIENT_OUTPUT");
|
||||||
|
require(reserveIn > 0 && reserveOut > 0, "AereRouter: INSUFFICIENT_LIQUIDITY");
|
||||||
|
uint256 numerator = reserveIn * amountOut * 1000;
|
||||||
|
uint256 denominator = (reserveOut - amountOut) * 997;
|
||||||
|
amountIn = (numerator / denominator) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAmountsOut(address _factory, uint256 amountIn, address[] memory path)
|
||||||
|
public view returns (uint256[] memory amounts)
|
||||||
|
{
|
||||||
|
require(path.length >= 2, "AereRouter: INVALID_PATH");
|
||||||
|
amounts = new uint256[](path.length);
|
||||||
|
amounts[0] = amountIn;
|
||||||
|
for (uint256 i = 0; i < path.length - 1; i++) {
|
||||||
|
(uint256 rI, uint256 rO) = getReserves(_factory, path[i], path[i + 1]);
|
||||||
|
amounts[i + 1] = getAmountOut(amounts[i], rI, rO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAmountsIn(address _factory, uint256 amountOut, address[] memory path)
|
||||||
|
public view returns (uint256[] memory amounts)
|
||||||
|
{
|
||||||
|
require(path.length >= 2, "AereRouter: INVALID_PATH");
|
||||||
|
amounts = new uint256[](path.length);
|
||||||
|
amounts[amounts.length - 1] = amountOut;
|
||||||
|
for (uint256 i = path.length - 1; i > 0; i--) {
|
||||||
|
(uint256 rI, uint256 rO) = getReserves(_factory, path[i - 1], path[i]);
|
||||||
|
amounts[i - 1] = getAmountIn(amounts[i], rI, rO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
// SAFE TRANSFERS
|
||||||
|
// ═════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
function _safeTransfer(address token, address to, uint256 value) private {
|
||||||
|
(bool ok, bytes memory data) =
|
||||||
|
token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
|
||||||
|
require(ok && (data.length == 0 || abi.decode(data, (bool))), "AereRouter: TRANSFER_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function _safeTransferFrom(address token, address from, address to, uint256 value) private {
|
||||||
|
(bool ok, bytes memory data) =
|
||||||
|
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
|
||||||
|
require(ok && (data.length == 0 || abi.decode(data, (bool))), "AereRouter: TRANSFER_FROM_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function _safeTransferAERE(address to, uint256 value) private {
|
||||||
|
(bool ok, ) = to.call{ value: value }("");
|
||||||
|
require(ok, "AereRouter: AERE_TRANSFER_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereToken (governance interface)
|
||||||
|
* @notice Minimal interface for AereGovernance compatibility.
|
||||||
|
*
|
||||||
|
* NOTE: AERE Network's native token is AERE itself (no ERC-20 contract). For
|
||||||
|
* DeFi compatibility we provide WAERE.sol (the wrapped ERC-20). This
|
||||||
|
* contract exists ONLY because AereGovernance.sol was written with an
|
||||||
|
* AereToken type assumption. It serves as the governance-voting-power
|
||||||
|
* proxy and reads circulating supply from WAERE.
|
||||||
|
*
|
||||||
|
* Pass the deployed WAERE address into the constructor; balanceOf(user) and
|
||||||
|
* getCirculatingSupply() are then routed through to WAERE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IWAERE {
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
function totalSupply() external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereToken {
|
||||||
|
IWAERE public immutable waere;
|
||||||
|
|
||||||
|
constructor(address _waere) {
|
||||||
|
waere = IWAERE(_waere);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Voting power = WAERE balance (user must wrap their AERE to vote)
|
||||||
|
function balanceOf(address account) external view returns (uint256) {
|
||||||
|
return waere.balanceOf(account);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Total wrapped AERE in circulation (used for governance quorum calc)
|
||||||
|
function getCirculatingSupply() external view returns (uint256) {
|
||||||
|
return waere.totalSupply();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function approve(address spender, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
function decimals() external view returns (uint8);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereOracle {
|
||||||
|
/// Returns (price scaled 1e8, ts, contributors). Same interface as AereLending used.
|
||||||
|
function getPrice(bytes32 symbol) external view returns (uint128 price, uint64 timestamp, uint256 contributors);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereTokenPaymaster
|
||||||
|
* @notice Pay AERE gas with any whitelisted ERC-20.
|
||||||
|
*
|
||||||
|
* How it works:
|
||||||
|
* 1. User submits a UserOperation with paymasterData = (token, maxTokenCost).
|
||||||
|
* 2. We read the token's USD price from AereOracle and AERE/USD price.
|
||||||
|
* 3. We compute the AERE cost of the op, convert to token, add markup, charge.
|
||||||
|
* 4. We pull tokens from the user via transferFrom (requires prior approve).
|
||||||
|
*
|
||||||
|
* Markup: configurable bps (default 500 = 5%). Markup keeps the paymaster
|
||||||
|
* profitable over time without active management.
|
||||||
|
*
|
||||||
|
* Refunds: if actual gas spent < maxCost, the unused portion is NOT refunded
|
||||||
|
* (gas-saving design; the markup absorbs the difference).
|
||||||
|
*
|
||||||
|
* Foundation pre-funds the paymaster with a small AERE float. The paymaster
|
||||||
|
* accumulates tokens (USDT, USDC, etc.) and the Foundation periodically swaps
|
||||||
|
* them on AereSwap to top up the AERE float.
|
||||||
|
*/
|
||||||
|
contract AereTokenPaymaster is PaymasterBase {
|
||||||
|
IAereOracle public oracle;
|
||||||
|
bytes32 public constant AERE_USD = keccak256("AERE/USD");
|
||||||
|
|
||||||
|
struct TokenConfig {
|
||||||
|
bool enabled;
|
||||||
|
bytes32 priceKey; // e.g. keccak256("USDT/USD") - returned by AereOracle
|
||||||
|
uint8 decimals;
|
||||||
|
}
|
||||||
|
mapping(address => TokenConfig) public tokens;
|
||||||
|
|
||||||
|
/// Markup over fair price, in basis points. 500 = 5%.
|
||||||
|
uint256 public markupBps = 500;
|
||||||
|
|
||||||
|
/// Fallback AERE/USD price (1e8 scale). Used while oracle has no AERE/USD feed.
|
||||||
|
uint256 public fallbackAereUsd1e8 = 10_000_000; // $0.10
|
||||||
|
|
||||||
|
event TokenSet(address indexed token, bool enabled, bytes32 priceKey, uint8 decimals);
|
||||||
|
event ConfigChanged(uint256 markupBps);
|
||||||
|
event Paid(address indexed sender, address indexed token, uint256 tokenAmount);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep, IAereOracle _oracle) PaymasterBase(_ep) {
|
||||||
|
oracle = _oracle;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setToken(address token, bytes32 priceKey, uint8 dec, bool enabled) external onlyOwner {
|
||||||
|
tokens[token] = TokenConfig(enabled, priceKey, dec);
|
||||||
|
emit TokenSet(token, enabled, priceKey, dec);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMarkup(uint256 _markupBps) external onlyOwner {
|
||||||
|
require(_markupBps <= 3000, "TokenPM: markup too high");
|
||||||
|
markupBps = _markupBps;
|
||||||
|
emit ConfigChanged(_markupBps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFallbackAereUsd(uint256 price1e8) external onlyOwner {
|
||||||
|
fallbackAereUsd1e8 = price1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdrawToken(address token, address to, uint256 amount) external onlyOwner {
|
||||||
|
IERC20(token).transferFrom(address(this), to, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Pricing ─────────────────────
|
||||||
|
|
||||||
|
function _aereUsd1e8() internal view returns (uint256) {
|
||||||
|
try oracle.getPrice(AERE_USD) returns (uint128 p, uint64, uint256) {
|
||||||
|
if (p > 0) return uint256(p);
|
||||||
|
} catch {}
|
||||||
|
return fallbackAereUsd1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quoteTokenAmount(address token, uint256 aereWei) public view returns (uint256 tokenAmount) {
|
||||||
|
TokenConfig memory cfg = tokens[token];
|
||||||
|
require(cfg.enabled, "TokenPM: token disabled");
|
||||||
|
(uint128 tokPrice, , ) = oracle.getPrice(cfg.priceKey);
|
||||||
|
require(tokPrice > 0, "TokenPM: oracle missing");
|
||||||
|
// USD value of the AERE: aereWei * AERE/USD (1e8) / 1e18
|
||||||
|
// Token amount = USD / (token/USD * 10^(18 - tokenDecimals))
|
||||||
|
// Combine: tokenAmount = aereWei * aereUsd / tokPrice (both prices share 1e8 scale → cancels)
|
||||||
|
// Adjust to token decimals: result is in 1e18 units of USD-AERE; divide by 10^(18-dec) to get token native units.
|
||||||
|
uint256 usdAmount = (aereWei * _aereUsd1e8()) / 1e8; // 1e18 USD-scaled
|
||||||
|
uint256 amount1e18 = (usdAmount * 1e8) / uint256(tokPrice); // 1e18 token-scaled
|
||||||
|
if (cfg.decimals < 18) {
|
||||||
|
tokenAmount = amount1e18 / (10 ** (18 - cfg.decimals));
|
||||||
|
} else {
|
||||||
|
tokenAmount = amount1e18 * (10 ** (cfg.decimals - 18));
|
||||||
|
}
|
||||||
|
// Apply markup
|
||||||
|
tokenAmount = (tokenAmount * (10_000 + markupBps)) / 10_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Paymaster hook ─────────────────────
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /*userOpHash*/,
|
||||||
|
uint256 maxCost
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
// paymasterAndData layout:
|
||||||
|
// bytes 0..20 - paymaster address
|
||||||
|
// bytes 20..36 - paymaster verification gas limit + post-op gas limit (32 bytes packed)
|
||||||
|
// bytes 52..72 - token address (20 bytes)
|
||||||
|
// bytes 72..104 - maxTokenCost (32 bytes)
|
||||||
|
require(userOp.paymasterAndData.length >= 104, "TokenPM: bad paymasterData");
|
||||||
|
address token = address(bytes20(userOp.paymasterAndData[52:72]));
|
||||||
|
uint256 maxTokenCost = uint256(bytes32(userOp.paymasterAndData[72:104]));
|
||||||
|
|
||||||
|
uint256 tokenCost = quoteTokenAmount(token, maxCost);
|
||||||
|
require(tokenCost <= maxTokenCost, "TokenPM: token cost exceeds max");
|
||||||
|
|
||||||
|
// Pull tokens up-front. User must have pre-approved this contract.
|
||||||
|
require(IERC20(token).transferFrom(userOp.sender, address(this), tokenCost), "TokenPM: pull failed");
|
||||||
|
|
||||||
|
emit Paid(userOp.sender, token, tokenCost);
|
||||||
|
return ("", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "./paymaster/PaymasterBase.sol";
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function approve(address spender, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
function decimals() external view returns (uint8);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereOracle {
|
||||||
|
/// Returns (price scaled 1e8, ts, contributors). Same interface as AereLending used.
|
||||||
|
function getPrice(bytes32 symbol) external view returns (uint128 price, uint64 timestamp, uint256 contributors);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereTokenPaymasterV2
|
||||||
|
* @notice Bug-fix redeploy of AereTokenPaymaster (V1 at
|
||||||
|
* 0xEb6e2Eb24e597C85392DdCD68a1F9b654FffdcB2).
|
||||||
|
*
|
||||||
|
* Pay AERE gas with any whitelisted ERC-20.
|
||||||
|
*
|
||||||
|
* ── Fix over V1 (MEDIUM) ──────────────────────────────────────────────────
|
||||||
|
* V1.withdrawToken used IERC20(token).transferFrom(address(this), to, amount),
|
||||||
|
* which requires the paymaster to hold an ERC-20 allowance for itself. No such
|
||||||
|
* self-allowance is ever set, so on standard (OZ) ERC-20s the call reverts with
|
||||||
|
* "ERC20: insufficient allowance" and every token the paymaster collects as gas
|
||||||
|
* revenue is permanently stuck. V2.withdrawToken uses transfer(to, amount) — the
|
||||||
|
* correct primitive when moving the contract's OWN balance — so the owner
|
||||||
|
* (Foundation) can sweep collected tokens.
|
||||||
|
*
|
||||||
|
* Everything else (oracle pricing, markup, validate hook, token config) is
|
||||||
|
* byte-for-byte identical to V1.
|
||||||
|
*
|
||||||
|
* How it works:
|
||||||
|
* 1. User submits a UserOperation with paymasterData = (token, maxTokenCost).
|
||||||
|
* 2. We read the token's USD price from AereOracle and AERE/USD price.
|
||||||
|
* 3. We compute the AERE cost of the op, convert to token, add markup, charge.
|
||||||
|
* 4. We pull tokens from the user via transferFrom (requires prior approve).
|
||||||
|
*/
|
||||||
|
contract AereTokenPaymasterV2 is PaymasterBase {
|
||||||
|
IAereOracle public oracle;
|
||||||
|
bytes32 public constant AERE_USD = keccak256("AERE/USD");
|
||||||
|
|
||||||
|
struct TokenConfig {
|
||||||
|
bool enabled;
|
||||||
|
bytes32 priceKey; // e.g. keccak256("USDT/USD") - returned by AereOracle
|
||||||
|
uint8 decimals;
|
||||||
|
}
|
||||||
|
mapping(address => TokenConfig) public tokens;
|
||||||
|
|
||||||
|
/// Markup over fair price, in basis points. 500 = 5%.
|
||||||
|
uint256 public markupBps = 500;
|
||||||
|
|
||||||
|
/// Fallback AERE/USD price (1e8 scale). Used while oracle has no AERE/USD feed.
|
||||||
|
uint256 public fallbackAereUsd1e8 = 10_000_000; // $0.10
|
||||||
|
|
||||||
|
event TokenSet(address indexed token, bool enabled, bytes32 priceKey, uint8 decimals);
|
||||||
|
event ConfigChanged(uint256 markupBps);
|
||||||
|
event Paid(address indexed sender, address indexed token, uint256 tokenAmount);
|
||||||
|
event Withdrawn(address indexed token, address indexed to, uint256 amount);
|
||||||
|
|
||||||
|
constructor(IEntryPoint _ep, IAereOracle _oracle) PaymasterBase(_ep) {
|
||||||
|
oracle = _oracle;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setToken(address token, bytes32 priceKey, uint8 dec, bool enabled) external onlyOwner {
|
||||||
|
tokens[token] = TokenConfig(enabled, priceKey, dec);
|
||||||
|
emit TokenSet(token, enabled, priceKey, dec);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMarkup(uint256 _markupBps) external onlyOwner {
|
||||||
|
require(_markupBps <= 3000, "TokenPM: markup too high");
|
||||||
|
markupBps = _markupBps;
|
||||||
|
emit ConfigChanged(_markupBps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFallbackAereUsd(uint256 price1e8) external onlyOwner {
|
||||||
|
fallbackAereUsd1e8 = price1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Sweep collected ERC-20 gas revenue to `to`. FIX: transfer (own
|
||||||
|
/// balance), not transferFrom(address(this)) which V1 used and which
|
||||||
|
/// requires a self-allowance that never exists.
|
||||||
|
function withdrawToken(address token, address to, uint256 amount) external onlyOwner {
|
||||||
|
require(IERC20(token).transfer(to, amount), "TokenPM: withdraw failed");
|
||||||
|
emit Withdrawn(token, to, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Pricing ─────────────────────
|
||||||
|
|
||||||
|
function _aereUsd1e8() internal view returns (uint256) {
|
||||||
|
try oracle.getPrice(AERE_USD) returns (uint128 p, uint64, uint256) {
|
||||||
|
if (p > 0) return uint256(p);
|
||||||
|
} catch {}
|
||||||
|
return fallbackAereUsd1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quoteTokenAmount(address token, uint256 aereWei) public view returns (uint256 tokenAmount) {
|
||||||
|
TokenConfig memory cfg = tokens[token];
|
||||||
|
require(cfg.enabled, "TokenPM: token disabled");
|
||||||
|
(uint128 tokPrice, , ) = oracle.getPrice(cfg.priceKey);
|
||||||
|
require(tokPrice > 0, "TokenPM: oracle missing");
|
||||||
|
// USD value of the AERE: aereWei * AERE/USD (1e8) / 1e18
|
||||||
|
// Token amount = USD / (token/USD * 10^(18 - tokenDecimals))
|
||||||
|
// Combine: tokenAmount = aereWei * aereUsd / tokPrice (both prices share 1e8 scale → cancels)
|
||||||
|
// Adjust to token decimals: result is in 1e18 units of USD-AERE; divide by 10^(18-dec) to get token native units.
|
||||||
|
uint256 usdAmount = (aereWei * _aereUsd1e8()) / 1e8; // 1e18 USD-scaled
|
||||||
|
uint256 amount1e18 = (usdAmount * 1e8) / uint256(tokPrice); // 1e18 token-scaled
|
||||||
|
if (cfg.decimals < 18) {
|
||||||
|
tokenAmount = amount1e18 / (10 ** (18 - cfg.decimals));
|
||||||
|
} else {
|
||||||
|
tokenAmount = amount1e18 * (10 ** (cfg.decimals - 18));
|
||||||
|
}
|
||||||
|
// Apply markup
|
||||||
|
tokenAmount = (tokenAmount * (10_000 + markupBps)) / 10_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Paymaster hook ─────────────────────
|
||||||
|
|
||||||
|
function _validatePaymasterUserOp(
|
||||||
|
PackedUserOperation calldata userOp,
|
||||||
|
bytes32 /*userOpHash*/,
|
||||||
|
uint256 maxCost
|
||||||
|
) internal override returns (bytes memory context, uint256 validationData) {
|
||||||
|
// paymasterAndData layout:
|
||||||
|
// bytes 0..20 - paymaster address
|
||||||
|
// bytes 20..36 - paymaster verification gas limit + post-op gas limit (32 bytes packed)
|
||||||
|
// bytes 52..72 - token address (20 bytes)
|
||||||
|
// bytes 72..104 - maxTokenCost (32 bytes)
|
||||||
|
require(userOp.paymasterAndData.length >= 104, "TokenPM: bad paymasterData");
|
||||||
|
address token = address(bytes20(userOp.paymasterAndData[52:72]));
|
||||||
|
uint256 maxTokenCost = uint256(bytes32(userOp.paymasterAndData[72:104]));
|
||||||
|
|
||||||
|
uint256 tokenCost = quoteTokenAmount(token, maxCost);
|
||||||
|
require(tokenCost <= maxTokenCost, "TokenPM: token cost exceeds max");
|
||||||
|
|
||||||
|
// Pull tokens up-front. User must have pre-approved this contract.
|
||||||
|
require(IERC20(token).transferFrom(userOp.sender, address(this), tokenCost), "TokenPM: pull failed");
|
||||||
|
|
||||||
|
emit Paid(userOp.sender, token, tokenCost);
|
||||||
|
return ("", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereTreasury
|
||||||
|
* @notice DAO treasury for AERE Network. Holds protocol-owned AERE.
|
||||||
|
* @dev Spends are queued by the owner (governance contract post-handover) with a
|
||||||
|
* timelock; anyone can execute after the delay. Provides transparency and
|
||||||
|
* gives the community a window to react to malicious proposals.
|
||||||
|
*/
|
||||||
|
contract AereTreasury is Ownable, ReentrancyGuard {
|
||||||
|
uint256 public constant TIMELOCK = 2 days;
|
||||||
|
|
||||||
|
struct Spend {
|
||||||
|
address to;
|
||||||
|
uint256 amount;
|
||||||
|
uint64 eta;
|
||||||
|
bool executed;
|
||||||
|
bool cancelled;
|
||||||
|
string reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
Spend[] public spends;
|
||||||
|
|
||||||
|
event Funded(address indexed from, uint256 amount);
|
||||||
|
event SpendQueued(uint256 indexed id, address indexed to, uint256 amount, uint64 eta, string reason);
|
||||||
|
event SpendExecuted(uint256 indexed id);
|
||||||
|
event SpendCancelled(uint256 indexed id);
|
||||||
|
|
||||||
|
receive() external payable { emit Funded(msg.sender, msg.value); }
|
||||||
|
|
||||||
|
function queueSpend(address to, uint256 amount, string calldata reason) external onlyOwner returns (uint256 id) {
|
||||||
|
require(to != address(0) && amount > 0, "params");
|
||||||
|
require(amount <= address(this).balance, "insufficient");
|
||||||
|
uint64 eta = uint64(block.timestamp + TIMELOCK);
|
||||||
|
spends.push(Spend({to: to, amount: amount, eta: eta, executed: false, cancelled: false, reason: reason}));
|
||||||
|
id = spends.length - 1;
|
||||||
|
emit SpendQueued(id, to, amount, eta, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
function executeSpend(uint256 id) external nonReentrant {
|
||||||
|
Spend storage s = spends[id];
|
||||||
|
require(!s.executed && !s.cancelled, "done");
|
||||||
|
require(block.timestamp >= s.eta, "timelock");
|
||||||
|
require(address(this).balance >= s.amount, "balance");
|
||||||
|
s.executed = true;
|
||||||
|
(bool ok, ) = s.to.call{value: s.amount}("");
|
||||||
|
require(ok, "transfer");
|
||||||
|
emit SpendExecuted(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelSpend(uint256 id) external onlyOwner {
|
||||||
|
Spend storage s = spends[id];
|
||||||
|
require(!s.executed && !s.cancelled, "done");
|
||||||
|
s.cancelled = true;
|
||||||
|
emit SpendCancelled(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function spendCount() external view returns (uint256) { return spends.length; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereYieldFarm
|
||||||
|
* @notice Stake LP tokens (e.g. AereSwap pair tokens) and earn rewards in native AERE.
|
||||||
|
* @dev Standard MasterChef-style accounting (accRewardPerShare * 1e12).
|
||||||
|
* Reward source: native AERE deposited via fundRewards() by treasury/governance.
|
||||||
|
* Pools are added by the owner; the same staking token can have multiple pools
|
||||||
|
* with different reward rates (e.g. boosted promotions).
|
||||||
|
*/
|
||||||
|
contract AereYieldFarm is Ownable, ReentrancyGuard {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
struct PoolInfo {
|
||||||
|
IERC20 stakeToken;
|
||||||
|
uint256 rewardPerSecond; // in wei AERE
|
||||||
|
uint256 lastRewardTime;
|
||||||
|
uint256 accRewardPerShare; // scaled 1e12
|
||||||
|
uint256 totalStaked;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UserInfo {
|
||||||
|
uint256 amount;
|
||||||
|
uint256 rewardDebt;
|
||||||
|
uint256 pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
PoolInfo[] public pools;
|
||||||
|
mapping(uint256 => mapping(address => UserInfo)) public users;
|
||||||
|
|
||||||
|
event PoolAdded(uint256 indexed pid, address stakeToken, uint256 rewardPerSecond);
|
||||||
|
event PoolRateUpdated(uint256 indexed pid, uint256 rewardPerSecond);
|
||||||
|
event Deposited(uint256 indexed pid, address indexed user, uint256 amount);
|
||||||
|
event Withdrawn(uint256 indexed pid, address indexed user, uint256 amount);
|
||||||
|
event Harvested(uint256 indexed pid, address indexed user, uint256 amount);
|
||||||
|
event RewardsFunded(uint256 amount);
|
||||||
|
|
||||||
|
receive() external payable { emit RewardsFunded(msg.value); }
|
||||||
|
|
||||||
|
function poolCount() external view returns (uint256) { return pools.length; }
|
||||||
|
|
||||||
|
function addPool(address stakeToken, uint256 rewardPerSecond) external onlyOwner returns (uint256 pid) {
|
||||||
|
require(stakeToken != address(0), "token");
|
||||||
|
pools.push(PoolInfo({
|
||||||
|
stakeToken: IERC20(stakeToken),
|
||||||
|
rewardPerSecond: rewardPerSecond,
|
||||||
|
lastRewardTime: block.timestamp,
|
||||||
|
accRewardPerShare: 0,
|
||||||
|
totalStaked: 0
|
||||||
|
}));
|
||||||
|
pid = pools.length - 1;
|
||||||
|
emit PoolAdded(pid, stakeToken, rewardPerSecond);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRewardRate(uint256 pid, uint256 rewardPerSecond) external onlyOwner {
|
||||||
|
_accrue(pid);
|
||||||
|
pools[pid].rewardPerSecond = rewardPerSecond;
|
||||||
|
emit PoolRateUpdated(pid, rewardPerSecond);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fundRewards() external payable { emit RewardsFunded(msg.value); }
|
||||||
|
|
||||||
|
function pendingReward(uint256 pid, address user) external view returns (uint256) {
|
||||||
|
PoolInfo memory p = pools[pid];
|
||||||
|
UserInfo memory u = users[pid][user];
|
||||||
|
uint256 acc = p.accRewardPerShare;
|
||||||
|
if (block.timestamp > p.lastRewardTime && p.totalStaked > 0) {
|
||||||
|
uint256 reward = (block.timestamp - p.lastRewardTime) * p.rewardPerSecond;
|
||||||
|
acc += (reward * 1e12) / p.totalStaked;
|
||||||
|
}
|
||||||
|
return u.pending + (u.amount * acc) / 1e12 - u.rewardDebt;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deposit(uint256 pid, uint256 amount) external nonReentrant {
|
||||||
|
_accrue(pid);
|
||||||
|
PoolInfo storage p = pools[pid];
|
||||||
|
UserInfo storage u = users[pid][msg.sender];
|
||||||
|
if (u.amount > 0) {
|
||||||
|
u.pending += (u.amount * p.accRewardPerShare) / 1e12 - u.rewardDebt;
|
||||||
|
}
|
||||||
|
if (amount > 0) {
|
||||||
|
p.stakeToken.safeTransferFrom(msg.sender, address(this), amount);
|
||||||
|
u.amount += amount;
|
||||||
|
p.totalStaked += amount;
|
||||||
|
}
|
||||||
|
u.rewardDebt = (u.amount * p.accRewardPerShare) / 1e12;
|
||||||
|
emit Deposited(pid, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdraw(uint256 pid, uint256 amount) external nonReentrant {
|
||||||
|
_accrue(pid);
|
||||||
|
PoolInfo storage p = pools[pid];
|
||||||
|
UserInfo storage u = users[pid][msg.sender];
|
||||||
|
require(u.amount >= amount, "balance");
|
||||||
|
u.pending += (u.amount * p.accRewardPerShare) / 1e12 - u.rewardDebt;
|
||||||
|
u.amount -= amount;
|
||||||
|
p.totalStaked -= amount;
|
||||||
|
u.rewardDebt = (u.amount * p.accRewardPerShare) / 1e12;
|
||||||
|
if (amount > 0) p.stakeToken.safeTransfer(msg.sender, amount);
|
||||||
|
emit Withdrawn(pid, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function harvest(uint256 pid) external nonReentrant {
|
||||||
|
_accrue(pid);
|
||||||
|
PoolInfo storage p = pools[pid];
|
||||||
|
UserInfo storage u = users[pid][msg.sender];
|
||||||
|
uint256 reward = u.pending + (u.amount * p.accRewardPerShare) / 1e12 - u.rewardDebt;
|
||||||
|
u.pending = 0;
|
||||||
|
u.rewardDebt = (u.amount * p.accRewardPerShare) / 1e12;
|
||||||
|
require(reward > 0, "nothing");
|
||||||
|
require(address(this).balance >= reward, "underfunded");
|
||||||
|
(bool ok, ) = msg.sender.call{value: reward}("");
|
||||||
|
require(ok, "transfer");
|
||||||
|
emit Harvested(pid, msg.sender, reward);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _accrue(uint256 pid) internal {
|
||||||
|
PoolInfo storage p = pools[pid];
|
||||||
|
if (block.timestamp <= p.lastRewardTime) return;
|
||||||
|
if (p.totalStaked == 0) { p.lastRewardTime = block.timestamp; return; }
|
||||||
|
uint256 reward = (block.timestamp - p.lastRewardTime) * p.rewardPerSecond;
|
||||||
|
p.accRewardPerShare += (reward * 1e12) / p.totalStaked;
|
||||||
|
p.lastRewardTime = block.timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title Wrapped AERE (WAERE)
|
||||||
|
* @notice ERC-20 wrapper for the native AERE token, enabling DeFi compatibility
|
||||||
|
* @dev Mirrors the WETH9 design — deposit native AERE, receive WAERE 1:1
|
||||||
|
*
|
||||||
|
* Native AERE is the gas/value token of AERE Network (Chain ID 2800). Many
|
||||||
|
* DeFi protocols (DEXes, lending, etc.) operate on ERC-20 interfaces and need
|
||||||
|
* a wrapped representation. WAERE provides that.
|
||||||
|
*/
|
||||||
|
contract WAERE {
|
||||||
|
string public constant name = "Wrapped AERE";
|
||||||
|
string public constant symbol = "WAERE";
|
||||||
|
uint8 public constant decimals = 18;
|
||||||
|
|
||||||
|
event Approval(address indexed src, address indexed guy, uint256 wad);
|
||||||
|
event Transfer(address indexed src, address indexed dst, uint256 wad);
|
||||||
|
event Deposit(address indexed dst, uint256 wad);
|
||||||
|
event Withdrawal(address indexed src, uint256 wad);
|
||||||
|
|
||||||
|
mapping(address => uint256) public balanceOf;
|
||||||
|
mapping(address => mapping(address => uint256)) public allowance;
|
||||||
|
|
||||||
|
receive() external payable {
|
||||||
|
deposit();
|
||||||
|
}
|
||||||
|
|
||||||
|
function deposit() public payable {
|
||||||
|
balanceOf[msg.sender] += msg.value;
|
||||||
|
emit Deposit(msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdraw(uint256 wad) external {
|
||||||
|
require(balanceOf[msg.sender] >= wad, "WAERE: insufficient balance");
|
||||||
|
balanceOf[msg.sender] -= wad;
|
||||||
|
(bool ok, ) = msg.sender.call{value: wad}("");
|
||||||
|
require(ok, "WAERE: AERE transfer failed");
|
||||||
|
emit Withdrawal(msg.sender, wad);
|
||||||
|
}
|
||||||
|
|
||||||
|
function totalSupply() external view returns (uint256) {
|
||||||
|
return address(this).balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
function approve(address guy, uint256 wad) external returns (bool) {
|
||||||
|
allowance[msg.sender][guy] = wad;
|
||||||
|
emit Approval(msg.sender, guy, wad);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function transfer(address dst, uint256 wad) external returns (bool) {
|
||||||
|
return transferFrom(msg.sender, dst, wad);
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferFrom(address src, address dst, uint256 wad) public returns (bool) {
|
||||||
|
require(balanceOf[src] >= wad, "WAERE: insufficient balance");
|
||||||
|
if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
|
||||||
|
require(allowance[src][msg.sender] >= wad, "WAERE: insufficient allowance");
|
||||||
|
allowance[src][msg.sender] -= wad;
|
||||||
|
}
|
||||||
|
balanceOf[src] -= wad;
|
||||||
|
balanceOf[dst] += wad;
|
||||||
|
emit Transfer(src, dst, wad);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
interface IAereAgent {
|
||||||
|
function debit(uint256 agentId, address token, address payee, uint256 amount) external;
|
||||||
|
function signerOf(uint256 agentId) external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereSinkFacilitator {
|
||||||
|
function flush(address token, uint256 amount) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE402Facilitator — HTTP 402 agentic settlement
|
||||||
|
* @notice Service providers (web APIs, MCP servers, agent-to-agent endpoints)
|
||||||
|
* exchange HTTP 402 (Payment Required) for an EIP-712 signed
|
||||||
|
* payment authorisation from an AereAgent. The provider then
|
||||||
|
* submits the authorisation to this contract; the facilitator
|
||||||
|
* debits the agent's prepaid balance (via the AereAgent registry),
|
||||||
|
* credits the provider, and routes a 25-bps protocol fee to
|
||||||
|
* AereSink (the flywheel).
|
||||||
|
*
|
||||||
|
* CORE FLOW per call:
|
||||||
|
* 1. Provider responds to a request with HTTP 402 +
|
||||||
|
* X-AERE402-Quote: { facilitator, token, amount, resourceId,
|
||||||
|
* providerAddress, nonce, deadline }.
|
||||||
|
* 2. Agent signs the authorisation (EIP-712 typed data) using
|
||||||
|
* its registered signer key.
|
||||||
|
* 3. Agent retries the request with X-AERE402-Sig: <hex>.
|
||||||
|
* 4. Provider POSTs the (auth + signature) to this contract via
|
||||||
|
* `settle(...)`. The facilitator:
|
||||||
|
* a. Validates signature against AereAgent.signerOf(agentId).
|
||||||
|
* b. Checks nonce hasn't been spent + deadline.
|
||||||
|
* c. Splits amount: (amount - fee) → provider, fee → sink.
|
||||||
|
* d. Calls AereAgent.debit(agentId, token, address(this), amount).
|
||||||
|
* e. Forwards the splits in one tx.
|
||||||
|
* 5. Provider serves the response now that settlement is final.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - AereAgent address fixed in constructor.
|
||||||
|
* - SINK address fixed.
|
||||||
|
* - 25-bps fee constant.
|
||||||
|
* - DOMAIN_SEPARATOR pinned.
|
||||||
|
*
|
||||||
|
* REPLAY-PROTECTION:
|
||||||
|
* - Per-(agentId, nonce) bitmap of consumed nonces.
|
||||||
|
* - Provider chooses nonces; convention: monotonic per provider-
|
||||||
|
* agent pair.
|
||||||
|
*/
|
||||||
|
contract AERE402Facilitator is ReentrancyGuard {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
/* ------------------------------- immutable ------------------------------- */
|
||||||
|
|
||||||
|
address public immutable AGENT_REGISTRY;
|
||||||
|
address public immutable SINK;
|
||||||
|
uint16 public constant PROTOCOL_FEE_BPS = 25; // 0.25%
|
||||||
|
|
||||||
|
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||||
|
bytes32 public constant AUTH_TYPEHASH = keccak256(
|
||||||
|
"PaymentAuth(uint256 agentId,address token,address payee,uint256 amount,bytes32 resourceId,uint256 nonce,uint256 deadline)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- state -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice agentId → nonce → consumed
|
||||||
|
mapping(uint256 => mapping(uint256 => bool)) public consumed;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event Settled(
|
||||||
|
uint256 indexed agentId,
|
||||||
|
address indexed payee,
|
||||||
|
address indexed token,
|
||||||
|
uint256 amount,
|
||||||
|
uint256 protocolFee,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 nonce
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error InvalidSignature();
|
||||||
|
error NonceAlreadyConsumed();
|
||||||
|
error DeadlinePassed();
|
||||||
|
error PayeeMismatch();
|
||||||
|
error ZeroAmount();
|
||||||
|
error TransferFailed();
|
||||||
|
error SelfDealForbidden(); // payee == agent's signer key
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
constructor(address agentRegistry, address sink) {
|
||||||
|
if (agentRegistry == address(0) || sink == address(0)) revert ZeroAddress();
|
||||||
|
AGENT_REGISTRY = agentRegistry;
|
||||||
|
SINK = sink;
|
||||||
|
DOMAIN_SEPARATOR = keccak256(abi.encode(
|
||||||
|
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
|
||||||
|
keccak256("AERE402Facilitator"),
|
||||||
|
keccak256("1"),
|
||||||
|
block.chainid,
|
||||||
|
address(this)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- settle ------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Provider settles a payment auth from an agent.
|
||||||
|
/// @dev msg.sender MUST equal the `payee` in the auth; this prevents
|
||||||
|
/// a third party from replaying someone else's auth toward an
|
||||||
|
/// attacker-controlled payee even if the agent's signature leaks.
|
||||||
|
function settle(
|
||||||
|
uint256 agentId,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 nonce,
|
||||||
|
uint256 deadline,
|
||||||
|
bytes calldata signature
|
||||||
|
) external nonReentrant {
|
||||||
|
if (block.timestamp > deadline) revert DeadlinePassed();
|
||||||
|
if (msg.sender != payee) revert PayeeMismatch();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (consumed[agentId][nonce]) revert NonceAlreadyConsumed();
|
||||||
|
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
AUTH_TYPEHASH,
|
||||||
|
agentId,
|
||||||
|
token,
|
||||||
|
payee,
|
||||||
|
amount,
|
||||||
|
resourceId,
|
||||||
|
nonce,
|
||||||
|
deadline
|
||||||
|
));
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
address signer = digest.recover(signature);
|
||||||
|
address expected = IAereAgent(AGENT_REGISTRY).signerOf(agentId);
|
||||||
|
if (signer == address(0) || signer != expected) revert InvalidSignature();
|
||||||
|
|
||||||
|
// Block self-deal: a compromised signer key cannot drain the agent
|
||||||
|
// balance by paying itself. The signer MUST sign a payment to a
|
||||||
|
// different address — typically an actual service provider.
|
||||||
|
if (payee == expected) revert SelfDealForbidden();
|
||||||
|
|
||||||
|
consumed[agentId][nonce] = true;
|
||||||
|
|
||||||
|
// Pull the full amount from the agent via the registry. The registry
|
||||||
|
// sends the AERE to address(this) (the facilitator); we then split
|
||||||
|
// into payee + sink.
|
||||||
|
IAereAgent(AGENT_REGISTRY).debit(agentId, token, address(this), amount);
|
||||||
|
|
||||||
|
uint256 fee = (amount * PROTOCOL_FEE_BPS) / 10_000;
|
||||||
|
uint256 toPayee = amount - fee;
|
||||||
|
|
||||||
|
if (toPayee > 0) {
|
||||||
|
bool ok = IERC20(token).transfer(payee, toPayee);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
}
|
||||||
|
if (fee > 0) {
|
||||||
|
// Forward to sink for flywheel; if the sink doesn't accept,
|
||||||
|
// the fee stays in the facilitator as residual (sweepable).
|
||||||
|
// ROUND-3 FIX: zero-then-set approve (USDT-style tokens revert
|
||||||
|
// on non-zero→non-zero); also re-zero after the call so no
|
||||||
|
// lingering allowance survives a silent sink failure.
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
IERC20(token).approve(SINK, fee);
|
||||||
|
(bool sinkOk, ) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", token, fee));
|
||||||
|
sinkOk; // intentional: don't gate user flow on sink success
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit Settled(agentId, payee, token, amount, fee, resourceId, nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- residual flush -------------------------- */
|
||||||
|
|
||||||
|
/// @notice Anyone can re-attempt the sink flush for a residual balance.
|
||||||
|
function flushResidual(address token, uint256 amount) external nonReentrant {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
IERC20(token).approve(SINK, amount);
|
||||||
|
(bool ok, ) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", token, amount));
|
||||||
|
if (!ok) {
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
revert TransferFailed();
|
||||||
|
}
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
|
||||||
|
/// @dev The AereAgentDID surface this facilitator consumes. The DID is the single
|
||||||
|
/// authorization oracle: one call to `authorize` enforces the Falcon ROOT
|
||||||
|
/// lifecycle, the session scope, the cumulative spend cap, the secp256k1 session
|
||||||
|
/// signature (ecrecover) and per-session anti-replay, and records the spend, or
|
||||||
|
/// reverts. `getSession` is used only to resolve which agent (Falcon root) funds
|
||||||
|
/// the payment and to guard self-deal. `keyRegistry` lets this contract locate the
|
||||||
|
/// registry so it can read the current key owner (the agent controller).
|
||||||
|
interface IAereAgentDID {
|
||||||
|
function authorize(uint256 sessionId, bytes32 scope, bytes32 actionHash, uint256 amount, bytes calldata sig)
|
||||||
|
external
|
||||||
|
returns (bool);
|
||||||
|
|
||||||
|
function getSession(uint256 sessionId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 rootKeyId,
|
||||||
|
address sessionAddr,
|
||||||
|
bytes32 scopeHash,
|
||||||
|
uint256 spendCap,
|
||||||
|
uint256 spent,
|
||||||
|
uint64 issuedBlock,
|
||||||
|
uint64 expiry,
|
||||||
|
uint64 actionNonce,
|
||||||
|
bool revoked
|
||||||
|
);
|
||||||
|
|
||||||
|
function isSessionValid(uint256 sessionId) external view returns (bool);
|
||||||
|
|
||||||
|
function agentExists(uint256 rootKeyId) external view returns (bool);
|
||||||
|
|
||||||
|
function keyRegistry() external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev The one AerePQCKeyRegistry read this facilitator needs: the current owner of a
|
||||||
|
/// key record. That owner is the agent's controller (the party that proved Falcon
|
||||||
|
/// possession at registration). ownerOf returns the owner for ACTIVE, ROTATED and
|
||||||
|
/// REVOKED records alike, so an operator can always withdraw an agent's idle vault
|
||||||
|
/// even after rotating or revoking its Falcon root; only session-authorized SPENDING
|
||||||
|
/// halts on a rotated/revoked root.
|
||||||
|
interface IAerePQCKeyRegistryLite {
|
||||||
|
function ownerOf(uint256 keyId) external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE402FacilitatorPQC — HTTP 402 agentic settlement rooted in a post-quantum identity
|
||||||
|
*
|
||||||
|
* @notice A settlement facilitator for machine (agent-to-service) payments whose spending
|
||||||
|
* authority is rooted in a quantum-durable Falcon key, not a bare secp256k1 signer.
|
||||||
|
*
|
||||||
|
* WHAT IS DIFFERENT FROM AERE402Facilitator / V2. The classic facilitators debit an
|
||||||
|
* AereAgent registry and authorize each payment with an EIP-712 signature from the
|
||||||
|
* agent's rotatable secp256k1 signer (AereAgent.signerOf). Here the payer is an
|
||||||
|
* AereAgentDID: an agent whose ROOT authority is a Falcon key held in
|
||||||
|
* AerePQCKeyRegistry, and whose day-to-day work is signed by cheap, short-lived,
|
||||||
|
* revocable secp256k1 SESSION keys. A payment is authorized by the agent's DID
|
||||||
|
* SESSION signature, and the whole payment path inherits the DID's guarantees:
|
||||||
|
*
|
||||||
|
* - ROOT LIFECYCLE ENFORCED. A session is valid only while its Falcon root is
|
||||||
|
* still ACTIVE in the registry. Rotating or revoking the Falcon root instantly
|
||||||
|
* halts every downstream payment under it — this facilitator delegates the
|
||||||
|
* check to AereAgentDID.authorize, which fails closed the moment the root is no
|
||||||
|
* longer ACTIVE Falcon. Spending authority lives in the quantum-durable key.
|
||||||
|
* - CHEAP HOT PATH. Per payment, the agent signs a raw secp256k1 signature over
|
||||||
|
* the DID action digest; verification is a single ecrecover (~3k gas). The
|
||||||
|
* Falcon key is a cold, high-value authority that only ever issues sessions; it
|
||||||
|
* is never exposed to the hot payment path.
|
||||||
|
* - PER-SESSION SCOPE + SPEND CAP. Each session is locked to an opaque scope tag
|
||||||
|
* and a cumulative spend cap. This facilitator passes the caller-supplied scope
|
||||||
|
* to the DID (which reverts on a mismatch) and passes the payment amount as the
|
||||||
|
* session spend (which reverts if the cap would be exceeded). A leaked session
|
||||||
|
* key is contained by its scope, cap, expiry and the on-chain revocation list.
|
||||||
|
*
|
||||||
|
* PREPAID VAULT. This contract holds a prepaid balance per (agent, token), keyed by
|
||||||
|
* the agent's Falcon root key id (the DID agent id). Anyone may `topUp` a registered
|
||||||
|
* agent's vault; only the agent's controller (the current registry owner of the root
|
||||||
|
* key) may `withdraw` idle balance or `setPaused`. On `settle`, the debited amount is
|
||||||
|
* split: (amount - fee) to the payee and a 25-bps protocol fee to AereSink (the
|
||||||
|
* flywheel), exactly as the classic facilitators, with the same best-effort flush.
|
||||||
|
*
|
||||||
|
* SETTLE FLOW per call:
|
||||||
|
* 1. Provider answers a request with HTTP 402 + an AERE402-PQC quote
|
||||||
|
* { facilitator, sessionId, scope, token, payee, amount, resourceId, deadline }.
|
||||||
|
* 2. The agent signs the DID action digest for its session with the session key
|
||||||
|
* (raw secp256k1) and returns the signature.
|
||||||
|
* 3. Provider calls settle(...) with the quote + signature. This contract:
|
||||||
|
* a. Checks the payment deadline, msg.sender == payee, amount, self-deal, and
|
||||||
|
* the agent's pause flag.
|
||||||
|
* b. Binds the payment terms into an actionHash committed to THIS facilitator.
|
||||||
|
* c. Delegates authorization to AereAgentDID.authorize — the single call that
|
||||||
|
* enforces root lifecycle + scope + spend cap + session signature +
|
||||||
|
* anti-replay, and records the spend.
|
||||||
|
* d. Debits the agent's prepaid vault and splits amount -> payee + sink.
|
||||||
|
* 4. Provider serves the response now that settlement is final.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer identity + settlement. This does NOT change AERE
|
||||||
|
* consensus (blocks are still Besu QBFT with classical ECDSA). Falcon verification
|
||||||
|
* is performed by AERE's live native precompile through AerePQCKeyRegistry, reached
|
||||||
|
* via the DID. This contract custodies prepaid ERC-20 balances only; it mints no
|
||||||
|
* token and has no owner.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY. AereAgentDID address, AerePQCKeyRegistry address (read from the DID
|
||||||
|
* at construction), SINK address and the 25-bps fee are all pinned. No admin can
|
||||||
|
* move funds, change the fee, or repoint the DID.
|
||||||
|
*/
|
||||||
|
contract AERE402FacilitatorPQC is ReentrancyGuard {
|
||||||
|
/* ------------------------------- immutable ------------------------------- */
|
||||||
|
|
||||||
|
/// @notice The AereAgentDID that roots authorization in a Falcon key and owns the
|
||||||
|
/// session model. The sole authorization oracle for `settle`.
|
||||||
|
IAereAgentDID public immutable DID;
|
||||||
|
|
||||||
|
/// @notice The AerePQCKeyRegistry the DID roots into (read from DID at construction).
|
||||||
|
/// Used only to resolve an agent's current controller (registry key owner).
|
||||||
|
IAerePQCKeyRegistryLite public immutable KEY_REGISTRY;
|
||||||
|
|
||||||
|
/// @notice AereSink (the flywheel) that receives the protocol fee.
|
||||||
|
address public immutable SINK;
|
||||||
|
|
||||||
|
/// @notice 0.25% protocol fee, identical to the classic facilitators.
|
||||||
|
uint16 public constant PROTOCOL_FEE_BPS = 25;
|
||||||
|
|
||||||
|
/// @notice Domain tag binding a payment's terms to THIS facilitator inside the DID
|
||||||
|
/// action commitment. The session key signs the DID action digest over this
|
||||||
|
/// actionHash, so the same session action can never be replayed against a
|
||||||
|
/// different facilitator or with different terms.
|
||||||
|
bytes32 public constant PAYMENT_DOMAIN = keccak256("AERE402FacilitatorPQC.v1.payment");
|
||||||
|
|
||||||
|
/* --------------------------------- state -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice rootKeyId (DID agent id) => token => prepaid balance.
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public balances;
|
||||||
|
|
||||||
|
/// @notice rootKeyId => paused. When true, `settle` reverts for this agent. Controlled
|
||||||
|
/// by the agent's controller as a cheap incident-response switch (independent of,
|
||||||
|
/// and in addition to, per-session revocation and root rotation/revocation).
|
||||||
|
mapping(uint256 => bool) public paused;
|
||||||
|
|
||||||
|
/// @notice token => failed-flush fee residual custodied by this contract but NOT owed to
|
||||||
|
/// any agent vault. It grows ONLY when a `settle` fee flush to the SINK fails
|
||||||
|
/// best-effort (the fee tokens then sit idle here), and shrinks only when
|
||||||
|
/// `flushResidual` successfully forwards them. It is the EXACT and only pool
|
||||||
|
/// `flushResidual` may move; prepaid vault balances are never reachable from it.
|
||||||
|
/// This is what keeps the vault-solvency invariant true:
|
||||||
|
/// tokenBalance(this) >= sum(balances[*][token]) + residual[token].
|
||||||
|
mapping(address => uint256) public residual;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event SettledPQC(
|
||||||
|
uint256 indexed rootKeyId,
|
||||||
|
uint256 indexed sessionId,
|
||||||
|
address indexed payee,
|
||||||
|
address token,
|
||||||
|
uint256 amount,
|
||||||
|
uint256 protocolFee,
|
||||||
|
bytes32 resourceId
|
||||||
|
);
|
||||||
|
event TopUp(uint256 indexed rootKeyId, address indexed token, address indexed funder, uint256 amount);
|
||||||
|
event Withdrawn(uint256 indexed rootKeyId, address indexed token, address indexed recipient, uint256 amount);
|
||||||
|
event PausedSet(uint256 indexed rootKeyId, bool paused, address by);
|
||||||
|
/// @notice A `settle` fee flush to the SINK failed; `amount` of fee is now tracked residual.
|
||||||
|
event ResidualAccrued(address indexed token, uint256 amount);
|
||||||
|
/// @notice `flushResidual` forwarded `amount` of tracked residual to the SINK.
|
||||||
|
event ResidualFlushed(address indexed token, address indexed by, uint256 amount);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error ZeroAmount();
|
||||||
|
error DeadlinePassed();
|
||||||
|
error PayeeMismatch();
|
||||||
|
error SelfDealForbidden(); // payee == the session's own key
|
||||||
|
error AgentPaused();
|
||||||
|
error UnknownAgent();
|
||||||
|
error NotController();
|
||||||
|
error SessionAuthFailed(); // DID.authorize did not confirm the payment
|
||||||
|
error InsufficientBalance(uint256 have, uint256 want);
|
||||||
|
error InsufficientResidual(uint256 have, uint256 want); // flushResidual bounded to tracked residual
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
constructor(address did, address sink) {
|
||||||
|
if (did == address(0) || sink == address(0)) revert ZeroAddress();
|
||||||
|
DID = IAereAgentDID(did);
|
||||||
|
address reg = IAereAgentDID(did).keyRegistry();
|
||||||
|
if (reg == address(0)) revert ZeroAddress();
|
||||||
|
KEY_REGISTRY = IAerePQCKeyRegistryLite(reg);
|
||||||
|
SINK = sink;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- funding --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Fund an agent's prepaid vault. Permissionless: anyone may top up a
|
||||||
|
/// registered agent (the operator, a sponsor, a treasury). Pulls `amount` of
|
||||||
|
/// `token` from msg.sender.
|
||||||
|
function topUp(uint256 rootKeyId, address token, uint256 amount) external nonReentrant {
|
||||||
|
if (!DID.agentExists(rootKeyId)) revert UnknownAgent();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (!IERC20(token).transferFrom(msg.sender, address(this), amount)) revert TransferFailed();
|
||||||
|
balances[rootKeyId][token] += amount;
|
||||||
|
emit TopUp(rootKeyId, token, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Withdraw idle vault balance. Only the agent's controller (the current
|
||||||
|
/// registry owner of the Falcon root key) may withdraw. A rotated or revoked
|
||||||
|
/// root does NOT strand funds: the registry still reports the same owner, so
|
||||||
|
/// the operator can always recover the prepaid balance.
|
||||||
|
function withdraw(uint256 rootKeyId, address token, uint256 amount, address recipient) external nonReentrant {
|
||||||
|
if (recipient == address(0)) revert ZeroAddress();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
_requireController(rootKeyId);
|
||||||
|
uint256 bal = balances[rootKeyId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
unchecked {
|
||||||
|
balances[rootKeyId][token] = bal - amount;
|
||||||
|
}
|
||||||
|
if (!IERC20(token).transfer(recipient, amount)) revert TransferFailed();
|
||||||
|
emit Withdrawn(rootKeyId, token, recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Pause or unpause an agent's settlement path. Only the agent's controller.
|
||||||
|
/// A cheap ECDSA incident switch that halts all `settle` calls for this agent
|
||||||
|
/// without touching the DID or the Falcon root.
|
||||||
|
function setPaused(uint256 rootKeyId, bool value) external {
|
||||||
|
_requireController(rootKeyId);
|
||||||
|
paused[rootKeyId] = value;
|
||||||
|
emit PausedSet(rootKeyId, value, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- settle -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Settle a machine payment authorized by an AereAgentDID session.
|
||||||
|
/// @dev msg.sender MUST equal `payee`: a third party cannot redirect a leaked
|
||||||
|
/// session signature to an attacker-controlled payee, and the payee's identity
|
||||||
|
/// is bound into the authorization commitment either way. All session/root
|
||||||
|
/// authorization (root lifecycle, scope, spend cap, secp256k1 session signature,
|
||||||
|
/// anti-replay) is enforced by the single DID.authorize call; this function adds
|
||||||
|
/// the payment-deadline, self-deal, pause and prepaid-balance layers.
|
||||||
|
/// @param sessionId the DID session authorizing the payment.
|
||||||
|
/// @param scope the scope tag for this payment (must equal the session's scopeHash).
|
||||||
|
/// @param token the settlement ERC-20.
|
||||||
|
/// @param payee the service provider being paid (== msg.sender).
|
||||||
|
/// @param amount gross payment (fee is taken from this); charged against the session cap.
|
||||||
|
/// @param resourceId opaque resource tag (e.g. keccak256("GET /v1/inference")).
|
||||||
|
/// @param deadline unix seconds after which the payment auth is stale.
|
||||||
|
/// @param sessionSig 65-byte secp256k1 signature by the session key over the DID action
|
||||||
|
/// digest for (sessionId, scope, paymentActionHash, amount, actionNonce).
|
||||||
|
function settle(
|
||||||
|
uint256 sessionId,
|
||||||
|
bytes32 scope,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 deadline,
|
||||||
|
bytes calldata sessionSig
|
||||||
|
) external nonReentrant {
|
||||||
|
if (block.timestamp > deadline) revert DeadlinePassed();
|
||||||
|
if (msg.sender != payee) revert PayeeMismatch();
|
||||||
|
if (payee == address(0)) revert ZeroAddress();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
|
||||||
|
// Resolve the funding agent (Falcon root) and the session key, for the self-deal
|
||||||
|
// guard and the vault debit. getSession reverts on an unknown session.
|
||||||
|
(uint256 rootKeyId, address sessionAddr,,,,,,,) = DID.getSession(sessionId);
|
||||||
|
|
||||||
|
// A compromised session key cannot drain the agent by paying itself.
|
||||||
|
if (payee == sessionAddr) revert SelfDealForbidden();
|
||||||
|
if (paused[rootKeyId]) revert AgentPaused();
|
||||||
|
|
||||||
|
// Bind the payment terms to THIS facilitator. The session key's signature (checked
|
||||||
|
// inside DID.authorize) is over the DID action digest, which commits to sessionId,
|
||||||
|
// scope, this actionHash, the amount and the session's own actionNonce — so every
|
||||||
|
// term below is authorized and this authorization cannot be replayed elsewhere.
|
||||||
|
bytes32 actionHash = _paymentActionHash(token, payee, resourceId, deadline);
|
||||||
|
|
||||||
|
// The single authorization gate: enforces root lifecycle + scope + spend cap +
|
||||||
|
// session signature + anti-replay, and records the spend, or reverts.
|
||||||
|
bool ok = DID.authorize(sessionId, scope, actionHash, amount, sessionSig);
|
||||||
|
if (!ok) revert SessionAuthFailed();
|
||||||
|
|
||||||
|
// Debit the prepaid vault (keyed by the Falcon root). Checks-effects before any
|
||||||
|
// token transfer; the whole tx (including the DID spend record) reverts if short.
|
||||||
|
uint256 bal = balances[rootKeyId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
unchecked {
|
||||||
|
balances[rootKeyId][token] = bal - amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint256 fee = (amount * PROTOCOL_FEE_BPS) / 10_000;
|
||||||
|
uint256 toPayee = amount - fee;
|
||||||
|
|
||||||
|
if (toPayee > 0) {
|
||||||
|
if (!IERC20(token).transfer(payee, toPayee)) revert TransferFailed();
|
||||||
|
}
|
||||||
|
if (fee > 0) {
|
||||||
|
// Best-effort forward to the sink; never gate the user flow on sink success. On
|
||||||
|
// failure the fee tokens stay idle in this facilitator, so we RECORD them as
|
||||||
|
// tracked residual — the ONLY pool flushResidual is ever allowed to move. Without
|
||||||
|
// this accounting, an unbounded flushResidual could push prepaid vault balances to
|
||||||
|
// the sink and strand user funds; here every token flushResidual can touch is
|
||||||
|
// matched one-for-one by a residual credit, so vault balances stay solvent.
|
||||||
|
if (!_tryFlushToSink(token, fee)) {
|
||||||
|
residual[token] += fee;
|
||||||
|
emit ResidualAccrued(token, fee);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emit SettledPQC(rootKeyId, sessionId, payee, token, amount, fee, resourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- residual flush -------------------------- */
|
||||||
|
|
||||||
|
/// @notice Anyone can re-attempt the sink flush for a FAILED-FLUSH fee residual.
|
||||||
|
/// @dev HARD BOUND: `amount` may not exceed `residual[token]`, the tokens this contract
|
||||||
|
/// holds that are NOT owed to any agent vault. This function can therefore never
|
||||||
|
/// move prepaid vault balances to the sink — the very drain that an unbounded,
|
||||||
|
/// unauthenticated flush would allow. The residual is debited FIRST
|
||||||
|
/// (checks-effects-interactions); a failed re-flush reverts the whole call, so the
|
||||||
|
/// residual is preserved for a later retry.
|
||||||
|
function flushResidual(address token, uint256 amount) external nonReentrant {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
uint256 r = residual[token];
|
||||||
|
if (amount > r) revert InsufficientResidual(r, amount);
|
||||||
|
unchecked {
|
||||||
|
residual[token] = r - amount;
|
||||||
|
}
|
||||||
|
if (!_tryFlushToSink(token, amount)) revert TransferFailed();
|
||||||
|
emit ResidualFlushed(token, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- views --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice The actionHash a session key must commit to (inside the DID action digest)
|
||||||
|
/// to authorize a payment with these exact terms on THIS facilitator. Off-chain
|
||||||
|
/// signers compute this, then sign DID.actionDigest(sessionId, scope, actionHash,
|
||||||
|
/// amount, actionNonce) with the session key.
|
||||||
|
function paymentActionHash(address token, address payee, bytes32 resourceId, uint256 deadline)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return _paymentActionHash(token, payee, resourceId, deadline);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The agent's current controller (registry owner of the Falcon root key), or
|
||||||
|
/// address(0) if the agent does not exist / the key has no owner.
|
||||||
|
function controllerOf(uint256 rootKeyId) public view returns (address) {
|
||||||
|
if (!DID.agentExists(rootKeyId)) return address(0);
|
||||||
|
return KEY_REGISTRY.ownerOf(rootKeyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `account` is the agent's current controller.
|
||||||
|
function isController(uint256 rootKeyId, address account) external view returns (bool) {
|
||||||
|
return account != address(0) && controllerOf(rootKeyId) == account;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience: the DID's live validity for a session (root ACTIVE Falcon,
|
||||||
|
/// not revoked, not expired). A settle for an invalid session always reverts.
|
||||||
|
function isSessionValid(uint256 sessionId) external view returns (bool) {
|
||||||
|
return DID.isSessionValid(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- internal ------------------------------- */
|
||||||
|
|
||||||
|
function _paymentActionHash(address token, address payee, bytes32 resourceId, uint256 deadline)
|
||||||
|
internal
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return keccak256(abi.encode(PAYMENT_DOMAIN, block.chainid, address(this), token, payee, resourceId, deadline));
|
||||||
|
}
|
||||||
|
|
||||||
|
function _requireController(uint256 rootKeyId) internal view {
|
||||||
|
if (!DID.agentExists(rootKeyId)) revert UnknownAgent();
|
||||||
|
address controller = KEY_REGISTRY.ownerOf(rootKeyId);
|
||||||
|
if (controller == address(0) || msg.sender != controller) revert NotController();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Best-effort forward of `amount` of `token` to the SINK via its flush(token,amount)
|
||||||
|
/// surface. Zero-then-set approve (USDT-style tokens revert on non-zero -> non-zero);
|
||||||
|
/// re-zero after so no lingering allowance survives a silent sink failure. Returns
|
||||||
|
/// whether the sink call reported success; callers decide how to account for a miss.
|
||||||
|
function _tryFlushToSink(address token, uint256 amount) internal returns (bool ok) {
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
IERC20(token).approve(SINK, amount);
|
||||||
|
(ok,) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", token, amount));
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
interface IAereAgent {
|
||||||
|
function debit(uint256 agentId, address token, address payee, uint256 amount) external;
|
||||||
|
function signerOf(uint256 agentId) external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IAereSinkFacilitator {
|
||||||
|
function flush(address token, uint256 amount) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AERE402FacilitatorV2 — HTTP 402 agentic settlement (F13 fix)
|
||||||
|
* @notice Bug-fix redeploy of AERE402Facilitator
|
||||||
|
* (0xbA6e6700D629a5E3C885778a42885a944CA84E56).
|
||||||
|
*
|
||||||
|
* FINDING F13 (liveness): V1's replay key was `consumed[agentId][nonce]`
|
||||||
|
* — a SINGLE nonce namespace shared by every provider settling against
|
||||||
|
* an agent. But the documented convention is a "monotonic nonce per
|
||||||
|
* provider-agent pair", so two independent providers naturally pick
|
||||||
|
* overlapping nonce sequences (both start at 1, 2, ...). When provider A
|
||||||
|
* settles (agentId, nonce=1), provider B's fully valid, agent-signed
|
||||||
|
* (agentId, nonce=1) toward a DIFFERENT payee reverts
|
||||||
|
* NonceAlreadyConsumed. No theft — a legitimate settlement is wrongly
|
||||||
|
* blocked (denial of settlement).
|
||||||
|
*
|
||||||
|
* FIX: the replay key is now `consumed[agentId][payee][nonce]`. Each
|
||||||
|
* (agent, payee) pair owns an independent nonce namespace, matching the
|
||||||
|
* per-provider convention. True replay — the SAME (agentId, payee,
|
||||||
|
* nonce) — still reverts NonceAlreadyConsumed, so replay protection is
|
||||||
|
* unchanged in strength; only the false collision across distinct
|
||||||
|
* payees is removed.
|
||||||
|
*
|
||||||
|
* Everything else is byte-for-byte identical to V1: EIP-712 typed data,
|
||||||
|
* signer check via AereAgent.signerOf, msg.sender == payee guard,
|
||||||
|
* self-deal block, 25-bps fee to the sink, and the best-effort sink
|
||||||
|
* flush. The EIP-712 domain `name` is intentionally unchanged
|
||||||
|
* ("AERE402Facilitator") — the new deployment is domain-separated by
|
||||||
|
* its `verifyingContract` address, so existing signer SDKs work by
|
||||||
|
* swapping only the address.
|
||||||
|
*
|
||||||
|
* CROSS-WIRING: AereAgent.debit is gated to the immutable
|
||||||
|
* AERE402_FACILITATOR, so this V2 facilitator is paired with an
|
||||||
|
* AereAgentV2 whose AERE402_FACILITATOR points here. See AereAgentV2.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY: AereAgent (registry) address, SINK, 25-bps fee, and
|
||||||
|
* DOMAIN_SEPARATOR all pinned in the constructor, exactly as V1.
|
||||||
|
*/
|
||||||
|
contract AERE402FacilitatorV2 is ReentrancyGuard {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
/* ------------------------------- immutable ------------------------------- */
|
||||||
|
|
||||||
|
address public immutable AGENT_REGISTRY;
|
||||||
|
address public immutable SINK;
|
||||||
|
uint16 public constant PROTOCOL_FEE_BPS = 25; // 0.25%
|
||||||
|
|
||||||
|
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||||
|
bytes32 public constant AUTH_TYPEHASH = keccak256(
|
||||||
|
"PaymentAuth(uint256 agentId,address token,address payee,uint256 amount,bytes32 resourceId,uint256 nonce,uint256 deadline)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- state -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice F13 FIX: replay key is per (agentId, payee, nonce) — each
|
||||||
|
/// (agent, payee) pair owns an independent nonce namespace.
|
||||||
|
mapping(uint256 => mapping(address => mapping(uint256 => bool))) public consumed;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event Settled(
|
||||||
|
uint256 indexed agentId,
|
||||||
|
address indexed payee,
|
||||||
|
address indexed token,
|
||||||
|
uint256 amount,
|
||||||
|
uint256 protocolFee,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 nonce
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error InvalidSignature();
|
||||||
|
error NonceAlreadyConsumed();
|
||||||
|
error DeadlinePassed();
|
||||||
|
error PayeeMismatch();
|
||||||
|
error ZeroAmount();
|
||||||
|
error TransferFailed();
|
||||||
|
error SelfDealForbidden(); // payee == agent's signer key
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
constructor(address agentRegistry, address sink) {
|
||||||
|
if (agentRegistry == address(0) || sink == address(0)) revert ZeroAddress();
|
||||||
|
AGENT_REGISTRY = agentRegistry;
|
||||||
|
SINK = sink;
|
||||||
|
DOMAIN_SEPARATOR = keccak256(abi.encode(
|
||||||
|
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
|
||||||
|
keccak256("AERE402Facilitator"),
|
||||||
|
keccak256("1"),
|
||||||
|
block.chainid,
|
||||||
|
address(this)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- settle ------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Provider settles a payment auth from an agent.
|
||||||
|
/// @dev msg.sender MUST equal the `payee` in the auth; this prevents a
|
||||||
|
/// third party from replaying someone else's auth toward an
|
||||||
|
/// attacker-controlled payee even if the agent's signature leaks.
|
||||||
|
function settle(
|
||||||
|
uint256 agentId,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 nonce,
|
||||||
|
uint256 deadline,
|
||||||
|
bytes calldata signature
|
||||||
|
) external nonReentrant {
|
||||||
|
if (block.timestamp > deadline) revert DeadlinePassed();
|
||||||
|
if (msg.sender != payee) revert PayeeMismatch();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
// F13 FIX: check the per-(agentId, payee, nonce) namespace.
|
||||||
|
if (consumed[agentId][payee][nonce]) revert NonceAlreadyConsumed();
|
||||||
|
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
AUTH_TYPEHASH,
|
||||||
|
agentId,
|
||||||
|
token,
|
||||||
|
payee,
|
||||||
|
amount,
|
||||||
|
resourceId,
|
||||||
|
nonce,
|
||||||
|
deadline
|
||||||
|
));
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
address signer = digest.recover(signature);
|
||||||
|
address expected = IAereAgent(AGENT_REGISTRY).signerOf(agentId);
|
||||||
|
if (signer == address(0) || signer != expected) revert InvalidSignature();
|
||||||
|
|
||||||
|
// Block self-deal: a compromised signer key cannot drain the agent
|
||||||
|
// balance by paying itself. The signer MUST sign a payment to a
|
||||||
|
// different address — typically an actual service provider.
|
||||||
|
if (payee == expected) revert SelfDealForbidden();
|
||||||
|
|
||||||
|
// F13 FIX: consume the per-(agentId, payee, nonce) slot.
|
||||||
|
consumed[agentId][payee][nonce] = true;
|
||||||
|
|
||||||
|
// Pull the full amount from the agent via the registry. The registry
|
||||||
|
// sends the AERE to address(this) (the facilitator); we then split
|
||||||
|
// into payee + sink.
|
||||||
|
IAereAgent(AGENT_REGISTRY).debit(agentId, token, address(this), amount);
|
||||||
|
|
||||||
|
uint256 fee = (amount * PROTOCOL_FEE_BPS) / 10_000;
|
||||||
|
uint256 toPayee = amount - fee;
|
||||||
|
|
||||||
|
if (toPayee > 0) {
|
||||||
|
bool ok = IERC20(token).transfer(payee, toPayee);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
}
|
||||||
|
if (fee > 0) {
|
||||||
|
// Forward to sink for flywheel; if the sink doesn't accept, the fee
|
||||||
|
// stays in the facilitator as residual (sweepable via flushResidual).
|
||||||
|
// Zero-then-set approve (USDT-style tokens revert on non-zero->non-
|
||||||
|
// zero); re-zero after the call so no lingering allowance survives a
|
||||||
|
// silent sink failure.
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
IERC20(token).approve(SINK, fee);
|
||||||
|
(bool sinkOk, ) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", token, fee));
|
||||||
|
sinkOk; // intentional: don't gate user flow on sink success
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit Settled(agentId, payee, token, amount, fee, resourceId, nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- residual flush -------------------------- */
|
||||||
|
|
||||||
|
/// @notice Anyone can re-attempt the sink flush for a residual balance.
|
||||||
|
function flushResidual(address token, uint256 amount) external nonReentrant {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
IERC20(token).approve(SINK, amount);
|
||||||
|
(bool ok, ) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", token, amount));
|
||||||
|
if (!ok) {
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
revert TransferFailed();
|
||||||
|
}
|
||||||
|
IERC20(token).approve(SINK, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
interface IAereAgentBond {
|
||||||
|
function bondOf(address operator, bytes32 agentId) external view returns (
|
||||||
|
uint256 amount, uint64 requestedAt, uint256 lifetimeSlashed, bool exists
|
||||||
|
);
|
||||||
|
function operatorLifetimeSlashed(address operator) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAIReputation — composable on-chain reputation for agents
|
||||||
|
* @notice Reputation = the sum of signed observations from registered
|
||||||
|
* attestors. An attestor is any party the protocol delegates the
|
||||||
|
* right to score from: the agent's customers (post AERE402 settle),
|
||||||
|
* a third-party model auditor (Cantina/Anthropic), an EAS schema
|
||||||
|
* operator, etc.
|
||||||
|
*
|
||||||
|
* The score is a uint256 — convention: 0 (no history) to 10_000
|
||||||
|
* (perfect, no slashes, many positive attestations). Apps decide
|
||||||
|
* their own cutoffs (e.g. AERE402 require >= 3000 before routing).
|
||||||
|
*
|
||||||
|
* Score formula (kept simple for Phase 1):
|
||||||
|
*
|
||||||
|
* score = positiveCount * 10
|
||||||
|
* - 10 * lifetimeSlashed / SLASH_UNIT
|
||||||
|
* - 20 * disputeCount
|
||||||
|
*
|
||||||
|
* clamped to [0, 10_000]. Apps that need a more sophisticated
|
||||||
|
* curve (decay, recency-weighting, attestor weighting) read the
|
||||||
|
* raw signal counts and compute their own.
|
||||||
|
*
|
||||||
|
* No PII. The agentId is a hash; the attestor identifier is a
|
||||||
|
* registered address; observations include only a hash of the
|
||||||
|
* off-chain evidence + an optional public URI.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - BOND immutable at deploy (the slashable-stake contract whose
|
||||||
|
* lifetimeSlashed feeds the formula).
|
||||||
|
* - SLASH_UNIT constant.
|
||||||
|
* - Registered attestors set at deploy; no admin add post-deploy.
|
||||||
|
* Phase 2 will use a DAO-voted attestor list; Phase 1 starts
|
||||||
|
* with Foundation + a few hand-picked auditors.
|
||||||
|
*/
|
||||||
|
contract AereAIReputation {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
IAereAgentBond public immutable BOND;
|
||||||
|
uint256 public constant MAX_SCORE = 10_000;
|
||||||
|
uint256 public constant SLASH_UNIT = 1e18; // 1 AERE slashed ⇒ -10 score points
|
||||||
|
|
||||||
|
mapping(address => bool) public isAttestor;
|
||||||
|
address[] public attestorList;
|
||||||
|
|
||||||
|
/* ================================= state ================================= */
|
||||||
|
|
||||||
|
struct AgentStats {
|
||||||
|
uint128 positiveCount;
|
||||||
|
uint128 disputeCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice (operator, agentId) → counters fed by attestors.
|
||||||
|
mapping(address => mapping(bytes32 => AgentStats)) internal _stats;
|
||||||
|
|
||||||
|
/// AUDIT FIX (HIGH #20): dedup attestations by evidenceHash per attestor
|
||||||
|
/// to prevent unbounded replay.
|
||||||
|
mapping(address => mapping(bytes32 => bool)) public usedEvidence;
|
||||||
|
|
||||||
|
/* ================================= events ================================= */
|
||||||
|
|
||||||
|
event Attested(
|
||||||
|
address indexed operator,
|
||||||
|
bytes32 indexed agentId,
|
||||||
|
address indexed attestor,
|
||||||
|
int8 delta, // +1 / -1 / 0
|
||||||
|
bytes32 evidenceHash,
|
||||||
|
string evidenceUri
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ================================= errors ================================= */
|
||||||
|
|
||||||
|
error NotAttestor();
|
||||||
|
error InvalidDelta();
|
||||||
|
error EmptyEvidenceHash();
|
||||||
|
error EvidenceReplay();
|
||||||
|
error SelfAttest();
|
||||||
|
|
||||||
|
/* =============================== modifiers ============================== */
|
||||||
|
|
||||||
|
modifier onlyAttestor() {
|
||||||
|
if (!isAttestor[msg.sender]) revert NotAttestor();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== constructor ============================= */
|
||||||
|
|
||||||
|
constructor(IAereAgentBond bond, address[] memory attestors) {
|
||||||
|
require(address(bond) != address(0), "zero-bond");
|
||||||
|
BOND = bond;
|
||||||
|
for (uint256 i = 0; i < attestors.length; i++) {
|
||||||
|
require(attestors[i] != address(0), "zero-attestor");
|
||||||
|
require(!isAttestor[attestors[i]], "dup-attestor");
|
||||||
|
isAttestor[attestors[i]] = true;
|
||||||
|
attestorList.push(attestors[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= write ================================= */
|
||||||
|
|
||||||
|
/// @notice Attestor records an observation. delta ∈ {-1, 0, +1}:
|
||||||
|
/// +1 positive interaction (settlement succeeded as agent
|
||||||
|
/// described; model output matched committed attestation).
|
||||||
|
/// 0 recorded-but-neutral (used for audit-trail without
|
||||||
|
/// score change).
|
||||||
|
/// -1 formal dispute (counted as malus; SEPARATE from a
|
||||||
|
/// slash, which is the bond contract's territory).
|
||||||
|
function attest(
|
||||||
|
address operator,
|
||||||
|
bytes32 agentId,
|
||||||
|
int8 delta,
|
||||||
|
bytes32 evidenceHash,
|
||||||
|
string calldata evidenceUri
|
||||||
|
) external onlyAttestor {
|
||||||
|
if (delta < -1 || delta > 1) revert InvalidDelta();
|
||||||
|
if (evidenceHash == bytes32(0)) revert EmptyEvidenceHash();
|
||||||
|
// AUDIT FIX (HIGH #22): block self-attest (attestor cannot rate
|
||||||
|
// themselves as operator).
|
||||||
|
if (msg.sender == operator) revert SelfAttest();
|
||||||
|
// AUDIT FIX (HIGH #20): dedup by (attestor, evidenceHash) so an
|
||||||
|
// attestor cannot replay the same evidence 1000× for free score.
|
||||||
|
if (usedEvidence[msg.sender][evidenceHash]) revert EvidenceReplay();
|
||||||
|
usedEvidence[msg.sender][evidenceHash] = true;
|
||||||
|
AgentStats storage s = _stats[operator][agentId];
|
||||||
|
if (delta == 1) s.positiveCount += 1;
|
||||||
|
else if (delta == -1) s.disputeCount += 1;
|
||||||
|
emit Attested(operator, agentId, msg.sender, delta, evidenceHash, evidenceUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= views ================================= */
|
||||||
|
|
||||||
|
function statsOf(address operator, bytes32 agentId) external view returns (
|
||||||
|
uint256 positiveCount, uint256 disputeCount, uint256 lifetimeSlashed
|
||||||
|
) {
|
||||||
|
AgentStats storage s = _stats[operator][agentId];
|
||||||
|
( , , uint256 slashed, ) = BOND.bondOf(operator, agentId);
|
||||||
|
return (s.positiveCount, s.disputeCount, slashed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Score formula: positiveCount * 10 - 10 * slashed/SLASH_UNIT
|
||||||
|
/// - 20 * disputeCount. Clamped to [0, 10_000].
|
||||||
|
function scoreOf(address operator, bytes32 agentId) external view returns (uint256) {
|
||||||
|
AgentStats storage s = _stats[operator][agentId];
|
||||||
|
( , , uint256 slashed, ) = BOND.bondOf(operator, agentId);
|
||||||
|
// AUDIT FIX (HIGH #21): roll in operator-level lifetime slash so a
|
||||||
|
// fresh agentId rotation cannot wipe the slash penalty. Apply at
|
||||||
|
// half-weight against the per-agent score so a single bad agent
|
||||||
|
// doesn't permanently destroy a separate clean agent's score —
|
||||||
|
// but the penalty doesn't disappear.
|
||||||
|
uint256 opSlashed = BOND.operatorLifetimeSlashed(operator);
|
||||||
|
uint256 effectiveSlashed = slashed + (opSlashed > slashed ? (opSlashed - slashed) / 2 : 0);
|
||||||
|
|
||||||
|
int256 raw = int256(uint256(s.positiveCount)) * 10
|
||||||
|
- int256(effectiveSlashed / SLASH_UNIT) * 10
|
||||||
|
- int256(uint256(s.disputeCount)) * 20;
|
||||||
|
|
||||||
|
if (raw <= 0) return 0;
|
||||||
|
uint256 r = uint256(raw);
|
||||||
|
return r > MAX_SCORE ? MAX_SCORE : r;
|
||||||
|
}
|
||||||
|
|
||||||
|
function attestors() external view returns (address[] memory) {
|
||||||
|
return attestorList;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAgent — machine-account registry for the agentic economy
|
||||||
|
* @notice Autonomous workers (Claude, GPT, Gemini, bespoke agents) register
|
||||||
|
* an on-chain identity, fund a prepaid balance, and then settle
|
||||||
|
* per-call payments to API providers via the AERE402 facilitator.
|
||||||
|
*
|
||||||
|
* Identity model:
|
||||||
|
* - Each agent has a stable agentId (monotonic uint256).
|
||||||
|
* - Each agent has an OPERATOR address (the human / org running
|
||||||
|
* the agent) and a SIGNING address (the secp256k1 key the
|
||||||
|
* agent uses for EIP-712 payment authorisations). Both are
|
||||||
|
* rotatable by the operator via setSigner / transferOperator.
|
||||||
|
* - Prepaid balance per (agent, settlementToken). Settlement
|
||||||
|
* token is whatever ERC-20 the operator funds (typically
|
||||||
|
* WAERE or USDC.e). Operators top up with `topUp(agentId,
|
||||||
|
* token, amount)` and withdraw idle balance with
|
||||||
|
* `withdraw(agentId, token, amount)`.
|
||||||
|
*
|
||||||
|
* Rate limits:
|
||||||
|
* - per-call cap (uint128, in token units)
|
||||||
|
* - per-hour cap (uint128, in token units)
|
||||||
|
* - per-day cap (uint128, in token units)
|
||||||
|
* Enforced at the AERE402Facilitator (which calls debit() here).
|
||||||
|
*
|
||||||
|
* Pause:
|
||||||
|
* - Operator can pause the agent instantly. Facilitator checks
|
||||||
|
* paused flag before debiting; reverts on a paused agent.
|
||||||
|
*
|
||||||
|
* @dev Only the AERE402_FACILITATOR (immutable, set in constructor)
|
||||||
|
* can call debit(). This makes the facilitator the SOLE
|
||||||
|
* spend-side authority, and lets the operator change keys
|
||||||
|
* without juggling token-level approvals.
|
||||||
|
*/
|
||||||
|
contract AereAgent is ReentrancyGuard {
|
||||||
|
|
||||||
|
/// @notice The only contract that may call debit().
|
||||||
|
address public immutable AERE402_FACILITATOR;
|
||||||
|
|
||||||
|
struct Agent {
|
||||||
|
bool registered;
|
||||||
|
bool paused;
|
||||||
|
address operator; // human / org running the agent (rotatable)
|
||||||
|
address signer; // secp256k1 key that signs payment auths (rotatable)
|
||||||
|
bytes32 passkeyPubX; // optional WebAuthn passkey for additional auth surface
|
||||||
|
bytes32 passkeyPubY;
|
||||||
|
uint128 perCallCap;
|
||||||
|
uint128 perHourCap;
|
||||||
|
uint128 perDayCap;
|
||||||
|
string metadataUri; // ipfs / https with agent description
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice agentId → Agent
|
||||||
|
mapping(uint256 => Agent) public agents;
|
||||||
|
uint256 public nextAgentId;
|
||||||
|
|
||||||
|
/// @notice agentId → token → prepaid balance
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public balances;
|
||||||
|
|
||||||
|
/// @notice agentId → token → (hour epoch, spent in that hour)
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public hourlySpentEpoch;
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public hourlySpent;
|
||||||
|
|
||||||
|
/// @notice agentId → token → (day epoch, spent in that day)
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public dailySpentEpoch;
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public dailySpent;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event AgentRegistered(uint256 indexed agentId, address indexed operator, address indexed signer, string metadataUri);
|
||||||
|
event OperatorTransferred(uint256 indexed agentId, address indexed oldOperator, address indexed newOperator);
|
||||||
|
event SignerSet(uint256 indexed agentId, address indexed newSigner);
|
||||||
|
event PasskeySet(uint256 indexed agentId, bytes32 pubX, bytes32 pubY);
|
||||||
|
event RateLimitsSet(uint256 indexed agentId, uint128 perCallCap, uint128 perHourCap, uint128 perDayCap);
|
||||||
|
event AgentPausedSet(uint256 indexed agentId, bool paused);
|
||||||
|
event MetadataUpdated(uint256 indexed agentId, string metadataUri);
|
||||||
|
event TopUp(uint256 indexed agentId, address indexed token, address indexed funder, uint256 amount);
|
||||||
|
event Withdrawn(uint256 indexed agentId, address indexed token, address indexed recipient, uint256 amount);
|
||||||
|
event Debited(uint256 indexed agentId, address indexed token, address indexed payee, uint256 amount);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error NotOperator();
|
||||||
|
error NotFacilitator();
|
||||||
|
error UnknownAgent();
|
||||||
|
error AgentPausedErr();
|
||||||
|
error InsufficientBalance(uint256 have, uint256 want);
|
||||||
|
error PerCallCapExceeded(uint256 want, uint256 cap);
|
||||||
|
error PerHourCapExceeded(uint256 wouldBe, uint256 cap);
|
||||||
|
error PerDayCapExceeded(uint256 wouldBe, uint256 cap);
|
||||||
|
error ZeroAddress();
|
||||||
|
error ZeroAmount();
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* ------------------------------- modifiers ------------------------------- */
|
||||||
|
|
||||||
|
modifier onlyOperator(uint256 agentId) {
|
||||||
|
Agent storage a = agents[agentId];
|
||||||
|
if (!a.registered) revert UnknownAgent();
|
||||||
|
if (msg.sender != a.operator) revert NotOperator();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
constructor(address facilitator) {
|
||||||
|
if (facilitator == address(0)) revert ZeroAddress();
|
||||||
|
AERE402_FACILITATOR = facilitator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- registration --------------------------- */
|
||||||
|
|
||||||
|
function registerAgent(
|
||||||
|
address signer,
|
||||||
|
bytes32 passkeyPubX,
|
||||||
|
bytes32 passkeyPubY,
|
||||||
|
uint128 perCallCap,
|
||||||
|
uint128 perHourCap,
|
||||||
|
uint128 perDayCap,
|
||||||
|
string calldata metadataUri
|
||||||
|
) external returns (uint256 agentId) {
|
||||||
|
if (signer == address(0)) revert ZeroAddress();
|
||||||
|
agentId = nextAgentId++;
|
||||||
|
agents[agentId] = Agent({
|
||||||
|
registered: true,
|
||||||
|
paused: false,
|
||||||
|
operator: msg.sender,
|
||||||
|
signer: signer,
|
||||||
|
passkeyPubX: passkeyPubX,
|
||||||
|
passkeyPubY: passkeyPubY,
|
||||||
|
perCallCap: perCallCap,
|
||||||
|
perHourCap: perHourCap,
|
||||||
|
perDayCap: perDayCap,
|
||||||
|
metadataUri: metadataUri
|
||||||
|
});
|
||||||
|
emit AgentRegistered(agentId, msg.sender, signer, metadataUri);
|
||||||
|
emit RateLimitsSet(agentId, perCallCap, perHourCap, perDayCap);
|
||||||
|
if (passkeyPubX != bytes32(0) || passkeyPubY != bytes32(0)) {
|
||||||
|
emit PasskeySet(agentId, passkeyPubX, passkeyPubY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferOperator(uint256 agentId, address newOperator) external onlyOperator(agentId) {
|
||||||
|
if (newOperator == address(0)) revert ZeroAddress();
|
||||||
|
address old = agents[agentId].operator;
|
||||||
|
agents[agentId].operator = newOperator;
|
||||||
|
emit OperatorTransferred(agentId, old, newOperator);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSigner(uint256 agentId, address newSigner) external onlyOperator(agentId) {
|
||||||
|
if (newSigner == address(0)) revert ZeroAddress();
|
||||||
|
agents[agentId].signer = newSigner;
|
||||||
|
emit SignerSet(agentId, newSigner);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPasskey(uint256 agentId, bytes32 pubX, bytes32 pubY) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].passkeyPubX = pubX;
|
||||||
|
agents[agentId].passkeyPubY = pubY;
|
||||||
|
emit PasskeySet(agentId, pubX, pubY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRateLimits(uint256 agentId, uint128 perCallCap, uint128 perHourCap, uint128 perDayCap) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].perCallCap = perCallCap;
|
||||||
|
agents[agentId].perHourCap = perHourCap;
|
||||||
|
agents[agentId].perDayCap = perDayCap;
|
||||||
|
emit RateLimitsSet(agentId, perCallCap, perHourCap, perDayCap);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPaused(uint256 agentId, bool paused) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].paused = paused;
|
||||||
|
emit AgentPausedSet(agentId, paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMetadata(uint256 agentId, string calldata metadataUri) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].metadataUri = metadataUri;
|
||||||
|
emit MetadataUpdated(agentId, metadataUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- balance --------------------------------- */
|
||||||
|
|
||||||
|
function topUp(uint256 agentId, address token, uint256 amount) external nonReentrant {
|
||||||
|
if (!agents[agentId].registered) revert UnknownAgent();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
bool ok = IERC20(token).transferFrom(msg.sender, address(this), amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
balances[agentId][token] += amount;
|
||||||
|
emit TopUp(agentId, token, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdraw(uint256 agentId, address token, uint256 amount, address recipient) external onlyOperator(agentId) nonReentrant {
|
||||||
|
if (recipient == address(0)) revert ZeroAddress();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
uint256 bal = balances[agentId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
unchecked { balances[agentId][token] = bal - amount; }
|
||||||
|
bool ok = IERC20(token).transfer(recipient, amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit Withdrawn(agentId, token, recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- debit -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Called by AERE402Facilitator to debit the agent's prepaid
|
||||||
|
/// balance and transfer `amount` of `token` to `payee`.
|
||||||
|
/// Enforces per-call / per-hour / per-day caps + paused.
|
||||||
|
function debit(
|
||||||
|
uint256 agentId,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount
|
||||||
|
) external nonReentrant {
|
||||||
|
if (msg.sender != AERE402_FACILITATOR) revert NotFacilitator();
|
||||||
|
Agent storage a = agents[agentId];
|
||||||
|
if (!a.registered) revert UnknownAgent();
|
||||||
|
if (a.paused) revert AgentPausedErr();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (payee == address(0)) revert ZeroAddress();
|
||||||
|
|
||||||
|
if (a.perCallCap != 0 && amount > a.perCallCap) revert PerCallCapExceeded(amount, a.perCallCap);
|
||||||
|
|
||||||
|
uint256 bal = balances[agentId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
|
||||||
|
uint256 thisHour = block.timestamp / 1 hours;
|
||||||
|
uint256 thisDay = block.timestamp / 1 days;
|
||||||
|
|
||||||
|
uint256 hourSpent = hourlySpentEpoch[agentId][token] == thisHour ? hourlySpent[agentId][token] : 0;
|
||||||
|
uint256 daySpent = dailySpentEpoch[agentId][token] == thisDay ? dailySpent[agentId][token] : 0;
|
||||||
|
|
||||||
|
uint256 newHourSpent = hourSpent + amount;
|
||||||
|
uint256 newDaySpent = daySpent + amount;
|
||||||
|
|
||||||
|
if (a.perHourCap != 0 && newHourSpent > a.perHourCap) revert PerHourCapExceeded(newHourSpent, a.perHourCap);
|
||||||
|
if (a.perDayCap != 0 && newDaySpent > a.perDayCap) revert PerDayCapExceeded(newDaySpent, a.perDayCap);
|
||||||
|
|
||||||
|
unchecked {
|
||||||
|
balances[agentId][token] = bal - amount;
|
||||||
|
hourlySpentEpoch[agentId][token] = thisHour;
|
||||||
|
hourlySpent[agentId][token] = newHourSpent;
|
||||||
|
dailySpentEpoch[agentId][token] = thisDay;
|
||||||
|
dailySpent[agentId][token] = newDaySpent;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ok = IERC20(token).transfer(payee, amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit Debited(agentId, token, payee, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- views -------------------------------- */
|
||||||
|
|
||||||
|
function signerOf(uint256 agentId) external view returns (address) {
|
||||||
|
return agents[agentId].signer;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAgentActionReceipt — PQC-anchored, publicly verifiable AI provenance
|
||||||
|
* (AERE chain 2800)
|
||||||
|
*
|
||||||
|
* @notice An on-chain provenance record for an autonomous/AI agent's output. An
|
||||||
|
* agent commits the HASH of an output (or action) it produced, signed by a
|
||||||
|
* short-lived secp256k1 SESSION key that was itself issued under a
|
||||||
|
* quantum-durable Falcon ROOT via AereAgentDID (proof-of-possession verified
|
||||||
|
* on-chain by AERE's live native PQC precompile). The result is a permanent,
|
||||||
|
* append-only, publicly re-verifiable statement: "agent A produced an output
|
||||||
|
* whose hash is H, authorized by session S under Falcon root A."
|
||||||
|
*
|
||||||
|
* WHY THIS EXISTS. A wallet claiming an AI output is a claim, not a property.
|
||||||
|
* Off-chain "the model said X" is unverifiable and forgeable. A receipt here
|
||||||
|
* binds the output hash to a PQC-rooted identity with a signature ANYONE can
|
||||||
|
* re-check in a single read, and cross-wires it to the agent's live economic
|
||||||
|
* accountability: its AereAgentBond stake and its AereAIReputation score /
|
||||||
|
* slashing history. A verifier learns, from one contract, both "is this
|
||||||
|
* provenance genuine?" and "how much is this agent economically on the hook,
|
||||||
|
* and has it been slashed?".
|
||||||
|
*
|
||||||
|
* QUANTUM DURABILITY. The receipt's authorship chain terminates at a Falcon
|
||||||
|
* root key. The hot session signature is classical secp256k1 (cheap ecrecover),
|
||||||
|
* but a session only exists because a Falcon PoP authorized it in AereAgentDID,
|
||||||
|
* and a session (hence any new receipt under it) stops validating the instant
|
||||||
|
* its Falcon root is rotated or revoked. The commitment hash itself is content
|
||||||
|
* you choose (e.g. a SHA3/Keccak digest of the output), durable by construction.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer provenance + authorization. This does NOT
|
||||||
|
* change AERE consensus (blocks are still Besu QBFT, classical ECDSA). Falcon
|
||||||
|
* verification lives in AereAgentDID / AerePQCKeyRegistry via the live native
|
||||||
|
* precompile, not here. This contract holds no funds and never mutates the DID,
|
||||||
|
* bond, or reputation contracts — it only reads them. Emitting is permissionless
|
||||||
|
* (any relayer may submit): the SESSION SIGNATURE is the sole authority, so the
|
||||||
|
* relayer paying gas is irrelevant to authorship.
|
||||||
|
*
|
||||||
|
* CROSS-WIRE CONVENTION. AereAgentDID keys an agent by its Falcon rootKeyId
|
||||||
|
* (a uint256). AereAgentBond / AereAIReputation key by (operator, bytes32
|
||||||
|
* agentId). This contract reads the economic layer at the canonical key
|
||||||
|
* (operator = the DID controller of the root key, agentId = bytes32(rootKeyId)).
|
||||||
|
* An operator that wants its DID-rooted agent's stake / reputation surfaced
|
||||||
|
* alongside its receipts posts its bond under agentId == bytes32(rootKeyId)
|
||||||
|
* (see {bondKeyOf}). If it does not, the cross-reads simply return zero — the
|
||||||
|
* provenance signature is unaffected and remains fully verifiable.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/// @dev Read-only surface of AereAgentDID used by this contract.
|
||||||
|
interface IAereAgentDID {
|
||||||
|
function getSession(uint256 sessionId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 rootKeyId,
|
||||||
|
address sessionAddr,
|
||||||
|
bytes32 scopeHash,
|
||||||
|
uint256 spendCap,
|
||||||
|
uint256 spent,
|
||||||
|
uint64 issuedBlock,
|
||||||
|
uint64 expiry,
|
||||||
|
uint64 actionNonce,
|
||||||
|
bool revoked
|
||||||
|
);
|
||||||
|
|
||||||
|
function isSessionValid(uint256 sessionId) external view returns (bool);
|
||||||
|
|
||||||
|
function getAgent(uint256 rootKeyId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (address controller, uint64 createdBlock, uint64 sessionNonce, uint256 sessionCountForAgent);
|
||||||
|
|
||||||
|
function agentExists(uint256 rootKeyId) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Read-only surface of AereAgentBond used for economic cross-reads.
|
||||||
|
interface IAereAgentBondView {
|
||||||
|
function bondOf(address operator, bytes32 agentId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (uint256 amount, uint64 requestedAt, uint256 lifetimeSlashed, bool exists);
|
||||||
|
|
||||||
|
function operatorLifetimeSlashed(address operator) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Read-only surface of AereAIReputation used for reputation cross-reads.
|
||||||
|
interface IAereAIReputationView {
|
||||||
|
function scoreOf(address operator, bytes32 agentId) external view returns (uint256);
|
||||||
|
|
||||||
|
function statsOf(address operator, bytes32 agentId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (uint256 positiveCount, uint256 disputeCount, uint256 lifetimeSlashed);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereAgentActionReceipt {
|
||||||
|
// ----- domain separator (distinct from AereAgentDID's ACTION_DOMAIN so a DID
|
||||||
|
// action signature can never be replayed as a provenance receipt) -----
|
||||||
|
bytes32 public constant RECEIPT_DOMAIN = keccak256("AereAgentActionReceipt.v1.receipt");
|
||||||
|
|
||||||
|
// ----- immutable wiring -----
|
||||||
|
IAereAgentDID public immutable did; // Falcon-rooted DID: session verification source of truth
|
||||||
|
address public immutable agentBond; // AereAgentBond (slashable stake) or 0
|
||||||
|
address public immutable aiReputation; // AereAIReputation (composable score) or 0
|
||||||
|
|
||||||
|
// ----- provenance records (global incrementing id; append-only) -----
|
||||||
|
struct Receipt {
|
||||||
|
uint256 agentId; // the Falcon rootKeyId (AereAgentDID agent) that authored this
|
||||||
|
uint256 sessionId; // the DID session that signed it
|
||||||
|
address signer; // the session secp256k1 address recovered at emit time
|
||||||
|
bytes32 outputHash; // the committed hash of the agent's output/action
|
||||||
|
bytes32 scope; // the session scope tag this output was produced under
|
||||||
|
uint64 nonce; // per-session receipt nonce used in the signed digest
|
||||||
|
uint64 emittedBlock;
|
||||||
|
uint64 emittedAt; // unix timestamp
|
||||||
|
bytes sig; // the 65-byte session signature (stored so anyone can re-verify)
|
||||||
|
}
|
||||||
|
|
||||||
|
Receipt[] private _receipts; // receiptId is the index (0-based)
|
||||||
|
mapping(uint256 => uint256[]) private _agentReceipts; // rootKeyId => receiptIds
|
||||||
|
mapping(uint256 => uint256[]) private _sessionReceipts; // sessionId => receiptIds
|
||||||
|
mapping(uint256 => uint64) private _receiptNonce; // sessionId => next receipt nonce
|
||||||
|
|
||||||
|
// ----- events -----
|
||||||
|
event ReceiptEmitted(
|
||||||
|
uint256 indexed receiptId,
|
||||||
|
uint256 indexed agentId,
|
||||||
|
uint256 indexed sessionId,
|
||||||
|
address signer,
|
||||||
|
bytes32 outputHash,
|
||||||
|
bytes32 scope,
|
||||||
|
uint64 nonce
|
||||||
|
);
|
||||||
|
|
||||||
|
// ----- errors -----
|
||||||
|
error ZeroDID();
|
||||||
|
error EmptyOutputHash();
|
||||||
|
error RevokedOrInvalidSession(uint256 sessionId);
|
||||||
|
error ScopeMismatch(uint256 sessionId);
|
||||||
|
error BadSessionSignature(uint256 sessionId);
|
||||||
|
error UnknownReceipt(uint256 receiptId);
|
||||||
|
|
||||||
|
constructor(address did_, address agentBond_, address aiReputation_) {
|
||||||
|
if (did_ == address(0)) revert ZeroDID();
|
||||||
|
did = IAereAgentDID(did_);
|
||||||
|
agentBond = agentBond_;
|
||||||
|
aiReputation = aiReputation_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Emit
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Record a provenance receipt for an agent output. Permissionless relay:
|
||||||
|
* the SESSION SIGNATURE is the authority, not msg.sender.
|
||||||
|
*
|
||||||
|
* Reverts (recording nothing) if the output hash is zero, the session is
|
||||||
|
* not currently valid (revoked / expired / its Falcon root no longer ACTIVE
|
||||||
|
* / unknown session), the scope does not match the session's scope, or the
|
||||||
|
* signature is not by the session key over the exact commitment (which binds
|
||||||
|
* the output hash — a tampered output hash recovers a different address and
|
||||||
|
* is rejected).
|
||||||
|
*
|
||||||
|
* @param sessionId the AereAgentDID session that signs this output.
|
||||||
|
* @param scope the scope tag for this output (must equal the session's scopeHash).
|
||||||
|
* @param outputHash a 32-byte commitment to the agent's output/action (non-zero).
|
||||||
|
* @param sig 65-byte secp256k1 signature (r||s||v) by the session address over
|
||||||
|
* receiptDigest(agentId, sessionId, outputHash, scope, nonce).
|
||||||
|
* @return receiptId the id of the newly recorded receipt.
|
||||||
|
*/
|
||||||
|
function emitReceipt(uint256 sessionId, bytes32 scope, bytes32 outputHash, bytes calldata sig)
|
||||||
|
external
|
||||||
|
returns (uint256 receiptId)
|
||||||
|
{
|
||||||
|
if (outputHash == bytes32(0)) revert EmptyOutputHash();
|
||||||
|
|
||||||
|
// A live session gates everything: revoked / expired / root-not-active / unknown
|
||||||
|
// all collapse to "invalid" here (isSessionValid returns false, never reverts).
|
||||||
|
if (!did.isSessionValid(sessionId)) revert RevokedOrInvalidSession(sessionId);
|
||||||
|
|
||||||
|
(uint256 rootKeyId, address sessionAddr, bytes32 scopeHash,,,,,,) = did.getSession(sessionId);
|
||||||
|
if (scope != scopeHash) revert ScopeMismatch(sessionId);
|
||||||
|
|
||||||
|
uint64 nonce = _receiptNonce[sessionId];
|
||||||
|
bytes32 digest = _receiptDigest(rootKeyId, sessionId, outputHash, scope, nonce);
|
||||||
|
address recovered = _recover(digest, sig);
|
||||||
|
// A tampered outputHash (or wrong signer) recovers a different / null address.
|
||||||
|
if (recovered == address(0) || recovered != sessionAddr) revert BadSessionSignature(sessionId);
|
||||||
|
|
||||||
|
// Effects.
|
||||||
|
_receiptNonce[sessionId] = nonce + 1;
|
||||||
|
receiptId = _receipts.length;
|
||||||
|
_receipts.push(
|
||||||
|
Receipt({
|
||||||
|
agentId: rootKeyId,
|
||||||
|
sessionId: sessionId,
|
||||||
|
signer: sessionAddr,
|
||||||
|
outputHash: outputHash,
|
||||||
|
scope: scope,
|
||||||
|
nonce: nonce,
|
||||||
|
emittedBlock: uint64(block.number),
|
||||||
|
emittedAt: uint64(block.timestamp),
|
||||||
|
sig: sig
|
||||||
|
})
|
||||||
|
);
|
||||||
|
_agentReceipts[rootKeyId].push(receiptId);
|
||||||
|
_sessionReceipts[sessionId].push(receiptId);
|
||||||
|
|
||||||
|
emit ReceiptEmitted(receiptId, rootKeyId, sessionId, sessionAddr, outputHash, scope, nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Verification
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Independently re-verify a stored receipt in one read. Re-derives the
|
||||||
|
* signed digest from the stored fields, recovers the signer from the stored
|
||||||
|
* signature, and reports whether it matches the recorded session key, plus
|
||||||
|
* whether that session is STILL live now (a receipt stays genuine forever;
|
||||||
|
* `sessionLiveNow` tells a consumer whether the agent is currently active or
|
||||||
|
* has since been revoked / expired / rotated away).
|
||||||
|
*
|
||||||
|
* @return sigValid the stored signature genuinely authorizes the stored output.
|
||||||
|
* @return sessionLiveNow the authoring session is valid at the current block.
|
||||||
|
* @return agentId the Falcon rootKeyId that authored the receipt.
|
||||||
|
* @return signer the session address the signature recovers to.
|
||||||
|
* @return outputHash the committed output hash.
|
||||||
|
*/
|
||||||
|
function verifyReceipt(uint256 receiptId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool sigValid, bool sessionLiveNow, uint256 agentId, address signer, bytes32 outputHash)
|
||||||
|
{
|
||||||
|
if (receiptId >= _receipts.length) revert UnknownReceipt(receiptId);
|
||||||
|
Receipt storage r = _receipts[receiptId];
|
||||||
|
bytes32 digest = _receiptDigest(r.agentId, r.sessionId, r.outputHash, r.scope, r.nonce);
|
||||||
|
address recovered = _recover(digest, r.sig);
|
||||||
|
sigValid = (recovered != address(0) && recovered == r.signer);
|
||||||
|
sessionLiveNow = did.isSessionValid(r.sessionId);
|
||||||
|
return (sigValid, sessionLiveNow, r.agentId, r.signer, r.outputHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Verify that a receipt attests EXACTLY `outputHash` and that its stored
|
||||||
|
* signature is genuine. This is the tamper check at read time: pass the hash
|
||||||
|
* of the output you hold; a byte-different output yields a different hash and
|
||||||
|
* returns false. Returns false (never reverts) for an out-of-range receiptId.
|
||||||
|
*/
|
||||||
|
function verifyReceiptOutput(uint256 receiptId, bytes32 outputHash) external view returns (bool) {
|
||||||
|
if (receiptId >= _receipts.length) return false;
|
||||||
|
Receipt storage r = _receipts[receiptId];
|
||||||
|
if (r.outputHash != outputHash) return false;
|
||||||
|
bytes32 digest = _receiptDigest(r.agentId, r.sessionId, r.outputHash, r.scope, r.nonce);
|
||||||
|
address recovered = _recover(digest, r.sig);
|
||||||
|
return (recovered != address(0) && recovered == r.signer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice The full provenance picture in one call: the receipt's identity + validity
|
||||||
|
* AND the agent's live economic accountability, read from AereAgentBond and
|
||||||
|
* AereAIReputation at the canonical cross-wire key (operator = DID controller,
|
||||||
|
* agentId = bytes32(rootKeyId)). All economic reads are defensive: if a
|
||||||
|
* cross-link is unset or reverts, its fields come back zero and the
|
||||||
|
* provenance fields (sigValid / signer / outputHash) are still returned.
|
||||||
|
*
|
||||||
|
* @return agentId the Falcon rootKeyId author.
|
||||||
|
* @return operator the DID controller (bond/reputation key operator).
|
||||||
|
* @return signer the authoring session key.
|
||||||
|
* @return outputHash the committed output hash.
|
||||||
|
* @return scope the scope the output was produced under.
|
||||||
|
* @return emittedAt unix timestamp the receipt was recorded.
|
||||||
|
* @return sigValid the stored signature genuinely authorizes the output.
|
||||||
|
* @return sessionLiveNow the authoring session is valid now.
|
||||||
|
* @return reputationScore AereAIReputation.scoreOf(operator, bytes32(agentId)).
|
||||||
|
* @return bondAmount current AereAgentBond stake at the canonical key.
|
||||||
|
* @return bondLifetimeSlashed cumulative slash on that (operator, agentId) bond.
|
||||||
|
* @return operatorTotalSlashed operator-level cumulative slash across all its agents.
|
||||||
|
*/
|
||||||
|
function provenanceOf(uint256 receiptId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 agentId,
|
||||||
|
address operator,
|
||||||
|
address signer,
|
||||||
|
bytes32 outputHash,
|
||||||
|
bytes32 scope,
|
||||||
|
uint64 emittedAt,
|
||||||
|
bool sigValid,
|
||||||
|
bool sessionLiveNow,
|
||||||
|
uint256 reputationScore,
|
||||||
|
uint256 bondAmount,
|
||||||
|
uint256 bondLifetimeSlashed,
|
||||||
|
uint256 operatorTotalSlashed
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (receiptId >= _receipts.length) revert UnknownReceipt(receiptId);
|
||||||
|
Receipt storage r = _receipts[receiptId];
|
||||||
|
|
||||||
|
agentId = r.agentId;
|
||||||
|
signer = r.signer;
|
||||||
|
outputHash = r.outputHash;
|
||||||
|
scope = r.scope;
|
||||||
|
emittedAt = r.emittedAt;
|
||||||
|
|
||||||
|
bytes32 digest = _receiptDigest(r.agentId, r.sessionId, r.outputHash, r.scope, r.nonce);
|
||||||
|
address recovered = _recover(digest, r.sig);
|
||||||
|
sigValid = (recovered != address(0) && recovered == r.signer);
|
||||||
|
sessionLiveNow = did.isSessionValid(r.sessionId);
|
||||||
|
|
||||||
|
operator = _operatorOf(r.agentId);
|
||||||
|
bytes32 bondKey = bytes32(r.agentId);
|
||||||
|
|
||||||
|
(reputationScore) = _scoreOf(operator, bondKey);
|
||||||
|
(bondAmount, bondLifetimeSlashed) = _bondOf(operator, bondKey);
|
||||||
|
operatorTotalSlashed = _operatorLifetimeSlashed(operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Digest / cross-wire views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice The digest a session key must sign to record a receipt at `nonce`.
|
||||||
|
function receiptDigest(uint256 agentId, uint256 sessionId, bytes32 outputHash, bytes32 scope, uint64 nonce)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return _receiptDigest(agentId, sessionId, outputHash, scope, nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _receiptDigest(uint256 agentId, uint256 sessionId, bytes32 outputHash, bytes32 scope, uint64 nonce)
|
||||||
|
internal
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(RECEIPT_DOMAIN, block.chainid, address(this), agentId, sessionId, outputHash, scope, nonce)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The next receipt nonce for a session (the value the next emit will sign).
|
||||||
|
function receiptNonceOf(uint256 sessionId) external view returns (uint64) {
|
||||||
|
return _receiptNonce[sessionId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The canonical AereAgentBond / AereAIReputation agentId for a DID rootKeyId.
|
||||||
|
/// Operators post their bond under this key to have stake surfaced by
|
||||||
|
/// {provenanceOf}. Pure — no state, just the encoding convention.
|
||||||
|
function bondKeyOf(uint256 rootKeyId) external pure returns (bytes32) {
|
||||||
|
return bytes32(rootKeyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The operator (bond/reputation key) this contract reads for an agent:
|
||||||
|
/// the DID controller of the root key. Returns address(0) if unknown.
|
||||||
|
function operatorOf(uint256 rootKeyId) external view returns (address) {
|
||||||
|
return _operatorOf(rootKeyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Total receipts ever recorded (receiptIds run 0..receiptCount-1).
|
||||||
|
function receiptCount() external view returns (uint256) {
|
||||||
|
return _receipts.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a receipt. Reverts on an out-of-range receiptId.
|
||||||
|
function getReceipt(uint256 receiptId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 agentId,
|
||||||
|
uint256 sessionId,
|
||||||
|
address signer,
|
||||||
|
bytes32 outputHash,
|
||||||
|
bytes32 scope,
|
||||||
|
uint64 nonce,
|
||||||
|
uint64 emittedBlock,
|
||||||
|
uint64 emittedAt,
|
||||||
|
bytes memory sig
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (receiptId >= _receipts.length) revert UnknownReceipt(receiptId);
|
||||||
|
Receipt storage r = _receipts[receiptId];
|
||||||
|
return (r.agentId, r.sessionId, r.signer, r.outputHash, r.scope, r.nonce, r.emittedBlock, r.emittedAt, r.sig);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice All receiptIds authored by an agent (append-only, chronological).
|
||||||
|
function receiptsOf(uint256 rootKeyId) external view returns (uint256[] memory) {
|
||||||
|
return _agentReceipts[rootKeyId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice All receiptIds recorded under a session (append-only, chronological).
|
||||||
|
function receiptsOfSession(uint256 sessionId) external view returns (uint256[] memory) {
|
||||||
|
return _sessionReceipts[sessionId];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Defensive economic cross-reads
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
function _operatorOf(uint256 rootKeyId) internal view returns (address) {
|
||||||
|
try did.getAgent(rootKeyId) returns (address controller, uint64, uint64, uint256) {
|
||||||
|
return controller;
|
||||||
|
} catch {
|
||||||
|
return address(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _scoreOf(address operator, bytes32 bondKey) internal view returns (uint256) {
|
||||||
|
if (aiReputation == address(0) || operator == address(0)) return 0;
|
||||||
|
try IAereAIReputationView(aiReputation).scoreOf(operator, bondKey) returns (uint256 s) {
|
||||||
|
return s;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _bondOf(address operator, bytes32 bondKey) internal view returns (uint256 amount, uint256 slashed) {
|
||||||
|
if (agentBond == address(0) || operator == address(0)) return (0, 0);
|
||||||
|
try IAereAgentBondView(agentBond).bondOf(operator, bondKey) returns (
|
||||||
|
uint256 a, uint64, uint256 sl, bool
|
||||||
|
) {
|
||||||
|
return (a, sl);
|
||||||
|
} catch {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _operatorLifetimeSlashed(address operator) internal view returns (uint256) {
|
||||||
|
if (agentBond == address(0) || operator == address(0)) return 0;
|
||||||
|
try IAereAgentBondView(agentBond).operatorLifetimeSlashed(operator) returns (uint256 s) {
|
||||||
|
return s;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// ECDSA recovery
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @dev Minimal ecrecover with malleability guard (low-s, v in {27,28}). Returns
|
||||||
|
/// address(0) on any malformed input so callers treat it as an invalid signature.
|
||||||
|
/// Mirrors AereAgentDID._recover so a session key signs both surfaces identically.
|
||||||
|
function _recover(bytes32 digest, bytes memory sig) internal pure returns (address) {
|
||||||
|
if (sig.length != 65) return address(0);
|
||||||
|
bytes32 r;
|
||||||
|
bytes32 s;
|
||||||
|
uint8 v;
|
||||||
|
assembly {
|
||||||
|
r := mload(add(sig, 0x20))
|
||||||
|
s := mload(add(sig, 0x40))
|
||||||
|
v := byte(0, mload(add(sig, 0x60)))
|
||||||
|
}
|
||||||
|
// Reject high-s (EIP-2) to prevent signature malleability.
|
||||||
|
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
|
||||||
|
return address(0);
|
||||||
|
}
|
||||||
|
if (v != 27 && v != 28) return address(0);
|
||||||
|
return ecrecover(digest, v, r, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAgentBond — slashable bond for autonomous AI agents
|
||||||
|
* @notice The agentic economy needs accountable agents. A wallet address
|
||||||
|
* claiming to be "OpenAI's research agent" or "an audited TPM-bound
|
||||||
|
* inference node" is a claim, not a property. AereAgentBond turns
|
||||||
|
* the claim into a financial commitment.
|
||||||
|
*
|
||||||
|
* An operator (the human / org behind an agent) posts a bond in AERE.
|
||||||
|
* A registry of slashing oracles — entities the protocol has
|
||||||
|
* committed to listen to — can slash the bond when they observe
|
||||||
|
* provable misbehaviour (model-attestation perjury, refusal of
|
||||||
|
* observation challenges, AERE402 payment fraud, etc.).
|
||||||
|
*
|
||||||
|
* Slashed AERE goes to AereSink — directly into the burn engine.
|
||||||
|
* No discretion, no recovery, no "we'll give it back if you fix it".
|
||||||
|
* The cost of a slash is a real economic loss, not a corporate
|
||||||
|
* knuckle-rap.
|
||||||
|
*
|
||||||
|
* Operators can WITHDRAW a bond, but only after a cooldown
|
||||||
|
* (default 7 days, immutable) during which the bond is still
|
||||||
|
* slashable. This prevents bad actors from withdrawing the moment
|
||||||
|
* they detect they're about to get caught.
|
||||||
|
*
|
||||||
|
* AGENT IDENTITY:
|
||||||
|
* This contract does NOT establish who "the agent" is — it just
|
||||||
|
* keys on (operator address, agentId). The agentId can be the
|
||||||
|
* hash of an OpenAI API key fingerprint, an AereAgent registry
|
||||||
|
* id, an EAS attestation id, or any external identifier. Read
|
||||||
|
* consistency is the consumer's problem.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - WITHDRAWAL_COOLDOWN constant.
|
||||||
|
* - SINK + AERE token addresses immutable at deploy.
|
||||||
|
* - Slashing oracles registered immutably at deploy. Cannot add
|
||||||
|
* new oracles post-deploy. Phase 2 will use a multi-sig
|
||||||
|
* quorum across oracles; Phase 1 supports a single Foundation
|
||||||
|
* oracle for fastest iteration.
|
||||||
|
*
|
||||||
|
* GOTCHA — cooldown semantics:
|
||||||
|
* When an operator calls `requestWithdraw()`, their bond is
|
||||||
|
* "marked for withdrawal". The bond is STILL slashable until
|
||||||
|
* the cooldown elapses. `withdraw()` then transfers the
|
||||||
|
* remaining (post-any-slashes) bond to the operator. Anyone
|
||||||
|
* can call `withdraw()` for an operator whose cooldown has
|
||||||
|
* elapsed (defensive: prevents griefing where operator never
|
||||||
|
* calls withdraw).
|
||||||
|
*/
|
||||||
|
contract AereAgentBond is ReentrancyGuard {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
IERC20 public immutable AERE; // bond token
|
||||||
|
address public immutable SINK; // AereSink for slashed-AERE forward
|
||||||
|
uint256 public constant WITHDRAWAL_COOLDOWN = 7 days;
|
||||||
|
|
||||||
|
/// @notice immutable set of slashing oracles. Each can slash any bond.
|
||||||
|
/// Phase 1: a single Foundation oracle. Phase 2: multi-sig quorum
|
||||||
|
/// across N oracles (would require redeploy, by design).
|
||||||
|
mapping(address => bool) public isOracle;
|
||||||
|
address[] public oracleList;
|
||||||
|
|
||||||
|
/* ================================= state ================================= */
|
||||||
|
|
||||||
|
struct Bond {
|
||||||
|
uint256 amount; // current AERE bonded (post any slashes)
|
||||||
|
uint64 requestedAt; // 0 if no withdrawal requested; else unix seconds
|
||||||
|
uint256 lifetimeSlashed; // cumulative AERE slashed (informational; never resets)
|
||||||
|
bool exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice (operator, agentId) → bond
|
||||||
|
mapping(address => mapping(bytes32 => Bond)) internal _bonds;
|
||||||
|
|
||||||
|
/// @notice cumulative AERE forwarded to sink (informational).
|
||||||
|
uint256 public totalSlashedToSink;
|
||||||
|
|
||||||
|
/// AUDIT FIX (HIGH #21): operator-level cumulative slash across all
|
||||||
|
/// agentIds. Rotating agentId cannot wipe this — reputation reads it
|
||||||
|
/// to apply a residual penalty on the operator's new agents.
|
||||||
|
mapping(address => uint256) public operatorLifetimeSlashed;
|
||||||
|
|
||||||
|
/* ================================= events ================================= */
|
||||||
|
|
||||||
|
event BondPosted(address indexed operator, bytes32 indexed agentId, uint256 amount, uint256 newTotal);
|
||||||
|
event BondToppedUp(address indexed operator, bytes32 indexed agentId, uint256 added, uint256 newTotal);
|
||||||
|
event WithdrawalRequested(address indexed operator, bytes32 indexed agentId, uint64 readyAt);
|
||||||
|
event WithdrawalCancelled(address indexed operator, bytes32 indexed agentId); // AUDIT FIX (MED #36)
|
||||||
|
event Withdrawn(address indexed operator, bytes32 indexed agentId, address indexed recipient, uint256 amount);
|
||||||
|
event Slashed(
|
||||||
|
address indexed operator,
|
||||||
|
bytes32 indexed agentId,
|
||||||
|
address indexed oracle,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 reasonHash,
|
||||||
|
string reasonUri
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ================================= errors ================================= */
|
||||||
|
|
||||||
|
error NotOracle();
|
||||||
|
error BondNotFound();
|
||||||
|
error WithdrawalAlreadyRequested();
|
||||||
|
error WithdrawalNotRequested();
|
||||||
|
error WithdrawalCooldownOpen(uint256 nowTs, uint256 readyAt);
|
||||||
|
error ZeroAmount();
|
||||||
|
error SlashAmountExceedsBond(uint256 amount, uint256 have);
|
||||||
|
error SlashExceedsCallCap(uint256 amount, uint256 cap);
|
||||||
|
error SlashCooldownActive(uint64 nowTs, uint64 earliest);
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* =============================== modifiers ============================== */
|
||||||
|
|
||||||
|
modifier onlyOracle() {
|
||||||
|
if (!isOracle[msg.sender]) revert NotOracle();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== constructor ============================= */
|
||||||
|
|
||||||
|
/// AUDIT FIX (HIGH #18): per-call slash cap (25% of bond) + per-(operator,agentId)
|
||||||
|
/// slash cooldown (24h) to limit single-key oracle blast.
|
||||||
|
uint16 public constant MAX_SLASH_BPS_PER_CALL = 2500; // 25%
|
||||||
|
uint64 public constant SLASH_COOLDOWN = 24 hours;
|
||||||
|
mapping(address => mapping(bytes32 => uint64)) public lastSlashAt;
|
||||||
|
|
||||||
|
constructor(IERC20 aere, address sink, address[] memory oracles) {
|
||||||
|
require(address(aere) != address(0), "zero-aere");
|
||||||
|
require(sink != address(0), "zero-sink");
|
||||||
|
require(oracles.length > 0, "no-oracles"); // AUDIT FIX (MED #33)
|
||||||
|
AERE = aere;
|
||||||
|
SINK = sink;
|
||||||
|
for (uint256 i = 0; i < oracles.length; i++) {
|
||||||
|
require(oracles[i] != address(0), "zero-oracle");
|
||||||
|
require(!isOracle[oracles[i]], "dup-oracle");
|
||||||
|
isOracle[oracles[i]] = true;
|
||||||
|
oracleList.push(oracles[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= write ================================= */
|
||||||
|
|
||||||
|
/// @notice Post or top-up a bond for (msg.sender, agentId). Pulls AERE
|
||||||
|
/// from the caller. Top-up clears any pending withdrawal request
|
||||||
|
/// — re-committing the bond.
|
||||||
|
function postBond(bytes32 agentId, uint256 amount) external nonReentrant {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (!AERE.transferFrom(msg.sender, address(this), amount)) revert TransferFailed();
|
||||||
|
|
||||||
|
Bond storage b = _bonds[msg.sender][agentId];
|
||||||
|
bool isNew = !b.exists;
|
||||||
|
b.exists = true;
|
||||||
|
b.amount += amount;
|
||||||
|
// Re-committing the bond cancels any in-flight withdrawal request.
|
||||||
|
if (b.requestedAt != 0) {
|
||||||
|
b.requestedAt = 0;
|
||||||
|
emit WithdrawalCancelled(msg.sender, agentId); // AUDIT FIX (MED #36)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNew) {
|
||||||
|
emit BondPosted(msg.sender, agentId, amount, b.amount);
|
||||||
|
} else {
|
||||||
|
emit BondToppedUp(msg.sender, agentId, amount, b.amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Operator requests withdrawal. Bond stays slashable for
|
||||||
|
/// WITHDRAWAL_COOLDOWN. Re-requesting before cooldown elapses
|
||||||
|
/// is forbidden (would extend exposure of slashers who already
|
||||||
|
/// observed the original request).
|
||||||
|
function requestWithdraw(bytes32 agentId) external {
|
||||||
|
Bond storage b = _bonds[msg.sender][agentId];
|
||||||
|
if (!b.exists || b.amount == 0) revert BondNotFound();
|
||||||
|
if (b.requestedAt != 0) revert WithdrawalAlreadyRequested();
|
||||||
|
b.requestedAt = uint64(block.timestamp);
|
||||||
|
emit WithdrawalRequested(msg.sender, agentId, uint64(block.timestamp + WITHDRAWAL_COOLDOWN));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Permissionless withdraw once cooldown has elapsed. Transfers
|
||||||
|
/// the (post-slash) remaining bond to the operator.
|
||||||
|
function withdraw(address operator, bytes32 agentId) external nonReentrant {
|
||||||
|
Bond storage b = _bonds[operator][agentId];
|
||||||
|
if (!b.exists || b.amount == 0) revert BondNotFound();
|
||||||
|
if (b.requestedAt == 0) revert WithdrawalNotRequested();
|
||||||
|
uint256 readyAt = uint256(b.requestedAt) + WITHDRAWAL_COOLDOWN;
|
||||||
|
if (block.timestamp < readyAt) revert WithdrawalCooldownOpen(block.timestamp, readyAt);
|
||||||
|
|
||||||
|
uint256 amount = b.amount;
|
||||||
|
b.amount = 0;
|
||||||
|
b.requestedAt = 0;
|
||||||
|
|
||||||
|
if (!AERE.transfer(operator, amount)) revert TransferFailed();
|
||||||
|
emit Withdrawn(operator, agentId, operator, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Slash a bond. Only registered oracles can call. Slashed AERE
|
||||||
|
/// forwarded immediately to AereSink — no holding period, no
|
||||||
|
/// "release to whitelist" route. Burn engine eats it.
|
||||||
|
/// @param reasonHash on-chain hash of the violation evidence (e.g.
|
||||||
|
/// keccak256 of the AereAIProof attestation that
|
||||||
|
/// contradicts the agent's claim, or the AERE402
|
||||||
|
/// dispute proof).
|
||||||
|
/// @param reasonUri optional human-readable evidence pointer
|
||||||
|
/// (ipfs://… or https://…). Stored as event arg only.
|
||||||
|
function slash(
|
||||||
|
address operator,
|
||||||
|
bytes32 agentId,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 reasonHash,
|
||||||
|
string calldata reasonUri
|
||||||
|
) external nonReentrant onlyOracle {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
Bond storage b = _bonds[operator][agentId];
|
||||||
|
if (!b.exists || b.amount == 0) revert BondNotFound();
|
||||||
|
if (amount > b.amount) revert SlashAmountExceedsBond(amount, b.amount);
|
||||||
|
// AUDIT FIX (HIGH #18): per-call cap (25%) limits blast radius of a
|
||||||
|
// compromised single-oracle key.
|
||||||
|
uint256 cap = (b.amount * MAX_SLASH_BPS_PER_CALL) / 10_000;
|
||||||
|
if (cap == 0) cap = b.amount; // tiny dust bonds — slash all (still ≤ b.amount)
|
||||||
|
if (amount > cap) revert SlashExceedsCallCap(amount, cap);
|
||||||
|
// Cooldown between slashes per (operator, agentId).
|
||||||
|
uint64 lastTs = lastSlashAt[operator][agentId];
|
||||||
|
if (lastTs != 0 && block.timestamp < uint256(lastTs) + SLASH_COOLDOWN) {
|
||||||
|
revert SlashCooldownActive(uint64(block.timestamp), lastTs + uint64(SLASH_COOLDOWN));
|
||||||
|
}
|
||||||
|
lastSlashAt[operator][agentId] = uint64(block.timestamp);
|
||||||
|
|
||||||
|
b.amount -= amount;
|
||||||
|
b.lifetimeSlashed += amount;
|
||||||
|
operatorLifetimeSlashed[operator] += amount; // AUDIT FIX (HIGH #21)
|
||||||
|
totalSlashedToSink += amount;
|
||||||
|
|
||||||
|
// Forward slashed AERE to sink via approve + flush. The sink
|
||||||
|
// requires transferFrom semantics from msg.sender.
|
||||||
|
AERE.approve(SINK, 0);
|
||||||
|
AERE.approve(SINK, amount);
|
||||||
|
(bool ok, ) = SINK.call(abi.encodeWithSignature("flush(address,uint256)", address(AERE), amount));
|
||||||
|
AERE.approve(SINK, 0);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
|
||||||
|
emit Slashed(operator, agentId, msg.sender, amount, reasonHash, reasonUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= views ================================= */
|
||||||
|
|
||||||
|
function bondOf(address operator, bytes32 agentId) external view returns (
|
||||||
|
uint256 amount, uint64 requestedAt, uint256 lifetimeSlashed, bool exists
|
||||||
|
) {
|
||||||
|
Bond storage b = _bonds[operator][agentId];
|
||||||
|
return (b.amount, b.requestedAt, b.lifetimeSlashed, b.exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience: true if the bond is currently >= `minBond` and
|
||||||
|
/// not requested for withdrawal. Consumers (AERE402 facilitator,
|
||||||
|
/// AereAIProof verifier) should require this before honoring
|
||||||
|
/// agent claims.
|
||||||
|
function isBonded(address operator, bytes32 agentId, uint256 minBond) external view returns (bool) {
|
||||||
|
Bond storage b = _bonds[operator][agentId];
|
||||||
|
return b.exists && b.amount >= minBond && b.requestedAt == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function oracles() external view returns (address[] memory) {
|
||||||
|
return oracleList;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAgentMemoryVault — portable, user-owned AI agent memory
|
||||||
|
* @notice Today every AI assistant rebuilds your context from scratch.
|
||||||
|
* Your ChatGPT history, your Claude preferences, the tone your
|
||||||
|
* trading bot has learned about you — none of it travels. Switch
|
||||||
|
* provider, the memory dies. The vendor owns the relationship.
|
||||||
|
*
|
||||||
|
* AereAgentMemoryVault flips that ownership. The USER (not the
|
||||||
|
* provider) is the namespace owner. Agents read and write to
|
||||||
|
* per-user slots under EXPLICIT user permission. When the user
|
||||||
|
* switches provider, the new agent gets read access to the same
|
||||||
|
* history with one signature. Privacy is preserved because the
|
||||||
|
* memory blobs themselves are ENCRYPTED off-chain — only
|
||||||
|
* commitments + access-control live on chain.
|
||||||
|
*
|
||||||
|
* MODEL:
|
||||||
|
*
|
||||||
|
* 1. Each user has a private namespace (keyed by their address).
|
||||||
|
* Within it, named "slots" hold versioned memory entries.
|
||||||
|
*
|
||||||
|
* 2. The user grants Permission to an agent address. A Permission
|
||||||
|
* specifies (agent, slot, write?, validUntil). Multiple
|
||||||
|
* permissions can coexist (read-only "memory consumer" agent
|
||||||
|
* + read/write "memory builder" agent).
|
||||||
|
*
|
||||||
|
* 3. An authorised agent writes an entry: a content hash + an
|
||||||
|
* opaque pointer (ipfs:// to the encrypted blob). The chain
|
||||||
|
* stores ONLY the commitment. Encryption keys are off-chain
|
||||||
|
* and exchanged out-of-band (e.g. via ECIES to the agent's
|
||||||
|
* registered key, or via a passkey-bound user device).
|
||||||
|
*
|
||||||
|
* 4. The user can REVOKE any permission at any time. The
|
||||||
|
* revocation is immediate; an agent's next write attempt
|
||||||
|
* reverts. Past entries written under that permission stay
|
||||||
|
* in history (the chain remembers; only the agent's ability
|
||||||
|
* to read goes away — the user can rotate keys to actually
|
||||||
|
* cut access).
|
||||||
|
*
|
||||||
|
* 5. PORTABILITY: when a user grants a fresh agent read access
|
||||||
|
* to ALL their slots, that agent immediately sees the full
|
||||||
|
* memory tree. The chain emits enough events for an indexer
|
||||||
|
* to reconstruct the canonical slot → latest-entry map.
|
||||||
|
*
|
||||||
|
* WHAT THE CHAIN DOES NOT DO:
|
||||||
|
* - Does NOT decrypt anything. Keys live with the user / agent.
|
||||||
|
* - Does NOT enforce schema. Slots are just bytes32 names.
|
||||||
|
* - Does NOT charge fees per write. (Gas is the only cost.)
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - No admin, no Foundation override. The user is the only
|
||||||
|
* authority over their own namespace.
|
||||||
|
* - Permissions table is append-only via events; the latest
|
||||||
|
* permission state per (user, agent, slot) is the source of
|
||||||
|
* truth.
|
||||||
|
*/
|
||||||
|
contract AereAgentMemoryVault {
|
||||||
|
|
||||||
|
/* ================================ types ================================ */
|
||||||
|
|
||||||
|
struct Permission {
|
||||||
|
bool canRead;
|
||||||
|
bool canWrite;
|
||||||
|
uint64 validUntil; // 0 = no expiry
|
||||||
|
bool exists; // true after first grant; never reset
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Entry {
|
||||||
|
bytes32 contentHash; // SHA256 of the encrypted blob
|
||||||
|
string blobUri; // ipfs:// or https:// (encrypted)
|
||||||
|
address writer;
|
||||||
|
uint64 version;
|
||||||
|
uint64 writtenAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ storage ================================ */
|
||||||
|
|
||||||
|
/// @notice user → agent → slot → Permission. Per-slot grain; wildcard
|
||||||
|
/// per (user, agent) NOT supported — agents must enumerate the
|
||||||
|
/// exact slots they're given access to.
|
||||||
|
mapping(address => mapping(address => mapping(bytes32 => Permission))) internal _perm;
|
||||||
|
|
||||||
|
/// @notice user → slot → next version counter. Starts at 1.
|
||||||
|
mapping(address => mapping(bytes32 => uint64)) public nextVersion;
|
||||||
|
|
||||||
|
/// @notice user → slot → latest Entry. Indexers can reconstruct full
|
||||||
|
/// history from events; the chain keeps only the head.
|
||||||
|
mapping(address => mapping(bytes32 => Entry)) internal _head;
|
||||||
|
|
||||||
|
/* ================================ events ================================ */
|
||||||
|
|
||||||
|
event PermissionSet(
|
||||||
|
address indexed user,
|
||||||
|
address indexed agent,
|
||||||
|
bytes32 indexed slot,
|
||||||
|
bool canRead,
|
||||||
|
bool canWrite,
|
||||||
|
uint64 validUntil
|
||||||
|
);
|
||||||
|
|
||||||
|
event PermissionRevoked(address indexed user, address indexed agent, bytes32 indexed slot);
|
||||||
|
|
||||||
|
event EntryWritten(
|
||||||
|
address indexed user,
|
||||||
|
bytes32 indexed slot,
|
||||||
|
address indexed agent,
|
||||||
|
uint64 version,
|
||||||
|
bytes32 contentHash,
|
||||||
|
string blobUri
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ================================ errors ================================ */
|
||||||
|
|
||||||
|
error NotWriter();
|
||||||
|
error PermissionExpired();
|
||||||
|
error NoSuchPermission();
|
||||||
|
error EmptyHash();
|
||||||
|
error InvalidValidity();
|
||||||
|
|
||||||
|
/* =========================== user-side permission ========================= */
|
||||||
|
|
||||||
|
/// @notice User grants (or updates) a per-slot permission to an agent.
|
||||||
|
/// msg.sender == user. validUntil = 0 means no expiry.
|
||||||
|
function grant(
|
||||||
|
address agent,
|
||||||
|
bytes32 slot,
|
||||||
|
bool canRead,
|
||||||
|
bool canWrite,
|
||||||
|
uint64 validUntil
|
||||||
|
) external {
|
||||||
|
if (validUntil != 0 && validUntil <= block.timestamp) revert InvalidValidity();
|
||||||
|
Permission storage p = _perm[msg.sender][agent][slot];
|
||||||
|
p.canRead = canRead;
|
||||||
|
p.canWrite = canWrite;
|
||||||
|
p.validUntil = validUntil;
|
||||||
|
p.exists = true;
|
||||||
|
emit PermissionSet(msg.sender, agent, slot, canRead, canWrite, validUntil);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice User revokes a permission. Immediate effect on writes.
|
||||||
|
function revoke(address agent, bytes32 slot) external {
|
||||||
|
Permission storage p = _perm[msg.sender][agent][slot];
|
||||||
|
if (!p.exists) revert NoSuchPermission();
|
||||||
|
p.canRead = false;
|
||||||
|
p.canWrite = false;
|
||||||
|
// We KEEP `exists` true so subsequent grants don't accidentally
|
||||||
|
// look like brand-new attestations; just zero the rights.
|
||||||
|
emit PermissionRevoked(msg.sender, agent, slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =============================== writes =============================== */
|
||||||
|
|
||||||
|
/// @notice Agent writes a memory entry for `user` at `slot`. msg.sender
|
||||||
|
/// must have an unexpired canWrite permission.
|
||||||
|
function write(
|
||||||
|
address user,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 contentHash,
|
||||||
|
string calldata blobUri
|
||||||
|
) external returns (uint64 version) {
|
||||||
|
if (contentHash == bytes32(0)) revert EmptyHash();
|
||||||
|
Permission storage p = _perm[user][msg.sender][slot];
|
||||||
|
if (!p.canWrite) revert NotWriter();
|
||||||
|
if (p.validUntil != 0 && block.timestamp > p.validUntil) revert PermissionExpired();
|
||||||
|
|
||||||
|
version = ++nextVersion[user][slot];
|
||||||
|
_head[user][slot] = Entry({
|
||||||
|
contentHash: contentHash,
|
||||||
|
blobUri: blobUri,
|
||||||
|
writer: msg.sender,
|
||||||
|
version: version,
|
||||||
|
writtenAt: uint64(block.timestamp)
|
||||||
|
});
|
||||||
|
emit EntryWritten(user, slot, msg.sender, version, contentHash, blobUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ views ================================ */
|
||||||
|
|
||||||
|
function permissionOf(address user, address agent, bytes32 slot) external view returns (
|
||||||
|
bool canRead, bool canWrite, uint64 validUntil, bool exists
|
||||||
|
) {
|
||||||
|
Permission storage p = _perm[user][agent][slot];
|
||||||
|
return (p.canRead, p.canWrite, p.validUntil, p.exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True if `agent` can currently read this slot (canRead +
|
||||||
|
/// not expired). Used by off-chain clients before requesting
|
||||||
|
/// the encrypted blob from the user's key-exchange service.
|
||||||
|
function canReadNow(address user, address agent, bytes32 slot) external view returns (bool) {
|
||||||
|
Permission storage p = _perm[user][agent][slot];
|
||||||
|
if (!p.canRead) return false;
|
||||||
|
if (p.validUntil != 0 && block.timestamp > p.validUntil) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function headOf(address user, bytes32 slot) external view returns (
|
||||||
|
bytes32 contentHash, string memory blobUri, address writer, uint64 version, uint64 writtenAt
|
||||||
|
) {
|
||||||
|
Entry storage e = _head[user][slot];
|
||||||
|
return (e.contentHash, e.blobUri, e.writer, e.version, e.writtenAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAgentV2 — machine-account registry (F13 companion redeploy)
|
||||||
|
* @notice Logic-identical companion to AereAgent
|
||||||
|
* (0xE96396B4b596B3A74e4195Be12aADd5257863536). The ONLY difference is
|
||||||
|
* the constructor argument: this instance's immutable
|
||||||
|
* AERE402_FACILITATOR points at AERE402FacilitatorV2 instead of the V1
|
||||||
|
* facilitator.
|
||||||
|
*
|
||||||
|
* WHY A COMPANION REDEPLOY IS REQUIRED: `debit` is access-gated to the
|
||||||
|
* immutable AERE402_FACILITATOR. The F13 fix lives in the facilitator
|
||||||
|
* (per-payee nonce namespace), which forces a new facilitator address;
|
||||||
|
* a new facilitator cannot call `debit` on the V1 AereAgent (its
|
||||||
|
* facilitator is pinned to the V1 address). So V2 facilitator + V2 agent
|
||||||
|
* are cross-wired: AereAgentV2.AERE402_FACILITATOR == AERE402FacilitatorV2
|
||||||
|
* and AERE402FacilitatorV2.AGENT_REGISTRY == AereAgentV2.
|
||||||
|
*
|
||||||
|
* Registry semantics are byte-for-byte identical to V1: identity
|
||||||
|
* (operator + signer + optional passkey), prepaid per-(agent,token)
|
||||||
|
* balance, per-call / per-hour / per-day caps, pause, and the
|
||||||
|
* facilitator-only debit path. No new token; no owner. See AereAgent for
|
||||||
|
* the full model documentation.
|
||||||
|
*/
|
||||||
|
contract AereAgentV2 is ReentrancyGuard {
|
||||||
|
|
||||||
|
/// @notice The only contract that may call debit().
|
||||||
|
address public immutable AERE402_FACILITATOR;
|
||||||
|
|
||||||
|
struct Agent {
|
||||||
|
bool registered;
|
||||||
|
bool paused;
|
||||||
|
address operator; // human / org running the agent (rotatable)
|
||||||
|
address signer; // secp256k1 key that signs payment auths (rotatable)
|
||||||
|
bytes32 passkeyPubX; // optional WebAuthn passkey for additional auth surface
|
||||||
|
bytes32 passkeyPubY;
|
||||||
|
uint128 perCallCap;
|
||||||
|
uint128 perHourCap;
|
||||||
|
uint128 perDayCap;
|
||||||
|
string metadataUri; // ipfs / https with agent description
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice agentId → Agent
|
||||||
|
mapping(uint256 => Agent) public agents;
|
||||||
|
uint256 public nextAgentId;
|
||||||
|
|
||||||
|
/// @notice agentId → token → prepaid balance
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public balances;
|
||||||
|
|
||||||
|
/// @notice agentId → token → (hour epoch, spent in that hour)
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public hourlySpentEpoch;
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public hourlySpent;
|
||||||
|
|
||||||
|
/// @notice agentId → token → (day epoch, spent in that day)
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public dailySpentEpoch;
|
||||||
|
mapping(uint256 => mapping(address => uint256)) public dailySpent;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event AgentRegistered(uint256 indexed agentId, address indexed operator, address indexed signer, string metadataUri);
|
||||||
|
event OperatorTransferred(uint256 indexed agentId, address indexed oldOperator, address indexed newOperator);
|
||||||
|
event SignerSet(uint256 indexed agentId, address indexed newSigner);
|
||||||
|
event PasskeySet(uint256 indexed agentId, bytes32 pubX, bytes32 pubY);
|
||||||
|
event RateLimitsSet(uint256 indexed agentId, uint128 perCallCap, uint128 perHourCap, uint128 perDayCap);
|
||||||
|
event AgentPausedSet(uint256 indexed agentId, bool paused);
|
||||||
|
event MetadataUpdated(uint256 indexed agentId, string metadataUri);
|
||||||
|
event TopUp(uint256 indexed agentId, address indexed token, address indexed funder, uint256 amount);
|
||||||
|
event Withdrawn(uint256 indexed agentId, address indexed token, address indexed recipient, uint256 amount);
|
||||||
|
event Debited(uint256 indexed agentId, address indexed token, address indexed payee, uint256 amount);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error NotOperator();
|
||||||
|
error NotFacilitator();
|
||||||
|
error UnknownAgent();
|
||||||
|
error AgentPausedErr();
|
||||||
|
error InsufficientBalance(uint256 have, uint256 want);
|
||||||
|
error PerCallCapExceeded(uint256 want, uint256 cap);
|
||||||
|
error PerHourCapExceeded(uint256 wouldBe, uint256 cap);
|
||||||
|
error PerDayCapExceeded(uint256 wouldBe, uint256 cap);
|
||||||
|
error ZeroAddress();
|
||||||
|
error ZeroAmount();
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* ------------------------------- modifiers ------------------------------- */
|
||||||
|
|
||||||
|
modifier onlyOperator(uint256 agentId) {
|
||||||
|
Agent storage a = agents[agentId];
|
||||||
|
if (!a.registered) revert UnknownAgent();
|
||||||
|
if (msg.sender != a.operator) revert NotOperator();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
constructor(address facilitator) {
|
||||||
|
if (facilitator == address(0)) revert ZeroAddress();
|
||||||
|
AERE402_FACILITATOR = facilitator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- registration --------------------------- */
|
||||||
|
|
||||||
|
function registerAgent(
|
||||||
|
address signer,
|
||||||
|
bytes32 passkeyPubX,
|
||||||
|
bytes32 passkeyPubY,
|
||||||
|
uint128 perCallCap,
|
||||||
|
uint128 perHourCap,
|
||||||
|
uint128 perDayCap,
|
||||||
|
string calldata metadataUri
|
||||||
|
) external returns (uint256 agentId) {
|
||||||
|
if (signer == address(0)) revert ZeroAddress();
|
||||||
|
agentId = nextAgentId++;
|
||||||
|
agents[agentId] = Agent({
|
||||||
|
registered: true,
|
||||||
|
paused: false,
|
||||||
|
operator: msg.sender,
|
||||||
|
signer: signer,
|
||||||
|
passkeyPubX: passkeyPubX,
|
||||||
|
passkeyPubY: passkeyPubY,
|
||||||
|
perCallCap: perCallCap,
|
||||||
|
perHourCap: perHourCap,
|
||||||
|
perDayCap: perDayCap,
|
||||||
|
metadataUri: metadataUri
|
||||||
|
});
|
||||||
|
emit AgentRegistered(agentId, msg.sender, signer, metadataUri);
|
||||||
|
emit RateLimitsSet(agentId, perCallCap, perHourCap, perDayCap);
|
||||||
|
if (passkeyPubX != bytes32(0) || passkeyPubY != bytes32(0)) {
|
||||||
|
emit PasskeySet(agentId, passkeyPubX, passkeyPubY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferOperator(uint256 agentId, address newOperator) external onlyOperator(agentId) {
|
||||||
|
if (newOperator == address(0)) revert ZeroAddress();
|
||||||
|
address old = agents[agentId].operator;
|
||||||
|
agents[agentId].operator = newOperator;
|
||||||
|
emit OperatorTransferred(agentId, old, newOperator);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSigner(uint256 agentId, address newSigner) external onlyOperator(agentId) {
|
||||||
|
if (newSigner == address(0)) revert ZeroAddress();
|
||||||
|
agents[agentId].signer = newSigner;
|
||||||
|
emit SignerSet(agentId, newSigner);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPasskey(uint256 agentId, bytes32 pubX, bytes32 pubY) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].passkeyPubX = pubX;
|
||||||
|
agents[agentId].passkeyPubY = pubY;
|
||||||
|
emit PasskeySet(agentId, pubX, pubY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRateLimits(uint256 agentId, uint128 perCallCap, uint128 perHourCap, uint128 perDayCap) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].perCallCap = perCallCap;
|
||||||
|
agents[agentId].perHourCap = perHourCap;
|
||||||
|
agents[agentId].perDayCap = perDayCap;
|
||||||
|
emit RateLimitsSet(agentId, perCallCap, perHourCap, perDayCap);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPaused(uint256 agentId, bool paused) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].paused = paused;
|
||||||
|
emit AgentPausedSet(agentId, paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateMetadata(uint256 agentId, string calldata metadataUri) external onlyOperator(agentId) {
|
||||||
|
agents[agentId].metadataUri = metadataUri;
|
||||||
|
emit MetadataUpdated(agentId, metadataUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- balance --------------------------------- */
|
||||||
|
|
||||||
|
function topUp(uint256 agentId, address token, uint256 amount) external nonReentrant {
|
||||||
|
if (!agents[agentId].registered) revert UnknownAgent();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
bool ok = IERC20(token).transferFrom(msg.sender, address(this), amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
balances[agentId][token] += amount;
|
||||||
|
emit TopUp(agentId, token, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function withdraw(uint256 agentId, address token, uint256 amount, address recipient) external onlyOperator(agentId) nonReentrant {
|
||||||
|
if (recipient == address(0)) revert ZeroAddress();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
uint256 bal = balances[agentId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
unchecked { balances[agentId][token] = bal - amount; }
|
||||||
|
bool ok = IERC20(token).transfer(recipient, amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit Withdrawn(agentId, token, recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- debit -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Called by AERE402FacilitatorV2 to debit the agent's prepaid
|
||||||
|
/// balance and transfer `amount` of `token` to `payee`. Enforces
|
||||||
|
/// per-call / per-hour / per-day caps + paused.
|
||||||
|
function debit(
|
||||||
|
uint256 agentId,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount
|
||||||
|
) external nonReentrant {
|
||||||
|
if (msg.sender != AERE402_FACILITATOR) revert NotFacilitator();
|
||||||
|
Agent storage a = agents[agentId];
|
||||||
|
if (!a.registered) revert UnknownAgent();
|
||||||
|
if (a.paused) revert AgentPausedErr();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (payee == address(0)) revert ZeroAddress();
|
||||||
|
|
||||||
|
if (a.perCallCap != 0 && amount > a.perCallCap) revert PerCallCapExceeded(amount, a.perCallCap);
|
||||||
|
|
||||||
|
uint256 bal = balances[agentId][token];
|
||||||
|
if (bal < amount) revert InsufficientBalance(bal, amount);
|
||||||
|
|
||||||
|
uint256 thisHour = block.timestamp / 1 hours;
|
||||||
|
uint256 thisDay = block.timestamp / 1 days;
|
||||||
|
|
||||||
|
uint256 hourSpent = hourlySpentEpoch[agentId][token] == thisHour ? hourlySpent[agentId][token] : 0;
|
||||||
|
uint256 daySpent = dailySpentEpoch[agentId][token] == thisDay ? dailySpent[agentId][token] : 0;
|
||||||
|
|
||||||
|
uint256 newHourSpent = hourSpent + amount;
|
||||||
|
uint256 newDaySpent = daySpent + amount;
|
||||||
|
|
||||||
|
if (a.perHourCap != 0 && newHourSpent > a.perHourCap) revert PerHourCapExceeded(newHourSpent, a.perHourCap);
|
||||||
|
if (a.perDayCap != 0 && newDaySpent > a.perDayCap) revert PerDayCapExceeded(newDaySpent, a.perDayCap);
|
||||||
|
|
||||||
|
unchecked {
|
||||||
|
balances[agentId][token] = bal - amount;
|
||||||
|
hourlySpentEpoch[agentId][token] = thisHour;
|
||||||
|
hourlySpent[agentId][token] = newHourSpent;
|
||||||
|
dailySpentEpoch[agentId][token] = thisDay;
|
||||||
|
dailySpent[agentId][token] = newDaySpent;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ok = IERC20(token).transfer(payee, amount);
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit Debited(agentId, token, payee, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- views -------------------------------- */
|
||||||
|
|
||||||
|
function signerOf(uint256 agentId) external view returns (address) {
|
||||||
|
return agents[agentId].signer;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereInferNet — EU AI Act Article 12 inference-log commitments
|
||||||
|
* @notice EU AI Act Article 12 (in force from August 2 2026) requires
|
||||||
|
* providers and deployers of HIGH-RISK AI systems to maintain
|
||||||
|
* automatic event logs covering the system's operation. The
|
||||||
|
* logs must allow ex-post traceability and incident analysis
|
||||||
|
* by the relevant national competent authority.
|
||||||
|
*
|
||||||
|
* Today, "logs" lives in vendor S3 buckets. A subpoena later
|
||||||
|
* can show whatever is convenient. AereInferNet turns the
|
||||||
|
* commitment into a public-good primitive:
|
||||||
|
*
|
||||||
|
* 1. Each inference provider registers their model + the TEE
|
||||||
|
* attestation that bounds it (e.g. Intel SGX / AMD SEV-SNP
|
||||||
|
* measurement). The registration is immutable per (provider,
|
||||||
|
* modelId) — the model commitment cannot be retroactively
|
||||||
|
* "amended" without a new modelId.
|
||||||
|
*
|
||||||
|
* 2. Each epoch (~24h), the provider commits a Merkle root of
|
||||||
|
* (requestHash, responseHash, timestampMs, deployerId)
|
||||||
|
* leaves for every inference served in that epoch. The
|
||||||
|
* commitment is one transaction per provider per epoch —
|
||||||
|
* cheap enough that even a multi-million-request/day
|
||||||
|
* provider pays cents in gas.
|
||||||
|
*
|
||||||
|
* 3. Anyone (regulator, customer, journalist, the deployer
|
||||||
|
* themselves) can later prove inclusion of a specific
|
||||||
|
* inference by submitting a Merkle proof against the
|
||||||
|
* committed root. If the provider denies serving a request
|
||||||
|
* and the proof shows it WAS served, the public record
|
||||||
|
* speaks.
|
||||||
|
*
|
||||||
|
* 4. Slashing: providers MAY post bond via AereAgentBond,
|
||||||
|
* keyed on agentId = keccak256(modelId, providerAddress).
|
||||||
|
* Regulators / customers can dispute → trigger the slash
|
||||||
|
* path. AereInferNet does NOT enforce this layer — it's
|
||||||
|
* composable. Consumers that need stronger guarantees can
|
||||||
|
* require `bond.isBonded(provider, agentId, minBond)`
|
||||||
|
* before accepting the provider's commitments.
|
||||||
|
*
|
||||||
|
* DEPLOYER COMMITMENT:
|
||||||
|
* Article 12 obligates BOTH providers and deployers. A
|
||||||
|
* deployer who wires an inference into their own application
|
||||||
|
* records the same leaves on their side and can publish their
|
||||||
|
* own Merkle root — making provider/deployer collusion
|
||||||
|
* detectable (the two roots' leaves must reconcile).
|
||||||
|
*
|
||||||
|
* NO PII:
|
||||||
|
* Both `requestHash` and `responseHash` are content hashes
|
||||||
|
* computed off-chain — the chain stores only commitments,
|
||||||
|
* never raw prompts or responses. Aligned with GDPR Art 5(1)(c).
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - Model registry is append-only; per (provider, modelId)
|
||||||
|
* we set once and never overwrite. Bug-fix releases bump
|
||||||
|
* modelId.
|
||||||
|
* - Commitments append to per-provider epoch history. A
|
||||||
|
* commitment for an epoch already committed reverts.
|
||||||
|
*/
|
||||||
|
contract AereInferNet {
|
||||||
|
|
||||||
|
/* ================================ types ================================ */
|
||||||
|
|
||||||
|
/// @notice Severity tier the model is offered for per EU AI Act Annex III.
|
||||||
|
/// Used by indexers to filter; not enforced on-chain.
|
||||||
|
enum RiskTier {
|
||||||
|
Minimal, // 0
|
||||||
|
Limited, // 1
|
||||||
|
High, // 2 — Article 12 logging strictly applies
|
||||||
|
Unacceptable // 3 — should never register; left for completeness
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ModelRegistration {
|
||||||
|
bytes32 modelDigest; // SHA256 of the model weights blob
|
||||||
|
bytes32 attestationDigest; // hash of the TEE attestation that pins the
|
||||||
|
// running binary to `modelDigest`
|
||||||
|
RiskTier risk;
|
||||||
|
string modelName; // human-readable, e.g. "claude-4.7-sonnet-20251022"
|
||||||
|
string attestationUri; // ipfs:// or https:// — full TEE quote + signing chain
|
||||||
|
uint64 registeredAt;
|
||||||
|
bool exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EpochCommitment {
|
||||||
|
bytes32 root; // Merkle root of (req, resp, ts, deployer) leaves
|
||||||
|
uint64 committedAt;
|
||||||
|
uint64 inferenceCount; // number of leaves under this root (informational)
|
||||||
|
string metadataUri; // optional pointer to provider-published leaves
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ storage ================================ */
|
||||||
|
|
||||||
|
/// @notice (provider, modelId) → ModelRegistration. modelId is provider-chosen.
|
||||||
|
mapping(address => mapping(bytes32 => ModelRegistration)) internal _models;
|
||||||
|
|
||||||
|
/// @notice (provider, modelId, epochId) → EpochCommitment.
|
||||||
|
/// AUDIT FIX (HIGH #25): previously the key was (provider, epochId) which
|
||||||
|
/// meant multi-model providers could only commit one root per epoch across
|
||||||
|
/// all models, and verifyInference had no way to bind a proof to a specific
|
||||||
|
/// model. Now keyed by all three.
|
||||||
|
mapping(address => mapping(bytes32 => mapping(uint64 => EpochCommitment))) internal _commits;
|
||||||
|
|
||||||
|
/// @notice (provider, modelId) → count of registered epochs (informational).
|
||||||
|
mapping(address => mapping(bytes32 => uint256)) public modelEpochCount;
|
||||||
|
|
||||||
|
/* ================================= events ================================= */
|
||||||
|
|
||||||
|
event ModelRegistered(
|
||||||
|
address indexed provider,
|
||||||
|
bytes32 indexed modelId,
|
||||||
|
bytes32 modelDigest,
|
||||||
|
bytes32 attestationDigest,
|
||||||
|
RiskTier risk,
|
||||||
|
string modelName,
|
||||||
|
string attestationUri
|
||||||
|
);
|
||||||
|
|
||||||
|
event EpochCommitted(
|
||||||
|
address indexed provider,
|
||||||
|
bytes32 indexed modelId,
|
||||||
|
uint64 indexed epochId,
|
||||||
|
bytes32 root,
|
||||||
|
uint64 inferenceCount,
|
||||||
|
string metadataUri
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ================================= errors ================================= */
|
||||||
|
|
||||||
|
error ModelExists();
|
||||||
|
error ModelUnknown();
|
||||||
|
error EpochExists();
|
||||||
|
error EpochOutOfRange();
|
||||||
|
error ZeroDigest();
|
||||||
|
error EmptyName();
|
||||||
|
|
||||||
|
/* ============================== model registry ============================ */
|
||||||
|
|
||||||
|
/// @notice Provider registers a new model. msg.sender is the provider.
|
||||||
|
/// Reverts if the (provider, modelId) is already set; cannot be
|
||||||
|
/// amended — register a new modelId for the next version.
|
||||||
|
function registerModel(
|
||||||
|
bytes32 modelId,
|
||||||
|
bytes32 modelDigest,
|
||||||
|
bytes32 attestationDigest,
|
||||||
|
RiskTier risk,
|
||||||
|
string calldata modelName,
|
||||||
|
string calldata attestationUri
|
||||||
|
) external {
|
||||||
|
if (modelDigest == bytes32(0) || attestationDigest == bytes32(0)) revert ZeroDigest();
|
||||||
|
if (bytes(modelName).length == 0) revert EmptyName();
|
||||||
|
ModelRegistration storage m = _models[msg.sender][modelId];
|
||||||
|
if (m.exists) revert ModelExists();
|
||||||
|
m.modelDigest = modelDigest;
|
||||||
|
m.attestationDigest = attestationDigest;
|
||||||
|
m.risk = risk;
|
||||||
|
m.modelName = modelName;
|
||||||
|
m.attestationUri = attestationUri;
|
||||||
|
m.registeredAt = uint64(block.timestamp);
|
||||||
|
m.exists = true;
|
||||||
|
emit ModelRegistered(msg.sender, modelId, modelDigest, attestationDigest, risk, modelName, attestationUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ epoch commitments ========================== */
|
||||||
|
|
||||||
|
/// @notice Provider commits the Merkle root for an epoch. The model
|
||||||
|
/// MUST already be registered (reverts otherwise — prevents
|
||||||
|
/// committing inferences for a phantom model).
|
||||||
|
/// epochId is provider-chosen but convention is unix-day:
|
||||||
|
/// epochId = uint64(block.timestamp / 86400)
|
||||||
|
function commitEpoch(
|
||||||
|
bytes32 modelId,
|
||||||
|
uint64 epochId,
|
||||||
|
bytes32 root,
|
||||||
|
uint64 inferenceCount,
|
||||||
|
string calldata metadataUri
|
||||||
|
) external {
|
||||||
|
if (root == bytes32(0)) revert ZeroDigest();
|
||||||
|
ModelRegistration storage m = _models[msg.sender][modelId];
|
||||||
|
if (!m.exists) revert ModelUnknown();
|
||||||
|
// AUDIT FIX (HIGH #26): epochId must be the current unix-day (with 1-day
|
||||||
|
// grace for the just-ended day). Prevents back-dating to rewrite history
|
||||||
|
// and forward-dating to commit to future inferences.
|
||||||
|
uint64 currentDay = uint64(block.timestamp / 86400);
|
||||||
|
if (epochId > currentDay) revert EpochOutOfRange();
|
||||||
|
if (currentDay > epochId && currentDay - epochId > 1) revert EpochOutOfRange();
|
||||||
|
EpochCommitment storage e = _commits[msg.sender][modelId][epochId];
|
||||||
|
if (e.committedAt != 0) revert EpochExists();
|
||||||
|
e.root = root;
|
||||||
|
e.committedAt = uint64(block.timestamp);
|
||||||
|
e.inferenceCount = inferenceCount;
|
||||||
|
e.metadataUri = metadataUri;
|
||||||
|
modelEpochCount[msg.sender][modelId] += 1;
|
||||||
|
emit EpochCommitted(msg.sender, modelId, epochId, root, inferenceCount, metadataUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= views ================================= */
|
||||||
|
|
||||||
|
function modelOf(address provider, bytes32 modelId) external view returns (
|
||||||
|
bytes32 modelDigest,
|
||||||
|
bytes32 attestationDigest,
|
||||||
|
RiskTier risk,
|
||||||
|
string memory modelName,
|
||||||
|
string memory attestationUri,
|
||||||
|
uint64 registeredAt,
|
||||||
|
bool exists
|
||||||
|
) {
|
||||||
|
ModelRegistration storage m = _models[provider][modelId];
|
||||||
|
return (m.modelDigest, m.attestationDigest, m.risk, m.modelName, m.attestationUri, m.registeredAt, m.exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
function epochOf(address provider, bytes32 modelId, uint64 epochId) external view returns (
|
||||||
|
bytes32 root, uint64 committedAt, uint64 inferenceCount, string memory metadataUri
|
||||||
|
) {
|
||||||
|
EpochCommitment storage e = _commits[provider][modelId][epochId];
|
||||||
|
return (e.root, e.committedAt, e.inferenceCount, e.metadataUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Verify that a specific (requestHash, responseHash, timestampMs,
|
||||||
|
/// deployerId) tuple is committed under the provider's root for
|
||||||
|
/// (modelId, epochId). Returns false if the proof is invalid or the
|
||||||
|
/// (modelId, epoch) was never committed.
|
||||||
|
/// AUDIT FIX (HIGH #25): modelId is now part of the lookup key.
|
||||||
|
function verifyInference(
|
||||||
|
address provider,
|
||||||
|
bytes32 modelId,
|
||||||
|
uint64 epochId,
|
||||||
|
bytes32 requestHash,
|
||||||
|
bytes32 responseHash,
|
||||||
|
uint64 timestampMs,
|
||||||
|
bytes32 deployerId,
|
||||||
|
bytes32[] calldata proof
|
||||||
|
) external view returns (bool) {
|
||||||
|
EpochCommitment storage e = _commits[provider][modelId][epochId];
|
||||||
|
if (e.committedAt == 0) return false;
|
||||||
|
bytes32 leaf = keccak256(abi.encode(requestHash, responseHash, timestampMs, deployerId));
|
||||||
|
return _verifyProof(proof, e.root, leaf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =============================== internal =============================== */
|
||||||
|
|
||||||
|
/// @dev OpenZeppelin-style Merkle proof verification (sorted-pairs hashing).
|
||||||
|
function _verifyProof(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
|
||||||
|
bytes32 h = leaf;
|
||||||
|
for (uint256 i = 0; i < proof.length; i++) {
|
||||||
|
bytes32 p = proof[i];
|
||||||
|
h = h <= p ? keccak256(abi.encodePacked(h, p)) : keccak256(abi.encodePacked(p, h));
|
||||||
|
}
|
||||||
|
return h == root;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,649 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
|
||||||
|
|
||||||
|
/// @dev The one AERE402Facilitator surface paidQuery consumes. The facilitator is the
|
||||||
|
/// existing agentic payment rail (see contracts/agentic/AERE402Facilitator.sol); this
|
||||||
|
/// contract references it and never redeploys it. `settle` debits the paying agent's
|
||||||
|
/// prepaid balance (via the AereAgent registry the facilitator is bound to), takes the
|
||||||
|
/// 25-bps protocol fee to AereSink, and transfers the remainder to `payee`. paidQuery
|
||||||
|
/// passes address(this) as `payee` so the facilitator's own `msg.sender == payee` guard
|
||||||
|
/// is satisfied, then forwards the received tokens to the store's payment recipient.
|
||||||
|
interface IAERE402Facilitator {
|
||||||
|
function settle(
|
||||||
|
uint256 agentId,
|
||||||
|
address token,
|
||||||
|
address payee,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 resourceId,
|
||||||
|
uint256 nonce,
|
||||||
|
uint256 deadline,
|
||||||
|
bytes calldata signature
|
||||||
|
) external;
|
||||||
|
|
||||||
|
function consumed(uint256 agentId, uint256 nonce) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereVectorStore, verifiable semantic memory for AI agents on AERE (chain 2800)
|
||||||
|
*
|
||||||
|
* @notice On-chain provenance, ownership and attested-retrieval for an AI agent's vector
|
||||||
|
* store (its long-term semantic memory). An owner (an account or an agent identity)
|
||||||
|
* commits a VERSIONED commitment root over the vectors + metadata it stores off-chain;
|
||||||
|
* a retrieval provider later attests "for this query, against store version V, these
|
||||||
|
* are the results (resultRoot)". A consumer can then verify, on-chain, that a returned
|
||||||
|
* vector was actually a member of a committed store version, that the retrieval named a
|
||||||
|
* committed version, and who owns the memory. Query access is metered through the
|
||||||
|
* existing AERE402 agentic payment rail.
|
||||||
|
*
|
||||||
|
* WHAT THE CHAIN GUARANTEES (buildable NOW, tested):
|
||||||
|
* 1. AUTHENTICITY of the committed root. A commit to a post-quantum store must carry
|
||||||
|
* a Falcon-512 signature that verifies, in full, on-chain, through AERE's LIVE
|
||||||
|
* native precompile at 0x0AE1 over this contract's per-version challenge. An
|
||||||
|
* invalid signature is rejected fail-closed; nothing is recorded.
|
||||||
|
* 2. APPEND-ONLY HISTORY. Each commit appends a new version; no function can rewrite
|
||||||
|
* or delete a committed root. There is no admin, no owner override, no upgrade
|
||||||
|
* hook. The current root and every past version stay queryable forever.
|
||||||
|
* 3. RETRIEVAL-AGAINST-A-COMMITTED-VERSION. attestRetrieval reverts unless the named
|
||||||
|
* version exists (1..current). A recorded attestation therefore always references a
|
||||||
|
* real, committed store state, and carries an inclusion-proof shape so a consumer
|
||||||
|
* can check a returned vector was in the committed root.
|
||||||
|
* 4. OWNERSHIP. Every store is bound to an owner at creation; a classical store's
|
||||||
|
* commits require msg.sender == owner, a post-quantum store's commits require the
|
||||||
|
* Falcon key (authorship IS the PQC signature, so a relayer only pays gas).
|
||||||
|
* 5. PAID, ATTESTED RETRIEVAL. On a priced store, a retrieval attestation must be
|
||||||
|
* backed by an AERE402 payment (paidQuery), so retrieval is metered on the rail.
|
||||||
|
*
|
||||||
|
* WHAT THE CHAIN DOES NOT GUARANTEE (off-chain, [MEASURE]):
|
||||||
|
* - It does NOT compute embeddings, does NOT run the vector similarity search, and
|
||||||
|
* does NOT hold the vectors. The embedding model + the nearest-neighbour index +
|
||||||
|
* the raw vector data all live off-chain. The chain proves PROVENANCE and OWNERSHIP
|
||||||
|
* of a committed root and that a retrieval named a committed version; it does NOT
|
||||||
|
* and CANNOT prove that the embeddings are semantically good, that the index is
|
||||||
|
* well-built, or that the provider ran an honest similarity search. Semantic
|
||||||
|
* quality is an off-chain property, measured off-chain.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer PQC authentication + settlement. This does NOT change
|
||||||
|
* AERE consensus: blocks are still produced and signed by Besu QBFT validators with
|
||||||
|
* classical ECDSA (secp256k1). PQC-authenticated memory commits do not make consensus
|
||||||
|
* post-quantum. What is post-quantum here is the AUTHENTICITY of a store commit, via the
|
||||||
|
* live Falcon-512 precompile. No new token is introduced; paid queries settle on the
|
||||||
|
* existing AERE402 rail in whatever ERC-20 the store owner selects.
|
||||||
|
*
|
||||||
|
* @dev Falcon-512 precompile I/O (0x0AE1), identical to AerePQCAttestation:
|
||||||
|
* input = pk(897) || sm
|
||||||
|
* sm = sigLen(2, big-endian) || nonce(40) || message(32) || esig
|
||||||
|
* esig = 0x29 || compressedSig, sigLen == esig.length
|
||||||
|
* falconSig = nonce(40) || esig (the envelope handed to commit)
|
||||||
|
* Output: a 32-byte word, 0x..01 valid else 0x..00. An empty/zero return (a stale
|
||||||
|
* caller hitting an address with no precompile) is treated as INVALID, so a pre-fork
|
||||||
|
* node can never record a commit.
|
||||||
|
*/
|
||||||
|
contract AereVectorStore is ReentrancyGuard {
|
||||||
|
using MerkleProof for bytes32[];
|
||||||
|
|
||||||
|
/* ------------------------------ Falcon-512 ------------------------------ */
|
||||||
|
|
||||||
|
uint8 internal constant SCHEME_FALCON512 = 1;
|
||||||
|
address public constant PRECOMPILE_FALCON512 = address(0x0AE1);
|
||||||
|
uint256 internal constant FALCON512_PK_LEN = 897;
|
||||||
|
uint8 internal constant FALCON512_PK_HEADER = 0x09; // 0x00 | logn=9
|
||||||
|
uint256 internal constant FALCON_NONCE_LEN = 40;
|
||||||
|
|
||||||
|
/// @notice Domain tag binding a commit challenge to THIS contract + chain + store + version.
|
||||||
|
bytes32 public constant COMMIT_DOMAIN = keccak256("AereVectorStore.v1.commit");
|
||||||
|
/// @notice Domain tag binding a paid-query resourceId to THIS contract + chain + store + query.
|
||||||
|
bytes32 public constant QUERY_DOMAIN = keccak256("AereVectorStore.v1.query");
|
||||||
|
|
||||||
|
/* ------------------------------- payment rail ---------------------------- */
|
||||||
|
|
||||||
|
/// @notice The existing AERE402 facilitator. Immutable; referenced, never redeployed.
|
||||||
|
IAERE402Facilitator public immutable FACILITATOR;
|
||||||
|
|
||||||
|
/* --------------------------------- types -------------------------------- */
|
||||||
|
|
||||||
|
struct Store {
|
||||||
|
bool exists;
|
||||||
|
address owner; // account / agent identity that owns the memory (fixed at creation)
|
||||||
|
address settlementToken; // ERC-20 that priced queries settle in (0 => free store)
|
||||||
|
address paymentRecipient; // where paidQuery net proceeds go (owner or retrieval provider)
|
||||||
|
uint256 queryPrice; // minimum AERE402 payment per query (0 => free, no payment gate)
|
||||||
|
uint64 version; // current version count (0 => no commits yet)
|
||||||
|
bytes falconPubKey; // empty => classical store; 897-byte Falcon-512 key => PQC store
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Version {
|
||||||
|
bytes32 vectorRoot; // Merkle/commitment root over the stored vectors + metadata
|
||||||
|
uint64 vectorCount; // number of vectors the root commits to
|
||||||
|
uint64 committedAt; // block.timestamp of the commit
|
||||||
|
uint64 blockNumber; // block the commit landed in
|
||||||
|
string uri; // pointer to the off-chain index snapshot (ipfs:// / https://)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Retrieval {
|
||||||
|
bool exists;
|
||||||
|
uint64 version; // the committed store version this retrieval was against
|
||||||
|
uint64 attestedAt;
|
||||||
|
uint64 blockNumber;
|
||||||
|
address provider; // the attester (retrieval provider)
|
||||||
|
bytes32 queryHash; // commitment to the query the results answer
|
||||||
|
bytes32 resultRoot; // Merkle root over the returned result set
|
||||||
|
}
|
||||||
|
|
||||||
|
struct QueryReceipt {
|
||||||
|
bool exists;
|
||||||
|
bool consumed; // flipped true when an attestRetrieval binds to it (one-shot)
|
||||||
|
uint64 paidAtVersion; // store version at payment time (informational)
|
||||||
|
bytes32 storeId; // the store the payment was for (binds a receipt to one store)
|
||||||
|
bytes32 queryHash; // the query the payment was for
|
||||||
|
uint256 amount; // gross amount paid through the rail
|
||||||
|
address payer; // msg.sender of paidQuery (provider relayer or consumer)
|
||||||
|
address provider; // the ONLY address allowed to consume this receipt in attestRetrieval
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- storage ------------------------------- */
|
||||||
|
|
||||||
|
mapping(bytes32 => Store) internal _stores;
|
||||||
|
mapping(bytes32 => Version[]) internal _versions; // storeId => append-only version history
|
||||||
|
mapping(bytes32 => Retrieval) internal _retrievals; // retrievalId => Retrieval
|
||||||
|
mapping(bytes32 => uint64) public retrievalCount; // storeId => number of attestations
|
||||||
|
mapping(bytes32 => QueryReceipt) internal _receipts; // receiptId => QueryReceipt
|
||||||
|
|
||||||
|
/// @notice Total commits recorded across all stores (monotonic).
|
||||||
|
uint256 public commitCount;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event StoreCreated(
|
||||||
|
bytes32 indexed storeId,
|
||||||
|
address indexed owner,
|
||||||
|
bool postQuantum,
|
||||||
|
address settlementToken,
|
||||||
|
uint256 queryPrice,
|
||||||
|
address paymentRecipient
|
||||||
|
);
|
||||||
|
event Committed(
|
||||||
|
bytes32 indexed storeId,
|
||||||
|
uint64 indexed version,
|
||||||
|
bytes32 vectorRoot,
|
||||||
|
uint64 vectorCount,
|
||||||
|
bytes32 challenge,
|
||||||
|
string uri
|
||||||
|
);
|
||||||
|
event RetrievalAttested(
|
||||||
|
bytes32 indexed storeId,
|
||||||
|
bytes32 indexed retrievalId,
|
||||||
|
uint64 indexed version,
|
||||||
|
address provider,
|
||||||
|
bytes32 queryHash,
|
||||||
|
bytes32 resultRoot
|
||||||
|
);
|
||||||
|
event QueryPaid(
|
||||||
|
bytes32 indexed storeId,
|
||||||
|
bytes32 indexed receiptId,
|
||||||
|
address indexed payer,
|
||||||
|
uint256 agentId,
|
||||||
|
uint256 amount,
|
||||||
|
bytes32 queryHash
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error StoreExists();
|
||||||
|
error UnknownStore();
|
||||||
|
error InvalidPubKey();
|
||||||
|
error InvalidConfig();
|
||||||
|
error NotOwner();
|
||||||
|
error EmptyRoot();
|
||||||
|
error InvalidSignatureLength();
|
||||||
|
error PQCVerificationFailed();
|
||||||
|
error UnknownVersion();
|
||||||
|
error StoreIsFree();
|
||||||
|
error PaymentRequired();
|
||||||
|
error ReceiptExists();
|
||||||
|
error ReceiptConsumed();
|
||||||
|
error ReceiptMismatch();
|
||||||
|
error NotReceiptProvider();
|
||||||
|
error Underpaid(uint256 paid, uint256 price);
|
||||||
|
error UnknownRetrieval();
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* ------------------------------- constructor ---------------------------- */
|
||||||
|
|
||||||
|
/// @param facilitator the existing AERE402Facilitator (the agentic payment rail).
|
||||||
|
constructor(address facilitator) {
|
||||||
|
if (facilitator == address(0)) revert ZeroAddress();
|
||||||
|
FACILITATOR = IAERE402Facilitator(facilitator);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ stores ================================ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Create a vector store bound to msg.sender as owner. Config is fixed at creation:
|
||||||
|
* there is no setter for the Falcon key, the price, the token or the recipient, so
|
||||||
|
* a store's authentication mode and payment terms cannot be silently changed later.
|
||||||
|
* @param storeId caller-chosen identifier (must be unused).
|
||||||
|
* @param falconPubKey empty for a classical (owner-signed) store, or a 897-byte
|
||||||
|
* Falcon-512 public key (header 0x09) for a post-quantum store whose
|
||||||
|
* commits are authenticated by the live 0x0AE1 precompile.
|
||||||
|
* @param settlementToken ERC-20 that priced queries settle in (must be set iff queryPrice>0).
|
||||||
|
* @param queryPrice minimum AERE402 payment per query, in settlementToken units
|
||||||
|
* (0 => free store, retrieval attestations need no payment).
|
||||||
|
* @param paymentRecipient where paidQuery net proceeds are forwarded (must be set iff priced).
|
||||||
|
*/
|
||||||
|
function createStore(
|
||||||
|
bytes32 storeId,
|
||||||
|
bytes calldata falconPubKey,
|
||||||
|
address settlementToken,
|
||||||
|
uint256 queryPrice,
|
||||||
|
address paymentRecipient
|
||||||
|
) external {
|
||||||
|
if (_stores[storeId].exists) revert StoreExists();
|
||||||
|
|
||||||
|
bool postQuantum = falconPubKey.length != 0;
|
||||||
|
if (postQuantum) {
|
||||||
|
// Fail-closed on a malformed PQC key: a store can never be created with a Falcon
|
||||||
|
// key the precompile could not parse.
|
||||||
|
if (falconPubKey.length != FALCON512_PK_LEN || uint8(falconPubKey[0]) != FALCON512_PK_HEADER) {
|
||||||
|
revert InvalidPubKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pricing config must be internally consistent: a priced store needs a token to be
|
||||||
|
// paid in and a recipient to be paid to; a free store must set neither.
|
||||||
|
if (queryPrice != 0) {
|
||||||
|
if (settlementToken == address(0) || paymentRecipient == address(0)) revert InvalidConfig();
|
||||||
|
} else {
|
||||||
|
if (settlementToken != address(0) || paymentRecipient != address(0)) revert InvalidConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
s.exists = true;
|
||||||
|
s.owner = msg.sender;
|
||||||
|
s.settlementToken = settlementToken;
|
||||||
|
s.paymentRecipient = paymentRecipient;
|
||||||
|
s.queryPrice = queryPrice;
|
||||||
|
s.falconPubKey = falconPubKey;
|
||||||
|
|
||||||
|
emit StoreCreated(storeId, msg.sender, postQuantum, settlementToken, queryPrice, paymentRecipient);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Append a new versioned commitment root for a store. Version numbers start at 1 and
|
||||||
|
* increase by exactly one per commit; the challenge binds the version, so a signature
|
||||||
|
* is single-use and history is append-only.
|
||||||
|
*
|
||||||
|
* AUTHENTICATION:
|
||||||
|
* - post-quantum store: `falconSig` MUST verify, on-chain via 0x0AE1, over
|
||||||
|
* commitChallenge(...). An invalid or malformed signature reverts
|
||||||
|
* PQCVerificationFailed / InvalidSignatureLength and records nothing (fail-closed).
|
||||||
|
* msg.sender is unrestricted: authorship is the Falcon signature, so any relayer
|
||||||
|
* may submit and only the key holder can produce a valid commit.
|
||||||
|
* - classical store: msg.sender MUST be the owner; `falconSig` is ignored.
|
||||||
|
*
|
||||||
|
* @return version the new version number (== the store's current version after this call).
|
||||||
|
*/
|
||||||
|
function commit(
|
||||||
|
bytes32 storeId,
|
||||||
|
bytes32 vectorRoot,
|
||||||
|
uint64 vectorCount,
|
||||||
|
string calldata uri,
|
||||||
|
bytes calldata falconSig
|
||||||
|
) external returns (uint64 version) {
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
if (vectorRoot == bytes32(0)) revert EmptyRoot();
|
||||||
|
|
||||||
|
version = s.version + 1;
|
||||||
|
bytes32 challenge = commitChallenge(storeId, version, vectorRoot, vectorCount, uri);
|
||||||
|
|
||||||
|
if (s.falconPubKey.length != 0) {
|
||||||
|
// Fail-closed post-quantum authentication.
|
||||||
|
if (!_verifyFalcon512(s.falconPubKey, challenge, falconSig)) revert PQCVerificationFailed();
|
||||||
|
} else {
|
||||||
|
// Classical owner authentication.
|
||||||
|
if (msg.sender != s.owner) revert NotOwner();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effects: append the new version. No path can overwrite an earlier entry.
|
||||||
|
_versions[storeId].push(
|
||||||
|
Version({
|
||||||
|
vectorRoot: vectorRoot,
|
||||||
|
vectorCount: vectorCount,
|
||||||
|
committedAt: uint64(block.timestamp),
|
||||||
|
blockNumber: uint64(block.number),
|
||||||
|
uri: uri
|
||||||
|
})
|
||||||
|
);
|
||||||
|
s.version = version;
|
||||||
|
commitCount += 1;
|
||||||
|
|
||||||
|
emit Committed(storeId, version, vectorRoot, vectorCount, challenge, uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== retrieval =============================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Record a retrieval attestation: a provider (msg.sender) attests that, for `queryHash`
|
||||||
|
* against committed store `version`, the returned result set is committed by `resultRoot`.
|
||||||
|
* The named version MUST exist (1..current) or the call reverts fail-closed, so an
|
||||||
|
* attestation can never reference a store state that was never committed.
|
||||||
|
*
|
||||||
|
* On a PRICED store, the attestation MUST be backed by a matching, unconsumed AERE402
|
||||||
|
* payment receipt (see paidQuery); the receipt is consumed one-shot AND only its bound
|
||||||
|
* provider (recorded at paidQuery) may consume it, so a third party cannot front-run the
|
||||||
|
* honest provider to burn the receipt with a junk resultRoot. On a FREE store, `receiptId`
|
||||||
|
* is ignored.
|
||||||
|
*
|
||||||
|
* @param version the committed store version the retrieval ran against.
|
||||||
|
* @param queryHash commitment to the query (e.g. keccak256 of the normalized query embedding).
|
||||||
|
* @param resultRoot Merkle root over the returned result set (leaves = per-result commitments).
|
||||||
|
* @param receiptId the paidQuery receipt backing this retrieval (priced stores only).
|
||||||
|
* @return retrievalId deterministic id of the recorded attestation.
|
||||||
|
*/
|
||||||
|
function attestRetrieval(
|
||||||
|
bytes32 storeId,
|
||||||
|
uint64 version,
|
||||||
|
bytes32 queryHash,
|
||||||
|
bytes32 resultRoot,
|
||||||
|
bytes32 receiptId
|
||||||
|
) external returns (bytes32 retrievalId) {
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
// Fail-closed: the store version must have been committed.
|
||||||
|
if (version == 0 || version > s.version) revert UnknownVersion();
|
||||||
|
if (resultRoot == bytes32(0)) revert EmptyRoot();
|
||||||
|
|
||||||
|
// Payment gate for priced stores.
|
||||||
|
if (s.queryPrice != 0) {
|
||||||
|
QueryReceipt storage r = _receipts[receiptId];
|
||||||
|
if (!r.exists) revert PaymentRequired();
|
||||||
|
if (r.consumed) revert ReceiptConsumed();
|
||||||
|
// Only the provider the payer bound at paidQuery may consume this receipt. Without this a
|
||||||
|
// third party could front-run the honest provider and burn the receipt with a junk
|
||||||
|
// resultRoot (griefing / denial-of-service on a paid-for retrieval).
|
||||||
|
if (r.provider != msg.sender) revert NotReceiptProvider();
|
||||||
|
if (r.storeId != storeId || r.queryHash != queryHash) revert ReceiptMismatch();
|
||||||
|
if (r.amount < s.queryPrice) revert Underpaid(r.amount, s.queryPrice);
|
||||||
|
r.consumed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint64 idx = retrievalCount[storeId];
|
||||||
|
retrievalId = keccak256(abi.encode(address(this), storeId, idx));
|
||||||
|
_retrievals[retrievalId] = Retrieval({
|
||||||
|
exists: true,
|
||||||
|
version: version,
|
||||||
|
attestedAt: uint64(block.timestamp),
|
||||||
|
blockNumber: uint64(block.number),
|
||||||
|
provider: msg.sender,
|
||||||
|
queryHash: queryHash,
|
||||||
|
resultRoot: resultRoot
|
||||||
|
});
|
||||||
|
retrievalCount[storeId] = idx + 1;
|
||||||
|
|
||||||
|
emit RetrievalAttested(storeId, retrievalId, version, msg.sender, queryHash, resultRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== paid query ============================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Pay for a query against a priced store, on the existing AERE402 rail, and mint a
|
||||||
|
* receipt that a retrieval provider can later cite in attestRetrieval. The paying
|
||||||
|
* AGENT authorizes the payment with its EIP-712 signature to the facilitator (exactly
|
||||||
|
* as any AERE402 payment); this contract is the `payee`, so the facilitator debits the
|
||||||
|
* agent, takes the protocol fee to AereSink, and transfers the remainder here, which is
|
||||||
|
* then forwarded to the store's payment recipient in the same transaction. This contract
|
||||||
|
* custodies no balance across calls.
|
||||||
|
*
|
||||||
|
* @param queryHash commitment to the query being paid for (bound into the receipt + resourceId).
|
||||||
|
* @param provider the retrieval provider this payment is for; the ONLY address that may later
|
||||||
|
* consume the minted receipt in attestRetrieval (binds the receipt so a third
|
||||||
|
* party cannot grief the honest provider). Must be non-zero.
|
||||||
|
* @param agentId the paying AERE402 agent id (in the AereAgent registry the facilitator uses).
|
||||||
|
* @param amount gross payment; must be >= the store's queryPrice.
|
||||||
|
* @param nonce the agent's AERE402 nonce for this payment (facilitator replay guard).
|
||||||
|
* @param deadline unix seconds after which the payment auth is stale.
|
||||||
|
* @param authSig the agent's EIP-712 PaymentAuth signature over (agentId, token, this, amount,
|
||||||
|
* resourceId, nonce, deadline) for the facilitator.
|
||||||
|
* @return receiptId deterministic id of the minted receipt.
|
||||||
|
*/
|
||||||
|
function paidQuery(
|
||||||
|
bytes32 storeId,
|
||||||
|
bytes32 queryHash,
|
||||||
|
address provider,
|
||||||
|
uint256 agentId,
|
||||||
|
uint256 amount,
|
||||||
|
uint256 nonce,
|
||||||
|
uint256 deadline,
|
||||||
|
bytes calldata authSig
|
||||||
|
) external nonReentrant returns (bytes32 receiptId) {
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
if (s.queryPrice == 0) revert StoreIsFree();
|
||||||
|
if (provider == address(0)) revert ZeroAddress();
|
||||||
|
if (amount < s.queryPrice) revert Underpaid(amount, s.queryPrice);
|
||||||
|
|
||||||
|
receiptId = keccak256(abi.encode(address(this), storeId, queryHash, agentId, nonce));
|
||||||
|
if (_receipts[receiptId].exists) revert ReceiptExists();
|
||||||
|
|
||||||
|
address token = s.settlementToken;
|
||||||
|
address recipient = s.paymentRecipient;
|
||||||
|
|
||||||
|
// Bind the payment to THIS store + query so the facilitator's resourceId is meaningful.
|
||||||
|
bytes32 resourceId = queryResourceId(storeId, queryHash);
|
||||||
|
|
||||||
|
// Settle on the AERE402 rail. address(this) is the payee, satisfying the facilitator's
|
||||||
|
// msg.sender == payee guard. The facilitator sends (amount - fee) here; measure the delta
|
||||||
|
// so a changed fee never strands tokens, then forward the whole receipt to the recipient.
|
||||||
|
uint256 balBefore = IERC20(token).balanceOf(address(this));
|
||||||
|
FACILITATOR.settle(agentId, token, address(this), amount, resourceId, nonce, deadline, authSig);
|
||||||
|
uint256 received = IERC20(token).balanceOf(address(this)) - balBefore;
|
||||||
|
|
||||||
|
if (received > 0) {
|
||||||
|
if (!IERC20(token).transfer(recipient, received)) revert TransferFailed();
|
||||||
|
}
|
||||||
|
|
||||||
|
_receipts[receiptId] = QueryReceipt({
|
||||||
|
exists: true,
|
||||||
|
consumed: false,
|
||||||
|
paidAtVersion: s.version,
|
||||||
|
storeId: storeId,
|
||||||
|
queryHash: queryHash,
|
||||||
|
amount: amount,
|
||||||
|
payer: msg.sender,
|
||||||
|
provider: provider
|
||||||
|
});
|
||||||
|
|
||||||
|
emit QueryPaid(storeId, receiptId, msg.sender, agentId, amount, queryHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================= inclusion ============================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Verify that `leaf` is a member of a committed store version's vectorRoot. This is the
|
||||||
|
* consumer's check that a returned vector was ACTUALLY in the committed store at version
|
||||||
|
* V. The leaf is the caller-supplied commitment to the vector + its metadata; the proof
|
||||||
|
* is a standard OpenZeppelin (sorted-pair keccak256) Merkle proof against vectorRoot.
|
||||||
|
* @dev Proves membership in a committed root only. It says nothing about semantic relevance;
|
||||||
|
* relevance is an off-chain property.
|
||||||
|
*/
|
||||||
|
function verifyVectorInclusion(bytes32 storeId, uint64 version, bytes32 leaf, bytes32[] calldata proof)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
if (version == 0 || version > s.version) revert UnknownVersion();
|
||||||
|
bytes32 root = _versions[storeId][version - 1].vectorRoot;
|
||||||
|
return proof.verify(root, leaf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Verify that `leaf` is a member of a recorded retrieval's resultRoot, i.e. that the
|
||||||
|
* returned result the consumer holds was in the set the provider attested to.
|
||||||
|
*/
|
||||||
|
function verifyResultInclusion(bytes32 retrievalId, bytes32 leaf, bytes32[] calldata proof)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
Retrieval storage r = _retrievals[retrievalId];
|
||||||
|
if (!r.exists) revert UnknownRetrieval();
|
||||||
|
return proof.verify(r.resultRoot, leaf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ views ================================ */
|
||||||
|
|
||||||
|
/// @notice The exact 32-byte challenge a Falcon-512 commit must sign for (storeId, version).
|
||||||
|
/// Off-chain signers query this to know what to sign.
|
||||||
|
function commitChallenge(bytes32 storeId, uint64 version, bytes32 vectorRoot, uint64 vectorCount, string calldata uri)
|
||||||
|
public
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(COMMIT_DOMAIN, block.chainid, address(this), storeId, version, vectorRoot, vectorCount, keccak256(bytes(uri)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The resourceId a paidQuery binds into its AERE402 settlement for (storeId, queryHash).
|
||||||
|
function queryResourceId(bytes32 storeId, bytes32 queryHash) public view returns (bytes32) {
|
||||||
|
return keccak256(abi.encode(QUERY_DOMAIN, block.chainid, address(this), storeId, queryHash));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff the store exists.
|
||||||
|
function storeExists(bytes32 storeId) external view returns (bool) {
|
||||||
|
return _stores[storeId].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a store's configuration and current version count.
|
||||||
|
function getStore(bytes32 storeId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
bool exists,
|
||||||
|
address owner,
|
||||||
|
bool postQuantum,
|
||||||
|
address settlementToken,
|
||||||
|
uint256 queryPrice,
|
||||||
|
address paymentRecipient,
|
||||||
|
uint64 version
|
||||||
|
)
|
||||||
|
{
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
return (s.exists, s.owner, s.falconPubKey.length != 0, s.settlementToken, s.queryPrice, s.paymentRecipient, s.version);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The registered Falcon-512 public key for a store (empty for a classical store).
|
||||||
|
function falconKeyOf(bytes32 storeId) external view returns (bytes memory) {
|
||||||
|
return _stores[storeId].falconPubKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The number of committed versions for a store (== current version; 0 if none).
|
||||||
|
function versionCount(bytes32 storeId) external view returns (uint64) {
|
||||||
|
return _stores[storeId].version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The current (latest) committed root for a store. Reverts if nothing committed yet.
|
||||||
|
function currentRoot(bytes32 storeId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (uint64 version, bytes32 vectorRoot, uint64 vectorCount, string memory uri)
|
||||||
|
{
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
if (s.version == 0) revert UnknownVersion();
|
||||||
|
Version storage v = _versions[storeId][s.version - 1];
|
||||||
|
return (s.version, v.vectorRoot, v.vectorCount, v.uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read any committed version (1..current) of a store.
|
||||||
|
function getVersion(bytes32 storeId, uint64 version)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bytes32 vectorRoot, uint64 vectorCount, uint64 committedAt, uint64 blockNumber, string memory uri)
|
||||||
|
{
|
||||||
|
Store storage s = _stores[storeId];
|
||||||
|
if (!s.exists) revert UnknownStore();
|
||||||
|
if (version == 0 || version > s.version) revert UnknownVersion();
|
||||||
|
Version storage v = _versions[storeId][version - 1];
|
||||||
|
return (v.vectorRoot, v.vectorCount, v.committedAt, v.blockNumber, v.uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a recorded retrieval attestation.
|
||||||
|
function getRetrieval(bytes32 retrievalId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
bool exists,
|
||||||
|
uint64 version,
|
||||||
|
address provider,
|
||||||
|
bytes32 queryHash,
|
||||||
|
bytes32 resultRoot,
|
||||||
|
uint64 attestedAt,
|
||||||
|
uint64 blockNumber
|
||||||
|
)
|
||||||
|
{
|
||||||
|
Retrieval storage r = _retrievals[retrievalId];
|
||||||
|
return (r.exists, r.version, r.provider, r.queryHash, r.resultRoot, r.attestedAt, r.blockNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a paid-query receipt.
|
||||||
|
function getReceipt(bytes32 receiptId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
bool exists,
|
||||||
|
bool consumed,
|
||||||
|
bytes32 storeId,
|
||||||
|
bytes32 queryHash,
|
||||||
|
uint256 amount,
|
||||||
|
address payer,
|
||||||
|
uint64 paidAtVersion,
|
||||||
|
address provider
|
||||||
|
)
|
||||||
|
{
|
||||||
|
QueryReceipt storage r = _receipts[receiptId];
|
||||||
|
return (r.exists, r.consumed, r.storeId, r.queryHash, r.amount, r.payer, r.paidAtVersion, r.provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ Falcon-512 verify ========================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Build the exact Falcon-512 precompile input for `message`, staticcall 0x0AE1, and return
|
||||||
|
* true iff it answers 0x..01. `falconSig` = nonce(40) || esig. Any empty/short/zero return
|
||||||
|
* (a pre-fork node) is invalid. Same construction as AerePQCAttestation, restricted to
|
||||||
|
* Falcon-512.
|
||||||
|
*/
|
||||||
|
function _verifyFalcon512(bytes memory pubKey, bytes32 message, bytes memory falconSig)
|
||||||
|
internal
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
if (falconSig.length <= FALCON_NONCE_LEN) revert InvalidSignatureLength();
|
||||||
|
uint256 sigLen = falconSig.length - FALCON_NONCE_LEN; // esig length
|
||||||
|
if (sigLen > type(uint16).max) revert InvalidSignatureLength();
|
||||||
|
|
||||||
|
bytes memory nonce = _slice(falconSig, 0, FALCON_NONCE_LEN);
|
||||||
|
bytes memory esig = _slice(falconSig, FALCON_NONCE_LEN, sigLen);
|
||||||
|
|
||||||
|
// sm = sigLen(2, big-endian) || nonce(40) || message(32) || esig
|
||||||
|
bytes memory sm = abi.encodePacked(uint16(sigLen), nonce, message, esig);
|
||||||
|
bytes memory input = abi.encodePacked(pubKey, sm);
|
||||||
|
|
||||||
|
(bool ok, bytes memory ret) = PRECOMPILE_FALCON512.staticcall(input);
|
||||||
|
return ok && ret.length >= 32 && ret[31] == 0x01;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _slice(bytes memory data, uint256 start, uint256 len) internal pure returns (bytes memory out) {
|
||||||
|
out = new bytes(len);
|
||||||
|
for (uint256 i = 0; i < len; i++) {
|
||||||
|
out[i] = data[start + i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Subset of the LIVE AereStorageProofVerifier used by this anchor.
|
||||||
|
* `verify` is a stateless view that reverts on an invalid SP1 proof and
|
||||||
|
* otherwise returns the tuple committed in the 192-byte public values.
|
||||||
|
* `submitProofWithExpectedRoot` re-verifies and records the slot only if
|
||||||
|
* the proof's committed stateRoot equals `expectedStateRoot`.
|
||||||
|
*/
|
||||||
|
interface IAereStorageProofVerifier {
|
||||||
|
function verify(bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 blockNumber,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
address account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
);
|
||||||
|
|
||||||
|
function submitProofWithExpectedRoot(
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata proof,
|
||||||
|
bytes32 expectedStateRoot
|
||||||
|
) external returns (bytes32 value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereHistoryStateRootAnchor
|
||||||
|
* @notice EIP-2935 sibling of AereStateRootAnchor. It binds an AERE state root
|
||||||
|
* to the CANONICAL chain for blocks FAR OLDER than the 256-block
|
||||||
|
* BLOCKHASH window, closing the same trust gap AereStorageProofVerifier
|
||||||
|
* leaves open (that verifier proves a value against a GIVEN root but
|
||||||
|
* cannot show the root is canonical).
|
||||||
|
*
|
||||||
|
* WHERE THE BLOCK HASH COMES FROM (this is the whole point).
|
||||||
|
* The canonical block hash is read, at call time, from the EIP-2935
|
||||||
|
* history-storage system contract at
|
||||||
|
* 0x0000F90827F1C53a10cb7A02335B175320002935 via STATICCALL. That
|
||||||
|
* contract is a protocol-native ring buffer: on the AerePQC fork
|
||||||
|
* (futureEips milestone, same futureEipsTime activation as the native
|
||||||
|
* PQC precompiles) Besu's PraguePreExecutionProcessor writes the parent
|
||||||
|
* block hash into slot (number-1) % 8191 at the start of EVERY block,
|
||||||
|
* as a system call from address 0xffff...fffe. No externally-owned
|
||||||
|
* account, relayer, keeper, or Foundation key ever writes it. The value
|
||||||
|
* this anchor trusts is therefore produced by consensus itself, exactly
|
||||||
|
* like the BLOCKHASH opcode but with an 8191-block reach instead of 256.
|
||||||
|
*
|
||||||
|
* At AERE's 0.5s block time, 8191 blocks is roughly 68 minutes of
|
||||||
|
* reach, versus the ~128 seconds BLOCKHASH gives. Once a header is
|
||||||
|
* anchored here, the (blockNumber -> stateRoot) record is permanent and
|
||||||
|
* independent of the moving 8191-block ring buffer.
|
||||||
|
*
|
||||||
|
* The block hash is recovered strictly from the system contract, never
|
||||||
|
* from a caller argument, so an attacker cannot anchor a fabricated
|
||||||
|
* root: keccak256(rlpHeader) must equal the ring buffer's answer.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY: VERIFIER is fixed at deploy. No owner, no admin, no
|
||||||
|
* upgrade path. Anyone may anchor any in-window header and anyone may
|
||||||
|
* prove against an anchored root.
|
||||||
|
*/
|
||||||
|
contract AereHistoryStateRootAnchor {
|
||||||
|
/// @notice Live AereStorageProofVerifier this anchor drives for proofs.
|
||||||
|
IAereStorageProofVerifier public immutable VERIFIER;
|
||||||
|
|
||||||
|
/// @notice EIP-2935 history-storage system contract (protocol-written ring buffer).
|
||||||
|
address public constant HISTORY_STORAGE_ADDRESS =
|
||||||
|
0x0000F90827F1C53a10cb7A02335B175320002935;
|
||||||
|
|
||||||
|
/// @notice EIP-2935 serve window: the ring buffer addresses the last 8191 blocks.
|
||||||
|
uint256 public constant HISTORY_SERVE_WINDOW = 8191;
|
||||||
|
|
||||||
|
struct AnchoredRoot {
|
||||||
|
bool exists;
|
||||||
|
bytes32 stateRoot; // header field index 3
|
||||||
|
bytes32 blockHash; // canonical hash the header was checked against
|
||||||
|
uint64 blockNumber;
|
||||||
|
uint64 verifiedAt; // block.timestamp when anchored
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice blockNumber => anchored canonical state root record.
|
||||||
|
mapping(uint256 => AnchoredRoot) private _anchored;
|
||||||
|
|
||||||
|
event HeaderAnchored(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed blockHash,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
uint256 verifiedAt
|
||||||
|
);
|
||||||
|
|
||||||
|
event ProvenAgainstAnchor(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed stateRoot,
|
||||||
|
address indexed account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
);
|
||||||
|
|
||||||
|
error ZeroVerifier();
|
||||||
|
error OutOfHistoryWindow(uint256 blockNumber, uint256 currentBlock);
|
||||||
|
error HistoryContractMissing();
|
||||||
|
error HeaderHashMismatch(bytes32 got, bytes32 canonical);
|
||||||
|
error MalformedHeader(uint256 code);
|
||||||
|
error NotAnchored(uint256 blockNumber);
|
||||||
|
error RootNotCanonical(bytes32 proofRoot, bytes32 anchoredRoot);
|
||||||
|
|
||||||
|
constructor(address verifier) {
|
||||||
|
if (verifier == address(0)) revert ZeroVerifier();
|
||||||
|
VERIFIER = IAereStorageProofVerifier(verifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Canonical block-hash source: the EIP-2935 history-storage contract.
|
||||||
|
* Overridable so tests can inject a REAL AERE canonical hash without a
|
||||||
|
* live fork; the production path always STATICCALLs the system
|
||||||
|
* contract, whose storage is written by consensus (see contract note).
|
||||||
|
*
|
||||||
|
* Read ABI (per EIP-2935 runtime code): input is the 32-byte big-endian
|
||||||
|
* block number; output is the 32-byte canonical hash. The contract
|
||||||
|
* REVERTS for any block outside [number-8191, number-1], so a revert or
|
||||||
|
* a non-32-byte return is treated as out-of-window.
|
||||||
|
*/
|
||||||
|
function _historyBlockHash(uint256 blockNumber) internal view virtual returns (bytes32 h) {
|
||||||
|
if (HISTORY_STORAGE_ADDRESS.code.length == 0) revert HistoryContractMissing();
|
||||||
|
(bool ok, bytes memory ret) =
|
||||||
|
HISTORY_STORAGE_ADDRESS.staticcall(abi.encode(blockNumber));
|
||||||
|
if (!ok || ret.length != 32) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
h = abi.decode(ret, (bytes32));
|
||||||
|
// A real block hash is never zero; zero means the slot was never written
|
||||||
|
// for this block number (out of the served window).
|
||||||
|
if (h == bytes32(0)) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Anchor the state root of a historical canonical block using the
|
||||||
|
* EIP-2935 ring buffer. Works for blocks up to 8191 back, far beyond
|
||||||
|
* the 256-block BLOCKHASH horizon.
|
||||||
|
* @param blockNumber The block whose header is being anchored. MUST be
|
||||||
|
* within the last 8191 blocks (EIP-2935 window) at call time.
|
||||||
|
* @param rlpHeader The exact RLP-encoded block header whose keccak256 is
|
||||||
|
* the canonical block hash. The state root is header field index 3.
|
||||||
|
* @return stateRoot The decoded, now-anchored canonical state root.
|
||||||
|
*/
|
||||||
|
function anchorHistoricalHeader(uint256 blockNumber, bytes calldata rlpHeader)
|
||||||
|
external
|
||||||
|
returns (bytes32 stateRoot)
|
||||||
|
{
|
||||||
|
bytes32 canonical = _historyBlockHash(blockNumber);
|
||||||
|
|
||||||
|
bytes32 got = keccak256(rlpHeader);
|
||||||
|
if (got != canonical) revert HeaderHashMismatch(got, canonical);
|
||||||
|
|
||||||
|
stateRoot = _decodeStateRoot(rlpHeader);
|
||||||
|
|
||||||
|
_anchored[blockNumber] = AnchoredRoot({
|
||||||
|
exists: true,
|
||||||
|
stateRoot: stateRoot,
|
||||||
|
blockHash: canonical,
|
||||||
|
blockNumber: uint64(blockNumber),
|
||||||
|
verifiedAt: uint64(block.timestamp)
|
||||||
|
});
|
||||||
|
|
||||||
|
emit HeaderAnchored(blockNumber, canonical, stateRoot, block.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Drive the live storage-proof verifier against an ANCHORED root.
|
||||||
|
* The proof's committed root is checked to equal the root anchored
|
||||||
|
* for the SAME block number (that block number is committed inside
|
||||||
|
* the proof, so the caller cannot mismatch them). Only then is the
|
||||||
|
* slot recorded in the verifier via {submitProofWithExpectedRoot}.
|
||||||
|
* @dev The verifier reverts the whole call on an invalid SP1 proof or a
|
||||||
|
* wrong chainId, so no unverified state can be recorded.
|
||||||
|
*/
|
||||||
|
function proveAgainstAnchor(bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
returns (bytes32 value)
|
||||||
|
{
|
||||||
|
(uint256 blockNumber, bytes32 stateRoot, address account, bytes32 slot, ) =
|
||||||
|
VERIFIER.verify(publicValues, proof);
|
||||||
|
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
if (a.stateRoot != stateRoot) revert RootNotCanonical(stateRoot, a.stateRoot);
|
||||||
|
|
||||||
|
value = VERIFIER.submitProofWithExpectedRoot(publicValues, proof, a.stateRoot);
|
||||||
|
emit ProvenAgainstAnchor(blockNumber, a.stateRoot, account, slot, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// RLP header state-root decode. Identical layout logic to
|
||||||
|
// AereStateRootAnchor: the first four header fields are fixed size, so the
|
||||||
|
// stateRoot sits at a fixed offset in the list payload.
|
||||||
|
// [0] parentHash 32 bytes (prefix 0xa0)
|
||||||
|
// [1] ommersHash 32 bytes (prefix 0xa0)
|
||||||
|
// [2] beneficiary 20 bytes (prefix 0x94)
|
||||||
|
// [3] stateRoot 32 bytes (prefix 0xa0) <-- what we want
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
function _decodeStateRoot(bytes calldata rlpHeader) internal pure returns (bytes32 stateRoot) {
|
||||||
|
uint256 len = rlpHeader.length;
|
||||||
|
if (len < 121) revert MalformedHeader(1);
|
||||||
|
|
||||||
|
uint8 first = uint8(rlpHeader[0]);
|
||||||
|
if (first < 0xf8) revert MalformedHeader(2);
|
||||||
|
|
||||||
|
uint256 numLenBytes = uint256(first) - 0xf7; // 1..8
|
||||||
|
uint256 payloadLen;
|
||||||
|
for (uint256 i = 0; i < numLenBytes; i++) {
|
||||||
|
payloadLen = (payloadLen << 8) | uint256(uint8(rlpHeader[1 + i]));
|
||||||
|
}
|
||||||
|
uint256 payloadStart = 1 + numLenBytes;
|
||||||
|
if (payloadStart + payloadLen != len) revert MalformedHeader(3);
|
||||||
|
if (payloadStart + 120 > len) revert MalformedHeader(4);
|
||||||
|
|
||||||
|
if (uint8(rlpHeader[payloadStart]) != 0xa0) revert MalformedHeader(5); // parentHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 33]) != 0xa0) revert MalformedHeader(6); // ommersHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 66]) != 0x94) revert MalformedHeader(7); // beneficiary
|
||||||
|
if (uint8(rlpHeader[payloadStart + 87]) != 0xa0) revert MalformedHeader(8); // stateRoot prefix
|
||||||
|
|
||||||
|
uint256 srContentOffset = payloadStart + 88;
|
||||||
|
assembly {
|
||||||
|
stateRoot := calldataload(add(rlpHeader.offset, srContentOffset))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------- views -----------------------------------
|
||||||
|
|
||||||
|
function getAnchoredRoot(uint256 blockNumber)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool exists, bytes32 stateRoot, bytes32 blockHash, uint64 blockNum, uint64 verifiedAt)
|
||||||
|
{
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
return (a.exists, a.stateRoot, a.blockHash, a.blockNumber, a.verifiedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Anchored state root for `blockNumber`; reverts if not anchored.
|
||||||
|
function anchoredStateRoot(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
return a.stateRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAnchored(uint256 blockNumber) external view returns (bool) {
|
||||||
|
return _anchored[blockNumber].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The canonical block hash the EIP-2935 ring buffer serves right now
|
||||||
|
/// for `blockNumber`. Reverts OutOfHistoryWindow if not served.
|
||||||
|
function historyBlockHash(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
return _historyBlockHash(blockNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `blockNumber` is currently served by the EIP-2935 buffer.
|
||||||
|
function isWithinHistoryWindow(uint256 blockNumber) external view returns (bool) {
|
||||||
|
if (HISTORY_STORAGE_ADDRESS.code.length == 0) return false;
|
||||||
|
(bool ok, bytes memory ret) =
|
||||||
|
HISTORY_STORAGE_ADDRESS.staticcall(abi.encode(blockNumber));
|
||||||
|
if (!ok || ret.length != 32) return false;
|
||||||
|
return abi.decode(ret, (bytes32)) != bytes32(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff the EIP-2935 system contract has code (fork active here).
|
||||||
|
function historyContractDeployed() external view returns (bool) {
|
||||||
|
return HISTORY_STORAGE_ADDRESS.code.length != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Preview the state root a header decodes to, WITHOUT canonicity
|
||||||
|
/// checks or recording. Pure helper for off-chain header assembly.
|
||||||
|
function previewStateRoot(bytes calldata rlpHeader) external pure returns (bytes32) {
|
||||||
|
return _decodeStateRoot(rlpHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
// Reuse the LIVE verifier interface and the AnchoredRoot semantics from the
|
||||||
|
// original anchor. Importing the V1 file also brings in IAereStorageProofVerifier
|
||||||
|
// so the two contracts share one interface definition and one ABI convention.
|
||||||
|
import "./AereHistoryStateRootAnchor.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereHistoryStateRootAnchorV2
|
||||||
|
* @notice Corrected redeploy of AereHistoryStateRootAnchor. The anchoring path
|
||||||
|
* (EIP-2935 ring-buffer block-hash recovery, keccak match, RLP state
|
||||||
|
* root decode, permanent record) is byte-for-byte identical to V1. The
|
||||||
|
* only change is in {proveAgainstAnchor}.
|
||||||
|
*
|
||||||
|
* WHAT V1 DID WRONG (audit FINDING 4, low).
|
||||||
|
* V1 called VERIFIER.verify() to recover the committed blockNumber and
|
||||||
|
* stateRoot, then called VERIFIER.submitProofWithExpectedRoot(), which
|
||||||
|
* re-runs the very same SP1 Groth16 pairing check on the very same
|
||||||
|
* publicValues and proof. The expensive proof verification therefore ran
|
||||||
|
* TWICE per call for no added safety, since submitProofWithExpectedRoot
|
||||||
|
* already reverts on an invalid proof and already enforces that the
|
||||||
|
* proof's committed root equals the expected root passed to it.
|
||||||
|
*
|
||||||
|
* WHAT V2 DOES.
|
||||||
|
* V2 decodes the block number, account, and slot LOCALLY from the fixed
|
||||||
|
* 192-byte public-values layout (no external call), looks up the root
|
||||||
|
* anchored for that block number, and calls ONLY
|
||||||
|
* submitProofWithExpectedRoot(publicValues, proof, anchoredRoot). The
|
||||||
|
* single verification inside submit still reverts on an invalid proof
|
||||||
|
* and still binds the committed root to the anchored root, so behaviour
|
||||||
|
* is unchanged while the redundant pairing check is removed.
|
||||||
|
*
|
||||||
|
* PUBLIC-VALUES LAYOUT (abi.encode, 6 words, 192 bytes):
|
||||||
|
* [0:32] chainId
|
||||||
|
* [32:64] blockNumber
|
||||||
|
* [64:96] stateRoot
|
||||||
|
* [96:128] account
|
||||||
|
* [128:160] slot
|
||||||
|
* [160:192] value
|
||||||
|
*
|
||||||
|
* IMMUTABILITY: VERIFIER is fixed at deploy. No owner, no admin, no
|
||||||
|
* upgrade path. Anyone may anchor any in-window header and anyone may
|
||||||
|
* prove against an anchored root.
|
||||||
|
*/
|
||||||
|
contract AereHistoryStateRootAnchorV2 {
|
||||||
|
/// @notice Live AereStorageProofVerifier this anchor drives for proofs.
|
||||||
|
IAereStorageProofVerifier public immutable VERIFIER;
|
||||||
|
|
||||||
|
/// @notice EIP-2935 history-storage system contract (protocol-written ring buffer).
|
||||||
|
address public constant HISTORY_STORAGE_ADDRESS =
|
||||||
|
0x0000F90827F1C53a10cb7A02335B175320002935;
|
||||||
|
|
||||||
|
/// @notice EIP-2935 serve window: the ring buffer addresses the last 8191 blocks.
|
||||||
|
uint256 public constant HISTORY_SERVE_WINDOW = 8191;
|
||||||
|
|
||||||
|
/// @notice Fixed byte length of the SP1 public values this anchor accepts.
|
||||||
|
uint256 public constant PUBLIC_VALUES_LEN = 192;
|
||||||
|
|
||||||
|
struct AnchoredRoot {
|
||||||
|
bool exists;
|
||||||
|
bytes32 stateRoot; // header field index 3
|
||||||
|
bytes32 blockHash; // canonical hash the header was checked against
|
||||||
|
uint64 blockNumber;
|
||||||
|
uint64 verifiedAt; // block.timestamp when anchored
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice blockNumber => anchored canonical state root record.
|
||||||
|
mapping(uint256 => AnchoredRoot) private _anchored;
|
||||||
|
|
||||||
|
event HeaderAnchored(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed blockHash,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
uint256 verifiedAt
|
||||||
|
);
|
||||||
|
|
||||||
|
event ProvenAgainstAnchor(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed stateRoot,
|
||||||
|
address indexed account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
);
|
||||||
|
|
||||||
|
error ZeroVerifier();
|
||||||
|
error OutOfHistoryWindow(uint256 blockNumber, uint256 currentBlock);
|
||||||
|
error HistoryContractMissing();
|
||||||
|
error HeaderHashMismatch(bytes32 got, bytes32 canonical);
|
||||||
|
error MalformedHeader(uint256 code);
|
||||||
|
error NotAnchored(uint256 blockNumber);
|
||||||
|
error BadPublicValuesLength(uint256 got);
|
||||||
|
|
||||||
|
constructor(address verifier) {
|
||||||
|
if (verifier == address(0)) revert ZeroVerifier();
|
||||||
|
VERIFIER = IAereStorageProofVerifier(verifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Canonical block-hash source: the EIP-2935 history-storage contract.
|
||||||
|
* Overridable so tests can inject a REAL AERE canonical hash without a
|
||||||
|
* live fork; the production path always STATICCALLs the system
|
||||||
|
* contract, whose storage is written by consensus (see the V1 contract
|
||||||
|
* note for the full rationale).
|
||||||
|
*
|
||||||
|
* Read ABI (per EIP-2935 runtime code): input is the 32-byte big-endian
|
||||||
|
* block number; output is the 32-byte canonical hash. The contract
|
||||||
|
* REVERTS for any block outside [number-8191, number-1], so a revert or
|
||||||
|
* a non-32-byte return is treated as out-of-window.
|
||||||
|
*/
|
||||||
|
function _historyBlockHash(uint256 blockNumber) internal view virtual returns (bytes32 h) {
|
||||||
|
if (HISTORY_STORAGE_ADDRESS.code.length == 0) revert HistoryContractMissing();
|
||||||
|
(bool ok, bytes memory ret) =
|
||||||
|
HISTORY_STORAGE_ADDRESS.staticcall(abi.encode(blockNumber));
|
||||||
|
if (!ok || ret.length != 32) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
h = abi.decode(ret, (bytes32));
|
||||||
|
// A real block hash is never zero; zero means the slot was never written
|
||||||
|
// for this block number (out of the served window).
|
||||||
|
if (h == bytes32(0)) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Anchor the state root of a historical canonical block using the
|
||||||
|
* EIP-2935 ring buffer. Works for blocks up to 8191 back, far beyond
|
||||||
|
* the 256-block BLOCKHASH horizon. Logic is identical to V1.
|
||||||
|
* @param blockNumber The block whose header is being anchored. MUST be
|
||||||
|
* within the last 8191 blocks (EIP-2935 window) at call time.
|
||||||
|
* @param rlpHeader The exact RLP-encoded block header whose keccak256 is
|
||||||
|
* the canonical block hash. The state root is header field index 3.
|
||||||
|
* @return stateRoot The decoded, now-anchored canonical state root.
|
||||||
|
*/
|
||||||
|
function anchorHistoricalHeader(uint256 blockNumber, bytes calldata rlpHeader)
|
||||||
|
external
|
||||||
|
returns (bytes32 stateRoot)
|
||||||
|
{
|
||||||
|
bytes32 canonical = _historyBlockHash(blockNumber);
|
||||||
|
|
||||||
|
bytes32 got = keccak256(rlpHeader);
|
||||||
|
if (got != canonical) revert HeaderHashMismatch(got, canonical);
|
||||||
|
|
||||||
|
stateRoot = _decodeStateRoot(rlpHeader);
|
||||||
|
|
||||||
|
_anchored[blockNumber] = AnchoredRoot({
|
||||||
|
exists: true,
|
||||||
|
stateRoot: stateRoot,
|
||||||
|
blockHash: canonical,
|
||||||
|
blockNumber: uint64(blockNumber),
|
||||||
|
verifiedAt: uint64(block.timestamp)
|
||||||
|
});
|
||||||
|
|
||||||
|
emit HeaderAnchored(blockNumber, canonical, stateRoot, block.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Drive the live storage-proof verifier against an ANCHORED root,
|
||||||
|
* running the SP1 proof verification EXACTLY ONCE.
|
||||||
|
* @dev The block number, account, and slot are decoded locally from the
|
||||||
|
* fixed 192-byte public-values layout, so no call to VERIFIER.verify
|
||||||
|
* is made. The anchored root for that block number is passed as the
|
||||||
|
* expected root to submitProofWithExpectedRoot, which performs the
|
||||||
|
* single verification, reverts on an invalid proof, and reverts if
|
||||||
|
* the proof's committed root does not equal the anchored root. This
|
||||||
|
* is the same guarantee V1 provided, without the redundant second
|
||||||
|
* verification.
|
||||||
|
*/
|
||||||
|
function proveAgainstAnchor(bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
returns (bytes32 value)
|
||||||
|
{
|
||||||
|
if (publicValues.length != PUBLIC_VALUES_LEN) {
|
||||||
|
revert BadPublicValuesLength(publicValues.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
(uint256 blockNumber, address account, bytes32 slot) =
|
||||||
|
_decodePublicValues(publicValues);
|
||||||
|
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
|
||||||
|
// Single verification. submitProofWithExpectedRoot reverts on an invalid
|
||||||
|
// SP1 proof and reverts unless the proof's committed root == a.stateRoot,
|
||||||
|
// so no unverified or off-root state can be recorded.
|
||||||
|
value = VERIFIER.submitProofWithExpectedRoot(publicValues, proof, a.stateRoot);
|
||||||
|
emit ProvenAgainstAnchor(blockNumber, a.stateRoot, account, slot, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Decode blockNumber (word 1), account (word 3), and slot (word 4) from
|
||||||
|
* the fixed 192-byte public-values layout. chainId, stateRoot, and value
|
||||||
|
* are not needed here: the committed stateRoot is bound to the anchored
|
||||||
|
* root inside submitProofWithExpectedRoot, and chainId is enforced by the
|
||||||
|
* verifier itself.
|
||||||
|
*/
|
||||||
|
function _decodePublicValues(bytes calldata publicValues)
|
||||||
|
internal
|
||||||
|
pure
|
||||||
|
returns (uint256 blockNumber, address account, bytes32 slot)
|
||||||
|
{
|
||||||
|
uint256 accountWord;
|
||||||
|
assembly {
|
||||||
|
blockNumber := calldataload(add(publicValues.offset, 32))
|
||||||
|
accountWord := calldataload(add(publicValues.offset, 96))
|
||||||
|
slot := calldataload(add(publicValues.offset, 128))
|
||||||
|
}
|
||||||
|
// Low 20 bytes of word 3, matching abi.decode of an address.
|
||||||
|
account = address(uint160(accountWord));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// RLP header state-root decode. Identical layout logic to
|
||||||
|
// AereHistoryStateRootAnchor: the first four header fields are fixed size,
|
||||||
|
// so the stateRoot sits at a fixed offset in the list payload.
|
||||||
|
// [0] parentHash 32 bytes (prefix 0xa0)
|
||||||
|
// [1] ommersHash 32 bytes (prefix 0xa0)
|
||||||
|
// [2] beneficiary 20 bytes (prefix 0x94)
|
||||||
|
// [3] stateRoot 32 bytes (prefix 0xa0) <-- what we want
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
function _decodeStateRoot(bytes calldata rlpHeader) internal pure returns (bytes32 stateRoot) {
|
||||||
|
uint256 len = rlpHeader.length;
|
||||||
|
if (len < 121) revert MalformedHeader(1);
|
||||||
|
|
||||||
|
uint8 first = uint8(rlpHeader[0]);
|
||||||
|
if (first < 0xf8) revert MalformedHeader(2);
|
||||||
|
|
||||||
|
uint256 numLenBytes = uint256(first) - 0xf7; // 1..8
|
||||||
|
uint256 payloadLen;
|
||||||
|
for (uint256 i = 0; i < numLenBytes; i++) {
|
||||||
|
payloadLen = (payloadLen << 8) | uint256(uint8(rlpHeader[1 + i]));
|
||||||
|
}
|
||||||
|
uint256 payloadStart = 1 + numLenBytes;
|
||||||
|
if (payloadStart + payloadLen != len) revert MalformedHeader(3);
|
||||||
|
if (payloadStart + 120 > len) revert MalformedHeader(4);
|
||||||
|
|
||||||
|
if (uint8(rlpHeader[payloadStart]) != 0xa0) revert MalformedHeader(5); // parentHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 33]) != 0xa0) revert MalformedHeader(6); // ommersHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 66]) != 0x94) revert MalformedHeader(7); // beneficiary
|
||||||
|
if (uint8(rlpHeader[payloadStart + 87]) != 0xa0) revert MalformedHeader(8); // stateRoot prefix
|
||||||
|
|
||||||
|
uint256 srContentOffset = payloadStart + 88;
|
||||||
|
assembly {
|
||||||
|
stateRoot := calldataload(add(rlpHeader.offset, srContentOffset))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------- views -----------------------------------
|
||||||
|
|
||||||
|
function getAnchoredRoot(uint256 blockNumber)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool exists, bytes32 stateRoot, bytes32 blockHash, uint64 blockNum, uint64 verifiedAt)
|
||||||
|
{
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
return (a.exists, a.stateRoot, a.blockHash, a.blockNumber, a.verifiedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Anchored state root for `blockNumber`; reverts if not anchored.
|
||||||
|
function anchoredStateRoot(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
return a.stateRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAnchored(uint256 blockNumber) external view returns (bool) {
|
||||||
|
return _anchored[blockNumber].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The canonical block hash the EIP-2935 ring buffer serves right now
|
||||||
|
/// for `blockNumber`. Reverts OutOfHistoryWindow if not served.
|
||||||
|
function historyBlockHash(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
return _historyBlockHash(blockNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `blockNumber` is currently served by the EIP-2935 buffer.
|
||||||
|
function isWithinHistoryWindow(uint256 blockNumber) external view returns (bool) {
|
||||||
|
if (HISTORY_STORAGE_ADDRESS.code.length == 0) return false;
|
||||||
|
(bool ok, bytes memory ret) =
|
||||||
|
HISTORY_STORAGE_ADDRESS.staticcall(abi.encode(blockNumber));
|
||||||
|
if (!ok || ret.length != 32) return false;
|
||||||
|
return abi.decode(ret, (bytes32)) != bytes32(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff the EIP-2935 system contract has code (fork active here).
|
||||||
|
function historyContractDeployed() external view returns (bool) {
|
||||||
|
return HISTORY_STORAGE_ADDRESS.code.length != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Preview the state root a header decodes to, WITHOUT canonicity
|
||||||
|
/// checks or recording. Pure helper for off-chain header assembly.
|
||||||
|
function previewStateRoot(bytes calldata rlpHeader) external pure returns (bytes32) {
|
||||||
|
return _decodeStateRoot(rlpHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Subset of the LIVE AereStorageProofVerifier
|
||||||
|
* (0xF9a1A183bEb3147D88dA5927301683fEbFb9362E) used by this anchor.
|
||||||
|
* `verify` is a stateless view that reverts on an invalid SP1 proof and
|
||||||
|
* otherwise returns the tuple committed in the 192-byte public values.
|
||||||
|
* `submitProofWithExpectedRoot` re-verifies and records the slot only if
|
||||||
|
* the proof's committed stateRoot equals `expectedStateRoot`.
|
||||||
|
*/
|
||||||
|
interface IAereStorageProofVerifier {
|
||||||
|
function verify(bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 blockNumber,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
address account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
);
|
||||||
|
|
||||||
|
function submitProofWithExpectedRoot(
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata proof,
|
||||||
|
bytes32 expectedStateRoot
|
||||||
|
) external returns (bytes32 value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereStateRootAnchor
|
||||||
|
* @notice Binds an AERE state root to the CANONICAL chain, closing the trust
|
||||||
|
* gap left open by AereStorageProofVerifier. That verifier proves a
|
||||||
|
* storage value against a GIVEN state root but cannot, on its own, show
|
||||||
|
* the root is canonical for a block on chain 2800. This contract does
|
||||||
|
* exactly that: it recovers a canonical block hash from the EVM and
|
||||||
|
* checks a caller-supplied RLP header against it, then records the
|
||||||
|
* header's state root as an anchored, trust-minimized value.
|
||||||
|
*
|
||||||
|
* CANONICITY SOURCE ON CHAIN 2800 (probed on-chain, 2026-07-10).
|
||||||
|
* - BLOCKHASH opcode: LIVE. Serves the last 256 blocks. This is the
|
||||||
|
* ONLY canonicity source available on chain 2800 today.
|
||||||
|
* - EIP-2935 history-storage contract
|
||||||
|
* (0x0000F90827F1C53a10cb7A02335B175320002935 and the two earlier
|
||||||
|
* devnet addresses): NOT deployed (eth_getCode == 0x). So the
|
||||||
|
* extended ~8191-block window is NOT available here.
|
||||||
|
* Therefore this anchor uses BLOCKHASH and its window is 256 blocks.
|
||||||
|
* At AERE's 0.5s block time that is only ~128 seconds of history, so
|
||||||
|
* `anchorRecentHeader` MUST be called promptly after the target block
|
||||||
|
* is produced. Once anchored, the (blockNumber -> stateRoot) record is
|
||||||
|
* permanent and independent of the moving BLOCKHASH window.
|
||||||
|
*
|
||||||
|
* The block hash is recovered strictly from consensus (the BLOCKHASH
|
||||||
|
* opcode), never from a caller argument, so an attacker cannot anchor a
|
||||||
|
* fabricated root: keccak256(rlpHeader) must equal the opcode's answer.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY: VERIFIER is fixed at deploy. No owner, no admin, no
|
||||||
|
* upgrade path. Anyone may anchor any in-window header and anyone may
|
||||||
|
* prove against an anchored root.
|
||||||
|
*/
|
||||||
|
contract AereStateRootAnchor {
|
||||||
|
/// @notice Live AereStorageProofVerifier this anchor drives for proofs.
|
||||||
|
IAereStorageProofVerifier public immutable VERIFIER;
|
||||||
|
|
||||||
|
/// @notice EVM BLOCKHASH window: the opcode addresses the last 256 blocks.
|
||||||
|
uint256 public constant BLOCKHASH_WINDOW = 256;
|
||||||
|
|
||||||
|
struct AnchoredRoot {
|
||||||
|
bool exists;
|
||||||
|
bytes32 stateRoot; // header field index 3
|
||||||
|
bytes32 blockHash; // canonical hash the header was checked against
|
||||||
|
uint64 blockNumber;
|
||||||
|
uint64 verifiedAt; // block.timestamp when anchored
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice blockNumber => anchored canonical state root record.
|
||||||
|
mapping(uint256 => AnchoredRoot) private _anchored;
|
||||||
|
|
||||||
|
event HeaderAnchored(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed blockHash,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
uint256 verifiedAt
|
||||||
|
);
|
||||||
|
|
||||||
|
event ProvenAgainstAnchor(
|
||||||
|
uint256 indexed blockNumber,
|
||||||
|
bytes32 indexed stateRoot,
|
||||||
|
address indexed account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
);
|
||||||
|
|
||||||
|
error ZeroVerifier();
|
||||||
|
error OutOfWindow(uint256 blockNumber, uint256 currentBlock);
|
||||||
|
error HeaderHashMismatch(bytes32 got, bytes32 canonical);
|
||||||
|
error MalformedHeader(uint256 code);
|
||||||
|
error NotAnchored(uint256 blockNumber);
|
||||||
|
error RootNotCanonical(bytes32 proofRoot, bytes32 anchoredRoot);
|
||||||
|
|
||||||
|
constructor(address verifier) {
|
||||||
|
if (verifier == address(0)) revert ZeroVerifier();
|
||||||
|
VERIFIER = IAereStorageProofVerifier(verifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Canonical block-hash source. Overridable so tests can inject a REAL
|
||||||
|
* AERE canonical hash for a block outside the live 256-block window
|
||||||
|
* (e.g. genesis) without weakening the production path, which always
|
||||||
|
* uses the BLOCKHASH opcode.
|
||||||
|
*/
|
||||||
|
function _blockHashOf(uint256 blockNumber) internal view virtual returns (bytes32) {
|
||||||
|
return blockhash(blockNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Anchor the state root of a recent canonical block.
|
||||||
|
* @param blockNumber The block whose header is being anchored. MUST be
|
||||||
|
* within the last 256 blocks (BLOCKHASH window) at call time.
|
||||||
|
* @param rlpHeader The exact RLP-encoded block header whose keccak256 is
|
||||||
|
* the canonical block hash. The state root is header field index 3.
|
||||||
|
* @return stateRoot The decoded, now-anchored canonical state root.
|
||||||
|
*
|
||||||
|
* Reverts OutOfWindow if BLOCKHASH cannot address the block (older than 256
|
||||||
|
* blocks, the current block, or a future block). Reverts HeaderHashMismatch
|
||||||
|
* if the supplied header does not hash to the canonical block hash.
|
||||||
|
*/
|
||||||
|
function anchorRecentHeader(uint256 blockNumber, bytes calldata rlpHeader)
|
||||||
|
external
|
||||||
|
returns (bytes32 stateRoot)
|
||||||
|
{
|
||||||
|
bytes32 canonical = _blockHashOf(blockNumber);
|
||||||
|
// BLOCKHASH returns 0 for any block it cannot address. A real block hash
|
||||||
|
// is never 0 (keccak of a nonempty header), so 0 == out of window.
|
||||||
|
if (canonical == bytes32(0)) revert OutOfWindow(blockNumber, block.number);
|
||||||
|
|
||||||
|
bytes32 got = keccak256(rlpHeader);
|
||||||
|
if (got != canonical) revert HeaderHashMismatch(got, canonical);
|
||||||
|
|
||||||
|
stateRoot = _decodeStateRoot(rlpHeader);
|
||||||
|
|
||||||
|
_anchored[blockNumber] = AnchoredRoot({
|
||||||
|
exists: true,
|
||||||
|
stateRoot: stateRoot,
|
||||||
|
blockHash: canonical,
|
||||||
|
blockNumber: uint64(blockNumber),
|
||||||
|
verifiedAt: uint64(block.timestamp)
|
||||||
|
});
|
||||||
|
|
||||||
|
emit HeaderAnchored(blockNumber, canonical, stateRoot, block.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Drive the live storage-proof verifier against an ANCHORED root.
|
||||||
|
* This is the trust-minimized end of the two-call pattern: rather
|
||||||
|
* than trusting a caller-supplied stateRoot, the proof's committed
|
||||||
|
* root is checked to equal the root anchored for the SAME block
|
||||||
|
* number (that block number is committed inside the proof, so the
|
||||||
|
* caller cannot mismatch them). Only then is the slot recorded in
|
||||||
|
* the verifier via {submitProofWithExpectedRoot}.
|
||||||
|
* @dev The verifier reverts the whole call on an invalid SP1 proof or a
|
||||||
|
* wrong chainId, so no unverified state can be recorded.
|
||||||
|
*/
|
||||||
|
function proveAgainstAnchor(bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
returns (bytes32 value)
|
||||||
|
{
|
||||||
|
(uint256 blockNumber, bytes32 stateRoot, address account, bytes32 slot, ) =
|
||||||
|
VERIFIER.verify(publicValues, proof);
|
||||||
|
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
if (a.stateRoot != stateRoot) revert RootNotCanonical(stateRoot, a.stateRoot);
|
||||||
|
|
||||||
|
value = VERIFIER.submitProofWithExpectedRoot(publicValues, proof, a.stateRoot);
|
||||||
|
emit ProvenAgainstAnchor(blockNumber, a.stateRoot, account, slot, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
// RLP header state-root decode.
|
||||||
|
//
|
||||||
|
// A block header is a long RLP list. Its first three fields are fixed size:
|
||||||
|
// [0] parentHash 32 bytes (prefix 0xa0)
|
||||||
|
// [1] ommersHash 32 bytes (prefix 0xa0)
|
||||||
|
// [2] beneficiary 20 bytes (prefix 0x94)
|
||||||
|
// [3] stateRoot 32 bytes (prefix 0xa0) <-- what we want
|
||||||
|
// so the state root sits at a fixed offset inside the list payload,
|
||||||
|
// regardless of any later fields (extraData, blob/beacon fields, or QBFT
|
||||||
|
// commit-seal handling), all of which come AFTER stateRoot.
|
||||||
|
// ----------------------------------------------------------------------
|
||||||
|
function _decodeStateRoot(bytes calldata rlpHeader) internal pure returns (bytes32 stateRoot) {
|
||||||
|
uint256 len = rlpHeader.length;
|
||||||
|
// Smallest possible header list prefix (1) + 4 leading fields.
|
||||||
|
if (len < 121) revert MalformedHeader(1);
|
||||||
|
|
||||||
|
uint8 first = uint8(rlpHeader[0]);
|
||||||
|
// Block headers are always long lists (payload > 55 bytes) -> 0xf8..0xff.
|
||||||
|
if (first < 0xf8) revert MalformedHeader(2);
|
||||||
|
|
||||||
|
uint256 numLenBytes = uint256(first) - 0xf7; // 1..8
|
||||||
|
uint256 payloadLen;
|
||||||
|
for (uint256 i = 0; i < numLenBytes; i++) {
|
||||||
|
payloadLen = (payloadLen << 8) | uint256(uint8(rlpHeader[1 + i]));
|
||||||
|
}
|
||||||
|
uint256 payloadStart = 1 + numLenBytes;
|
||||||
|
// The declared payload length must exactly cover the rest of the input.
|
||||||
|
if (payloadStart + payloadLen != len) revert MalformedHeader(3);
|
||||||
|
// Need room for the four leading fixed fields: 33 + 33 + 21 + 33 = 120.
|
||||||
|
if (payloadStart + 120 > len) revert MalformedHeader(4);
|
||||||
|
|
||||||
|
// Validate the fixed-size field prefixes so we know the layout is a
|
||||||
|
// standard Ethereum-style header and offset 88 truly is the stateRoot.
|
||||||
|
if (uint8(rlpHeader[payloadStart]) != 0xa0) revert MalformedHeader(5); // parentHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 33]) != 0xa0) revert MalformedHeader(6); // ommersHash
|
||||||
|
if (uint8(rlpHeader[payloadStart + 66]) != 0x94) revert MalformedHeader(7); // beneficiary
|
||||||
|
if (uint8(rlpHeader[payloadStart + 87]) != 0xa0) revert MalformedHeader(8); // stateRoot prefix
|
||||||
|
|
||||||
|
uint256 srContentOffset = payloadStart + 88;
|
||||||
|
assembly {
|
||||||
|
stateRoot := calldataload(add(rlpHeader.offset, srContentOffset))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------- views -----------------------------------
|
||||||
|
|
||||||
|
function getAnchoredRoot(uint256 blockNumber)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool exists, bytes32 stateRoot, bytes32 blockHash, uint64 blockNum, uint64 verifiedAt)
|
||||||
|
{
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
return (a.exists, a.stateRoot, a.blockHash, a.blockNumber, a.verifiedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Anchored state root for `blockNumber`; reverts if not anchored.
|
||||||
|
function anchoredStateRoot(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
AnchoredRoot memory a = _anchored[blockNumber];
|
||||||
|
if (!a.exists) revert NotAnchored(blockNumber);
|
||||||
|
return a.stateRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAnchored(uint256 blockNumber) external view returns (bool) {
|
||||||
|
return _anchored[blockNumber].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The canonical block hash the anchor would use right now (0 if the
|
||||||
|
/// block is outside the addressable BLOCKHASH window).
|
||||||
|
function canonicalBlockHash(uint256 blockNumber) external view returns (bytes32) {
|
||||||
|
return _blockHashOf(blockNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `blockNumber` is currently anchorable (in the BLOCKHASH window).
|
||||||
|
function isWithinWindow(uint256 blockNumber) external view returns (bool) {
|
||||||
|
return _blockHashOf(blockNumber) != bytes32(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience preview of the state root a given header decodes to,
|
||||||
|
/// WITHOUT checking canonicity or recording anything. Pure helper
|
||||||
|
/// for off-chain callers assembling a header before anchoring.
|
||||||
|
function previewStateRoot(bytes calldata rlpHeader) external pure returns (bytes32) {
|
||||||
|
return _decodeStateRoot(rlpHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "../AereStateRootAnchor.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Test-only subclass that lets a test inject a canonical block hash for a
|
||||||
|
* given block number. This is used to exercise the FULL anchor logic
|
||||||
|
* (keccak match + RLP state-root decode + record) against a REAL AERE
|
||||||
|
* canonical block (the genesis block) whose hash is outside the live
|
||||||
|
* 256-block BLOCKHASH window. Production always uses the real BLOCKHASH
|
||||||
|
* opcode via the un-overridden AereStateRootAnchor._blockHashOf.
|
||||||
|
*/
|
||||||
|
contract MockBlockhashAnchor is AereStateRootAnchor {
|
||||||
|
mapping(uint256 => bytes32) public injected;
|
||||||
|
|
||||||
|
constructor(address verifier) AereStateRootAnchor(verifier) {}
|
||||||
|
|
||||||
|
function setBlockHash(uint256 blockNumber, bytes32 h) external {
|
||||||
|
injected[blockNumber] = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _blockHashOf(uint256 blockNumber) internal view override returns (bytes32) {
|
||||||
|
return injected[blockNumber];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Faithful stand-in for the LIVE AereStorageProofVerifier's two entry
|
||||||
|
* points used by the anchor. It decodes the SAME 192-byte public-values
|
||||||
|
* convention and enforces the SAME expected-root check, so the
|
||||||
|
* proveAgainstAnchor end-to-end path is exercised exactly as it would be
|
||||||
|
* against the real verifier (whose SP1 pairing check we do not re-run in a
|
||||||
|
* unit test). `shouldValidate=false` simulates an invalid SP1 proof.
|
||||||
|
*/
|
||||||
|
contract MockStorageProofVerifier is IAereStorageProofVerifier {
|
||||||
|
bool public shouldValidate = true;
|
||||||
|
|
||||||
|
/// @notice keccak256(publicValues) => recorded, for assertions.
|
||||||
|
mapping(bytes32 => bool) public recorded;
|
||||||
|
|
||||||
|
function setValidate(bool v) external {
|
||||||
|
shouldValidate = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verify(bytes calldata publicValues, bytes calldata /*proof*/)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 blockNumber,
|
||||||
|
bytes32 stateRoot,
|
||||||
|
address account,
|
||||||
|
bytes32 slot,
|
||||||
|
bytes32 value
|
||||||
|
)
|
||||||
|
{
|
||||||
|
require(shouldValidate, "InvalidProof");
|
||||||
|
require(publicValues.length == 192, "BadPublicValuesLength");
|
||||||
|
(, blockNumber, stateRoot, account, slot, value) = abi.decode(
|
||||||
|
publicValues,
|
||||||
|
(uint256, uint256, bytes32, address, bytes32, bytes32)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitProofWithExpectedRoot(
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata /*proof*/,
|
||||||
|
bytes32 expectedStateRoot
|
||||||
|
) external returns (bytes32 value) {
|
||||||
|
require(shouldValidate, "InvalidProof");
|
||||||
|
require(publicValues.length == 192, "BadPublicValuesLength");
|
||||||
|
(, , bytes32 stateRoot, , , bytes32 v) = abi.decode(
|
||||||
|
publicValues,
|
||||||
|
(uint256, uint256, bytes32, address, bytes32, bytes32)
|
||||||
|
);
|
||||||
|
require(stateRoot == expectedStateRoot, "StateRootMismatch");
|
||||||
|
recorded[keccak256(publicValues)] = true;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
// Import ONLY the V2 history anchor. It transitively imports the V1 history
|
||||||
|
// anchor (and its single IAereStorageProofVerifier declaration), so this
|
||||||
|
// compilation closure sees exactly one copy of that interface. It deliberately
|
||||||
|
// does NOT import AereStateRootAnchor.sol, which declares a same-named interface
|
||||||
|
// and would collide.
|
||||||
|
import "../AereHistoryStateRootAnchorV2.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Test-only subclass of the ORIGINAL history anchor (V1) that injects a
|
||||||
|
* canonical block hash for a block number, standing in for the EIP-2935
|
||||||
|
* ring buffer without a live fork. Everything else is the production V1
|
||||||
|
* logic, including the redundant double verification in proveAgainstAnchor.
|
||||||
|
*/
|
||||||
|
contract MockHistoryAnchorV1 is AereHistoryStateRootAnchor {
|
||||||
|
mapping(uint256 => bytes32) public injected;
|
||||||
|
|
||||||
|
constructor(address verifier) AereHistoryStateRootAnchor(verifier) {}
|
||||||
|
|
||||||
|
function setHistoryBlockHash(uint256 blockNumber, bytes32 h) external {
|
||||||
|
injected[blockNumber] = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _historyBlockHash(uint256 blockNumber) internal view override returns (bytes32) {
|
||||||
|
bytes32 h = injected[blockNumber];
|
||||||
|
if (h == bytes32(0)) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Test-only subclass of the corrected history anchor (V2) with the same
|
||||||
|
* injectable canonical block hash. proveAgainstAnchor runs the single
|
||||||
|
* corrected path.
|
||||||
|
*/
|
||||||
|
contract MockHistoryAnchorV2 is AereHistoryStateRootAnchorV2 {
|
||||||
|
mapping(uint256 => bytes32) public injected;
|
||||||
|
|
||||||
|
constructor(address verifier) AereHistoryStateRootAnchorV2(verifier) {}
|
||||||
|
|
||||||
|
function setHistoryBlockHash(uint256 blockNumber, bytes32 h) external {
|
||||||
|
injected[blockNumber] = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _historyBlockHash(uint256 blockNumber) internal view override returns (bytes32) {
|
||||||
|
bytes32 h = injected[blockNumber];
|
||||||
|
if (h == bytes32(0)) revert OutOfHistoryWindow(blockNumber, block.number);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Counting stand-in for the LIVE AereStorageProofVerifier used to prove
|
||||||
|
* how many SP1 verifications a caller triggers.
|
||||||
|
*
|
||||||
|
* submitProofWithExpectedRoot is the ONE verification the corrected anchor
|
||||||
|
* must run: it validates, binds the committed root to the expected root,
|
||||||
|
* records, and increments `submitCalls`.
|
||||||
|
*
|
||||||
|
* verify() reverts with RedundantVerifyCall. The live verify() is a
|
||||||
|
* stateless view whose whole cost is the SP1 Groth16 pairing; the original
|
||||||
|
* anchor calls it purely to read the block number, which the corrected
|
||||||
|
* anchor derives locally. Making verify() revert here means any code path
|
||||||
|
* that still calls it (the V1 double-verify) fails loudly, while the
|
||||||
|
* corrected path (which never calls verify) is unaffected. `submitCalls`
|
||||||
|
* then witnesses that exactly one verification ran.
|
||||||
|
*/
|
||||||
|
contract CountingStorageProofVerifier is IAereStorageProofVerifier {
|
||||||
|
bool public shouldValidate = true;
|
||||||
|
uint256 public submitCalls;
|
||||||
|
|
||||||
|
/// @notice keccak256(publicValues) => recorded, for assertions.
|
||||||
|
mapping(bytes32 => bool) public recorded;
|
||||||
|
|
||||||
|
error RedundantVerifyCall();
|
||||||
|
|
||||||
|
function setValidate(bool v) external {
|
||||||
|
shouldValidate = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verify(bytes calldata, bytes calldata)
|
||||||
|
external
|
||||||
|
pure
|
||||||
|
returns (uint256, bytes32, address, bytes32, bytes32)
|
||||||
|
{
|
||||||
|
revert RedundantVerifyCall();
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitProofWithExpectedRoot(
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata /*proof*/,
|
||||||
|
bytes32 expectedStateRoot
|
||||||
|
) external returns (bytes32 value) {
|
||||||
|
require(shouldValidate, "InvalidProof");
|
||||||
|
require(publicValues.length == 192, "BadPublicValuesLength");
|
||||||
|
(, , bytes32 stateRoot, , , bytes32 v) = abi.decode(
|
||||||
|
publicValues,
|
||||||
|
(uint256, uint256, bytes32, address, bytes32, bytes32)
|
||||||
|
);
|
||||||
|
require(stateRoot == expectedStateRoot, "StateRootMismatch");
|
||||||
|
recorded[keccak256(publicValues)] = true;
|
||||||
|
submitCalls += 1;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereBestExReceipt — MiCA Article 78 best-execution receipts on-chain
|
||||||
|
* @notice EU MiCA Title V (CASP conduct) Article 78 requires every Crypto
|
||||||
|
* Asset Service Provider to demonstrate "best execution" — that the
|
||||||
|
* price, costs, speed, likelihood, size, nature and other relevant
|
||||||
|
* considerations led to the most favourable result for the client.
|
||||||
|
* Until now, this proof has lived in CASPs' private back-office logs.
|
||||||
|
* AERE turns it into an open, append-only on-chain record.
|
||||||
|
*
|
||||||
|
* For every trade executed on behalf of an EU client, a registered
|
||||||
|
* CASP MUST mint a receipt here. The receipt commits to:
|
||||||
|
*
|
||||||
|
* - which venue was used (executedVenue)
|
||||||
|
* - the price and quantity actually filled
|
||||||
|
* - the alternative venues considered, with their best quotes
|
||||||
|
* at the time of decision (alternativesRoot — Merkle root)
|
||||||
|
* - the speed (millisecond timestamp at which the order was
|
||||||
|
* accepted vs the execution timestamp)
|
||||||
|
* - the protocol/SOR algorithm version that made the routing call
|
||||||
|
*
|
||||||
|
* Anyone — clients, supervisors, journalists — can later verify by
|
||||||
|
* (a) reading the on-chain receipt and (b) reproducing the
|
||||||
|
* alternative-quote Merkle tree from the CASP's published snapshot.
|
||||||
|
*
|
||||||
|
* @dev DESIGN CHOICES:
|
||||||
|
*
|
||||||
|
* 1. NOT an NFT. ERC-721 carries semantics (transfer, marketplace)
|
||||||
|
* that don't fit a regulatory artefact. Receipts are bound to
|
||||||
|
* the CASP that issued them; transfer/ownership is irrelevant.
|
||||||
|
* Each receipt is a struct in a sealed mapping.
|
||||||
|
*
|
||||||
|
* 2. CASP registry is owned by the Foundation but registration is
|
||||||
|
* by-reference: Foundation publishes the CASP's MiCA licence
|
||||||
|
* number + national competent authority + LEI. The Foundation
|
||||||
|
* CANNOT amend a receipt after issuance, only register new
|
||||||
|
* CASPs and pause-register a bad actor.
|
||||||
|
*
|
||||||
|
* 3. No self-policing of receipt content. The contract does NOT
|
||||||
|
* attempt to validate that the venue chosen actually was the
|
||||||
|
* best — only that the CASP COMMITTED to a specific decision
|
||||||
|
* with a specific information set. Off-chain auditors / clients
|
||||||
|
* / supervisors detect non-compliance by reading the open
|
||||||
|
* record. This is the same model as Chainlink: the oracle
|
||||||
|
* commits, the market detects mispricing.
|
||||||
|
*
|
||||||
|
* 4. Per-CASP rolling counter (receiptNonce[casp]) avoids global
|
||||||
|
* counter contention. Each CASP can issue receipts in parallel
|
||||||
|
* without coordinating.
|
||||||
|
*
|
||||||
|
* 5. Pause is at the *issuance* level. A paused CASP cannot mint
|
||||||
|
* new receipts but historical receipts remain queryable and
|
||||||
|
* verifiable forever. Compliance discipline, not data deletion.
|
||||||
|
*
|
||||||
|
* @dev GAS BUDGET (target):
|
||||||
|
* - issueReceipt: ~95-105k gas (mostly cold storage SSTOREs).
|
||||||
|
* - At 0.5 gwei base × 100k gas = 50_000 gwei = 0.00005 AERE
|
||||||
|
* (~ tiny fraction of a cent at any plausible AERE price).
|
||||||
|
* - A CASP doing 10M trades/yr pays << €500/yr in receipt gas.
|
||||||
|
* - That cost is the chain's competitive moat versus Polygon /
|
||||||
|
* Arbitrum / Base — at MiCA scale it stays a rounding error.
|
||||||
|
*/
|
||||||
|
contract AereBestExReceipt {
|
||||||
|
|
||||||
|
/* ================================ types ================================ */
|
||||||
|
|
||||||
|
/// @notice Permitted classification for the receipt (matches MiCA Art 78).
|
||||||
|
enum OrderType {
|
||||||
|
Market, // 0
|
||||||
|
Limit, // 1
|
||||||
|
StopLoss, // 2
|
||||||
|
StopLimit, // 3
|
||||||
|
TWAP, // 4
|
||||||
|
VWAP, // 5
|
||||||
|
RFQ, // 6
|
||||||
|
Other // 7
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Permitted client classification under MiCA / MiFID II.
|
||||||
|
enum ClientClass {
|
||||||
|
Retail, // 0 — MiCA Title V conduct rules fully apply
|
||||||
|
Professional, // 1 — opt-out clients
|
||||||
|
Eligible // 2 — eligible counterparties
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CaspRegistration {
|
||||||
|
bytes32 licenceRef; // hash of (MiCA-licence-number || NCA-code || LEI)
|
||||||
|
uint64 registeredAt; // unix seconds
|
||||||
|
bool paused; // emergency stop on issuance
|
||||||
|
bool exists; // set true on registration; never unset
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Receipt {
|
||||||
|
// identity
|
||||||
|
address casp; // issuing CASP (== msg.sender at mint)
|
||||||
|
bytes32 clientHash; // keccak256(client-id || casp-internal-salt) — pseudonymous, MiCA Art 78(2)
|
||||||
|
ClientClass clientClass;
|
||||||
|
|
||||||
|
// order
|
||||||
|
bytes32 orderId; // CASP's internal order id (opaque); used by client to find this record
|
||||||
|
OrderType orderType;
|
||||||
|
bytes32 instrumentSymbol; // e.g. keccak256("BTC/EUR") — short stable identifier
|
||||||
|
uint128 requestedQty; // base asset, scaled to 18 dec
|
||||||
|
uint128 executedQty; // base asset, scaled to 18 dec
|
||||||
|
uint128 executedPrice; // quote asset per base, scaled to 18 dec
|
||||||
|
|
||||||
|
// routing decision
|
||||||
|
bytes32 executedVenue; // keccak256(venue identifier — e.g. "Binance.com", "Coinbase Exchange")
|
||||||
|
bytes32 alternativesRoot; // Merkle root of (venue, best-bid, best-ask, depth, timestamp) tuples
|
||||||
|
// considered at routing time; CASP publishes the leaves off-chain.
|
||||||
|
bytes32 algorithmRef; // hash of (SOR algo name || version || commit-sha) — pins which logic chose
|
||||||
|
uint64 decisionTsMs; // ms timestamp at which routing decision was made
|
||||||
|
uint64 executionTsMs; // ms timestamp at which fill confirmed
|
||||||
|
|
||||||
|
// metadata pointer
|
||||||
|
string evidenceUri; // ipfs://… or https://… — full alternatives JSON, fee schedule, etc.
|
||||||
|
// referenced read-only; chain stores only the root.
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =============================== storage =============================== */
|
||||||
|
|
||||||
|
address public immutable FOUNDATION;
|
||||||
|
|
||||||
|
/// @notice CASP address → registration metadata. Once `exists`, never unset.
|
||||||
|
mapping(address => CaspRegistration) public caspOf;
|
||||||
|
|
||||||
|
/// @notice CASP → next nonce. receiptId = keccak256(casp, nonce).
|
||||||
|
mapping(address => uint256) public receiptNonce;
|
||||||
|
|
||||||
|
/// @notice global receiptId → Receipt. Append-only; never edited or deleted.
|
||||||
|
mapping(bytes32 => Receipt) internal _receipts;
|
||||||
|
|
||||||
|
/// @notice CASP → cumulative receipts issued.
|
||||||
|
mapping(address => uint256) public issuedCount;
|
||||||
|
|
||||||
|
/* ================================ events ================================ */
|
||||||
|
|
||||||
|
event CaspRegistered(address indexed casp, bytes32 licenceRef);
|
||||||
|
event CaspPaused(address indexed casp, bool paused);
|
||||||
|
event ReceiptIssued(
|
||||||
|
address indexed casp,
|
||||||
|
bytes32 indexed receiptId,
|
||||||
|
bytes32 indexed clientHash,
|
||||||
|
bytes32 instrumentSymbol,
|
||||||
|
bytes32 executedVenue,
|
||||||
|
bytes32 alternativesRoot,
|
||||||
|
uint128 executedQty,
|
||||||
|
uint128 executedPrice,
|
||||||
|
uint64 decisionTsMs,
|
||||||
|
uint64 executionTsMs,
|
||||||
|
bytes32 algorithmRef,
|
||||||
|
string evidenceUri
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ================================ errors ================================ */
|
||||||
|
|
||||||
|
error NotFoundation();
|
||||||
|
error CaspExists();
|
||||||
|
error CaspUnknown();
|
||||||
|
error CaspIsPaused();
|
||||||
|
error ReceiptExists();
|
||||||
|
error ZeroLicence();
|
||||||
|
error BadTimestamps();
|
||||||
|
error BadQuantities();
|
||||||
|
error BadAlternatives();
|
||||||
|
|
||||||
|
/* =============================== modifiers ============================== */
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert NotFoundation();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== constructor ============================= */
|
||||||
|
|
||||||
|
constructor(address foundation) {
|
||||||
|
require(foundation != address(0), "zero-foundation");
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================= registry ops ============================= */
|
||||||
|
|
||||||
|
/// @notice Foundation registers a new CASP. licenceRef MUST hash an
|
||||||
|
/// actual MiCA licence + NCA + LEI off-chain (no on-chain PII).
|
||||||
|
function registerCasp(address casp, bytes32 licenceRef) external onlyFoundation {
|
||||||
|
if (casp == address(0)) revert CaspUnknown();
|
||||||
|
if (licenceRef == bytes32(0)) revert ZeroLicence();
|
||||||
|
if (caspOf[casp].exists) revert CaspExists();
|
||||||
|
|
||||||
|
caspOf[casp] = CaspRegistration({
|
||||||
|
licenceRef: licenceRef,
|
||||||
|
registeredAt: uint64(block.timestamp),
|
||||||
|
paused: false,
|
||||||
|
exists: true
|
||||||
|
});
|
||||||
|
emit CaspRegistered(casp, licenceRef);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Pause / unpause issuance for a CASP. Historical receipts
|
||||||
|
/// remain queryable and verifiable.
|
||||||
|
function setCaspPaused(address casp, bool paused) external onlyFoundation {
|
||||||
|
CaspRegistration storage r = caspOf[casp];
|
||||||
|
if (!r.exists) revert CaspUnknown();
|
||||||
|
r.paused = paused;
|
||||||
|
emit CaspPaused(casp, paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ issuance path ============================ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Mint a new best-execution receipt. msg.sender MUST be a
|
||||||
|
* registered, non-paused CASP. The receipt is bound to this
|
||||||
|
* CASP forever and cannot be amended.
|
||||||
|
* @return receiptId = keccak256(abi.encode(msg.sender, nonce)).
|
||||||
|
*/
|
||||||
|
function issueReceipt(Receipt calldata r) external returns (bytes32 receiptId) {
|
||||||
|
CaspRegistration storage reg = caspOf[msg.sender];
|
||||||
|
if (!reg.exists) revert CaspUnknown();
|
||||||
|
if (reg.paused) revert CaspIsPaused();
|
||||||
|
|
||||||
|
if (r.casp != msg.sender) revert CaspUnknown();
|
||||||
|
if (r.executionTsMs < r.decisionTsMs) revert BadTimestamps();
|
||||||
|
if (r.executedQty == 0 || r.executedPrice == 0) revert BadQuantities();
|
||||||
|
if (r.executedQty > r.requestedQty) revert BadQuantities();
|
||||||
|
if (r.alternativesRoot == bytes32(0)) revert BadAlternatives();
|
||||||
|
if (r.executedVenue == bytes32(0)) revert BadAlternatives();
|
||||||
|
|
||||||
|
uint256 nonce = receiptNonce[msg.sender]++;
|
||||||
|
receiptId = keccak256(abi.encode(msg.sender, nonce));
|
||||||
|
if (_receipts[receiptId].casp != address(0)) revert ReceiptExists();
|
||||||
|
|
||||||
|
_receipts[receiptId] = r;
|
||||||
|
issuedCount[msg.sender] = nonce + 1;
|
||||||
|
|
||||||
|
emit ReceiptIssued(
|
||||||
|
msg.sender,
|
||||||
|
receiptId,
|
||||||
|
r.clientHash,
|
||||||
|
r.instrumentSymbol,
|
||||||
|
r.executedVenue,
|
||||||
|
r.alternativesRoot,
|
||||||
|
r.executedQty,
|
||||||
|
r.executedPrice,
|
||||||
|
r.decisionTsMs,
|
||||||
|
r.executionTsMs,
|
||||||
|
r.algorithmRef,
|
||||||
|
r.evidenceUri
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ views ================================ */
|
||||||
|
|
||||||
|
/// @notice Read a receipt by its id. Reverts not applied — caller checks
|
||||||
|
/// `r.casp == address(0)` for not-found.
|
||||||
|
function getReceipt(bytes32 receiptId) external view returns (Receipt memory r) {
|
||||||
|
return _receipts[receiptId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Deterministic receipt id for the next mint by `casp`.
|
||||||
|
/// Useful for relayer dry-runs.
|
||||||
|
function nextReceiptId(address casp) external view returns (bytes32) {
|
||||||
|
return keccak256(abi.encode(casp, receiptNonce[casp]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The decision-to-execution latency in milliseconds. One of the
|
||||||
|
/// "speed" inputs MiCA Art 78 names. Stored derivable for indexers.
|
||||||
|
function executionLatencyMs(bytes32 receiptId) external view returns (uint64) {
|
||||||
|
Receipt storage r = _receipts[receiptId];
|
||||||
|
return r.executionTsMs - r.decisionTsMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice CASP is registered, non-paused, and has issued ≥ 1 receipt.
|
||||||
|
/// The minimum filter a client should apply when choosing a CASP.
|
||||||
|
function caspIsActive(address casp) external view returns (bool) {
|
||||||
|
CaspRegistration storage reg = caspOf[casp];
|
||||||
|
return reg.exists && !reg.paused && issuedCount[casp] > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
|
||||||
|
import "./AereSpokePool.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereERC7683
|
||||||
|
* @notice ERC-7683 IOriginSettler implementation for AERE.
|
||||||
|
* Lets standards-compliant intent aggregators (UniswapX, CoW, Across UI,
|
||||||
|
* 1inch Fusion) submit cross-chain intents to AERE via a single uniform
|
||||||
|
* interface. The settler delegates execution to AereSpokePool.
|
||||||
|
*
|
||||||
|
* Reference: https://eips.ethereum.org/EIPS/eip-7683
|
||||||
|
*
|
||||||
|
* Two intent flavours:
|
||||||
|
* - GaslessCrossChainOrder: user signs an off-chain intent, anyone can open it.
|
||||||
|
* The user pays gas indirectly via the filler. Used for true gasless UX.
|
||||||
|
* - OnchainCrossChainOrder: user submits the intent on-chain themselves.
|
||||||
|
* Used by aggregators that prefer simpler flow.
|
||||||
|
*
|
||||||
|
* We implement both. Both delegate to the underlying AereSpokePool.
|
||||||
|
*/
|
||||||
|
|
||||||
|
struct OnchainCrossChainOrder {
|
||||||
|
uint32 fillDeadline;
|
||||||
|
bytes32 orderDataType;
|
||||||
|
bytes orderData;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GaslessCrossChainOrder {
|
||||||
|
address originSettler;
|
||||||
|
address user;
|
||||||
|
uint256 nonce;
|
||||||
|
uint256 originChainId;
|
||||||
|
uint32 openDeadline;
|
||||||
|
uint32 fillDeadline;
|
||||||
|
bytes32 orderDataType;
|
||||||
|
bytes orderData;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Output {
|
||||||
|
bytes32 token;
|
||||||
|
uint256 amount;
|
||||||
|
bytes32 recipient;
|
||||||
|
uint256 chainId;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FillInstruction {
|
||||||
|
uint64 destinationChainId;
|
||||||
|
bytes32 destinationSettler;
|
||||||
|
bytes originData;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ResolvedCrossChainOrder {
|
||||||
|
address user;
|
||||||
|
uint256 originChainId;
|
||||||
|
uint32 openDeadline;
|
||||||
|
uint32 fillDeadline;
|
||||||
|
bytes32 orderId;
|
||||||
|
Output[] maxSpent;
|
||||||
|
Output[] minReceived;
|
||||||
|
FillInstruction[] fillInstructions;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IOriginSettler {
|
||||||
|
event Open(bytes32 indexed orderId, ResolvedCrossChainOrder resolvedOrder);
|
||||||
|
|
||||||
|
function open(OnchainCrossChainOrder calldata order) external;
|
||||||
|
function openFor(GaslessCrossChainOrder calldata order, bytes calldata signature, bytes calldata originFillerData) external;
|
||||||
|
function resolve(OnchainCrossChainOrder calldata order) external view returns (ResolvedCrossChainOrder memory);
|
||||||
|
function resolveFor(GaslessCrossChainOrder calldata order, bytes calldata originFillerData) external view returns (ResolvedCrossChainOrder memory);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereERC7683 is IOriginSettler, EIP712, ReentrancyGuard {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
/// AERE-side SpokePool we route deposits through.
|
||||||
|
AereSpokePool public immutable spokePool;
|
||||||
|
|
||||||
|
/// Order-data type hash that this settler accepts.
|
||||||
|
/// Off-chain code constructs orderData as abi.encode(AereOrder) and uses this constant.
|
||||||
|
bytes32 public constant AERE_ORDER_TYPE = keccak256("AereCrossChainOrder(address inputToken,uint256 inputAmount,address outputToken,uint256 outputAmount,uint32 destinationChainId,address recipient)");
|
||||||
|
|
||||||
|
/// EIP-712 type hash for gasless orders.
|
||||||
|
bytes32 private constant GASLESS_ORDER_TYPEHASH = keccak256(
|
||||||
|
"GaslessCrossChainOrder(address originSettler,address user,uint256 nonce,uint256 originChainId,uint32 openDeadline,uint32 fillDeadline,bytes32 orderDataType,bytes orderData)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Per-user nonce tracking for gasless orders.
|
||||||
|
mapping(address => mapping(uint256 => bool)) public usedNonces;
|
||||||
|
|
||||||
|
struct AereOrderInner {
|
||||||
|
address inputToken;
|
||||||
|
uint256 inputAmount;
|
||||||
|
address outputToken;
|
||||||
|
uint256 outputAmount;
|
||||||
|
uint32 destinationChainId;
|
||||||
|
address recipient;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(AereSpokePool _spokePool) EIP712("AereERC7683", "1") {
|
||||||
|
spokePool = _spokePool;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Onchain order ─────────────────────
|
||||||
|
|
||||||
|
function open(OnchainCrossChainOrder calldata order) external override nonReentrant {
|
||||||
|
require(order.orderDataType == AERE_ORDER_TYPE, "ERC7683: unknown orderDataType");
|
||||||
|
require(order.fillDeadline > block.timestamp, "ERC7683: deadline passed");
|
||||||
|
|
||||||
|
AereOrderInner memory inner = abi.decode(order.orderData, (AereOrderInner));
|
||||||
|
|
||||||
|
// Pull the input tokens from msg.sender first, then approve SpokePool to take them.
|
||||||
|
IERC20(inner.inputToken).safeTransferFrom(msg.sender, address(this), inner.inputAmount);
|
||||||
|
IERC20(inner.inputToken).forceApprove(address(spokePool), inner.inputAmount);
|
||||||
|
|
||||||
|
spokePool.deposit(
|
||||||
|
inner.inputToken,
|
||||||
|
inner.inputAmount,
|
||||||
|
inner.outputToken,
|
||||||
|
inner.outputAmount,
|
||||||
|
inner.destinationChainId,
|
||||||
|
inner.recipient,
|
||||||
|
order.fillDeadline
|
||||||
|
);
|
||||||
|
|
||||||
|
bytes32 orderId = keccak256(abi.encode(msg.sender, order));
|
||||||
|
emit Open(orderId, _resolve(msg.sender, order.fillDeadline, 0, inner, orderId));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolve(OnchainCrossChainOrder calldata order) external view override returns (ResolvedCrossChainOrder memory) {
|
||||||
|
require(order.orderDataType == AERE_ORDER_TYPE, "ERC7683: unknown orderDataType");
|
||||||
|
AereOrderInner memory inner = abi.decode(order.orderData, (AereOrderInner));
|
||||||
|
bytes32 orderId = keccak256(abi.encode(msg.sender, order));
|
||||||
|
return _resolve(msg.sender, order.fillDeadline, 0, inner, orderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Gasless order ─────────────────────
|
||||||
|
|
||||||
|
function openFor(
|
||||||
|
GaslessCrossChainOrder calldata order,
|
||||||
|
bytes calldata signature,
|
||||||
|
bytes calldata /*originFillerData*/
|
||||||
|
) external override nonReentrant {
|
||||||
|
require(order.originSettler == address(this), "ERC7683: wrong settler");
|
||||||
|
require(order.originChainId == block.chainid, "ERC7683: wrong chain");
|
||||||
|
require(order.orderDataType == AERE_ORDER_TYPE, "ERC7683: unknown orderDataType");
|
||||||
|
require(order.openDeadline > block.timestamp, "ERC7683: open deadline passed");
|
||||||
|
require(order.fillDeadline > block.timestamp, "ERC7683: fill deadline passed");
|
||||||
|
require(!usedNonces[order.user][order.nonce], "ERC7683: nonce used");
|
||||||
|
|
||||||
|
// Verify user signature
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
GASLESS_ORDER_TYPEHASH,
|
||||||
|
order.originSettler,
|
||||||
|
order.user,
|
||||||
|
order.nonce,
|
||||||
|
order.originChainId,
|
||||||
|
order.openDeadline,
|
||||||
|
order.fillDeadline,
|
||||||
|
order.orderDataType,
|
||||||
|
keccak256(order.orderData)
|
||||||
|
));
|
||||||
|
bytes32 digest = _hashTypedDataV4(structHash);
|
||||||
|
address signer = ECDSA.recover(digest, signature);
|
||||||
|
require(signer == order.user, "ERC7683: bad signature");
|
||||||
|
|
||||||
|
usedNonces[order.user][order.nonce] = true;
|
||||||
|
|
||||||
|
AereOrderInner memory inner = abi.decode(order.orderData, (AereOrderInner));
|
||||||
|
|
||||||
|
// Pull input from the USER (they pre-approved this settler).
|
||||||
|
IERC20(inner.inputToken).safeTransferFrom(order.user, address(this), inner.inputAmount);
|
||||||
|
IERC20(inner.inputToken).forceApprove(address(spokePool), inner.inputAmount);
|
||||||
|
|
||||||
|
spokePool.deposit(
|
||||||
|
inner.inputToken,
|
||||||
|
inner.inputAmount,
|
||||||
|
inner.outputToken,
|
||||||
|
inner.outputAmount,
|
||||||
|
inner.destinationChainId,
|
||||||
|
inner.recipient,
|
||||||
|
order.fillDeadline
|
||||||
|
);
|
||||||
|
|
||||||
|
bytes32 orderId = keccak256(abi.encode(order));
|
||||||
|
emit Open(orderId, _resolve(order.user, order.fillDeadline, order.openDeadline, inner, orderId));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveFor(
|
||||||
|
GaslessCrossChainOrder calldata order,
|
||||||
|
bytes calldata /*originFillerData*/
|
||||||
|
) external view override returns (ResolvedCrossChainOrder memory) {
|
||||||
|
require(order.orderDataType == AERE_ORDER_TYPE, "ERC7683: unknown orderDataType");
|
||||||
|
AereOrderInner memory inner = abi.decode(order.orderData, (AereOrderInner));
|
||||||
|
bytes32 orderId = keccak256(abi.encode(order));
|
||||||
|
return _resolve(order.user, order.fillDeadline, order.openDeadline, inner, orderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Internal ─────────────────────
|
||||||
|
|
||||||
|
function _resolve(
|
||||||
|
address user,
|
||||||
|
uint32 fillDeadline,
|
||||||
|
uint32 openDeadline,
|
||||||
|
AereOrderInner memory inner,
|
||||||
|
bytes32 orderId
|
||||||
|
) internal view returns (ResolvedCrossChainOrder memory r) {
|
||||||
|
r.user = user;
|
||||||
|
r.originChainId = block.chainid;
|
||||||
|
r.openDeadline = openDeadline;
|
||||||
|
r.fillDeadline = fillDeadline;
|
||||||
|
r.orderId = orderId;
|
||||||
|
|
||||||
|
r.maxSpent = new Output[](1);
|
||||||
|
r.maxSpent[0] = Output({
|
||||||
|
token: bytes32(uint256(uint160(inner.inputToken))),
|
||||||
|
amount: inner.inputAmount,
|
||||||
|
recipient: bytes32(uint256(uint160(address(spokePool)))),
|
||||||
|
chainId: block.chainid
|
||||||
|
});
|
||||||
|
|
||||||
|
r.minReceived = new Output[](1);
|
||||||
|
r.minReceived[0] = Output({
|
||||||
|
token: bytes32(uint256(uint160(inner.outputToken))),
|
||||||
|
amount: inner.outputAmount,
|
||||||
|
recipient: bytes32(uint256(uint160(inner.recipient))),
|
||||||
|
chainId: inner.destinationChainId
|
||||||
|
});
|
||||||
|
|
||||||
|
r.fillInstructions = new FillInstruction[](1);
|
||||||
|
r.fillInstructions[0] = FillInstruction({
|
||||||
|
destinationChainId: uint64(inner.destinationChainId),
|
||||||
|
destinationSettler: spokePool.remoteSpokePool(inner.destinationChainId),
|
||||||
|
originData: abi.encode(
|
||||||
|
block.chainid,
|
||||||
|
inner,
|
||||||
|
fillDeadline,
|
||||||
|
user
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereIGP (Interchain Gas Paymaster)
|
||||||
|
* @notice Receives AERE fees from outbound cross-chain messages.
|
||||||
|
* Foundation/relayer claims these and uses them to fund the gas paid
|
||||||
|
* on destination chains when delivering inbound messages from AERE.
|
||||||
|
*
|
||||||
|
* Hyperlane-compatible interface — apps using Hyperlane's `quoteDispatch` helpers
|
||||||
|
* query us for the AERE fee required to relay a message to a given destination.
|
||||||
|
*
|
||||||
|
* Pricing model (configurable per destination):
|
||||||
|
* fee = gasOverhead * gasPriceQuote
|
||||||
|
*
|
||||||
|
* gasOverhead = chain-specific gas estimate (e.g. Ethereum ~150k, BSC ~80k).
|
||||||
|
* gasPriceQuote = AERE-denominated quote of destination chain's gas price.
|
||||||
|
* Owner sets this; in v2 we'll pull from AereOracle once cross-chain price
|
||||||
|
* feeds are wired.
|
||||||
|
*/
|
||||||
|
contract AereIGP is Ownable {
|
||||||
|
struct DestinationConfig {
|
||||||
|
uint256 gasOverhead;
|
||||||
|
uint256 gasPriceQuoteAere; // wei AERE per unit of destination gas
|
||||||
|
}
|
||||||
|
mapping(uint32 => DestinationConfig) public destinations;
|
||||||
|
|
||||||
|
address public payoutRecipient;
|
||||||
|
|
||||||
|
event GasPaymentReceived(bytes32 indexed messageId, uint32 destDomain, uint256 amount);
|
||||||
|
event DestinationConfigured(uint32 indexed domain, uint256 gasOverhead, uint256 gasPriceQuote);
|
||||||
|
event PayoutRecipientChanged(address indexed recipient);
|
||||||
|
|
||||||
|
constructor(address _payoutRecipient) {
|
||||||
|
payoutRecipient = _payoutRecipient;
|
||||||
|
}
|
||||||
|
|
||||||
|
function configure(uint32 domain, uint256 gasOverhead, uint256 gasPriceQuoteAere) external onlyOwner {
|
||||||
|
destinations[domain] = DestinationConfig(gasOverhead, gasPriceQuoteAere);
|
||||||
|
emit DestinationConfigured(domain, gasOverhead, gasPriceQuoteAere);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPayoutRecipient(address _r) external onlyOwner {
|
||||||
|
payoutRecipient = _r;
|
||||||
|
emit PayoutRecipientChanged(_r);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quote the AERE fee required to relay a message to `destDomain`.
|
||||||
|
function quoteGasPayment(uint32 destDomain) external view returns (uint256) {
|
||||||
|
DestinationConfig memory c = destinations[destDomain];
|
||||||
|
return c.gasOverhead * c.gasPriceQuoteAere;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called by AereMessenger via postDispatch when a message includes an IGP fee.
|
||||||
|
function postDispatch(bytes calldata, bytes calldata data) external payable {
|
||||||
|
(bytes32 messageId, uint32 destDomain) = abi.decode(data, (bytes32, uint32));
|
||||||
|
emit GasPaymentReceived(messageId, destDomain, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sweep accumulated fees to the payout recipient (relayer's hot wallet).
|
||||||
|
function claim() external {
|
||||||
|
uint256 bal = address(this).balance;
|
||||||
|
require(bal > 0, "AereIGP: nothing to claim");
|
||||||
|
(bool ok, ) = payoutRecipient.call{ value: bal }("");
|
||||||
|
require(ok, "AereIGP: payout failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,526 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereMailboxV3 + AereIGPV3
|
||||||
|
* @notice Fix for the quoteDispatch gap in AERE's Hyperlane core on chain 2800.
|
||||||
|
*
|
||||||
|
* ROOT CAUSE this file fixes (diagnosed on-chain 2026-07-10):
|
||||||
|
* 1. The deployed AereMessenger (0xe54c2329f0786CFE3420c566B646148D25477325)
|
||||||
|
* does NOT implement quoteDispatch(uint32,bytes32,bytes) at all. Selector
|
||||||
|
* 0x9c42bd18 is absent from its runtime bytecode, so every eth_call to
|
||||||
|
* quoteDispatch reverts with empty data. It is not upgradeable, so no
|
||||||
|
* configuration can add the function.
|
||||||
|
* 2. The deployed AereIGP (0x61B48615F490A23945988c92835eF35fdD86E837) has
|
||||||
|
* zero destination gas configs (gasOverhead=0, gasPriceQuoteAere=0 for
|
||||||
|
* every domain), so even its own quoteGasPayment(uint32) returns 0.
|
||||||
|
* 3. Both are owned by the Foundation multisig, so neither could be
|
||||||
|
* reconfigured by the deployer anyway.
|
||||||
|
*
|
||||||
|
* WHAT THIS IS:
|
||||||
|
* - AereMailboxV3: a Hyperlane v3 wire-format mailbox. Messages are packed
|
||||||
|
* exactly like Hyperlane v3 (version || nonce || origin || sender ||
|
||||||
|
* destination || recipient || body), messageId = keccak256(message).
|
||||||
|
* quoteDispatch(uint32,bytes32,bytes) works and returns the fee that
|
||||||
|
* dispatch requires as msg.value. dispatch REQUIRES the quoted fee and
|
||||||
|
* forwards it to the post-dispatch hook (the IGP), emitting the same
|
||||||
|
* Dispatch / DispatchId events as Hyperlane v3.
|
||||||
|
* - Inbound verification keeps the AereMessenger operational model: an
|
||||||
|
* owner-managed ECDSA validator set with a threshold, signature bytes are
|
||||||
|
* passed as the `metadata` argument of process(bytes,bytes). This is the
|
||||||
|
* same trust model as the live AereMessenger relayer, so no infra change.
|
||||||
|
* - AereIGPV3: a Hyperlane v3 post-dispatch hook (hookType 4,
|
||||||
|
* INTERCHAIN_GAS_PAYMASTER). quoteDispatch(metadata, message) parses the
|
||||||
|
* destination domain from the packed message and prices it as
|
||||||
|
* (gasOverhead + gasLimit) * gasPriceAereWei. gasLimit comes from
|
||||||
|
* StandardHookMetadata if provided, else DEFAULT_GAS_USAGE (50k, same
|
||||||
|
* default as Hyperlane's IGP).
|
||||||
|
*
|
||||||
|
* NO TOKEN of any kind is introduced. Fees are native AERE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ─────────────────────────── Hyperlane v3 message lib ───────────────────────────
|
||||||
|
|
||||||
|
library HypMessageV3 {
|
||||||
|
uint8 internal constant VERSION = 3;
|
||||||
|
|
||||||
|
// Packed layout offsets (bytes):
|
||||||
|
// version [0,1)
|
||||||
|
// nonce [1,5)
|
||||||
|
// origin [5,9)
|
||||||
|
// sender [9,41)
|
||||||
|
// destination[41,45)
|
||||||
|
// recipient [45,77)
|
||||||
|
// body [77,..)
|
||||||
|
uint256 internal constant BODY_OFFSET = 77;
|
||||||
|
|
||||||
|
function format(
|
||||||
|
uint32 _nonce,
|
||||||
|
uint32 _origin,
|
||||||
|
bytes32 _sender,
|
||||||
|
uint32 _destination,
|
||||||
|
bytes32 _recipient,
|
||||||
|
bytes calldata _body
|
||||||
|
) internal pure returns (bytes memory) {
|
||||||
|
return abi.encodePacked(VERSION, _nonce, _origin, _sender, _destination, _recipient, _body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function id(bytes memory _message) internal pure returns (bytes32) {
|
||||||
|
return keccak256(_message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function version(bytes calldata _message) internal pure returns (uint8) {
|
||||||
|
return uint8(bytes1(_message[0:1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function nonce(bytes calldata _message) internal pure returns (uint32) {
|
||||||
|
return uint32(bytes4(_message[1:5]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function origin(bytes calldata _message) internal pure returns (uint32) {
|
||||||
|
return uint32(bytes4(_message[5:9]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function sender(bytes calldata _message) internal pure returns (bytes32) {
|
||||||
|
return bytes32(_message[9:41]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function destination(bytes calldata _message) internal pure returns (uint32) {
|
||||||
|
return uint32(bytes4(_message[41:45]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function recipient(bytes calldata _message) internal pure returns (bytes32) {
|
||||||
|
return bytes32(_message[45:77]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function recipientAddress(bytes calldata _message) internal pure returns (address) {
|
||||||
|
return address(uint160(uint256(recipient(_message))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function body(bytes calldata _message) internal pure returns (bytes calldata) {
|
||||||
|
return _message[BODY_OFFSET:];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────── Interfaces ───────────────────────────
|
||||||
|
|
||||||
|
interface IPostDispatchHookV3 {
|
||||||
|
function hookType() external view returns (uint8);
|
||||||
|
function supportsMetadata(bytes calldata metadata) external view returns (bool);
|
||||||
|
function postDispatch(bytes calldata metadata, bytes calldata message) external payable;
|
||||||
|
function quoteDispatch(bytes calldata metadata, bytes calldata message) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IMessageRecipientV3 {
|
||||||
|
function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────── AereIGPV3 (post-dispatch hook) ───────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Interchain Gas Paymaster, Hyperlane v3 hook flavour.
|
||||||
|
* fee(domain, gasLimit) = (gasOverhead[domain] + gasLimit) * gasPriceAereWei[domain]
|
||||||
|
* gasPriceAereWei is the owner-set, AERE-denominated price of ONE unit of
|
||||||
|
* destination-chain gas (destination gas price x destination-token/AERE rate,
|
||||||
|
* folded into a single number until a cross-chain price oracle is wired).
|
||||||
|
*/
|
||||||
|
contract AereIGPV3 is Ownable, IPostDispatchHookV3 {
|
||||||
|
// Hyperlane v3 IPostDispatchHook.Types.INTERCHAIN_GAS_PAYMASTER
|
||||||
|
uint8 public constant HOOK_TYPE = 4;
|
||||||
|
// Same default as Hyperlane's InterchainGasPaymaster when metadata omits gasLimit.
|
||||||
|
uint256 public constant DEFAULT_GAS_USAGE = 50_000;
|
||||||
|
|
||||||
|
struct DomainGasConfig {
|
||||||
|
uint96 gasOverhead; // destination-side fixed gas overhead (ISM verify + mailbox process)
|
||||||
|
uint256 gasPriceAereWei; // wei of AERE per unit of destination gas
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GasParam {
|
||||||
|
uint32 remoteDomain;
|
||||||
|
DomainGasConfig config;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(uint32 => DomainGasConfig) public destinationGasConfigs;
|
||||||
|
|
||||||
|
/// Fees accumulate here and are claimable to the beneficiary (relayer funding wallet).
|
||||||
|
address public beneficiary;
|
||||||
|
|
||||||
|
event GasPayment(bytes32 indexed messageId, uint32 indexed destinationDomain, uint256 gasAmount, uint256 payment);
|
||||||
|
event DestinationGasConfigSet(uint32 indexed remoteDomain, uint96 gasOverhead, uint256 gasPriceAereWei);
|
||||||
|
event BeneficiarySet(address indexed beneficiary);
|
||||||
|
event Claimed(address indexed beneficiary, uint256 amount);
|
||||||
|
|
||||||
|
constructor(address _beneficiary) {
|
||||||
|
require(_beneficiary != address(0), "AereIGPV3: zero beneficiary");
|
||||||
|
beneficiary = _beneficiary;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── owner config ──
|
||||||
|
|
||||||
|
function setDestinationGasConfigs(GasParam[] calldata params) external onlyOwner {
|
||||||
|
for (uint256 i = 0; i < params.length; i++) {
|
||||||
|
require(params[i].config.gasPriceAereWei > 0, "AereIGPV3: zero gas price");
|
||||||
|
destinationGasConfigs[params[i].remoteDomain] = params[i].config;
|
||||||
|
emit DestinationGasConfigSet(
|
||||||
|
params[i].remoteDomain,
|
||||||
|
params[i].config.gasOverhead,
|
||||||
|
params[i].config.gasPriceAereWei
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBeneficiary(address _beneficiary) external onlyOwner {
|
||||||
|
require(_beneficiary != address(0), "AereIGPV3: zero beneficiary");
|
||||||
|
beneficiary = _beneficiary;
|
||||||
|
emit BeneficiarySet(_beneficiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── quoting ──
|
||||||
|
|
||||||
|
function quoteGasPayment(uint32 destinationDomain, uint256 gasLimit) public view returns (uint256) {
|
||||||
|
DomainGasConfig memory c = destinationGasConfigs[destinationDomain];
|
||||||
|
require(c.gasPriceAereWei > 0, "AereIGPV3: domain not configured");
|
||||||
|
return (uint256(c.gasOverhead) + gasLimit) * c.gasPriceAereWei;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── IPostDispatchHookV3 ──
|
||||||
|
|
||||||
|
function hookType() external pure returns (uint8) {
|
||||||
|
return HOOK_TYPE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Metadata is either empty or StandardHookMetadata:
|
||||||
|
/// variant(2) || msgValue(32) || gasLimit(32) || refundAddress(20)
|
||||||
|
function supportsMetadata(bytes calldata metadata) external pure returns (bool) {
|
||||||
|
return metadata.length == 0 || (metadata.length >= 66 && uint16(bytes2(metadata[0:2])) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _gasLimit(bytes calldata metadata) internal pure returns (uint256) {
|
||||||
|
if (metadata.length >= 66 && uint16(bytes2(metadata[0:2])) == 1) {
|
||||||
|
return uint256(bytes32(metadata[34:66]));
|
||||||
|
}
|
||||||
|
return DEFAULT_GAS_USAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _refundAddress(bytes calldata metadata) internal pure returns (address) {
|
||||||
|
if (metadata.length >= 86 && uint16(bytes2(metadata[0:2])) == 1) {
|
||||||
|
return address(bytes20(metadata[66:86]));
|
||||||
|
}
|
||||||
|
return address(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function quoteDispatch(bytes calldata metadata, bytes calldata message) public view returns (uint256) {
|
||||||
|
return quoteGasPayment(HypMessageV3.destination(message), _gasLimit(metadata));
|
||||||
|
}
|
||||||
|
|
||||||
|
function postDispatch(bytes calldata metadata, bytes calldata message) external payable {
|
||||||
|
uint256 gasLimit = _gasLimit(metadata);
|
||||||
|
uint32 destination = HypMessageV3.destination(message);
|
||||||
|
uint256 required = quoteGasPayment(destination, gasLimit);
|
||||||
|
require(msg.value >= required, "AereIGPV3: insufficient gas payment");
|
||||||
|
|
||||||
|
uint256 overpayment = msg.value - required;
|
||||||
|
if (overpayment > 0) {
|
||||||
|
address refundTo = _refundAddress(metadata);
|
||||||
|
if (refundTo != address(0)) {
|
||||||
|
(bool ok, ) = refundTo.call{ value: overpayment }("");
|
||||||
|
require(ok, "AereIGPV3: refund failed");
|
||||||
|
}
|
||||||
|
// If no refund address was given, the overpayment stays claimable
|
||||||
|
// by the beneficiary (identical to Hyperlane IGP behaviour when
|
||||||
|
// refunding is not possible).
|
||||||
|
}
|
||||||
|
|
||||||
|
emit GasPayment(keccak256(message), destination, gasLimit, required);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── payout ──
|
||||||
|
|
||||||
|
function claim() external {
|
||||||
|
uint256 bal = address(this).balance;
|
||||||
|
require(bal > 0, "AereIGPV3: nothing to claim");
|
||||||
|
address to = beneficiary;
|
||||||
|
(bool ok, ) = to.call{ value: bal }("");
|
||||||
|
require(ok, "AereIGPV3: payout failed");
|
||||||
|
emit Claimed(to, bal);
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────── AereMailboxV3 ───────────────────────────
|
||||||
|
|
||||||
|
contract AereMailboxV3 is Ownable, ReentrancyGuard {
|
||||||
|
using HypMessageV3 for bytes;
|
||||||
|
|
||||||
|
uint8 public constant VERSION = HypMessageV3.VERSION;
|
||||||
|
|
||||||
|
uint32 public immutable localDomain;
|
||||||
|
|
||||||
|
/// Outbound nonce, incremented per dispatch (Hyperlane v3 semantics).
|
||||||
|
uint32 public nonce;
|
||||||
|
|
||||||
|
/// Latest dispatched message id (Hyperlane v3 parity).
|
||||||
|
bytes32 public latestDispatchedId;
|
||||||
|
|
||||||
|
/// Post-dispatch hooks. requiredHook is charged first, then defaultHook.
|
||||||
|
/// Either may be zero (skipped). For AERE both quoting and payment go to
|
||||||
|
/// the AereIGPV3 as defaultHook; requiredHook is left zero at deploy.
|
||||||
|
IPostDispatchHookV3 public defaultHook;
|
||||||
|
IPostDispatchHookV3 public requiredHook;
|
||||||
|
|
||||||
|
/// Inbound verification: owner-managed ECDSA validator set (same
|
||||||
|
/// operational model as the live AereMessenger, so the existing relayer
|
||||||
|
/// design carries over; Foundation rotates the set).
|
||||||
|
address[] public validators;
|
||||||
|
mapping(address => bool) public isValidator;
|
||||||
|
uint8 public threshold = 1;
|
||||||
|
|
||||||
|
/// messageId => delivered (replay protection).
|
||||||
|
mapping(bytes32 => bool) public deliveredMessages;
|
||||||
|
|
||||||
|
bool public paused;
|
||||||
|
|
||||||
|
// Hyperlane v3 events, byte-for-byte compatible with indexers.
|
||||||
|
event Dispatch(address indexed sender, uint32 indexed destination, bytes32 indexed recipient, bytes message);
|
||||||
|
event DispatchId(bytes32 indexed messageId);
|
||||||
|
event Process(uint32 indexed origin, bytes32 indexed sender, address indexed recipient);
|
||||||
|
event ProcessId(bytes32 indexed messageId);
|
||||||
|
|
||||||
|
event ValidatorAdded(address indexed validator);
|
||||||
|
event ValidatorRemoved(address indexed validator);
|
||||||
|
event ThresholdChanged(uint8 newThreshold);
|
||||||
|
event DefaultHookSet(address indexed hook);
|
||||||
|
event RequiredHookSet(address indexed hook);
|
||||||
|
event PausedSet(bool paused);
|
||||||
|
|
||||||
|
constructor(uint32 _localDomain) {
|
||||||
|
localDomain = _localDomain;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier whenNotPaused() {
|
||||||
|
require(!paused, "AereMailboxV3: paused");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Outbound ─────────────────────
|
||||||
|
|
||||||
|
function dispatch(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody
|
||||||
|
) external payable returns (bytes32) {
|
||||||
|
return _dispatch(destinationDomain, recipientAddress, messageBody, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hyperlane v3 overload: dispatch with StandardHookMetadata (custom gas limit / refund address).
|
||||||
|
function dispatch(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody,
|
||||||
|
bytes calldata hookMetadata
|
||||||
|
) external payable returns (bytes32) {
|
||||||
|
return _dispatch(destinationDomain, recipientAddress, messageBody, hookMetadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _dispatch(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody,
|
||||||
|
bytes memory hookMetadata
|
||||||
|
) internal whenNotPaused nonReentrant returns (bytes32) {
|
||||||
|
uint32 n = nonce;
|
||||||
|
bytes memory message = HypMessageV3.format(
|
||||||
|
n,
|
||||||
|
localDomain,
|
||||||
|
bytes32(uint256(uint160(msg.sender))),
|
||||||
|
destinationDomain,
|
||||||
|
recipientAddress,
|
||||||
|
messageBody
|
||||||
|
);
|
||||||
|
bytes32 messageId = HypMessageV3.id(message);
|
||||||
|
|
||||||
|
nonce = n + 1;
|
||||||
|
latestDispatchedId = messageId;
|
||||||
|
|
||||||
|
emit Dispatch(msg.sender, destinationDomain, recipientAddress, message);
|
||||||
|
emit DispatchId(messageId);
|
||||||
|
|
||||||
|
// Charge hooks: required first, then default.
|
||||||
|
uint256 remaining = msg.value;
|
||||||
|
remaining = _payHook(requiredHook, hookMetadata, message, remaining);
|
||||||
|
remaining = _payHook(defaultHook, hookMetadata, message, remaining);
|
||||||
|
|
||||||
|
// Refund anything the hooks did not require.
|
||||||
|
if (remaining > 0) {
|
||||||
|
(bool ok, ) = msg.sender.call{ value: remaining }("");
|
||||||
|
require(ok, "AereMailboxV3: refund failed");
|
||||||
|
}
|
||||||
|
return messageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _payHook(
|
||||||
|
IPostDispatchHookV3 hook,
|
||||||
|
bytes memory metadata,
|
||||||
|
bytes memory message,
|
||||||
|
uint256 available
|
||||||
|
) internal returns (uint256) {
|
||||||
|
if (address(hook) == address(0)) return available;
|
||||||
|
uint256 fee = _quoteHook(hook, metadata, message);
|
||||||
|
require(available >= fee, "AereMailboxV3: insufficient hook payment");
|
||||||
|
hook.postDispatch{ value: fee }(metadata, message);
|
||||||
|
return available - fee;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _quoteHook(
|
||||||
|
IPostDispatchHookV3 hook,
|
||||||
|
bytes memory metadata,
|
||||||
|
bytes memory message
|
||||||
|
) internal view returns (uint256) {
|
||||||
|
if (address(hook) == address(0)) return 0;
|
||||||
|
return hook.quoteDispatch(metadata, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Quoting (THE FIX) ─────────────────────
|
||||||
|
|
||||||
|
/// @notice Hyperlane v3 quoteDispatch — the function the old AereMessenger
|
||||||
|
/// never had. Returns the exact msg.value dispatch() requires.
|
||||||
|
function quoteDispatch(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody
|
||||||
|
) external view returns (uint256) {
|
||||||
|
return _quote(destinationDomain, recipientAddress, messageBody, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// v3 overload with hook metadata.
|
||||||
|
function quoteDispatch(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody,
|
||||||
|
bytes calldata hookMetadata
|
||||||
|
) external view returns (uint256) {
|
||||||
|
return _quote(destinationDomain, recipientAddress, messageBody, hookMetadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _quote(
|
||||||
|
uint32 destinationDomain,
|
||||||
|
bytes32 recipientAddress,
|
||||||
|
bytes calldata messageBody,
|
||||||
|
bytes memory hookMetadata
|
||||||
|
) internal view returns (uint256) {
|
||||||
|
bytes memory message = HypMessageV3.format(
|
||||||
|
nonce,
|
||||||
|
localDomain,
|
||||||
|
bytes32(uint256(uint160(msg.sender))),
|
||||||
|
destinationDomain,
|
||||||
|
recipientAddress,
|
||||||
|
messageBody
|
||||||
|
);
|
||||||
|
return
|
||||||
|
_quoteHook(requiredHook, hookMetadata, message) +
|
||||||
|
_quoteHook(defaultHook, hookMetadata, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Inbound ─────────────────────
|
||||||
|
|
||||||
|
/// @notice Hyperlane v3 process signature. `metadata` carries concatenated
|
||||||
|
/// 65-byte ECDSA validator signatures over the eth-signed messageId.
|
||||||
|
function process(bytes calldata metadata, bytes calldata message) external nonReentrant whenNotPaused {
|
||||||
|
require(message.version() == VERSION, "AereMailboxV3: bad version");
|
||||||
|
require(message.destination() == localDomain, "AereMailboxV3: wrong destination");
|
||||||
|
|
||||||
|
bytes32 messageId = keccak256(message);
|
||||||
|
require(!deliveredMessages[messageId], "AereMailboxV3: already delivered");
|
||||||
|
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageId));
|
||||||
|
require(metadata.length % 65 == 0, "AereMailboxV3: bad sig length");
|
||||||
|
uint256 sigCount = metadata.length / 65;
|
||||||
|
require(sigCount >= threshold, "AereMailboxV3: below threshold");
|
||||||
|
|
||||||
|
address[] memory seen = new address[](sigCount);
|
||||||
|
for (uint256 i = 0; i < sigCount; i++) {
|
||||||
|
bytes32 r;
|
||||||
|
bytes32 s;
|
||||||
|
uint8 v;
|
||||||
|
assembly {
|
||||||
|
let off := add(metadata.offset, mul(i, 65))
|
||||||
|
r := calldataload(off)
|
||||||
|
s := calldataload(add(off, 32))
|
||||||
|
v := byte(0, calldataload(add(off, 64)))
|
||||||
|
}
|
||||||
|
address signer = ecrecover(digest, v, r, s);
|
||||||
|
require(signer != address(0), "AereMailboxV3: bad signature");
|
||||||
|
require(isValidator[signer], "AereMailboxV3: not a validator");
|
||||||
|
for (uint256 j = 0; j < i; j++) {
|
||||||
|
require(seen[j] != signer, "AereMailboxV3: duplicate signer");
|
||||||
|
}
|
||||||
|
seen[i] = signer;
|
||||||
|
}
|
||||||
|
|
||||||
|
deliveredMessages[messageId] = true;
|
||||||
|
IMessageRecipientV3(message.recipientAddress()).handle(
|
||||||
|
message.origin(),
|
||||||
|
message.sender(),
|
||||||
|
message.body()
|
||||||
|
);
|
||||||
|
emit Process(message.origin(), message.sender(), message.recipientAddress());
|
||||||
|
emit ProcessId(messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function delivered(bytes32 messageId) external view returns (bool) {
|
||||||
|
return deliveredMessages[messageId];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function setDefaultHook(address _hook) external onlyOwner {
|
||||||
|
defaultHook = IPostDispatchHookV3(_hook);
|
||||||
|
emit DefaultHookSet(_hook);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setRequiredHook(address _hook) external onlyOwner {
|
||||||
|
requiredHook = IPostDispatchHookV3(_hook);
|
||||||
|
emit RequiredHookSet(_hook);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addValidator(address v) external onlyOwner {
|
||||||
|
require(v != address(0), "AereMailboxV3: zero validator");
|
||||||
|
require(!isValidator[v], "AereMailboxV3: already added");
|
||||||
|
isValidator[v] = true;
|
||||||
|
validators.push(v);
|
||||||
|
emit ValidatorAdded(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeValidator(address v) external onlyOwner {
|
||||||
|
require(isValidator[v], "AereMailboxV3: not found");
|
||||||
|
isValidator[v] = false;
|
||||||
|
for (uint256 i = 0; i < validators.length; i++) {
|
||||||
|
if (validators[i] == v) {
|
||||||
|
validators[i] = validators[validators.length - 1];
|
||||||
|
validators.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require(threshold <= validators.length, "AereMailboxV3: threshold too high after removal");
|
||||||
|
emit ValidatorRemoved(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setThreshold(uint8 _threshold) external onlyOwner {
|
||||||
|
require(_threshold > 0 && _threshold <= validators.length, "AereMailboxV3: bad threshold");
|
||||||
|
threshold = _threshold;
|
||||||
|
emit ThresholdChanged(_threshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPaused(bool _paused) external onlyOwner {
|
||||||
|
paused = _paused;
|
||||||
|
emit PausedSet(_paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatorCount() external view returns (uint256) {
|
||||||
|
return validators.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
// Test-only helpers for AereMailboxV3. Not for mainnet deployment.
|
||||||
|
|
||||||
|
contract TestRecipientV3 {
|
||||||
|
uint32 public lastOrigin;
|
||||||
|
bytes32 public lastSender;
|
||||||
|
bytes public lastBody;
|
||||||
|
uint256 public handleCount;
|
||||||
|
|
||||||
|
event Handled(uint32 origin, bytes32 sender, bytes body);
|
||||||
|
|
||||||
|
function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable {
|
||||||
|
lastOrigin = origin;
|
||||||
|
lastSender = sender;
|
||||||
|
lastBody = body;
|
||||||
|
handleCount += 1;
|
||||||
|
emit Handled(origin, sender, body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereMessenger
|
||||||
|
* @notice Cross-chain messaging hub for AERE Network, designed for compatibility
|
||||||
|
* with the Hyperlane Mailbox interface so we can plug into the public
|
||||||
|
* Hyperlane validator/relayer network once registered.
|
||||||
|
*
|
||||||
|
* For now this is a self-contained messaging contract: an off-chain validator
|
||||||
|
* set we operate signs outgoing messages. The signature scheme + ISM design
|
||||||
|
* are deliberately compatible with Hyperlane's ECDSA-multisig ISM, so when
|
||||||
|
* Hyperlane Labs accepts AERE into the public registry we can swap our
|
||||||
|
* signers for the public validator set with one parameter change — no
|
||||||
|
* contract redeploy.
|
||||||
|
*
|
||||||
|
* Compatible with Hyperlane Mailbox semantics:
|
||||||
|
* - 32-bit domain identifier (we use Chain ID 2800)
|
||||||
|
* - dispatch(destDomain, recipient, body) emits outbound messages
|
||||||
|
* - process(metadata, message) verifies + delivers inbound messages
|
||||||
|
* - Recipients implement IMessageRecipient
|
||||||
|
* - Default ISM is a multisig of named validators
|
||||||
|
*
|
||||||
|
* When AERE is added to the Hyperlane registry, this contract continues to
|
||||||
|
* work — Hyperlane validators sign with the same ECDSA scheme.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface IMessageRecipient {
|
||||||
|
function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IPostDispatchHook {
|
||||||
|
function postDispatch(bytes calldata metadata, bytes calldata message) external payable;
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereMessenger is Ownable, ReentrancyGuard {
|
||||||
|
/// AERE's domain (= chain ID).
|
||||||
|
uint32 public immutable localDomain;
|
||||||
|
|
||||||
|
/// Outbound nonce — incremented per dispatch.
|
||||||
|
uint32 public nonce;
|
||||||
|
|
||||||
|
/// Validator set authorised to sign inbound messages. ECDSA-signed digests.
|
||||||
|
address[] public validators;
|
||||||
|
mapping(address => bool) public isValidator;
|
||||||
|
|
||||||
|
/// Threshold: how many distinct validator signatures required to accept an inbound message.
|
||||||
|
uint8 public threshold = 1;
|
||||||
|
|
||||||
|
/// Delivered message digest tracking (per-origin) to prevent replay.
|
||||||
|
mapping(uint32 => mapping(bytes32 => bool)) public delivered;
|
||||||
|
|
||||||
|
/// Optional post-dispatch hook (e.g. AereIGP — Interchain Gas Paymaster).
|
||||||
|
address public defaultHook;
|
||||||
|
|
||||||
|
/// Pause flag for emergency halt.
|
||||||
|
bool public paused;
|
||||||
|
|
||||||
|
event Dispatch(
|
||||||
|
uint32 indexed destDomain,
|
||||||
|
bytes32 indexed recipient,
|
||||||
|
uint32 indexed nonce,
|
||||||
|
bytes32 sender,
|
||||||
|
bytes body,
|
||||||
|
bytes32 messageId
|
||||||
|
);
|
||||||
|
event Process(
|
||||||
|
uint32 indexed origin,
|
||||||
|
bytes32 indexed sender,
|
||||||
|
address indexed recipient,
|
||||||
|
bytes32 messageId
|
||||||
|
);
|
||||||
|
event ValidatorAdded(address indexed validator);
|
||||||
|
event ValidatorRemoved(address indexed validator);
|
||||||
|
event ThresholdChanged(uint8 newThreshold);
|
||||||
|
event HookSet(address indexed hook);
|
||||||
|
event Paused(bool paused);
|
||||||
|
|
||||||
|
constructor(uint32 _localDomain) {
|
||||||
|
localDomain = _localDomain;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier whenNotPaused() {
|
||||||
|
require(!paused, "AereMessenger: paused");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Outbound ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Send a cross-chain message.
|
||||||
|
* @param destDomain Destination chain's domain ID (= chain ID).
|
||||||
|
* @param recipient Recipient contract on destination chain, padded to bytes32.
|
||||||
|
* @param body Application-defined payload.
|
||||||
|
* @return messageId Unique digest of this message.
|
||||||
|
*/
|
||||||
|
function dispatch(
|
||||||
|
uint32 destDomain,
|
||||||
|
bytes32 recipient,
|
||||||
|
bytes calldata body
|
||||||
|
) external payable whenNotPaused returns (bytes32 messageId) {
|
||||||
|
uint32 n = nonce;
|
||||||
|
nonce = n + 1;
|
||||||
|
bytes32 sender = bytes32(uint256(uint160(msg.sender)));
|
||||||
|
messageId = keccak256(abi.encode(localDomain, destDomain, n, sender, recipient, body));
|
||||||
|
emit Dispatch(destDomain, recipient, n, sender, body, messageId);
|
||||||
|
|
||||||
|
if (defaultHook != address(0) && msg.value > 0) {
|
||||||
|
// Forward the IGP fee to the hook (e.g. interchain gas payment).
|
||||||
|
IPostDispatchHook(defaultHook).postDispatch{ value: msg.value }("", abi.encode(messageId, destDomain));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Inbound ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Process an inbound message after verifying validator signatures.
|
||||||
|
* @param signatures Concatenated 65-byte ECDSA signatures (one per validator).
|
||||||
|
* @param origin Origin chain's domain ID.
|
||||||
|
* @param sender Sender on origin chain (address padded to bytes32).
|
||||||
|
* @param recipient Recipient contract address on AERE.
|
||||||
|
* @param body Payload to deliver.
|
||||||
|
* @param originNonce Sender's nonce on origin chain — used for replay protection.
|
||||||
|
*/
|
||||||
|
function process(
|
||||||
|
bytes calldata signatures,
|
||||||
|
uint32 origin,
|
||||||
|
bytes32 sender,
|
||||||
|
address recipient,
|
||||||
|
bytes calldata body,
|
||||||
|
uint32 originNonce
|
||||||
|
) external nonReentrant whenNotPaused {
|
||||||
|
bytes32 messageId = keccak256(abi.encode(origin, localDomain, originNonce, sender, bytes32(uint256(uint160(recipient))), body));
|
||||||
|
require(!delivered[origin][messageId], "AereMessenger: replay");
|
||||||
|
|
||||||
|
// Verify threshold signatures over the messageId (Ethereum-signed-message prefix).
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageId));
|
||||||
|
require(signatures.length % 65 == 0, "AereMessenger: bad sig length");
|
||||||
|
uint256 sigCount = signatures.length / 65;
|
||||||
|
require(sigCount >= threshold, "AereMessenger: below threshold");
|
||||||
|
|
||||||
|
address[] memory seen = new address[](sigCount);
|
||||||
|
uint256 validCount = 0;
|
||||||
|
for (uint256 i = 0; i < sigCount; i++) {
|
||||||
|
bytes32 r;
|
||||||
|
bytes32 s;
|
||||||
|
uint8 v;
|
||||||
|
assembly {
|
||||||
|
let off := add(signatures.offset, mul(i, 65))
|
||||||
|
r := calldataload(off)
|
||||||
|
s := calldataload(add(off, 32))
|
||||||
|
v := byte(0, calldataload(add(off, 64)))
|
||||||
|
}
|
||||||
|
address signer = ecrecover(digest, v, r, s);
|
||||||
|
require(signer != address(0), "AereMessenger: bad signature");
|
||||||
|
require(isValidator[signer], "AereMessenger: not a validator");
|
||||||
|
|
||||||
|
// No-double-counting: ensure each signer is distinct.
|
||||||
|
for (uint256 j = 0; j < validCount; j++) {
|
||||||
|
require(seen[j] != signer, "AereMessenger: duplicate signer");
|
||||||
|
}
|
||||||
|
seen[validCount] = signer;
|
||||||
|
validCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
delivered[origin][messageId] = true;
|
||||||
|
IMessageRecipient(recipient).handle(origin, sender, body);
|
||||||
|
emit Process(origin, sender, recipient, messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function addValidator(address v) external onlyOwner {
|
||||||
|
require(!isValidator[v], "AereMessenger: already added");
|
||||||
|
isValidator[v] = true;
|
||||||
|
validators.push(v);
|
||||||
|
emit ValidatorAdded(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeValidator(address v) external onlyOwner {
|
||||||
|
require(isValidator[v], "AereMessenger: not found");
|
||||||
|
isValidator[v] = false;
|
||||||
|
for (uint256 i = 0; i < validators.length; i++) {
|
||||||
|
if (validators[i] == v) {
|
||||||
|
validators[i] = validators[validators.length - 1];
|
||||||
|
validators.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit ValidatorRemoved(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setThreshold(uint8 _threshold) external onlyOwner {
|
||||||
|
require(_threshold > 0 && _threshold <= validators.length, "AereMessenger: bad threshold");
|
||||||
|
threshold = _threshold;
|
||||||
|
emit ThresholdChanged(_threshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDefaultHook(address _hook) external onlyOwner {
|
||||||
|
defaultHook = _hook;
|
||||||
|
emit HookSet(_hook);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPaused(bool _paused) external onlyOwner {
|
||||||
|
paused = _paused;
|
||||||
|
emit Paused(_paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatorCount() external view returns (uint256) {
|
||||||
|
return validators.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "./AereMessenger.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSpokePool
|
||||||
|
* @notice Across-protocol-compatible spoke pool for AERE Network.
|
||||||
|
* Implements the intent-based bridging model:
|
||||||
|
*
|
||||||
|
* 1. User deposits inputToken on this chain via `deposit(...)`.
|
||||||
|
* Emits a `V3FundsDeposited` event with intent parameters.
|
||||||
|
* 2. Solver observes the event, sees a profitable spread, and calls
|
||||||
|
* `fillRelay(...)` on the destination chain's SpokePool, transferring
|
||||||
|
* outputToken to the user's recipient address.
|
||||||
|
* 3. After fill, the destination SpokePool emits `FilledV3Relay` and
|
||||||
|
* sends a settlement message via AereMessenger to the origin
|
||||||
|
* SpokePool. The origin SpokePool then releases the locked
|
||||||
|
* inputToken to the solver's repayment address.
|
||||||
|
*
|
||||||
|
* If fillDeadline expires without a fill, user calls `claimRefund(...)`
|
||||||
|
* to recover their input tokens.
|
||||||
|
*
|
||||||
|
* This is the canonical Across v3 flow. By using AereMessenger for the
|
||||||
|
* settlement message layer, AERE's SpokePool is fully Hyperlane-compatible
|
||||||
|
* and ready for the public Across solver network once registered.
|
||||||
|
*/
|
||||||
|
contract AereSpokePool is Ownable, ReentrancyGuard, IMessageRecipient {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
AereMessenger public immutable messenger;
|
||||||
|
uint32 public immutable localDomain;
|
||||||
|
|
||||||
|
/// Grace period, added on top of fillDeadline, before a depositor may claim
|
||||||
|
/// a refund.
|
||||||
|
///
|
||||||
|
/// A solver may legitimately fill on the destination at any t < fillDeadline
|
||||||
|
/// (fillRelay irreversibly delivers outputToken to the recipient), while the
|
||||||
|
/// authenticated settlement that credits the solver only reaches this origin
|
||||||
|
/// chain after a cross-chain relay delay L (destination finality + validator
|
||||||
|
/// signing + relayer submission). If a refund were gated on fillDeadline
|
||||||
|
/// alone, a depositor could front-run a still-in-flight settlement in the
|
||||||
|
/// window [fillDeadline, fillDeadline + L]: pull the locked input back, after
|
||||||
|
/// which handle() reverts on the `refunded` flag and the solver who already
|
||||||
|
/// delivered the output is never repaid.
|
||||||
|
///
|
||||||
|
/// REFUND_BUFFER must generously exceed the worst-case L for the messenger's
|
||||||
|
/// validator set (including finality, signer polling, relayer congestion and
|
||||||
|
/// outage-driven retries). 3 hours is deliberately conservative: it is orders
|
||||||
|
/// of magnitude above the seconds-to-minutes of a healthy relay yet still
|
||||||
|
/// bounds how long a genuinely unfilled deposit's principal is held before the
|
||||||
|
/// depositor can recover it. A settlement for a fill dispatched at (or just
|
||||||
|
/// before) the deadline is therefore delivered, setting `settled`, before any
|
||||||
|
/// refund becomes possible.
|
||||||
|
///
|
||||||
|
/// NOTE: a timer-based refund cannot fully adjudicate the refund-vs-fill
|
||||||
|
/// outcome; if the relay were delayed beyond REFUND_BUFFER a refund could
|
||||||
|
/// still front-run it. Fully closing that would require an authenticated
|
||||||
|
/// "not filled" attestation over the same messenger path (as Across does).
|
||||||
|
/// While the messenger only carries fill-settlements, this buffer is the
|
||||||
|
/// pragmatic mitigation.
|
||||||
|
uint256 public constant REFUND_BUFFER = 3 hours;
|
||||||
|
|
||||||
|
/// Auto-incrementing deposit counter — used as the unique deposit ID.
|
||||||
|
uint32 public depositCounter;
|
||||||
|
|
||||||
|
/// Each enrolled remote SpokePool we can talk to.
|
||||||
|
mapping(uint32 => bytes32) public remoteSpokePool;
|
||||||
|
|
||||||
|
/// Deposit record: locked input tokens by depositId.
|
||||||
|
/// The requested output leg (outputToken / outputAmount / recipient) is
|
||||||
|
/// stored in full so the origin can verify, at settlement time, that the
|
||||||
|
/// output a solver actually delivered on the destination satisfies the
|
||||||
|
/// order before any locked principal is released.
|
||||||
|
struct Deposit {
|
||||||
|
address depositor;
|
||||||
|
address inputToken;
|
||||||
|
uint256 inputAmount;
|
||||||
|
address outputToken;
|
||||||
|
uint256 outputAmount;
|
||||||
|
address recipient;
|
||||||
|
uint32 destinationChainId;
|
||||||
|
uint32 fillDeadline;
|
||||||
|
bool settled;
|
||||||
|
bool refunded;
|
||||||
|
}
|
||||||
|
mapping(uint32 => Deposit) public deposits;
|
||||||
|
|
||||||
|
/// Filled relays — replay protection on the destination side.
|
||||||
|
mapping(bytes32 => bool) public filled;
|
||||||
|
|
||||||
|
/// Pending refunds for solvers awaiting settlement on the origin chain.
|
||||||
|
/// solver => inputToken => amount
|
||||||
|
mapping(address => mapping(address => uint256)) public pendingSettlement;
|
||||||
|
|
||||||
|
bool public paused;
|
||||||
|
|
||||||
|
event V3FundsDeposited(
|
||||||
|
uint32 indexed depositId,
|
||||||
|
address indexed depositor,
|
||||||
|
address inputToken,
|
||||||
|
uint256 inputAmount,
|
||||||
|
uint32 destinationChainId,
|
||||||
|
address outputToken,
|
||||||
|
uint256 outputAmount,
|
||||||
|
address recipient,
|
||||||
|
uint32 fillDeadline
|
||||||
|
);
|
||||||
|
event FilledV3Relay(
|
||||||
|
bytes32 indexed relayHash,
|
||||||
|
address indexed solver,
|
||||||
|
uint32 originChainId,
|
||||||
|
uint32 depositId,
|
||||||
|
address recipient,
|
||||||
|
uint256 outputAmount
|
||||||
|
);
|
||||||
|
event SettlementClaimed(address indexed solver, address indexed token, uint256 amount);
|
||||||
|
event Refunded(uint32 indexed depositId, address indexed depositor, uint256 amount);
|
||||||
|
event RemoteSpokePoolEnrolled(uint32 indexed domain, bytes32 spokePool);
|
||||||
|
event Paused(bool paused);
|
||||||
|
|
||||||
|
constructor(AereMessenger _messenger) {
|
||||||
|
messenger = _messenger;
|
||||||
|
localDomain = _messenger.localDomain();
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier whenNotPaused() {
|
||||||
|
require(!paused, "SpokePool: paused");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
function enrollRemoteSpokePool(uint32 destChainId, bytes32 spokePool) external onlyOwner {
|
||||||
|
remoteSpokePool[destChainId] = spokePool;
|
||||||
|
emit RemoteSpokePoolEnrolled(destChainId, spokePool);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPaused(bool _paused) external onlyOwner {
|
||||||
|
paused = _paused;
|
||||||
|
emit Paused(_paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Deposit (origin-chain user flow) ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice User deposits inputToken on this chain, committing to receive
|
||||||
|
* outputAmount of outputToken on destinationChainId before fillDeadline.
|
||||||
|
*/
|
||||||
|
function deposit(
|
||||||
|
address inputToken,
|
||||||
|
uint256 inputAmount,
|
||||||
|
address outputToken,
|
||||||
|
uint256 outputAmount,
|
||||||
|
uint32 destinationChainId,
|
||||||
|
address recipient,
|
||||||
|
uint32 fillDeadline
|
||||||
|
) external nonReentrant whenNotPaused returns (uint32 depositId) {
|
||||||
|
require(remoteSpokePool[destinationChainId] != bytes32(0), "SpokePool: dest not enrolled");
|
||||||
|
require(fillDeadline > block.timestamp, "SpokePool: deadline passed");
|
||||||
|
require(inputAmount > 0 && outputAmount > 0, "SpokePool: zero amount");
|
||||||
|
|
||||||
|
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
|
||||||
|
|
||||||
|
depositId = ++depositCounter;
|
||||||
|
deposits[depositId] = Deposit({
|
||||||
|
depositor: msg.sender,
|
||||||
|
inputToken: inputToken,
|
||||||
|
inputAmount: inputAmount,
|
||||||
|
outputToken: outputToken,
|
||||||
|
outputAmount: outputAmount,
|
||||||
|
recipient: recipient,
|
||||||
|
destinationChainId: destinationChainId,
|
||||||
|
fillDeadline: fillDeadline,
|
||||||
|
settled: false,
|
||||||
|
refunded: false
|
||||||
|
});
|
||||||
|
|
||||||
|
emit V3FundsDeposited(
|
||||||
|
depositId,
|
||||||
|
msg.sender,
|
||||||
|
inputToken,
|
||||||
|
inputAmount,
|
||||||
|
destinationChainId,
|
||||||
|
outputToken,
|
||||||
|
outputAmount,
|
||||||
|
recipient,
|
||||||
|
fillDeadline
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User reclaims input tokens if fill deadline has passed without delivery.
|
||||||
|
///
|
||||||
|
/// The refund is gated on fillDeadline + REFUND_BUFFER, not fillDeadline
|
||||||
|
/// alone, so an authenticated settlement for a fill dispatched at/just-before
|
||||||
|
/// the deadline always lands (setting `settled`) before a refund is possible.
|
||||||
|
/// This closes the theft-of-principal race where a depositor front-runs an
|
||||||
|
/// in-flight settlement to pull their input back while the solver has already
|
||||||
|
/// delivered the output on the destination. See REFUND_BUFFER above.
|
||||||
|
///
|
||||||
|
/// A settlement that somehow arrives after a refund still cannot double-pay:
|
||||||
|
/// handle() rejects it on the `refunded` flag. A refund after a genuine
|
||||||
|
/// expiry (no fill) still works once the buffer has elapsed.
|
||||||
|
function claimRefund(uint32 depositId) external nonReentrant {
|
||||||
|
Deposit storage d = deposits[depositId];
|
||||||
|
require(d.depositor == msg.sender, "SpokePool: not depositor");
|
||||||
|
require(!d.refunded && !d.settled, "SpokePool: already resolved");
|
||||||
|
require(block.timestamp > uint256(d.fillDeadline) + REFUND_BUFFER, "SpokePool: refund buffer not elapsed");
|
||||||
|
d.refunded = true;
|
||||||
|
IERC20(d.inputToken).safeTransfer(msg.sender, d.inputAmount);
|
||||||
|
emit Refunded(depositId, msg.sender, d.inputAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Fill (destination-chain solver flow) ─────────────────────
|
||||||
|
|
||||||
|
/// Relay struct sent from origin chain in the V3FundsDeposited event.
|
||||||
|
struct RelayData {
|
||||||
|
uint32 originChainId;
|
||||||
|
uint32 depositId;
|
||||||
|
address depositor;
|
||||||
|
address inputToken;
|
||||||
|
uint256 inputAmount;
|
||||||
|
address outputToken;
|
||||||
|
uint256 outputAmount;
|
||||||
|
address recipient;
|
||||||
|
uint32 fillDeadline;
|
||||||
|
address solverRepaymentAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Solver delivers outputToken to recipient on this chain.
|
||||||
|
* Solver MUST hold the outputToken in advance (it's their working capital).
|
||||||
|
*/
|
||||||
|
function fillRelay(RelayData calldata r) external nonReentrant whenNotPaused {
|
||||||
|
require(r.fillDeadline > block.timestamp, "SpokePool: fill window closed");
|
||||||
|
// A fill must actually deliver something. A zero-output "fill" delivers
|
||||||
|
// nothing and must never be able to unlock the origin principal.
|
||||||
|
require(r.outputAmount > 0, "SpokePool: zero output");
|
||||||
|
bytes32 relayHash = _relayHash(r);
|
||||||
|
require(!filled[relayHash], "SpokePool: already filled");
|
||||||
|
filled[relayHash] = true;
|
||||||
|
|
||||||
|
// Solver delivers output tokens directly to recipient
|
||||||
|
IERC20(r.outputToken).safeTransferFrom(msg.sender, r.recipient, r.outputAmount);
|
||||||
|
|
||||||
|
// Solver accrues a claim on the origin-chain SpokePool's locked input.
|
||||||
|
// The settlement message carries a commitment to the OUTPUT that was
|
||||||
|
// actually delivered here (token / amount / recipient) so the origin can
|
||||||
|
// verify it satisfies the deposit order before releasing any principal.
|
||||||
|
bytes memory body = abi.encode(
|
||||||
|
r.depositId,
|
||||||
|
r.inputToken,
|
||||||
|
r.inputAmount,
|
||||||
|
r.outputToken,
|
||||||
|
r.outputAmount,
|
||||||
|
r.recipient,
|
||||||
|
msg.sender, // solver who filled
|
||||||
|
r.solverRepaymentAddress
|
||||||
|
);
|
||||||
|
messenger.dispatch(r.originChainId, remoteSpokePool[r.originChainId], body);
|
||||||
|
|
||||||
|
emit FilledV3Relay(relayHash, msg.sender, r.originChainId, r.depositId, r.recipient, r.outputAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _relayHash(RelayData calldata r) internal pure returns (bytes32) {
|
||||||
|
return keccak256(abi.encode(
|
||||||
|
r.originChainId, r.depositId, r.depositor, r.inputToken, r.inputAmount,
|
||||||
|
r.outputToken, r.outputAmount, r.recipient, r.fillDeadline, r.solverRepaymentAddress
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Settlement (origin-chain inbound) ─────────────────────
|
||||||
|
|
||||||
|
/// Called by AereMessenger when a destination chain confirms a fill.
|
||||||
|
function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable override {
|
||||||
|
require(msg.sender == address(messenger), "SpokePool: caller not messenger");
|
||||||
|
require(sender == remoteSpokePool[origin], "SpokePool: unknown remote spoke");
|
||||||
|
|
||||||
|
(
|
||||||
|
uint32 depositId,
|
||||||
|
address inputToken,
|
||||||
|
uint256 inputAmount,
|
||||||
|
address outputToken,
|
||||||
|
uint256 outputAmount,
|
||||||
|
address recipient,
|
||||||
|
address solver,
|
||||||
|
address solverRepayment
|
||||||
|
) = abi.decode(body, (uint32, address, uint256, address, uint256, address, address, address));
|
||||||
|
|
||||||
|
Deposit storage d = deposits[depositId];
|
||||||
|
require(!d.settled, "SpokePool: settled");
|
||||||
|
require(!d.refunded, "SpokePool: refunded");
|
||||||
|
require(d.inputToken == inputToken && d.inputAmount == inputAmount, "SpokePool: settle mismatch");
|
||||||
|
|
||||||
|
// Bind the release of principal to the OUTPUT that was actually
|
||||||
|
// delivered on the destination. Repay only if the fill satisfied the
|
||||||
|
// depositor's order: the correct output token, delivered to the intended
|
||||||
|
// recipient, in at least the requested amount. This closes the theft
|
||||||
|
// where a fill that delivered nothing (or the wrong output, or to the
|
||||||
|
// wrong recipient) could still unlock and steal the locked principal.
|
||||||
|
require(outputToken == d.outputToken, "SpokePool: output token mismatch");
|
||||||
|
require(recipient == d.recipient, "SpokePool: recipient mismatch");
|
||||||
|
require(outputAmount >= d.outputAmount, "SpokePool: output below requested");
|
||||||
|
|
||||||
|
d.settled = true;
|
||||||
|
|
||||||
|
// Use repayment address from the message — solver may want to receive on a different address
|
||||||
|
address payoutTo = solverRepayment != address(0) ? solverRepayment : solver;
|
||||||
|
pendingSettlement[payoutTo][inputToken] += inputAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Solver withdraws accumulated settlements.
|
||||||
|
function claimSettlement(address token) external nonReentrant {
|
||||||
|
uint256 amount = pendingSettlement[msg.sender][token];
|
||||||
|
require(amount > 0, "SpokePool: nothing to claim");
|
||||||
|
pendingSettlement[msg.sender][token] = 0;
|
||||||
|
IERC20(token).safeTransfer(msg.sender, amount);
|
||||||
|
emit SettlementClaimed(msg.sender, token, amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "./AereMessenger.sol";
|
||||||
|
|
||||||
|
interface IERC20 {
|
||||||
|
function transfer(address to, uint256 amount) external returns (bool);
|
||||||
|
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||||
|
function balanceOf(address) external view returns (uint256);
|
||||||
|
function mint(address to, uint256 amount) external;
|
||||||
|
function burn(address from, uint256 amount) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereWarpRoute
|
||||||
|
* @notice Typed cross-chain token bridge built on AereMessenger.
|
||||||
|
* One AereWarpRoute per token per chain. Two flavours:
|
||||||
|
*
|
||||||
|
* Collateral mode (token has natural liquidity on this chain):
|
||||||
|
* - transferRemote: lock tokens on this chain → emit message → mint on remote
|
||||||
|
* - handle (incoming): receive message → unlock tokens on this chain to recipient
|
||||||
|
*
|
||||||
|
* Synthetic mode (token is a bridged representation):
|
||||||
|
* - transferRemote: burn synthetic tokens here → emit message → mint on remote
|
||||||
|
* - handle (incoming): receive message → mint synthetic tokens here to recipient
|
||||||
|
*
|
||||||
|
* This contract pattern mirrors Hyperlane Warp Route exactly, so apps built
|
||||||
|
* against Hyperlane's tooling work on AERE with only the contract address change.
|
||||||
|
*
|
||||||
|
* For Bank28: USDC.aere, USDT.aere, WETH.aere, cbBTC.aere are all separate
|
||||||
|
* AereWarpRoute deployments in collateral mode (on the origin chain) and
|
||||||
|
* synthetic mode (on AERE) — totalling 8 deployments for 4 assets across
|
||||||
|
* 2 chain pairs.
|
||||||
|
*/
|
||||||
|
contract AereWarpRoute is IMessageRecipient, Ownable, ReentrancyGuard {
|
||||||
|
enum Mode { Collateral, Synthetic }
|
||||||
|
|
||||||
|
AereMessenger public immutable messenger;
|
||||||
|
IERC20 public immutable token;
|
||||||
|
Mode public immutable mode;
|
||||||
|
|
||||||
|
/// Remote AereWarpRoute deployments per destination domain.
|
||||||
|
/// bytes32 because Hyperlane convention is to pad addresses.
|
||||||
|
mapping(uint32 => bytes32) public remoteRouter;
|
||||||
|
|
||||||
|
/// Lifetime metrics for transparency.
|
||||||
|
uint256 public totalSentOut;
|
||||||
|
uint256 public totalReceivedIn;
|
||||||
|
|
||||||
|
event SentTransferRemote(uint32 indexed destDomain, bytes32 indexed recipient, uint256 amount, bytes32 messageId);
|
||||||
|
event ReceivedTransferRemote(uint32 indexed origin, address indexed recipient, uint256 amount);
|
||||||
|
event RemoteRouterEnrolled(uint32 indexed domain, bytes32 router);
|
||||||
|
|
||||||
|
constructor(AereMessenger _messenger, IERC20 _token, Mode _mode) {
|
||||||
|
messenger = _messenger;
|
||||||
|
token = _token;
|
||||||
|
mode = _mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Admin ─────────────────────
|
||||||
|
|
||||||
|
/// Bind a remote AereWarpRoute deployment so it can talk to us.
|
||||||
|
function enrollRemoteRouter(uint32 domain, bytes32 router) external onlyOwner {
|
||||||
|
remoteRouter[domain] = router;
|
||||||
|
emit RemoteRouterEnrolled(domain, router);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Outbound ─────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Send tokens to a recipient on another chain via Hyperlane-compatible bridging.
|
||||||
|
* @dev User must have approved this contract for `amount` of `token` first.
|
||||||
|
*/
|
||||||
|
function transferRemote(
|
||||||
|
uint32 destDomain,
|
||||||
|
bytes32 recipient,
|
||||||
|
uint256 amount
|
||||||
|
) external payable nonReentrant returns (bytes32 messageId) {
|
||||||
|
require(remoteRouter[destDomain] != bytes32(0), "WarpRoute: no remote router");
|
||||||
|
require(amount > 0, "WarpRoute: zero amount");
|
||||||
|
|
||||||
|
if (mode == Mode.Collateral) {
|
||||||
|
// Pull tokens; they remain locked here until a withdrawal arrives.
|
||||||
|
require(token.transferFrom(msg.sender, address(this), amount), "WarpRoute: pull failed");
|
||||||
|
} else {
|
||||||
|
// Burn synthetic tokens from the sender — the remote side will mint the original.
|
||||||
|
token.burn(msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes memory body = abi.encode(recipient, amount);
|
||||||
|
messageId = messenger.dispatch{ value: msg.value }(destDomain, remoteRouter[destDomain], body);
|
||||||
|
|
||||||
|
totalSentOut += amount;
|
||||||
|
emit SentTransferRemote(destDomain, recipient, amount, messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ───────────────────── Inbound (only callable by Messenger) ─────────────────────
|
||||||
|
|
||||||
|
function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable override {
|
||||||
|
require(msg.sender == address(messenger), "WarpRoute: caller not messenger");
|
||||||
|
require(sender == remoteRouter[origin], "WarpRoute: unknown remote router");
|
||||||
|
|
||||||
|
(bytes32 recipient32, uint256 amount) = abi.decode(body, (bytes32, uint256));
|
||||||
|
address recipient = address(uint160(uint256(recipient32)));
|
||||||
|
|
||||||
|
if (mode == Mode.Collateral) {
|
||||||
|
// Release locked tokens to recipient.
|
||||||
|
require(token.transfer(recipient, amount), "WarpRoute: release failed");
|
||||||
|
} else {
|
||||||
|
// Mint synthetic tokens to recipient.
|
||||||
|
token.mint(recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
totalReceivedIn += amount;
|
||||||
|
emit ReceivedTransferRemote(origin, recipient, amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import "../stablecoins/IHypMailbox.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereWarpRouteV3
|
||||||
|
* @notice Hyperlane v3 TokenRouter for USDC.e on AERE chain 2800, bound to the
|
||||||
|
* WORKING AereMailboxV3 (0x7BF113Ab1BCd2b6da01804764065776e3057605a) and
|
||||||
|
* its default post-dispatch hook AereIGPV3
|
||||||
|
* (0x5e4B8e9b196B1c7b3Be86148769aB0047c79744c).
|
||||||
|
*
|
||||||
|
* This REPLACES the dead legacy path. The prior AereWarpRoute pointed at
|
||||||
|
* AereMessenger, whose runtime bytecode has NO quoteDispatch selector, so
|
||||||
|
* every quote reverted and the route was unusable. AereMailboxV3 exposes
|
||||||
|
* a real quoteDispatch(uint32,bytes32,bytes) and routes the quoted fee to
|
||||||
|
* AereIGPV3 internally on dispatch, so this router works end to end on the
|
||||||
|
* AERE side.
|
||||||
|
*
|
||||||
|
* TOKEN HANDLING — two immutable modes, chosen at deploy:
|
||||||
|
*
|
||||||
|
* Mode.MintBurn (canonical synthetic; USDC.e is the bridged representation):
|
||||||
|
* - transferRemote burns the caller's USDC.e (TOKEN.burnFrom), then dispatches.
|
||||||
|
* - handle mints USDC.e to the recipient (TOKEN.mint).
|
||||||
|
* Use this ONLY when the existing USDC.e grants THIS router mint/burn rights
|
||||||
|
* (i.e. its immutable BRIDGE == this router). No NEW token is minted here;
|
||||||
|
* USDC.e is the existing bridged-collateral representation, 1:1 backed by the
|
||||||
|
* native USDC locked in the sister AereHypERC20Collateral on Ethereum.
|
||||||
|
*
|
||||||
|
* Mode.Lock (lock/release against an existing token this router does NOT
|
||||||
|
* control the mint of):
|
||||||
|
* - transferRemote pulls (locks) the existing token via safeTransferFrom.
|
||||||
|
* - handle releases the locked token via safeTransfer to the recipient.
|
||||||
|
*
|
||||||
|
* WIRE FORMAT: Hyperlane HypERC20 convention — body = abi.encodePacked(
|
||||||
|
* bytes32 recipient, uint256 amount) = exactly 64 bytes.
|
||||||
|
*
|
||||||
|
* V3 FEE FLOW: dispatch() forwards the quoted fee to the mailbox's default hook
|
||||||
|
* (the IGP). Callers pay the fee as msg.value to transferRemote; anything above
|
||||||
|
* the quote is refunded to the caller. quoteDispatch on the mailbox already
|
||||||
|
* includes the IGP hook price, so this router quotes against the mailbox (the
|
||||||
|
* canonical v3 flow) and keeps an immutable IGP reference only for the
|
||||||
|
* transparency view quoteGasPayment().
|
||||||
|
*
|
||||||
|
* NO new ERC-20 / wrapped / governance token is introduced by this contract.
|
||||||
|
*/
|
||||||
|
contract AereWarpRouteV3 is Ownable, ReentrancyGuard, IHypMessageRecipient {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
using TypeCasts for address;
|
||||||
|
using TypeCasts for bytes32;
|
||||||
|
|
||||||
|
enum Mode { Lock, MintBurn }
|
||||||
|
|
||||||
|
/* --------------------------------- immutables --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice AereMailboxV3 — dispatch + quoteDispatch endpoint on chain 2800.
|
||||||
|
IHypMailbox public immutable MAILBOX;
|
||||||
|
/// @notice AereIGPV3 — the mailbox default post-dispatch hook (fee sink).
|
||||||
|
/// Referenced for the quoteGasPayment() transparency view only; the
|
||||||
|
/// authoritative fee for a dispatch is MAILBOX.quoteDispatch(...).
|
||||||
|
IAereIGPV3View public immutable IGP;
|
||||||
|
/// @notice Existing USDC.e representation on AERE (or the token this router
|
||||||
|
/// locks/releases). NEVER a token minted by this contract's deploy.
|
||||||
|
IERC20 public immutable TOKEN;
|
||||||
|
/// @notice Lock (release existing) or MintBurn (mint/burn existing USDC.e).
|
||||||
|
Mode public immutable MODE;
|
||||||
|
|
||||||
|
/* ----------------------------------- state ------------------------------------ */
|
||||||
|
|
||||||
|
/// @notice Hyperlane domain id => trusted remote router (bytes32-padded address).
|
||||||
|
mapping(uint32 => bytes32) public routers;
|
||||||
|
|
||||||
|
uint256 public totalSentOut;
|
||||||
|
uint256 public totalReceivedIn;
|
||||||
|
|
||||||
|
/* ----------------------------------- events ----------------------------------- */
|
||||||
|
|
||||||
|
event RemoteRouterEnrolled(uint32 indexed domain, bytes32 router);
|
||||||
|
event SentTransferRemote(uint32 indexed destination, bytes32 indexed recipient, uint256 amount, bytes32 messageId);
|
||||||
|
event ReceivedTransferRemote(uint32 indexed origin, address indexed recipient, uint256 amount);
|
||||||
|
|
||||||
|
/* ----------------------------------- errors ----------------------------------- */
|
||||||
|
|
||||||
|
error NotMailbox();
|
||||||
|
error UnknownRouter(uint32 origin, bytes32 sender);
|
||||||
|
error NoRouterEnrolled(uint32 destination);
|
||||||
|
error InsufficientGasPayment(uint256 paid, uint256 required);
|
||||||
|
error ZeroAmount();
|
||||||
|
error ZeroRecipient();
|
||||||
|
error RefundFailed();
|
||||||
|
|
||||||
|
/* --------------------------------- modifiers ---------------------------------- */
|
||||||
|
|
||||||
|
modifier onlyMailbox() {
|
||||||
|
if (msg.sender != address(MAILBOX)) revert NotMailbox();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- constructor --------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mailbox AereMailboxV3 address (must be non-zero).
|
||||||
|
* @param igp AereIGPV3 address (mailbox default hook). May be zero if the
|
||||||
|
* operator does not want the on-chain transparency view; the
|
||||||
|
* dispatch fee path never depends on it.
|
||||||
|
* @param token Existing USDC.e (MintBurn) or existing token to lock (Lock).
|
||||||
|
* @param mode Lock or MintBurn.
|
||||||
|
*/
|
||||||
|
constructor(address mailbox, address igp, address token, Mode mode) {
|
||||||
|
require(mailbox != address(0) && token != address(0), "zero address");
|
||||||
|
MAILBOX = IHypMailbox(mailbox);
|
||||||
|
IGP = IAereIGPV3View(igp);
|
||||||
|
TOKEN = IERC20(token);
|
||||||
|
MODE = mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- router enroll -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Bind the single trusted remote router for a domain (owner-gated).
|
||||||
|
function enrollRemoteRouter(uint32 domain, bytes32 router) external onlyOwner {
|
||||||
|
routers[domain] = router;
|
||||||
|
emit RemoteRouterEnrolled(domain, router);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Remove the trusted remote router for a domain (owner-gated).
|
||||||
|
function unenrollRemoteRouter(uint32 domain) external onlyOwner {
|
||||||
|
delete routers[domain];
|
||||||
|
emit RemoteRouterEnrolled(domain, bytes32(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- outbound --------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Pull `amount` of TOKEN from the caller and dispatch a Hyperlane v3
|
||||||
|
* message instructing the enrolled router on `destination` to release
|
||||||
|
* (or mint) the corresponding asset to `recipient`.
|
||||||
|
* @param destination Hyperlane domain id of the remote chain.
|
||||||
|
* @param recipient bytes32-padded recipient address on the remote chain.
|
||||||
|
* @param amount Token units to send (USDC.e has 6 decimals).
|
||||||
|
* @return messageId The dispatched Hyperlane v3 message id.
|
||||||
|
*/
|
||||||
|
function transferRemote(
|
||||||
|
uint32 destination,
|
||||||
|
bytes32 recipient,
|
||||||
|
uint256 amount
|
||||||
|
) external payable nonReentrant returns (bytes32 messageId) {
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
if (recipient == bytes32(0)) revert ZeroRecipient();
|
||||||
|
bytes32 remoteRouter = routers[destination];
|
||||||
|
if (remoteRouter == bytes32(0)) revert NoRouterEnrolled(destination);
|
||||||
|
|
||||||
|
bytes memory body = abi.encodePacked(recipient, amount);
|
||||||
|
|
||||||
|
// Authoritative fee for the v3 dispatch. The mailbox forwards this to the
|
||||||
|
// IGP hook internally, so we send exactly this as msg.value to dispatch().
|
||||||
|
uint256 fee = MAILBOX.quoteDispatch(destination, remoteRouter, body);
|
||||||
|
if (msg.value < fee) revert InsufficientGasPayment(msg.value, fee);
|
||||||
|
|
||||||
|
// Pull the caller's tokens BEFORE the cross-chain dispatch.
|
||||||
|
if (MODE == Mode.MintBurn) {
|
||||||
|
IWarpMintBurn(address(TOKEN)).burnFrom(msg.sender, amount);
|
||||||
|
} else {
|
||||||
|
TOKEN.safeTransferFrom(msg.sender, address(this), amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
messageId = MAILBOX.dispatch{value: fee}(destination, remoteRouter, body);
|
||||||
|
|
||||||
|
// Refund any msg.value above the quoted fee to the caller.
|
||||||
|
if (msg.value > fee) {
|
||||||
|
(bool ok, ) = msg.sender.call{value: msg.value - fee}("");
|
||||||
|
if (!ok) revert RefundFailed();
|
||||||
|
}
|
||||||
|
|
||||||
|
totalSentOut += amount;
|
||||||
|
emit SentTransferRemote(destination, recipient, amount, messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- inbound ---------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Called by AereMailboxV3 after its validator set verified the
|
||||||
|
* message. Releases (Lock) or mints (MintBurn) `amount` to the
|
||||||
|
* recipient parsed from the 64-byte Hyperlane body.
|
||||||
|
*/
|
||||||
|
function handle(
|
||||||
|
uint32 origin,
|
||||||
|
bytes32 sender,
|
||||||
|
bytes calldata body
|
||||||
|
) external payable override onlyMailbox nonReentrant {
|
||||||
|
bytes32 expected = routers[origin];
|
||||||
|
if (expected == bytes32(0) || expected != sender) revert UnknownRouter(origin, sender);
|
||||||
|
|
||||||
|
require(body.length == 64, "invalid body length");
|
||||||
|
bytes32 recipientB32;
|
||||||
|
uint256 amount;
|
||||||
|
assembly {
|
||||||
|
recipientB32 := calldataload(body.offset)
|
||||||
|
amount := calldataload(add(body.offset, 32))
|
||||||
|
}
|
||||||
|
address recipient = recipientB32.bytes32ToAddress();
|
||||||
|
|
||||||
|
if (MODE == Mode.MintBurn) {
|
||||||
|
IWarpMintBurn(address(TOKEN)).mint(recipient, amount);
|
||||||
|
} else {
|
||||||
|
TOKEN.safeTransfer(recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
totalReceivedIn += amount;
|
||||||
|
emit ReceivedTransferRemote(origin, recipient, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------ views ----------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Fee that transferRemote(destination, recipient, amount) requires as
|
||||||
|
/// msg.value, quoted against AereMailboxV3 (includes the IGP hook).
|
||||||
|
function quoteTransferRemote(
|
||||||
|
uint32 destination,
|
||||||
|
bytes32 recipient,
|
||||||
|
uint256 amount
|
||||||
|
) external view returns (uint256 fee) {
|
||||||
|
bytes memory body = abi.encodePacked(recipient, amount);
|
||||||
|
return MAILBOX.quoteDispatch(destination, routers[destination], body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Transparency view straight off AereIGPV3 for a given destination
|
||||||
|
/// and gas limit. Reverts if IGP was not set at deploy.
|
||||||
|
function quoteGasPayment(uint32 destination, uint256 gasLimit) external view returns (uint256) {
|
||||||
|
return IGP.quoteGasPayment(destination, gasLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Locked balance held by this router (Lock mode reserve view).
|
||||||
|
function lockedSupply() external view returns (uint256) {
|
||||||
|
return TOKEN.balanceOf(address(this));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- helper interfaces -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice USDC.e mint/burn surface (matches contracts/stablecoins/USDCe.sol).
|
||||||
|
interface IWarpMintBurn {
|
||||||
|
function mint(address to, uint256 amount) external;
|
||||||
|
function burnFrom(address from, uint256 amount) external;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice AereIGPV3 quoting surface for the transparency view.
|
||||||
|
interface IAereIGPV3View {
|
||||||
|
function quoteGasPayment(uint32 destinationDomain, uint256 gasLimit) external view returns (uint256);
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "../stablecoins/IHypMailbox.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title MockWarpMailboxV3 — faithful stand-in for AereMailboxV3's external
|
||||||
|
* surface used by AereWarpRouteV3 tests. Not for mainnet.
|
||||||
|
*
|
||||||
|
* @dev Mirrors the real AereMailboxV3 behaviour the router depends on:
|
||||||
|
* - quoteDispatch(uint32,bytes32,bytes) returns a configurable fee.
|
||||||
|
* - dispatch(...) requires msg.value >= fee, keeps the fee, refunds any
|
||||||
|
* excess to msg.sender (exactly like AereMailboxV3._dispatch), records
|
||||||
|
* the call, returns a v3-style messageId.
|
||||||
|
* - mockDeliver(...) lets a test drive an inbound handle() so the
|
||||||
|
* recipient sees msg.sender == this mailbox (like process()).
|
||||||
|
*/
|
||||||
|
contract MockWarpMailboxV3 is IHypMailbox {
|
||||||
|
uint32 public override localDomain;
|
||||||
|
uint256 public feeAmount = 0.001 ether;
|
||||||
|
|
||||||
|
// Recorded from the last dispatch — asserted by tests.
|
||||||
|
uint32 public lastDestination;
|
||||||
|
bytes32 public lastRecipient;
|
||||||
|
bytes public lastBody;
|
||||||
|
uint256 public lastFeePaid;
|
||||||
|
bytes32 public lastMessageId;
|
||||||
|
uint32 public dispatchNonce;
|
||||||
|
|
||||||
|
event Dispatched(uint32 indexed destination, bytes32 indexed recipient, bytes body, uint256 feePaid);
|
||||||
|
|
||||||
|
constructor(uint32 _localDomain) {
|
||||||
|
localDomain = _localDomain;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setFee(uint256 f) external {
|
||||||
|
feeAmount = f;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quoteDispatch(uint32, bytes32, bytes calldata) external view override returns (uint256) {
|
||||||
|
return feeAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispatch(
|
||||||
|
uint32 destination,
|
||||||
|
bytes32 recipient,
|
||||||
|
bytes calldata body
|
||||||
|
) external payable override returns (bytes32) {
|
||||||
|
require(msg.value >= feeAmount, "MockWarpMailboxV3: insufficient fee");
|
||||||
|
lastDestination = destination;
|
||||||
|
lastRecipient = recipient;
|
||||||
|
lastBody = body;
|
||||||
|
lastFeePaid = feeAmount;
|
||||||
|
|
||||||
|
bytes32 id = keccak256(abi.encodePacked(localDomain, dispatchNonce, destination, recipient, body));
|
||||||
|
dispatchNonce += 1;
|
||||||
|
lastMessageId = id;
|
||||||
|
emit Dispatched(destination, recipient, body, feeAmount);
|
||||||
|
|
||||||
|
uint256 excess = msg.value - feeAmount;
|
||||||
|
if (excess > 0) {
|
||||||
|
(bool ok, ) = msg.sender.call{value: excess}("");
|
||||||
|
require(ok, "MockWarpMailboxV3: refund failed");
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Test-only inbound delivery: call recipient.handle so it sees
|
||||||
|
/// msg.sender == this mailbox.
|
||||||
|
function mockDeliver(
|
||||||
|
address recipient,
|
||||||
|
uint32 origin,
|
||||||
|
bytes32 sender,
|
||||||
|
bytes calldata body
|
||||||
|
) external {
|
||||||
|
IHypMessageRecipient(recipient).handle(origin, sender, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title MockWarpIGPV3 — minimal AereIGPV3 quoting surface for the router's
|
||||||
|
* quoteGasPayment() transparency view test.
|
||||||
|
*/
|
||||||
|
contract MockWarpIGPV3 {
|
||||||
|
function quoteGasPayment(uint32, uint256 gasLimit) external pure returns (uint256) {
|
||||||
|
// Deterministic: 1 gwei of AERE per unit of destination gas.
|
||||||
|
return gasLimit * 1e9;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.20;
|
||||||
|
|
||||||
|
import {AereUSDC} from "./AereUSDC.sol";
|
||||||
|
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
|
||||||
|
|
||||||
|
/// @title AereBridge — Foundation-attested on-ramp from Ethereum USDC to AereUSDC
|
||||||
|
/// @notice The off-chain bridge watcher (Foundation-operated, source under
|
||||||
|
/// /opt/aere-bridge-watcher) monitors a Foundation receiver address on
|
||||||
|
/// Ethereum mainnet for incoming USDC. When a deposit is detected and
|
||||||
|
/// confirmed (≥12 block confirmations), the watcher calls
|
||||||
|
/// `attestDeposit(ethTxHash, ethSender, aereDestination, amount)` on this
|
||||||
|
/// contract, which mints AereUSDC to the destination.
|
||||||
|
///
|
||||||
|
/// Replay protection: every (ethTxHash, logIndex) is recorded — re-attesting
|
||||||
|
/// the same deposit is a no-op.
|
||||||
|
///
|
||||||
|
/// Honest framing: this contract assumes a trusted ATTESTOR role. Phase 1
|
||||||
|
/// the attestor is a Foundation-controlled EOA. Phase 2 swaps to a multisig.
|
||||||
|
/// Phase 3 replaces with trustless settlement via Across/Hyperlane.
|
||||||
|
contract AereBridge is AccessControl {
|
||||||
|
bytes32 public constant ATTESTOR_ROLE = keccak256("ATTESTOR_ROLE");
|
||||||
|
|
||||||
|
AereUSDC public immutable aereUSDC;
|
||||||
|
|
||||||
|
/// @notice Foundation's USDC receiver address on Ethereum mainnet — informational
|
||||||
|
/// only; the watcher actually decides which Ethereum address to monitor.
|
||||||
|
string public ethReceiverHint;
|
||||||
|
|
||||||
|
/// @notice (ethTxHash, logIndex) tuple → already-attested marker. Prevents double-mint.
|
||||||
|
mapping(bytes32 => bool) public attestedDeposits;
|
||||||
|
|
||||||
|
/// @notice Total bridged in (USDC, 6 decimals). Visible for transparency dashboard.
|
||||||
|
uint256 public totalBridgedIn;
|
||||||
|
|
||||||
|
struct Deposit {
|
||||||
|
bytes32 ethTxHash;
|
||||||
|
uint64 ethLogIndex;
|
||||||
|
address ethSender;
|
||||||
|
address aereDestination;
|
||||||
|
uint256 amount;
|
||||||
|
uint64 attestedAt;
|
||||||
|
uint64 attestedBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Append-only deposit log. Phase 1 only; off-chain indexer reads events.
|
||||||
|
Deposit[] public deposits;
|
||||||
|
|
||||||
|
event Attested(
|
||||||
|
uint256 indexed depositId,
|
||||||
|
bytes32 indexed ethTxHash,
|
||||||
|
address indexed aereDestination,
|
||||||
|
address ethSender,
|
||||||
|
uint256 amount
|
||||||
|
);
|
||||||
|
event EthReceiverHintUpdated(string ethReceiver);
|
||||||
|
|
||||||
|
error AlreadyAttested();
|
||||||
|
error InvalidAmount();
|
||||||
|
error InvalidDestination();
|
||||||
|
|
||||||
|
constructor(address foundation, address _aereUSDC, address initialAttestor, string memory _ethReceiverHint) {
|
||||||
|
require(_aereUSDC != address(0), "bridge: aereUSDC=0");
|
||||||
|
aereUSDC = AereUSDC(_aereUSDC);
|
||||||
|
ethReceiverHint = _ethReceiverHint;
|
||||||
|
_grantRole(DEFAULT_ADMIN_ROLE, foundation);
|
||||||
|
_grantRole(ATTESTOR_ROLE, initialAttestor);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Off-chain watcher calls this when an Ethereum USDC deposit is confirmed.
|
||||||
|
/// @param ethTxHash The Ethereum transaction hash containing the USDC Transfer.
|
||||||
|
/// @param ethLogIndex The log index within that tx (multiple logs per tx possible).
|
||||||
|
/// @param ethSender The Ethereum address that sent the USDC (used for refund routing).
|
||||||
|
/// @param aereDestination The AERE address to receive AereUSDC.
|
||||||
|
/// @param amount The amount in USDC units (6 decimals).
|
||||||
|
function attestDeposit(
|
||||||
|
bytes32 ethTxHash,
|
||||||
|
uint64 ethLogIndex,
|
||||||
|
address ethSender,
|
||||||
|
address aereDestination,
|
||||||
|
uint256 amount
|
||||||
|
) external onlyRole(ATTESTOR_ROLE) {
|
||||||
|
if (amount == 0) revert InvalidAmount();
|
||||||
|
if (aereDestination == address(0)) revert InvalidDestination();
|
||||||
|
bytes32 key = keccak256(abi.encodePacked(ethTxHash, ethLogIndex));
|
||||||
|
if (attestedDeposits[key]) revert AlreadyAttested();
|
||||||
|
attestedDeposits[key] = true;
|
||||||
|
|
||||||
|
uint256 id = deposits.length;
|
||||||
|
deposits.push(Deposit({
|
||||||
|
ethTxHash: ethTxHash,
|
||||||
|
ethLogIndex: ethLogIndex,
|
||||||
|
ethSender: ethSender,
|
||||||
|
aereDestination: aereDestination,
|
||||||
|
amount: amount,
|
||||||
|
attestedAt: uint64(block.timestamp),
|
||||||
|
attestedBlock: uint64(block.number)
|
||||||
|
}));
|
||||||
|
totalBridgedIn += amount;
|
||||||
|
|
||||||
|
aereUSDC.mint(aereDestination, amount);
|
||||||
|
emit Attested(id, ethTxHash, aereDestination, ethSender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Foundation can update the receiver-address hint shown to users.
|
||||||
|
function setEthReceiverHint(string calldata _ethReceiverHint) external onlyRole(DEFAULT_ADMIN_ROLE) {
|
||||||
|
ethReceiverHint = _ethReceiverHint;
|
||||||
|
emit EthReceiverHintUpdated(_ethReceiverHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
function depositCount() external view returns (uint256) {
|
||||||
|
return deposits.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.20;
|
||||||
|
|
||||||
|
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||||
|
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
|
||||||
|
|
||||||
|
/// @title AereUSDC — Foundation-attested bridged USDC on AERE chain 2800
|
||||||
|
/// @notice Each AereUSDC is 1:1-backed by a USDC reserve held by AERE Foundation on
|
||||||
|
/// Ethereum mainnet. The Foundation address (currently a Trust Wallet receiver,
|
||||||
|
/// eventually a multisig) holds the real USDC. AereUSDC is minted on chain 2800
|
||||||
|
/// when the off-chain bridge watcher attests a deposit; burned when the user
|
||||||
|
/// requests withdrawal (Phase 2 — currently manual).
|
||||||
|
///
|
||||||
|
/// Decimals: 6 (matches Ethereum USDC, so 1 USDC = 1 AereUSDC numerically).
|
||||||
|
/// Symbol: aUSDC. Name: "Aere-Bridged USDC".
|
||||||
|
///
|
||||||
|
/// Roles:
|
||||||
|
/// - DEFAULT_ADMIN_ROLE: Foundation, sets bridge address, can pause minting in emergency.
|
||||||
|
/// - MINTER_ROLE: AereBridge contract only. Foundation grants on deploy.
|
||||||
|
/// - BURNER_ROLE: AereBridge contract (Phase 2 — Foundation will add for withdrawal flow).
|
||||||
|
///
|
||||||
|
/// Honest framing: this is a CUSTODIAL bridged asset. Foundation can theoretically
|
||||||
|
/// mint unbacked tokens or refuse withdrawal. Phase 2 wires trustless settlement
|
||||||
|
/// (Across/Hyperlane) when funds available for sister-chain deploys.
|
||||||
|
contract AereUSDC is ERC20, AccessControl {
|
||||||
|
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
|
||||||
|
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
|
||||||
|
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
|
||||||
|
|
||||||
|
bool public mintPaused;
|
||||||
|
|
||||||
|
event MintPaused(bool paused);
|
||||||
|
|
||||||
|
error MintingPaused();
|
||||||
|
|
||||||
|
/// @param initialAdmin The address that gets DEFAULT_ADMIN_ROLE at deploy time.
|
||||||
|
/// Typically the deployer, who then grants MINTER to bridge,
|
||||||
|
/// transfers admin to Foundation, and renounces own admin —
|
||||||
|
/// all in the same deploy script.
|
||||||
|
constructor(address initialAdmin) ERC20("Aere-Bridged USDC", "aUSDC") {
|
||||||
|
_grantRole(DEFAULT_ADMIN_ROLE, initialAdmin);
|
||||||
|
_grantRole(PAUSER_ROLE, initialAdmin);
|
||||||
|
}
|
||||||
|
|
||||||
|
function decimals() public pure override returns (uint8) {
|
||||||
|
return 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Mint AereUSDC backed by an attested Ethereum USDC deposit.
|
||||||
|
/// @dev Only callable by the AereBridge contract (MINTER_ROLE).
|
||||||
|
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
|
||||||
|
if (mintPaused) revert MintingPaused();
|
||||||
|
_mint(to, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Burn AereUSDC (for withdrawal back to Ethereum USDC).
|
||||||
|
/// @dev Phase 2 — currently bridge has BURNER_ROLE for symmetry but withdrawal
|
||||||
|
/// processing is manual via Foundation.
|
||||||
|
function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
|
||||||
|
_burn(from, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Emergency pause for new mints. Existing balances are unaffected.
|
||||||
|
function setMintPaused(bool paused) external onlyRole(PAUSER_ROLE) {
|
||||||
|
mintPaused = paused;
|
||||||
|
emit MintPaused(paused);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereStateChannels — single-contract bidirectional payment channels
|
||||||
|
* with HTLC support (Connext/Hop-style)
|
||||||
|
* @notice Two parties (A, B) lock ERC-20 funds into a channel. They
|
||||||
|
* transact off-chain by exchanging EIP-712 signed channel states
|
||||||
|
* {channelId, nonce, balanceA, balanceB, htlcLocked, lockHash, lockTimeout}.
|
||||||
|
* When done, EITHER party can close the channel:
|
||||||
|
* - Cooperative: both sign the latest state, instant settlement.
|
||||||
|
* - Challenge: one party submits the latest signed state and
|
||||||
|
* starts a 24h challenge window. Counterparty can submit a
|
||||||
|
* newer-nonce state to override. After window expires,
|
||||||
|
* anyone can call `finalize` to release funds.
|
||||||
|
*
|
||||||
|
* HTLC payments inside the channel are settled by revealing a
|
||||||
|
* hash preimage on-chain (`settleHtlc`) within the lockTimeout.
|
||||||
|
* If timeout expires unrevealed, the lock returns to the funder.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - DOMAIN_SEPARATOR pinned at deploy
|
||||||
|
* - CHALLENGE_WINDOW immutable at deploy
|
||||||
|
* - No admin, no owner, no upgrade path
|
||||||
|
*
|
||||||
|
* OUT OF SCOPE for V1:
|
||||||
|
* - Multi-hop routing (would need a Lightning-style HTLC graph)
|
||||||
|
* - Watchtowers (off-chain monitoring services)
|
||||||
|
* - Probabilistic micropayments
|
||||||
|
* These belong in Phase 2 contracts that USE this as the
|
||||||
|
* settlement primitive.
|
||||||
|
*
|
||||||
|
* @dev Nonce is monotonic per channel. Challenge with a higher nonce
|
||||||
|
* wins; ties + lower nonces are rejected.
|
||||||
|
*/
|
||||||
|
contract AereStateChannels is ReentrancyGuard {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
/* ------------------------------- immutable ------------------------------- */
|
||||||
|
|
||||||
|
uint64 public immutable CHALLENGE_WINDOW; // seconds
|
||||||
|
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||||
|
bytes32 public constant STATE_TYPEHASH = keccak256(
|
||||||
|
"ChannelState(bytes32 channelId,uint256 nonce,uint256 balanceA,uint256 balanceB,uint256 htlcLockedFromA,uint256 htlcLockedFromB,bytes32 lockHash,uint256 lockTimeout)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/// @notice Safety-valve deadline for an Open channel that is never co-signed
|
||||||
|
/// closed. After this long past `open()`, with the channel still in
|
||||||
|
/// Status.Open (no cooperative close, no challenge), EITHER party may
|
||||||
|
/// call `closeOpenTimeout` to reclaim their ORIGINAL deposit. This
|
||||||
|
/// removes the "counterparty refuses to ever co-sign" freeze — most
|
||||||
|
/// acute in a one-directional channel (depositB == 0), where B stakes
|
||||||
|
/// nothing and griefing A would otherwise be free and permanent.
|
||||||
|
/// Deliberately generous so it can never pre-empt a channel that is
|
||||||
|
/// still being used off-chain; a party owed more than its deposit by a
|
||||||
|
/// later co-signed state simply submits it via `startChallenge` before
|
||||||
|
/// the timeout, which flips the channel out of Status.Open and disables
|
||||||
|
/// this path entirely.
|
||||||
|
uint256 public constant CHANNEL_OPEN_TIMEOUT = 30 days;
|
||||||
|
|
||||||
|
/* --------------------------------- types --------------------------------- */
|
||||||
|
|
||||||
|
enum Status { None, Open, Challenged, Finalised }
|
||||||
|
|
||||||
|
struct Channel {
|
||||||
|
Status status;
|
||||||
|
address partyA;
|
||||||
|
address partyB;
|
||||||
|
address token;
|
||||||
|
uint256 depositA;
|
||||||
|
uint256 depositB;
|
||||||
|
// Latest acknowledged state (post-challenge or cooperative-close).
|
||||||
|
uint256 latestNonce;
|
||||||
|
uint256 latestBalanceA;
|
||||||
|
uint256 latestBalanceB;
|
||||||
|
uint256 latestHtlcLockedFromA;
|
||||||
|
uint256 latestHtlcLockedFromB;
|
||||||
|
bytes32 latestLockHash;
|
||||||
|
uint256 latestLockTimeout;
|
||||||
|
// Challenge window bookkeeping.
|
||||||
|
uint64 challengeStartedAt;
|
||||||
|
// HTLC settlement.
|
||||||
|
bytes32 settledHtlcLockHash; // last revealed preimage's hash
|
||||||
|
bool htlcResolved;
|
||||||
|
// Open-timeout safety valve bookkeeping (appended so the public getter's
|
||||||
|
// existing field ordering is preserved).
|
||||||
|
uint64 openedAt; // block.timestamp at open()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ChannelState {
|
||||||
|
bytes32 channelId;
|
||||||
|
uint256 nonce;
|
||||||
|
uint256 balanceA;
|
||||||
|
uint256 balanceB;
|
||||||
|
uint256 htlcLockedFromA;
|
||||||
|
uint256 htlcLockedFromB;
|
||||||
|
bytes32 lockHash; // keccak256(preimage); 0 = no active HTLC
|
||||||
|
uint256 lockTimeout; // unix seconds; 0 if no HTLC
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- state -------------------------------- */
|
||||||
|
|
||||||
|
mapping(bytes32 => Channel) public channels;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event Opened(bytes32 indexed channelId, address indexed partyA, address indexed partyB, address token, uint256 depositA, uint256 depositB);
|
||||||
|
event CooperativeClosed(bytes32 indexed channelId, uint256 finalBalanceA, uint256 finalBalanceB);
|
||||||
|
event ChallengeStarted(bytes32 indexed channelId, address indexed by, uint256 nonce, uint64 deadline);
|
||||||
|
event ChallengeOverridden(bytes32 indexed channelId, uint256 newNonce);
|
||||||
|
event Finalised(bytes32 indexed channelId, uint256 finalA, uint256 finalB);
|
||||||
|
event HtlcSettled(bytes32 indexed channelId, bytes32 indexed lockHash, address indexed beneficiary);
|
||||||
|
event HtlcExpired(bytes32 indexed channelId, bytes32 indexed lockHash);
|
||||||
|
event Withdrawn(bytes32 indexed channelId, address indexed recipient, uint256 amount);
|
||||||
|
event OpenTimeoutClosed(bytes32 indexed channelId, address indexed by, uint256 refundA, uint256 refundB);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error ZeroAmount();
|
||||||
|
error ChannelExists();
|
||||||
|
error ChannelNotOpen();
|
||||||
|
error ChannelNotChallenged();
|
||||||
|
error ChannelNotFinalised();
|
||||||
|
error NotParticipant();
|
||||||
|
error WrongChannelId();
|
||||||
|
error BadSignature(string which);
|
||||||
|
error NonceNotHigher(uint256 incoming, uint256 latest);
|
||||||
|
error WindowOpen();
|
||||||
|
error WindowExpired();
|
||||||
|
error OpenTimeoutNotReached();
|
||||||
|
error BalancesMismatch(uint256 sum, uint256 deposits);
|
||||||
|
error HtlcAlreadyResolved();
|
||||||
|
error PreimageMismatch();
|
||||||
|
error LockExpired();
|
||||||
|
error LockNotExpired();
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
/* ----------------------------- constructor ------------------------------ */
|
||||||
|
|
||||||
|
constructor(uint64 challengeWindow) {
|
||||||
|
CHALLENGE_WINDOW = challengeWindow;
|
||||||
|
DOMAIN_SEPARATOR = keccak256(abi.encode(
|
||||||
|
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
|
||||||
|
keccak256("AereStateChannels"),
|
||||||
|
keccak256("1"),
|
||||||
|
block.chainid,
|
||||||
|
address(this)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- open --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Opens a channel between (partyA, partyB) with deterministic id.
|
||||||
|
/// BOTH parties' tokens must be `transferFrom`-able to this contract.
|
||||||
|
/// Order of (partyA, partyB) matters for channelId derivation.
|
||||||
|
/// @dev The caller MUST be one of the two channel parties. This blocks a
|
||||||
|
/// third party from using A's (or B's) standing ERC-20 approval to
|
||||||
|
/// force their tokens into a channel they never agreed to — which,
|
||||||
|
/// combined with the every-close-needs-both-signatures rule, could
|
||||||
|
/// otherwise strand those tokens until the open-timeout fallback.
|
||||||
|
function open(address partyA, address partyB, address token, uint256 depositA, uint256 depositB) external nonReentrant returns (bytes32 channelId) {
|
||||||
|
if (partyA == address(0) || partyB == address(0) || token == address(0)) revert ZeroAddress();
|
||||||
|
if (partyA == partyB) revert ZeroAddress();
|
||||||
|
if (msg.sender != partyA && msg.sender != partyB) revert NotParticipant();
|
||||||
|
channelId = keccak256(abi.encode(partyA, partyB, token, block.timestamp, block.number, msg.sender));
|
||||||
|
if (channels[channelId].status != Status.None) revert ChannelExists();
|
||||||
|
if (depositA + depositB == 0) revert ZeroAmount();
|
||||||
|
|
||||||
|
if (depositA > 0 && !IERC20(token).transferFrom(partyA, address(this), depositA)) revert TransferFailed();
|
||||||
|
if (depositB > 0 && !IERC20(token).transferFrom(partyB, address(this), depositB)) revert TransferFailed();
|
||||||
|
|
||||||
|
Channel storage c = channels[channelId];
|
||||||
|
c.status = Status.Open;
|
||||||
|
c.partyA = partyA;
|
||||||
|
c.partyB = partyB;
|
||||||
|
c.token = token;
|
||||||
|
c.depositA = depositA;
|
||||||
|
c.depositB = depositB;
|
||||||
|
// Initial state: balances equal deposits, no HTLC, nonce=0.
|
||||||
|
c.latestBalanceA = depositA;
|
||||||
|
c.latestBalanceB = depositB;
|
||||||
|
c.openedAt = uint64(block.timestamp);
|
||||||
|
|
||||||
|
emit Opened(channelId, partyA, partyB, token, depositA, depositB);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------- cooperative close --------------------------- */
|
||||||
|
|
||||||
|
function cooperativeClose(
|
||||||
|
ChannelState calldata state,
|
||||||
|
bytes calldata sigA,
|
||||||
|
bytes calldata sigB
|
||||||
|
) external nonReentrant {
|
||||||
|
Channel storage c = channels[state.channelId];
|
||||||
|
if (c.status != Status.Open) revert ChannelNotOpen();
|
||||||
|
if (state.channelId == bytes32(0)) revert WrongChannelId();
|
||||||
|
_checkBalances(c, state);
|
||||||
|
bytes32 digest = _hashState(state);
|
||||||
|
if (digest.recover(sigA) != c.partyA) revert BadSignature("A");
|
||||||
|
if (digest.recover(sigB) != c.partyB) revert BadSignature("B");
|
||||||
|
|
||||||
|
c.status = Status.Finalised;
|
||||||
|
c.latestNonce = state.nonce;
|
||||||
|
c.latestBalanceA = state.balanceA + state.htlcLockedFromA + state.htlcLockedFromB; // unlock HTLC to A on coop close
|
||||||
|
c.latestBalanceB = state.balanceB; // simplified — see NOTE below
|
||||||
|
// NOTE on cooperative close: parties agree on final off-chain.
|
||||||
|
// HTLC tokens go back to their funder unless the state already
|
||||||
|
// resolved them (state.lockHash == 0). For real production,
|
||||||
|
// parties typically settle HTLCs before cooperative close.
|
||||||
|
if (state.lockHash != bytes32(0)) {
|
||||||
|
// unresolved HTLC at coop close — refund to funder (whoever
|
||||||
|
// contributed htlcLockedFromX is credited that X amount).
|
||||||
|
c.latestBalanceA = state.balanceA + state.htlcLockedFromA;
|
||||||
|
c.latestBalanceB = state.balanceB + state.htlcLockedFromB;
|
||||||
|
} else {
|
||||||
|
c.latestBalanceA = state.balanceA;
|
||||||
|
c.latestBalanceB = state.balanceB;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit CooperativeClosed(state.channelId, c.latestBalanceA, c.latestBalanceB);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------- open-timeout close -------------------------- */
|
||||||
|
|
||||||
|
/// @notice Safety valve against a non-cooperating counterparty. If a channel
|
||||||
|
/// is still Status.Open CHANNEL_OPEN_TIMEOUT after it was opened —
|
||||||
|
/// meaning NO co-signed state was ever brought on-chain (no
|
||||||
|
/// cooperativeClose, no startChallenge) — EITHER party may finalise
|
||||||
|
/// it here and reclaim their ORIGINAL deposit, then `withdraw`.
|
||||||
|
///
|
||||||
|
/// Without this, every close path requires BOTH signatures, so a
|
||||||
|
/// counterparty who simply never co-signs any closing state can
|
||||||
|
/// permanently freeze the other party's funds (costless in a
|
||||||
|
/// one-directional channel where depositB == 0).
|
||||||
|
///
|
||||||
|
/// @dev SECURITY — this can never override a legitimately-signed newer
|
||||||
|
/// state:
|
||||||
|
/// * It only runs while `status == Status.Open`. The instant any
|
||||||
|
/// co-signed state is submitted, the channel leaves Open
|
||||||
|
/// (cooperativeClose -> Finalised, startChallenge -> Challenged),
|
||||||
|
/// so this function reverts with ChannelNotOpen thereafter.
|
||||||
|
/// * While Open, `latestBalanceA/B` still equal the deposits set in
|
||||||
|
/// `open()` (no on-chain state ever mutated them), so refunding
|
||||||
|
/// the deposits is the only provable allocation.
|
||||||
|
/// * A party owed more than its deposit by a later off-chain state
|
||||||
|
/// has the full CHANNEL_OPEN_TIMEOUT window to enforce it via
|
||||||
|
/// `startChallenge`; doing so moves the channel to Challenged and
|
||||||
|
/// permanently disables this path.
|
||||||
|
function closeOpenTimeout(bytes32 channelId) external nonReentrant {
|
||||||
|
Channel storage c = channels[channelId];
|
||||||
|
if (c.status != Status.Open) revert ChannelNotOpen();
|
||||||
|
if (msg.sender != c.partyA && msg.sender != c.partyB) revert NotParticipant();
|
||||||
|
if (block.timestamp < uint256(c.openedAt) + CHANNEL_OPEN_TIMEOUT) revert OpenTimeoutNotReached();
|
||||||
|
|
||||||
|
// No co-signed state was ever recorded: refund the original deposits.
|
||||||
|
// (latestBalanceA/B already equal depositA/depositB from open(); set
|
||||||
|
// explicitly for clarity and defence in depth.)
|
||||||
|
c.status = Status.Finalised;
|
||||||
|
c.latestBalanceA = c.depositA;
|
||||||
|
c.latestBalanceB = c.depositB;
|
||||||
|
|
||||||
|
emit OpenTimeoutClosed(channelId, msg.sender, c.depositA, c.depositB);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ challenge close -------------------------- */
|
||||||
|
|
||||||
|
/// @notice Submit the latest signed state — starts the challenge window.
|
||||||
|
/// Counterparty has CHALLENGE_WINDOW seconds to submit a higher
|
||||||
|
/// nonce. After window expires, anyone calls finalize.
|
||||||
|
function startChallenge(
|
||||||
|
ChannelState calldata state,
|
||||||
|
bytes calldata sigA,
|
||||||
|
bytes calldata sigB
|
||||||
|
) external nonReentrant {
|
||||||
|
Channel storage c = channels[state.channelId];
|
||||||
|
if (c.status != Status.Open) revert ChannelNotOpen();
|
||||||
|
_checkBalances(c, state);
|
||||||
|
bytes32 digest = _hashState(state);
|
||||||
|
if (digest.recover(sigA) != c.partyA) revert BadSignature("A");
|
||||||
|
if (digest.recover(sigB) != c.partyB) revert BadSignature("B");
|
||||||
|
|
||||||
|
c.status = Status.Challenged;
|
||||||
|
c.latestNonce = state.nonce;
|
||||||
|
c.latestBalanceA = state.balanceA;
|
||||||
|
c.latestBalanceB = state.balanceB;
|
||||||
|
c.latestHtlcLockedFromA = state.htlcLockedFromA;
|
||||||
|
c.latestHtlcLockedFromB = state.htlcLockedFromB;
|
||||||
|
c.latestLockHash = state.lockHash;
|
||||||
|
c.latestLockTimeout = state.lockTimeout;
|
||||||
|
c.challengeStartedAt = uint64(block.timestamp);
|
||||||
|
|
||||||
|
emit ChallengeStarted(state.channelId, msg.sender, state.nonce, uint64(block.timestamp + CHALLENGE_WINDOW));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Override a pending challenge with a higher-nonce state.
|
||||||
|
function overrideChallenge(
|
||||||
|
ChannelState calldata state,
|
||||||
|
bytes calldata sigA,
|
||||||
|
bytes calldata sigB
|
||||||
|
) external nonReentrant {
|
||||||
|
Channel storage c = channels[state.channelId];
|
||||||
|
if (c.status != Status.Challenged) revert ChannelNotChallenged();
|
||||||
|
if (block.timestamp >= uint256(c.challengeStartedAt) + CHALLENGE_WINDOW) revert WindowExpired();
|
||||||
|
if (state.nonce <= c.latestNonce) revert NonceNotHigher(state.nonce, c.latestNonce);
|
||||||
|
_checkBalances(c, state);
|
||||||
|
bytes32 digest = _hashState(state);
|
||||||
|
if (digest.recover(sigA) != c.partyA) revert BadSignature("A");
|
||||||
|
if (digest.recover(sigB) != c.partyB) revert BadSignature("B");
|
||||||
|
|
||||||
|
c.latestNonce = state.nonce;
|
||||||
|
c.latestBalanceA = state.balanceA;
|
||||||
|
c.latestBalanceB = state.balanceB;
|
||||||
|
c.latestHtlcLockedFromA = state.htlcLockedFromA;
|
||||||
|
c.latestHtlcLockedFromB = state.htlcLockedFromB;
|
||||||
|
c.latestLockHash = state.lockHash;
|
||||||
|
c.latestLockTimeout = state.lockTimeout;
|
||||||
|
|
||||||
|
emit ChallengeOverridden(state.channelId, state.nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice After window expires, anyone can finalise. Resolves HTLC:
|
||||||
|
/// if lockHash is set and `settleHtlc` was called within
|
||||||
|
/// lockTimeout, HTLC tokens go to the receiver (partyB if
|
||||||
|
/// funded by A, partyA if funded by B). Otherwise (no
|
||||||
|
/// settle or settle was late), HTLC tokens return to funder.
|
||||||
|
function finalize(bytes32 channelId) external nonReentrant {
|
||||||
|
Channel storage c = channels[channelId];
|
||||||
|
if (c.status != Status.Challenged) revert ChannelNotChallenged();
|
||||||
|
if (block.timestamp < uint256(c.challengeStartedAt) + CHALLENGE_WINDOW) revert WindowOpen();
|
||||||
|
|
||||||
|
// Resolve HTLC.
|
||||||
|
uint256 htlcToA;
|
||||||
|
uint256 htlcToB;
|
||||||
|
if (c.latestLockHash != bytes32(0)) {
|
||||||
|
// ROUND-3 FIX: previously this check also required
|
||||||
|
// `block.timestamp <= latestLockTimeout + CHALLENGE_WINDOW`, which
|
||||||
|
// penalised a receiver who legitimately revealed the preimage
|
||||||
|
// inside lockTimeout (settleHtlc already enforces that) whenever
|
||||||
|
// finalize was called late. settleHtlc is the authoritative
|
||||||
|
// timeliness gate; finalize must honour its result regardless of
|
||||||
|
// when finalize itself runs.
|
||||||
|
bool settled = c.htlcResolved && c.settledHtlcLockHash == c.latestLockHash;
|
||||||
|
if (settled) {
|
||||||
|
// Funder loses, receiver gains. Convention: A funds → B
|
||||||
|
// gets, B funds → A gets.
|
||||||
|
htlcToB += c.latestHtlcLockedFromA;
|
||||||
|
htlcToA += c.latestHtlcLockedFromB;
|
||||||
|
} else {
|
||||||
|
// Refund to funder.
|
||||||
|
htlcToA += c.latestHtlcLockedFromA;
|
||||||
|
htlcToB += c.latestHtlcLockedFromB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.status = Status.Finalised;
|
||||||
|
c.latestBalanceA += htlcToA;
|
||||||
|
c.latestBalanceB += htlcToB;
|
||||||
|
|
||||||
|
emit Finalised(channelId, c.latestBalanceA, c.latestBalanceB);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- HTLC ----------------------------- */
|
||||||
|
|
||||||
|
/// @notice Anyone with the preimage can settle an HTLC during the
|
||||||
|
/// challenge window. Records on-chain that the lock was opened.
|
||||||
|
function settleHtlc(bytes32 channelId, bytes calldata preimage) external {
|
||||||
|
Channel storage c = channels[channelId];
|
||||||
|
if (c.status != Status.Challenged) revert ChannelNotChallenged();
|
||||||
|
if (c.htlcResolved) revert HtlcAlreadyResolved();
|
||||||
|
if (block.timestamp > c.latestLockTimeout) revert LockExpired();
|
||||||
|
bytes32 hash = keccak256(preimage);
|
||||||
|
if (hash != c.latestLockHash) revert PreimageMismatch();
|
||||||
|
c.htlcResolved = true;
|
||||||
|
c.settledHtlcLockHash = hash;
|
||||||
|
emit HtlcSettled(channelId, hash, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ withdraw -------------------------------- */
|
||||||
|
|
||||||
|
function withdraw(bytes32 channelId) external nonReentrant {
|
||||||
|
Channel storage c = channels[channelId];
|
||||||
|
if (c.status != Status.Finalised) revert ChannelNotFinalised();
|
||||||
|
if (msg.sender != c.partyA && msg.sender != c.partyB) revert NotParticipant();
|
||||||
|
uint256 amount;
|
||||||
|
if (msg.sender == c.partyA) {
|
||||||
|
amount = c.latestBalanceA;
|
||||||
|
c.latestBalanceA = 0;
|
||||||
|
} else {
|
||||||
|
amount = c.latestBalanceB;
|
||||||
|
c.latestBalanceB = 0;
|
||||||
|
}
|
||||||
|
if (amount == 0) return;
|
||||||
|
if (!IERC20(c.token).transfer(msg.sender, amount)) revert TransferFailed();
|
||||||
|
emit Withdrawn(channelId, msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- internal ------------------------------- */
|
||||||
|
|
||||||
|
function _hashState(ChannelState calldata s) internal view returns (bytes32) {
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
STATE_TYPEHASH, s.channelId, s.nonce, s.balanceA, s.balanceB,
|
||||||
|
s.htlcLockedFromA, s.htlcLockedFromB, s.lockHash, s.lockTimeout
|
||||||
|
));
|
||||||
|
return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
}
|
||||||
|
|
||||||
|
function _checkBalances(Channel storage c, ChannelState calldata s) internal view {
|
||||||
|
uint256 total = s.balanceA + s.balanceB + s.htlcLockedFromA + s.htlcLockedFromB;
|
||||||
|
uint256 deposits = c.depositA + c.depositB;
|
||||||
|
if (total != deposits) revert BalancesMismatch(total, deposits);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAIProof — anchors signed (model, input, output) triples for
|
||||||
|
* AI inference / generation provenance
|
||||||
|
* @notice AI providers register a `modelId` with a signing key. For each
|
||||||
|
* inference / generation request they expose, the provider commits
|
||||||
|
* an EIP-712 signed statement:
|
||||||
|
* {modelId, inputHash, outputHash, timestamp, requesterHash}
|
||||||
|
* where requesterHash is keccak256(abi.encode(requester, nonce)).
|
||||||
|
*
|
||||||
|
* Use cases:
|
||||||
|
* - Agentic transactions (AERE402 caller proves the LLM output
|
||||||
|
* it acted on came from a specific signed model)
|
||||||
|
* - Tamper-evident audit logs for regulated AI deployments
|
||||||
|
* - Cross-tenant accountability without revealing raw I/O
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - Provider's signer key is rotatable (via setSigner) but the
|
||||||
|
* modelId itself is permanent once registered
|
||||||
|
* - Anchored attestations are append-only — never editable
|
||||||
|
*
|
||||||
|
* PRIVACY:
|
||||||
|
* - inputHash + outputHash + requesterHash are all hashes
|
||||||
|
* - The on-chain record never sees raw prompts or completions
|
||||||
|
*
|
||||||
|
* @dev EIP-712 domain pinned at deploy. Signatures are verified by
|
||||||
|
* ECDSA.recover against the provider's currently-registered signer.
|
||||||
|
*/
|
||||||
|
contract AereAIProof {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
/* --------------------------------- types --------------------------------- */
|
||||||
|
|
||||||
|
struct Model {
|
||||||
|
bool registered;
|
||||||
|
address signer;
|
||||||
|
address operator; // can rotate signer
|
||||||
|
string description; // human-readable identifier
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Attestation {
|
||||||
|
bytes32 modelId;
|
||||||
|
bytes32 inputHash;
|
||||||
|
bytes32 outputHash;
|
||||||
|
bytes32 requesterHash;
|
||||||
|
uint256 timestamp;
|
||||||
|
uint256 nonce; // per-modelId monotonic
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- immutable ------------------------------- */
|
||||||
|
|
||||||
|
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||||
|
bytes32 public constant ATTESTATION_TYPEHASH = keccak256(
|
||||||
|
"Attestation(bytes32 modelId,bytes32 inputHash,bytes32 outputHash,bytes32 requesterHash,uint256 timestamp,uint256 nonce)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- state -------------------------------- */
|
||||||
|
|
||||||
|
mapping(bytes32 => Model) public models;
|
||||||
|
mapping(bytes32 => mapping(uint256 => bool)) public usedNonce; // modelId → nonce → consumed
|
||||||
|
mapping(bytes32 => uint256) public attestationCount; // modelId → total anchored
|
||||||
|
/// @notice M3 fix: nonces below this watermark are inadmissible — set
|
||||||
|
/// to the highest used nonce + 1 on every signer rotation so
|
||||||
|
/// the new signer cannot re-use nonces issued under the old
|
||||||
|
/// signer's context, polluting provenance history.
|
||||||
|
mapping(bytes32 => uint256) public minValidNonce;
|
||||||
|
mapping(bytes32 => uint256) public highestNonceSeen;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event ModelRegistered(bytes32 indexed modelId, address indexed operator, address indexed signer, string description);
|
||||||
|
event SignerRotated(bytes32 indexed modelId, address indexed newSigner);
|
||||||
|
event Anchored(
|
||||||
|
bytes32 indexed modelId,
|
||||||
|
bytes32 indexed inputHash,
|
||||||
|
bytes32 indexed outputHash,
|
||||||
|
bytes32 requesterHash,
|
||||||
|
uint256 timestamp,
|
||||||
|
uint256 nonce
|
||||||
|
);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error ModelExists();
|
||||||
|
error UnknownModel();
|
||||||
|
error NotOperator();
|
||||||
|
error BadSignature();
|
||||||
|
error NonceConsumed();
|
||||||
|
error NonceBelowWatermark(uint256 got, uint256 minValid);
|
||||||
|
error AttestationInFuture();
|
||||||
|
error ZeroAddress();
|
||||||
|
|
||||||
|
/* ----------------------------- constructor ------------------------------ */
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
DOMAIN_SEPARATOR = keccak256(abi.encode(
|
||||||
|
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
|
||||||
|
keccak256("AereAIProof"),
|
||||||
|
keccak256("1"),
|
||||||
|
block.chainid,
|
||||||
|
address(this)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ registration ---------------------------- */
|
||||||
|
|
||||||
|
function registerModel(bytes32 modelId, address signer, string calldata description) external {
|
||||||
|
if (modelId == bytes32(0)) revert ZeroAddress();
|
||||||
|
if (signer == address(0)) revert ZeroAddress();
|
||||||
|
if (models[modelId].registered) revert ModelExists();
|
||||||
|
models[modelId] = Model({
|
||||||
|
registered: true,
|
||||||
|
signer: signer,
|
||||||
|
operator: msg.sender,
|
||||||
|
description: description
|
||||||
|
});
|
||||||
|
emit ModelRegistered(modelId, msg.sender, signer, description);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSigner(bytes32 modelId, address newSigner) external {
|
||||||
|
Model storage m = models[modelId];
|
||||||
|
if (!m.registered) revert UnknownModel();
|
||||||
|
if (msg.sender != m.operator) revert NotOperator();
|
||||||
|
if (newSigner == address(0)) revert ZeroAddress();
|
||||||
|
m.signer = newSigner;
|
||||||
|
// M3 fix: invalidate any nonces below this point so new signer
|
||||||
|
// cannot reuse the old signer's nonce space.
|
||||||
|
minValidNonce[modelId] = highestNonceSeen[modelId] + 1;
|
||||||
|
emit SignerRotated(modelId, newSigner);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- anchor --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Submit a provider-signed attestation. Anyone can submit
|
||||||
|
/// (the provider, the requester, an indexer). The signature
|
||||||
|
/// must come from the model's CURRENT signer.
|
||||||
|
function anchor(
|
||||||
|
bytes32 modelId,
|
||||||
|
bytes32 inputHash,
|
||||||
|
bytes32 outputHash,
|
||||||
|
bytes32 requesterHash,
|
||||||
|
uint256 timestamp,
|
||||||
|
uint256 nonce,
|
||||||
|
bytes calldata signature
|
||||||
|
) external {
|
||||||
|
Model memory m = models[modelId];
|
||||||
|
if (!m.registered) revert UnknownModel();
|
||||||
|
if (timestamp > block.timestamp) revert AttestationInFuture();
|
||||||
|
if (usedNonce[modelId][nonce]) revert NonceConsumed();
|
||||||
|
// M3 fix: post-rotation, old nonce space is gone.
|
||||||
|
if (nonce < minValidNonce[modelId]) revert NonceBelowWatermark(nonce, minValidNonce[modelId]);
|
||||||
|
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
ATTESTATION_TYPEHASH,
|
||||||
|
modelId, inputHash, outputHash, requesterHash, timestamp, nonce
|
||||||
|
));
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
address recovered = digest.recover(signature);
|
||||||
|
if (recovered == address(0) || recovered != m.signer) revert BadSignature();
|
||||||
|
|
||||||
|
usedNonce[modelId][nonce] = true;
|
||||||
|
if (nonce > highestNonceSeen[modelId]) highestNonceSeen[modelId] = nonce;
|
||||||
|
attestationCount[modelId] += 1;
|
||||||
|
|
||||||
|
emit Anchored(modelId, inputHash, outputHash, requesterHash, timestamp, nonce);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAttestationGateway — unified registry for regulator attestations
|
||||||
|
* @notice The compliance landscape splits the same primitive — "this entity
|
||||||
|
* has been assessed by an authorised body" — into incompatible silos:
|
||||||
|
*
|
||||||
|
* - MiCA Title II/V: CASP licence + best-execution conformity
|
||||||
|
* - EU AI Act Annex III: high-risk AI conformity
|
||||||
|
* - SEC 1099-DA: broker reporting compliance
|
||||||
|
* - FCA CP24/x: UK consumer-duty conformity
|
||||||
|
* - FINMA / MAS: equivalents in CH / SG
|
||||||
|
*
|
||||||
|
* AereAttestationGateway gives those bodies (and the protocols
|
||||||
|
* that need to RELY on their judgement) a single on-chain shape.
|
||||||
|
*
|
||||||
|
* MODEL:
|
||||||
|
*
|
||||||
|
* 1. The Foundation publishes a SCHEMA when a new attestation
|
||||||
|
* shape is needed. Each schema has an id (e.g. keccak256
|
||||||
|
* ("mica-casp-v1") ), an immutable hash of the off-chain
|
||||||
|
* human-readable spec, and a semver pin. Schemas are
|
||||||
|
* append-only — fixing typos requires a new schemaId.
|
||||||
|
*
|
||||||
|
* 2. Per-schema, the Foundation registers AUTHORISED ATTESTORS
|
||||||
|
* — addresses that this schema accepts as valid issuers.
|
||||||
|
* The Foundation is one such attestor for some schemas; for
|
||||||
|
* others (MiCA-Art-78 conformity, say) the only valid
|
||||||
|
* attestor is the customer's own NCA-registered auditor.
|
||||||
|
*
|
||||||
|
* 3. An attestor issues an attestation. The payload itself
|
||||||
|
* lives off-chain (ipfs:// or https://, the full PDF / JSON
|
||||||
|
* spec); the chain stores ONLY the hash + validity window
|
||||||
|
* + the schema/subject/attestor triple. No PII.
|
||||||
|
*
|
||||||
|
* 4. Revocation: the issuing attestor can revoke at any time.
|
||||||
|
* Reads return `isValidNow(...) == false` immediately. A
|
||||||
|
* revoked attestation cannot be un-revoked (the attestor
|
||||||
|
* would issue a fresh one). The previous attestation's
|
||||||
|
* revocation is preserved in event history forever.
|
||||||
|
*
|
||||||
|
* 5. INHERITANCE (optional): an attestation can reference a
|
||||||
|
* parent attestation id. The validity check chases the
|
||||||
|
* chain: if any ancestor is revoked or expired, the child
|
||||||
|
* fails. Useful for "this provider is allowed to issue
|
||||||
|
* best-execution receipts BECAUSE Foundation has attested
|
||||||
|
* their MiCA licence." Cycle protection via depth bound.
|
||||||
|
*
|
||||||
|
* WHY NOT EAS?
|
||||||
|
* Ethereum Attestation Service does generic on-chain
|
||||||
|
* attestations beautifully. This contract is intentionally
|
||||||
|
* narrower: it bakes in inheritance + per-schema attestor
|
||||||
|
* gating + a Foundation-published schema registry. Consumers
|
||||||
|
* that need richer features can adopt EAS in parallel.
|
||||||
|
*
|
||||||
|
* GAS:
|
||||||
|
* attest() ~70-80k cold-path (1 SSTORE for the main record,
|
||||||
|
* 1 for the per-(subject,schema) head pointer).
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - FOUNDATION immutable.
|
||||||
|
* - Schemas append-only; cannot be edited or removed.
|
||||||
|
* - Attestor authorisation flags can be toggled OFF but never
|
||||||
|
* retroactively invalidate past attestations the attestor
|
||||||
|
* issued while authorised.
|
||||||
|
* - MAX_INHERITANCE_DEPTH constant.
|
||||||
|
*/
|
||||||
|
contract AereAttestationGateway {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
address public immutable FOUNDATION;
|
||||||
|
uint256 public constant MAX_INHERITANCE_DEPTH = 8;
|
||||||
|
|
||||||
|
/* ================================= types ================================= */
|
||||||
|
|
||||||
|
struct Schema {
|
||||||
|
bytes32 specHash; // SHA256 of the off-chain human-readable spec
|
||||||
|
string name; // e.g. "mica-casp-v1"
|
||||||
|
string semver; // e.g. "1.0.0"
|
||||||
|
string specUri; // ipfs:// or https:// — full spec doc
|
||||||
|
uint64 publishedAt;
|
||||||
|
bool exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Attestation {
|
||||||
|
bytes32 schemaId;
|
||||||
|
bytes32 subject; // keccak256 of the subject identifier
|
||||||
|
address attestor;
|
||||||
|
bytes32 parentId; // 0x0 if no parent
|
||||||
|
bytes32 payloadHash; // SHA256 of the off-chain payload
|
||||||
|
string payloadUri;
|
||||||
|
uint64 validFrom;
|
||||||
|
uint64 validUntil; // 0 = no expiry
|
||||||
|
bool revoked;
|
||||||
|
bool exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ storage ================================ */
|
||||||
|
|
||||||
|
/// @notice schemaId → Schema metadata. Append-only.
|
||||||
|
mapping(bytes32 => Schema) public schemas;
|
||||||
|
|
||||||
|
/// @notice schemaId → attestor → authorised flag. Toggleable.
|
||||||
|
mapping(bytes32 => mapping(address => bool)) public isAuthorisedAttestor;
|
||||||
|
|
||||||
|
/// @notice attestor → next nonce (used to derive attestationId).
|
||||||
|
mapping(address => uint256) public attestorNonce;
|
||||||
|
|
||||||
|
/// @notice attestationId → Attestation. Append-only except for `revoked`.
|
||||||
|
mapping(bytes32 => Attestation) internal _attestations;
|
||||||
|
|
||||||
|
/// @notice (subject, schemaId) → most-recent attestationId for that pair.
|
||||||
|
/// Convenience for consumers that just want "is this subject
|
||||||
|
/// currently attested under this schema?"
|
||||||
|
/// AUDIT FIX (HIGH #24): only updated when prior is invalid OR new
|
||||||
|
/// passes _isValid at write-time. Prevents griefing where attestor B
|
||||||
|
/// posts an already-expired record that wipes attestor A's valid one.
|
||||||
|
mapping(bytes32 => mapping(bytes32 => bytes32)) public latestFor;
|
||||||
|
/// @notice (subject, schemaId, attestor) → that attestor's most-recent
|
||||||
|
/// attestation id for that subject. Consumers reading per-attestor
|
||||||
|
/// data go through this map.
|
||||||
|
mapping(bytes32 => mapping(bytes32 => mapping(address => bytes32))) public latestForBy;
|
||||||
|
|
||||||
|
/* ================================ events ================================ */
|
||||||
|
|
||||||
|
event SchemaPublished(bytes32 indexed schemaId, bytes32 specHash, string name, string semver, string specUri);
|
||||||
|
event AttestorAuthorisation(bytes32 indexed schemaId, address indexed attestor, bool authorised);
|
||||||
|
event Attested(
|
||||||
|
bytes32 indexed attestationId,
|
||||||
|
bytes32 indexed schemaId,
|
||||||
|
bytes32 indexed subject,
|
||||||
|
address attestor,
|
||||||
|
bytes32 parentId,
|
||||||
|
bytes32 payloadHash,
|
||||||
|
uint64 validFrom,
|
||||||
|
uint64 validUntil,
|
||||||
|
string payloadUri
|
||||||
|
);
|
||||||
|
event Revoked(bytes32 indexed attestationId, address indexed attestor);
|
||||||
|
|
||||||
|
/* ================================ errors ================================ */
|
||||||
|
|
||||||
|
error NotFoundation();
|
||||||
|
error SchemaExists();
|
||||||
|
error SchemaUnknown();
|
||||||
|
error EmptySpec();
|
||||||
|
error NotAuthorisedAttestor();
|
||||||
|
error AttestationExists();
|
||||||
|
error AttestationUnknown();
|
||||||
|
error AlreadyRevoked();
|
||||||
|
error NotIssuer();
|
||||||
|
error BadValidityWindow();
|
||||||
|
error InheritanceDepthExceeded();
|
||||||
|
error ParentInvalid();
|
||||||
|
error ParentSubjectMismatch();
|
||||||
|
|
||||||
|
/* =============================== modifiers ============================== */
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert NotFoundation();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== constructor ============================= */
|
||||||
|
|
||||||
|
constructor(address foundation) {
|
||||||
|
require(foundation != address(0), "zero-foundation");
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== schema ops ============================== */
|
||||||
|
|
||||||
|
function publishSchema(
|
||||||
|
bytes32 schemaId,
|
||||||
|
bytes32 specHash,
|
||||||
|
string calldata name,
|
||||||
|
string calldata semver,
|
||||||
|
string calldata specUri
|
||||||
|
) external onlyFoundation {
|
||||||
|
if (specHash == bytes32(0)) revert EmptySpec();
|
||||||
|
if (schemas[schemaId].exists) revert SchemaExists();
|
||||||
|
schemas[schemaId] = Schema({
|
||||||
|
specHash: specHash,
|
||||||
|
name: name,
|
||||||
|
semver: semver,
|
||||||
|
specUri: specUri,
|
||||||
|
publishedAt: uint64(block.timestamp),
|
||||||
|
exists: true
|
||||||
|
});
|
||||||
|
emit SchemaPublished(schemaId, specHash, name, semver, specUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAttestor(bytes32 schemaId, address attestor, bool authorised) external onlyFoundation {
|
||||||
|
if (!schemas[schemaId].exists) revert SchemaUnknown();
|
||||||
|
isAuthorisedAttestor[schemaId][attestor] = authorised;
|
||||||
|
emit AttestorAuthorisation(schemaId, attestor, authorised);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== attest path ============================= */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Issue an attestation. msg.sender MUST be authorised for the
|
||||||
|
* schema. The attestationId is keccak256(attestor, nonce++).
|
||||||
|
* @return attestationId The deterministic id.
|
||||||
|
*/
|
||||||
|
function attest(
|
||||||
|
bytes32 schemaId,
|
||||||
|
bytes32 subject,
|
||||||
|
bytes32 parentId,
|
||||||
|
bytes32 payloadHash,
|
||||||
|
uint64 validFrom,
|
||||||
|
uint64 validUntil,
|
||||||
|
string calldata payloadUri
|
||||||
|
) external returns (bytes32 attestationId) {
|
||||||
|
if (!schemas[schemaId].exists) revert SchemaUnknown();
|
||||||
|
if (!isAuthorisedAttestor[schemaId][msg.sender]) revert NotAuthorisedAttestor();
|
||||||
|
if (validUntil != 0 && validUntil < validFrom) revert BadValidityWindow();
|
||||||
|
|
||||||
|
// If a parent is supplied, sanity-check inheritance depth + existence
|
||||||
|
// BEFORE writing the new record. The chase is shallow (≤ MAX_DEPTH).
|
||||||
|
if (parentId != bytes32(0)) {
|
||||||
|
Attestation storage parent = _attestations[parentId];
|
||||||
|
if (!parent.exists) revert ParentInvalid();
|
||||||
|
// AUDIT FIX (HIGH #23): parent must attest the SAME subject. Without
|
||||||
|
// this, low-bar attestors could chain inheritance to high-bar parents
|
||||||
|
// of unrelated subjects, fabricating transitive trust.
|
||||||
|
if (parent.subject != subject) revert ParentSubjectMismatch();
|
||||||
|
_checkInheritanceDepth(parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint256 nonce = attestorNonce[msg.sender]++;
|
||||||
|
attestationId = keccak256(abi.encode(msg.sender, nonce));
|
||||||
|
if (_attestations[attestationId].exists) revert AttestationExists();
|
||||||
|
|
||||||
|
_attestations[attestationId] = Attestation({
|
||||||
|
schemaId: schemaId,
|
||||||
|
subject: subject,
|
||||||
|
attestor: msg.sender,
|
||||||
|
parentId: parentId,
|
||||||
|
payloadHash: payloadHash,
|
||||||
|
payloadUri: payloadUri,
|
||||||
|
validFrom: validFrom,
|
||||||
|
validUntil: validUntil,
|
||||||
|
revoked: false,
|
||||||
|
exists: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Per-attestor latest pointer always updates (consumer chooses
|
||||||
|
// which attestor to read).
|
||||||
|
latestForBy[subject][schemaId][msg.sender] = attestationId;
|
||||||
|
// AUDIT FIX (HIGH #24): only overwrite the schema-wide latestFor
|
||||||
|
// when the prior is invalid (revoked/expired/missing) OR the new
|
||||||
|
// attestation is itself currently valid.
|
||||||
|
bytes32 prior = latestFor[subject][schemaId];
|
||||||
|
bool priorValid = prior != bytes32(0) && _isValid(prior, block.timestamp, 0);
|
||||||
|
bool newValidNow = (validFrom <= block.timestamp) && (validUntil == 0 || validUntil >= block.timestamp);
|
||||||
|
if (!priorValid || newValidNow) {
|
||||||
|
latestFor[subject][schemaId] = attestationId;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit Attested(attestationId, schemaId, subject, msg.sender, parentId, payloadHash, validFrom, validUntil, payloadUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
function revoke(bytes32 attestationId) external {
|
||||||
|
Attestation storage a = _attestations[attestationId];
|
||||||
|
if (!a.exists) revert AttestationUnknown();
|
||||||
|
if (a.attestor != msg.sender) revert NotIssuer();
|
||||||
|
if (a.revoked) revert AlreadyRevoked();
|
||||||
|
a.revoked = true;
|
||||||
|
emit Revoked(attestationId, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ views ================================= */
|
||||||
|
|
||||||
|
/// @notice Full attestation record (struct memory copy).
|
||||||
|
function attestationOf(bytes32 attestationId) external view returns (Attestation memory) {
|
||||||
|
return _attestations[attestationId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The "is this attestation good RIGHT NOW" check.
|
||||||
|
/// Returns false if:
|
||||||
|
/// - the attestation doesn't exist
|
||||||
|
/// - it's revoked
|
||||||
|
/// - block.timestamp is outside [validFrom, validUntil]
|
||||||
|
/// - any ancestor (within MAX depth) fails the same check
|
||||||
|
function isValidNow(bytes32 attestationId) external view returns (bool) {
|
||||||
|
return _isValid(attestationId, block.timestamp, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _isValid(bytes32 id, uint256 nowTs, uint256 depth) internal view returns (bool) {
|
||||||
|
if (depth >= MAX_INHERITANCE_DEPTH) return false;
|
||||||
|
Attestation storage a = _attestations[id];
|
||||||
|
if (!a.exists || a.revoked) return false;
|
||||||
|
if (nowTs < a.validFrom) return false;
|
||||||
|
if (a.validUntil != 0 && nowTs > a.validUntil) return false;
|
||||||
|
if (a.parentId == bytes32(0)) return true;
|
||||||
|
return _isValid(a.parentId, nowTs, depth + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience: subject is currently attested under schema by
|
||||||
|
/// the LATEST issued attestation for that (subject, schema).
|
||||||
|
function subjectCurrentlyAttested(bytes32 subject, bytes32 schemaId) external view returns (bool) {
|
||||||
|
bytes32 id = latestFor[subject][schemaId];
|
||||||
|
if (id == bytes32(0)) return false;
|
||||||
|
return _isValid(id, block.timestamp, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Validates that walking up from parent doesn't exceed MAX_DEPTH.
|
||||||
|
function _checkInheritanceDepth(bytes32 parentId) internal view {
|
||||||
|
uint256 depth = 1;
|
||||||
|
bytes32 cur = parentId;
|
||||||
|
while (cur != bytes32(0)) {
|
||||||
|
if (depth >= MAX_INHERITANCE_DEPTH) revert InheritanceDepthExceeded();
|
||||||
|
Attestation storage a = _attestations[cur];
|
||||||
|
if (!a.exists) revert ParentInvalid();
|
||||||
|
cur = a.parentId;
|
||||||
|
unchecked { depth++; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/// @dev Matches Succinct's canonical SP1 verifier / SP1VerifierGateway ABI: verifyProof RETURNS
|
||||||
|
/// NOTHING and REVERTS on an invalid proof. Used here as the (future) NON-REVOCATION proof
|
||||||
|
/// verifier. See AereZKScreen.sol for the same pattern already used in Aere's compliance stack.
|
||||||
|
interface INonRevocationVerifier {
|
||||||
|
function verifyProof(bytes32 programVKey, bytes calldata publicValues, bytes calldata proof) external view;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereBitstringStatusList, a W3C Bitstring Status List for credential revocation / suspension
|
||||||
|
*
|
||||||
|
* @notice An on-chain implementation of the W3C Bitstring Status List v1.0 mechanism. A status list
|
||||||
|
* is a compact bitset; every credential is assigned a status INDEX into a list, and the bit
|
||||||
|
* at that index encodes the credential's status (default 0 = active; 1 = revoked or
|
||||||
|
* suspended, per the list's purpose). Revoking a credential flips one bit. Because a single
|
||||||
|
* list packs many credentials, a verifier learns only "the bit at index i", which gives herd
|
||||||
|
* privacy: it cannot tell WHICH credential a status update concerns from the list alone.
|
||||||
|
*
|
||||||
|
* PURPOSES. A list is created for exactly one W3C statusPurpose:
|
||||||
|
* - Revocation: a status change is PERMANENT. Once a bit is set it can never be cleared
|
||||||
|
* (monotonic), matching revocation's terminal semantics.
|
||||||
|
* - Suspension: a status change is REVERSIBLE. A bit may be set and later cleared.
|
||||||
|
*
|
||||||
|
* ZERO-KNOWLEDGE NON-REVOCATION (see the zk section below). The plain on-chain read
|
||||||
|
* statusOf(listId, index) is public and reveals the queried index. For privacy-preserving
|
||||||
|
* verification, a holder can instead prove in zero knowledge that "the status bit of the
|
||||||
|
* credential I hold is 0" WITHOUT revealing which index it is, binding the proof to the list's
|
||||||
|
* current committed state. This file defines that verifier interface and the exact
|
||||||
|
* public-input shape; the SP1 circuit that produces such a proof is [MEASURE] (to be
|
||||||
|
* implemented against Aere's existing SP1 zk stack, the same stack behind AereZKScreen).
|
||||||
|
*
|
||||||
|
* @dev HONEST SCOPE. Application-layer compliance tooling. Holds no funds; changes nothing about
|
||||||
|
* Aere consensus (classical secp256k1 ECDSA QBFT). No PII on chain: a status list is an
|
||||||
|
* anonymous bitset keyed by numeric index only.
|
||||||
|
*/
|
||||||
|
contract AereBitstringStatusList {
|
||||||
|
/// @notice W3C statusPurpose for a list.
|
||||||
|
enum Purpose {
|
||||||
|
Revocation,
|
||||||
|
Suspension
|
||||||
|
}
|
||||||
|
|
||||||
|
struct List {
|
||||||
|
address controller; // the party (typically the issuer) that owns this list's bits
|
||||||
|
Purpose purpose;
|
||||||
|
uint256 capacity; // number of status entries (bits) in the list
|
||||||
|
uint64 createdAt;
|
||||||
|
uint64 epoch; // increments on every bit mutation (monotonic version counter)
|
||||||
|
uint64 lastMutatedAt;
|
||||||
|
bytes32 publishedRoot; // controller-attested commitment to the CURRENT bitstring [MEASURE]
|
||||||
|
uint64 rootEpoch; // the epoch publishedRoot was published at (freshness anchor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// listId is the index into _lists.
|
||||||
|
List[] private _lists;
|
||||||
|
// listId => wordIndex => 256-bit packed status word (bit j of word w is entry w*256 + j).
|
||||||
|
mapping(uint256 => mapping(uint256 => uint256)) private _words;
|
||||||
|
|
||||||
|
// ---- zero-knowledge non-revocation program (network-level config) ----
|
||||||
|
|
||||||
|
/// @notice The admin allowed to publish the non-revocation program vkey (the deployer). This is
|
||||||
|
/// intentionally NOT the per-list controller: the circuit is a network artifact.
|
||||||
|
address public immutable ADMIN;
|
||||||
|
|
||||||
|
/// @notice The SP1 verifier (SP1VerifierGateway) that checks a non-revocation proof. May be the
|
||||||
|
/// zero address at deploy, in which case the zk non-revocation path is fail-closed off
|
||||||
|
/// until configured. Immutable once set at construction.
|
||||||
|
INonRevocationVerifier public immutable NON_REVOCATION_VERIFIER;
|
||||||
|
|
||||||
|
/// @notice The SP1 program verification key for the non-revocation circuit. Zero until the
|
||||||
|
/// circuit is built and its vkey published. [MEASURE]: the circuit itself is pending.
|
||||||
|
bytes32 public nonRevocationVKey;
|
||||||
|
|
||||||
|
event ListCreated(uint256 indexed listId, address indexed controller, Purpose purpose, uint256 capacity);
|
||||||
|
event StatusSet(uint256 indexed listId, uint256 indexed index, bool value, uint64 epoch);
|
||||||
|
event StatusRootPublished(uint256 indexed listId, bytes32 root, uint64 epoch);
|
||||||
|
event NonRevocationVKeySet(bytes32 oldVKey, bytes32 newVKey);
|
||||||
|
|
||||||
|
error NotAdmin();
|
||||||
|
error NotController(uint256 listId);
|
||||||
|
error UnknownList(uint256 listId);
|
||||||
|
error ZeroCapacity();
|
||||||
|
error IndexOutOfRange(uint256 listId, uint256 index);
|
||||||
|
error RevocationIsTerminal(uint256 listId, uint256 index); // cannot clear a revocation bit
|
||||||
|
error NoStatusChange(uint256 listId, uint256 index); // the bit already holds `value`
|
||||||
|
error NonRevocationNotConfigured();
|
||||||
|
error VerifierHasNoCode();
|
||||||
|
|
||||||
|
constructor(address nonRevocationVerifier_) {
|
||||||
|
ADMIN = msg.sender;
|
||||||
|
// A non-zero but CODE-LESS verifier would make the try/verifyProof in verifyNonRevocation
|
||||||
|
// succeed silently (verifyProof returns no data), so a revoked credential would prove "not
|
||||||
|
// revoked" = fail-open. Guard it exactly as the sibling AereFinalityCertificateVerifier does.
|
||||||
|
// The zero address is still allowed: it keeps the zk non-revocation path fail-closed OFF until
|
||||||
|
// a real gateway is configured (nonRevocationConfigured() stays false).
|
||||||
|
if (nonRevocationVerifier_ != address(0) && nonRevocationVerifier_.code.length == 0) {
|
||||||
|
revert VerifierHasNoCode();
|
||||||
|
}
|
||||||
|
NON_REVOCATION_VERIFIER = INonRevocationVerifier(nonRevocationVerifier_); // zero allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Lists
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Create a status list for a single W3C statusPurpose. msg.sender becomes its controller
|
||||||
|
/// (typically the credential issuer). Returns the new listId.
|
||||||
|
/// @param purpose Revocation (terminal bits) or Suspension (reversible bits).
|
||||||
|
/// @param capacity the number of status entries (bits) the list holds. [VERIFY] W3C recommends a
|
||||||
|
/// large minimum (e.g. 131072) for herd privacy; that is a deployment policy
|
||||||
|
/// choice and is NOT enforced here.
|
||||||
|
function createList(Purpose purpose, uint256 capacity) external returns (uint256 listId) {
|
||||||
|
if (capacity == 0) revert ZeroCapacity();
|
||||||
|
listId = _lists.length;
|
||||||
|
_lists.push(
|
||||||
|
List({
|
||||||
|
controller: msg.sender,
|
||||||
|
purpose: purpose,
|
||||||
|
capacity: capacity,
|
||||||
|
createdAt: uint64(block.timestamp),
|
||||||
|
epoch: 0,
|
||||||
|
lastMutatedAt: uint64(block.timestamp),
|
||||||
|
publishedRoot: bytes32(0),
|
||||||
|
rootEpoch: 0
|
||||||
|
})
|
||||||
|
);
|
||||||
|
emit ListCreated(listId, msg.sender, purpose, capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Set the status bit of a credential index. Controller-only.
|
||||||
|
/// Revocation lists: `value` must be true and the bit must currently be 0 (monotonic,
|
||||||
|
/// terminal). Suspension lists: `value` may be true or false (reversible). Reverts if the
|
||||||
|
/// bit already equals `value` (no silent no-op).
|
||||||
|
function setStatus(uint256 listId, uint256 index, bool value) public {
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
if (msg.sender != l.controller) revert NotController(listId);
|
||||||
|
if (index >= l.capacity) revert IndexOutOfRange(listId, index);
|
||||||
|
|
||||||
|
bool current = _getBit(listId, index);
|
||||||
|
if (current == value) revert NoStatusChange(listId, index);
|
||||||
|
if (l.purpose == Purpose.Revocation && !value) revert RevocationIsTerminal(listId, index);
|
||||||
|
|
||||||
|
_setBit(listId, index, value);
|
||||||
|
unchecked {
|
||||||
|
l.epoch += 1;
|
||||||
|
}
|
||||||
|
l.lastMutatedAt = uint64(block.timestamp);
|
||||||
|
emit StatusSet(listId, index, value, l.epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience: revoke (set bit to 1) the credential at `index` on a Revocation list.
|
||||||
|
function revoke(uint256 listId, uint256 index) external {
|
||||||
|
setStatus(listId, index, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Publish a controller-attested commitment to the CURRENT bitstring, anchored to the
|
||||||
|
/// current epoch. A zk non-revocation proof (below) binds to this root, so a verifier
|
||||||
|
/// accepts a proof only against an up-to-date root.
|
||||||
|
/// @dev [MEASURE] The root is controller-attested in this version: the controller is trusted
|
||||||
|
/// to publish a commitment matching the live bits it just wrote. A future version derives
|
||||||
|
/// the root on-chain (or inside the SP1 VM) from getWord so it is trustless. The raw words
|
||||||
|
/// are exposed by getWord for independent recomputation regardless.
|
||||||
|
function publishStatusRoot(uint256 listId, bytes32 root) external {
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
if (msg.sender != l.controller) revert NotController(listId);
|
||||||
|
l.publishedRoot = root;
|
||||||
|
l.rootEpoch = l.epoch;
|
||||||
|
emit StatusRootPublished(listId, root, l.epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Reads
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice The status bit of a credential index (true = revoked/suspended per the list purpose).
|
||||||
|
function statusOf(uint256 listId, uint256 index) external view returns (bool) {
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
if (index >= l.capacity) revert IndexOutOfRange(listId, index);
|
||||||
|
return _getBit(listId, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The raw 256-bit packed word at `wordIndex` (entries [wordIndex*256, wordIndex*256+255]).
|
||||||
|
/// Exposed so anyone can recompute a commitment over the full bitstring off-chain.
|
||||||
|
function getWord(uint256 listId, uint256 wordIndex) external view returns (uint256) {
|
||||||
|
_requireList(listId);
|
||||||
|
return _words[listId][wordIndex];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The number of 256-bit words backing a list's capacity.
|
||||||
|
function wordCount(uint256 listId) external view returns (uint256) {
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
return (l.capacity + 255) / 256;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Number of lists ever created (listId runs 0..listCount-1).
|
||||||
|
function listCount() external view returns (uint256) {
|
||||||
|
return _lists.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a list's metadata. Reverts on an unknown listId.
|
||||||
|
function getList(uint256 listId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
address controller,
|
||||||
|
Purpose purpose,
|
||||||
|
uint256 capacity,
|
||||||
|
uint64 createdAt,
|
||||||
|
uint64 epoch,
|
||||||
|
uint64 lastMutatedAt,
|
||||||
|
bytes32 publishedRoot,
|
||||||
|
uint64 rootEpoch
|
||||||
|
)
|
||||||
|
{
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
return (l.controller, l.purpose, l.capacity, l.createdAt, l.epoch, l.lastMutatedAt, l.publishedRoot, l.rootEpoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Zero-knowledge non-revocation
|
||||||
|
// ==========================================================================
|
||||||
|
//
|
||||||
|
// GOAL. Let a credential HOLDER prove "the status bit of my credential is 0" (i.e. my credential
|
||||||
|
// is NOT revoked) WITHOUT revealing which status index it is, and bind that proof to the list's
|
||||||
|
// current on-chain state so a stale proof is rejected.
|
||||||
|
//
|
||||||
|
// PUBLIC-INPUT SHAPE (the SP1 program's committed public values), ABI-encoded exactly as:
|
||||||
|
// abi.encode(
|
||||||
|
// uint256 chainId, // must equal block.chainid
|
||||||
|
// address statusListContract, // must equal address(this)
|
||||||
|
// uint256 statusListId, // the list the credential's status lives in
|
||||||
|
// bytes32 statusRoot, // commitment to the list bitstring the proof was made against
|
||||||
|
// bytes32 credentialCommitment,// hiding commitment to the holder's credential (binds a real
|
||||||
|
// // anchored credential without revealing its index)
|
||||||
|
// uint8 purpose // must equal uint8(list.purpose)
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// IN-CIRCUIT WITNESS (private, [MEASURE] to be implemented):
|
||||||
|
// - the status index i of the holder's credential,
|
||||||
|
// - an opening of `statusRoot` at i proving bitstring[i] == 0,
|
||||||
|
// - an opening of `credentialCommitment` to the credential (issuer, type, index i),
|
||||||
|
// so the statement proven is: "there is an index i, committed by credentialCommitment, whose
|
||||||
|
// bit under statusRoot is 0", revealing neither i nor the credential.
|
||||||
|
//
|
||||||
|
// ON-CHAIN BINDING. verifyNonRevocation enforces chainId / contract / listId / purpose, and
|
||||||
|
// requires statusRoot to equal the list's publishedRoot AT THE CURRENT EPOCH (rootEpoch == epoch),
|
||||||
|
// so a proof is only accepted against the freshest committed state. It then delegates soundness of
|
||||||
|
// the bit-is-0 statement to the SP1 verifier. FAIL-CLOSED if the verifier or vkey is unconfigured.
|
||||||
|
|
||||||
|
/// @notice The canonical ABI type string of the non-revocation public inputs (for off-chain tooling).
|
||||||
|
string public constant NON_REVOCATION_PUBLIC_VALUES_ABI =
|
||||||
|
"(uint256 chainId,address statusListContract,uint256 statusListId,bytes32 statusRoot,bytes32 credentialCommitment,uint8 purpose)";
|
||||||
|
|
||||||
|
/// @notice Publish the SP1 non-revocation program vkey (admin-only). Settable because the circuit
|
||||||
|
/// is [MEASURE]: once built and its vkey known, the admin sets it; setting it to a fresh
|
||||||
|
/// value is how the program is upgraded. Emits the transition for auditability.
|
||||||
|
function setNonRevocationVKey(bytes32 vkey) external {
|
||||||
|
if (msg.sender != ADMIN) revert NotAdmin();
|
||||||
|
bytes32 old = nonRevocationVKey;
|
||||||
|
nonRevocationVKey = vkey;
|
||||||
|
emit NonRevocationVKeySet(old, vkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True once a non-revocation verifier AND a program vkey are both configured.
|
||||||
|
function nonRevocationConfigured() public view returns (bool) {
|
||||||
|
return address(NON_REVOCATION_VERIFIER) != address(0) && nonRevocationVKey != bytes32(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Verify a zero-knowledge NON-REVOCATION proof for `listId` against its current committed
|
||||||
|
* state. Returns true iff (a) the public inputs bind this chain, this contract, this list
|
||||||
|
* and its purpose, (b) the proof's statusRoot equals the list's publishedRoot at the
|
||||||
|
* current epoch (freshness), and (c) the SP1 verifier accepts the proof. FAIL-CLOSED:
|
||||||
|
* returns false (never reverts) on any binding mismatch or invalid proof, and reverts
|
||||||
|
* with NonRevocationNotConfigured only when the program is not yet configured, so callers
|
||||||
|
* cannot mistake "unconfigured" for "not revoked".
|
||||||
|
*
|
||||||
|
* @dev [MEASURE] The SP1 circuit that produces the proof is not yet implemented; when it is,
|
||||||
|
* its vkey is published via setNonRevocationVKey and the verifier accepts real proofs. The
|
||||||
|
* on-chain binding here is complete and final; only the circuit is pending.
|
||||||
|
*/
|
||||||
|
function verifyNonRevocation(uint256 listId, bytes calldata publicValues, bytes calldata proof)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
List storage l = _requireList(listId);
|
||||||
|
if (!nonRevocationConfigured()) revert NonRevocationNotConfigured();
|
||||||
|
|
||||||
|
// Exact length check (6 * 32 = 192) prevents a trailing-bytes decode spoof.
|
||||||
|
if (publicValues.length != 192) return false;
|
||||||
|
(
|
||||||
|
uint256 chainId,
|
||||||
|
address statusListContract,
|
||||||
|
uint256 statusListId,
|
||||||
|
bytes32 statusRoot,
|
||||||
|
, // credentialCommitment: bound inside the circuit, not re-checked on chain
|
||||||
|
uint8 purpose
|
||||||
|
) = abi.decode(publicValues, (uint256, address, uint256, bytes32, bytes32, uint8));
|
||||||
|
|
||||||
|
if (chainId != block.chainid) return false;
|
||||||
|
if (statusListContract != address(this)) return false;
|
||||||
|
if (statusListId != listId) return false;
|
||||||
|
if (purpose != uint8(l.purpose)) return false;
|
||||||
|
// Freshness: the proof must be against the current published root (root must be up to date).
|
||||||
|
if (l.publishedRoot == bytes32(0)) return false;
|
||||||
|
if (l.rootEpoch != l.epoch) return false;
|
||||||
|
if (statusRoot != l.publishedRoot) return false;
|
||||||
|
|
||||||
|
// Delegate the "bit is 0 for a hidden index" statement to the SP1 verifier (reverts if invalid).
|
||||||
|
try NON_REVOCATION_VERIFIER.verifyProof(nonRevocationVKey, publicValues, proof) {
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
function _requireList(uint256 listId) internal view returns (List storage l) {
|
||||||
|
if (listId >= _lists.length) revert UnknownList(listId);
|
||||||
|
l = _lists[listId];
|
||||||
|
}
|
||||||
|
|
||||||
|
function _getBit(uint256 listId, uint256 index) internal view returns (bool) {
|
||||||
|
uint256 word = _words[listId][index >> 8];
|
||||||
|
return ((word >> (index & 0xff)) & 1) == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _setBit(uint256 listId, uint256 index, bool value) internal {
|
||||||
|
uint256 wordIndex = index >> 8;
|
||||||
|
uint256 mask = uint256(1) << (index & 0xff);
|
||||||
|
uint256 word = _words[listId][wordIndex];
|
||||||
|
if (value) {
|
||||||
|
word |= mask;
|
||||||
|
} else {
|
||||||
|
word &= ~mask;
|
||||||
|
}
|
||||||
|
_words[listId][wordIndex] = word;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCompliancePool — Privacy Pools + Travel Rule hybrid
|
||||||
|
* @notice Implements the Privacy Pools construction of Buterin, Illum,
|
||||||
|
* Nadler, Schar & Soleimani (eprint 2023/1366) — zk-mixer with
|
||||||
|
* association-set proofs that let honest users prove their deposit
|
||||||
|
* belongs to a curated "clean" subset, while sanctioned addresses
|
||||||
|
* cannot exit via the pool because their commitment never enters
|
||||||
|
* the association set.
|
||||||
|
*
|
||||||
|
* The deposit root is computed on-chain from a deterministic
|
||||||
|
* append-only Merkle tree of committed leaves (audit fix HIGH #28).
|
||||||
|
* The Foundation cannot publish a fake tree to drain the pool.
|
||||||
|
*
|
||||||
|
* Hashing: keccak256 (cheap on EVM, no trusted setup, no MiMC).
|
||||||
|
* Depth: 20 (1,048,576 leaves per pool).
|
||||||
|
* History: last 64 roots remain valid simultaneously so a user with
|
||||||
|
* a proof built against a slightly-old root can still withdraw.
|
||||||
|
*
|
||||||
|
* The Foundation still publishes ASSOCIATION roots through the 24h
|
||||||
|
* challenge process, since the association set is an off-chain
|
||||||
|
* classification.
|
||||||
|
*/
|
||||||
|
interface IPrivacyPoolVerifier {
|
||||||
|
/// @param publicInputs [poolId, depositRoot, associationRoot, nullifierHash,
|
||||||
|
/// recipientWord, feeRecipientWord, refundWord, feeWord]
|
||||||
|
function verify(bytes calldata proof, uint256[] calldata publicInputs) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Append-only zk-mixer Merkle tree with rolling-history root cache.
|
||||||
|
/// Construction follows the Privacy Pools paper (Buterin et al. 2023).
|
||||||
|
abstract contract MerkleTreeWithHistory {
|
||||||
|
uint32 public constant TREE_DEPTH = 20;
|
||||||
|
/// AUDIT FIX R5 (MED-10): raised from 64 → 256. At 0.5s blocks, 64 deposits
|
||||||
|
/// fit in ~32s; honest provers building proofs against a 30s-old root
|
||||||
|
/// were getting DoS'd by deposit bursts. 256 gives ~2min headroom which
|
||||||
|
/// matches expected prover latency on AERE.
|
||||||
|
uint32 public constant ROOT_HISTORY_SIZE = 256;
|
||||||
|
|
||||||
|
bytes32 public constant ZERO_VALUE = keccak256("aere.compliance-pool.v1.empty-leaf");
|
||||||
|
|
||||||
|
bytes32[TREE_DEPTH] public filledSubtrees;
|
||||||
|
bytes32[TREE_DEPTH] public zeros;
|
||||||
|
bytes32[ROOT_HISTORY_SIZE] public roots;
|
||||||
|
uint32 public currentRootIndex;
|
||||||
|
uint32 public nextLeafIndex;
|
||||||
|
|
||||||
|
error TreeFull();
|
||||||
|
|
||||||
|
event TreeNearCapacity(uint32 indexed leaves, uint32 capacity); // AUDIT FIX R4 (MED)
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// AUDIT FIX R4 (LOW): do NOT seed the empty-tree root into the rolling
|
||||||
|
// history — that would let withdrawals against an empty-tree proof
|
||||||
|
// succeed for the first ROOT_HISTORY_SIZE deposits. Instead, leave all
|
||||||
|
// history slots at bytes32(0); isKnownRoot already returns false for
|
||||||
|
// zero. The first real _insert writes the first valid root.
|
||||||
|
bytes32 z = ZERO_VALUE;
|
||||||
|
for (uint32 i = 0; i < TREE_DEPTH; i++) {
|
||||||
|
zeros[i] = z;
|
||||||
|
filledSubtrees[i] = z;
|
||||||
|
z = keccak256(abi.encodePacked(z, z));
|
||||||
|
}
|
||||||
|
// history intentionally left as zeros.
|
||||||
|
}
|
||||||
|
|
||||||
|
function _insert(bytes32 leaf) internal returns (uint32 idx) {
|
||||||
|
idx = nextLeafIndex;
|
||||||
|
if (idx >= uint32(1 << TREE_DEPTH)) revert TreeFull();
|
||||||
|
nextLeafIndex = idx + 1;
|
||||||
|
|
||||||
|
uint32 cur = idx;
|
||||||
|
bytes32 left;
|
||||||
|
bytes32 right;
|
||||||
|
bytes32 node = leaf;
|
||||||
|
for (uint32 i = 0; i < TREE_DEPTH; i++) {
|
||||||
|
if (cur & 1 == 0) {
|
||||||
|
left = node;
|
||||||
|
right = zeros[i];
|
||||||
|
filledSubtrees[i] = node;
|
||||||
|
} else {
|
||||||
|
left = filledSubtrees[i];
|
||||||
|
right = node;
|
||||||
|
}
|
||||||
|
node = keccak256(abi.encodePacked(left, right));
|
||||||
|
cur >>= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32 newRootIdx = (currentRootIndex + 1) % ROOT_HISTORY_SIZE;
|
||||||
|
currentRootIndex = newRootIdx;
|
||||||
|
roots[newRootIdx] = node;
|
||||||
|
|
||||||
|
// AUDIT FIX R4 (MED): warn at 90% and 99% capacity so operators can
|
||||||
|
// schedule a sibling-pool deployment before depositors hit TreeFull.
|
||||||
|
uint32 cap = uint32(1 << TREE_DEPTH);
|
||||||
|
uint32 leaves = nextLeafIndex;
|
||||||
|
if (leaves == (cap * 90) / 100 || leaves == (cap * 99) / 100) {
|
||||||
|
emit TreeNearCapacity(leaves, cap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Returns true if `root` is in the recent ROOT_HISTORY_SIZE roots.
|
||||||
|
function isKnownRoot(bytes32 root) public view returns (bool) {
|
||||||
|
if (root == bytes32(0)) return false;
|
||||||
|
uint32 i = currentRootIndex;
|
||||||
|
do {
|
||||||
|
if (roots[i] == root) return true;
|
||||||
|
if (i == 0) i = ROOT_HISTORY_SIZE;
|
||||||
|
i--;
|
||||||
|
} while (i != currentRootIndex);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLastRoot() external view returns (bytes32) {
|
||||||
|
return roots[currentRootIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereCompliancePool is MerkleTreeWithHistory, ReentrancyGuard {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
IERC20 public immutable TOKEN;
|
||||||
|
uint256 public immutable DENOMINATION;
|
||||||
|
address public immutable FOUNDATION;
|
||||||
|
IPrivacyPoolVerifier public immutable VERIFIER;
|
||||||
|
bytes32 public immutable POOL_ID;
|
||||||
|
|
||||||
|
/* ================================= state ================================= */
|
||||||
|
|
||||||
|
/// AUDIT FIX (MED #28): association roots still go through 24h challenge.
|
||||||
|
mapping(bytes32 => uint64) public associationRootPublishedAt;
|
||||||
|
mapping(bytes32 => uint64) public associationRootProposedAt;
|
||||||
|
mapping(bytes32 => bool) public associationRootChallenged;
|
||||||
|
/// AUDIT FIX R5 (HIGH-2): cap dismissals + slashable challenge bond.
|
||||||
|
mapping(bytes32 => uint8) public associationRootDismissCount;
|
||||||
|
mapping(bytes32 => address) public associationRootChallenger;
|
||||||
|
uint8 public constant MAX_DISMISSALS_PER_ROOT = 2;
|
||||||
|
uint256 public constant CHALLENGE_BOND = 100 ether; // 100 AERE — burnt on dismissal
|
||||||
|
address public constant CHALLENGE_BOND_BURN = 0x000000000000000000000000000000000000dEaD;
|
||||||
|
IERC20 public immutable BOND_TOKEN; // bond paid in same TOKEN as DENOMINATION
|
||||||
|
uint64 public constant ASSOCIATION_ROOT_CHALLENGE_WINDOW = 24 hours;
|
||||||
|
|
||||||
|
mapping(bytes32 => bool) public spentNullifiers;
|
||||||
|
mapping(bytes32 => bool) public commitmentSeen; // prevents duplicate commitment deposits
|
||||||
|
uint256 public depositCount;
|
||||||
|
|
||||||
|
mapping(address => bool) public isComplianceProvider;
|
||||||
|
address[] public complianceProviderList;
|
||||||
|
|
||||||
|
/* ================================= events ================================= */
|
||||||
|
|
||||||
|
event Deposited(
|
||||||
|
uint256 indexed depositId,
|
||||||
|
address indexed sender,
|
||||||
|
bytes32 commitment,
|
||||||
|
bytes32 travelRuleHash,
|
||||||
|
address indexed complianceProvider,
|
||||||
|
string travelRuleUri,
|
||||||
|
uint32 leafIndex,
|
||||||
|
bytes32 newRoot
|
||||||
|
);
|
||||||
|
event AssociationRootProposed(bytes32 indexed root, uint64 challengeEndsAt);
|
||||||
|
event AssociationRootChallenged(bytes32 indexed root, address indexed challenger, string reason);
|
||||||
|
event AssociationRootChallengeDismissed(bytes32 indexed root, address indexed challenger, uint8 dismissCount); // R5 HIGH-2
|
||||||
|
event AssociationRootPublished(bytes32 indexed root);
|
||||||
|
event Withdrawn(
|
||||||
|
bytes32 indexed nullifierHash,
|
||||||
|
address indexed recipient,
|
||||||
|
address indexed feeRecipient,
|
||||||
|
uint256 fee,
|
||||||
|
uint256 refund,
|
||||||
|
bytes32 depositRoot,
|
||||||
|
bytes32 associationRoot
|
||||||
|
);
|
||||||
|
event ComplianceProviderSet(address indexed provider, bool allowed);
|
||||||
|
|
||||||
|
/* ================================= errors ================================= */
|
||||||
|
|
||||||
|
error NotFoundation();
|
||||||
|
error ZeroAddr();
|
||||||
|
error NotAComplianceProvider();
|
||||||
|
error AlreadySpent();
|
||||||
|
error UnknownAssociationRoot();
|
||||||
|
error UnknownDepositRoot();
|
||||||
|
error InvalidProof();
|
||||||
|
error WrongDenomination();
|
||||||
|
error TransferFailed();
|
||||||
|
error FeeTooLarge();
|
||||||
|
error CommitmentReused();
|
||||||
|
error ChallengeBondTransferFailed(); // R5 HIGH-2
|
||||||
|
error MaxDismissalsReached(); // R5 HIGH-2
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert NotFoundation();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
IERC20 token,
|
||||||
|
uint256 denomination,
|
||||||
|
address foundation,
|
||||||
|
IPrivacyPoolVerifier verifier
|
||||||
|
) MerkleTreeWithHistory() {
|
||||||
|
if (address(token) == address(0) || foundation == address(0) || address(verifier) == address(0)) {
|
||||||
|
revert ZeroAddr();
|
||||||
|
}
|
||||||
|
require(denomination > 0, "zero-denom");
|
||||||
|
TOKEN = token;
|
||||||
|
BOND_TOKEN = token; // R5 HIGH-2: same asset as DENOMINATION
|
||||||
|
DENOMINATION = denomination;
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
VERIFIER = verifier;
|
||||||
|
POOL_ID = keccak256(abi.encodePacked(address(this), block.chainid));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ compliance provider ========================= */
|
||||||
|
|
||||||
|
function setComplianceProvider(address provider, bool allowed) external onlyFoundation {
|
||||||
|
if (provider == address(0)) revert ZeroAddr();
|
||||||
|
bool prev = isComplianceProvider[provider];
|
||||||
|
isComplianceProvider[provider] = allowed;
|
||||||
|
if (!prev && allowed) complianceProviderList.push(provider);
|
||||||
|
emit ComplianceProviderSet(provider, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== deposit path ============================= */
|
||||||
|
|
||||||
|
function deposit(
|
||||||
|
bytes32 commitment,
|
||||||
|
bytes32 travelRuleHash,
|
||||||
|
address complianceProvider,
|
||||||
|
string calldata travelRuleUri
|
||||||
|
) external nonReentrant {
|
||||||
|
if (!isComplianceProvider[complianceProvider]) revert NotAComplianceProvider();
|
||||||
|
if (commitment == bytes32(0) || commitment == ZERO_VALUE) revert CommitmentReused();
|
||||||
|
// AUDIT FIX R5 (MED-11): bind commitment to msg.sender. Mempool
|
||||||
|
// front-run by another address now produces a DIFFERENT actualLeaf so
|
||||||
|
// the victim's deposit still succeeds. The ZK circuit will need to
|
||||||
|
// constrain that the witnessed leaf = keccak256(commitment, depositor).
|
||||||
|
bytes32 actualLeaf = keccak256(abi.encodePacked(commitment, msg.sender));
|
||||||
|
if (commitmentSeen[actualLeaf]) revert CommitmentReused();
|
||||||
|
commitmentSeen[actualLeaf] = true;
|
||||||
|
|
||||||
|
if (!TOKEN.transferFrom(msg.sender, address(this), DENOMINATION)) revert TransferFailed();
|
||||||
|
|
||||||
|
uint32 leafIndex = _insert(actualLeaf);
|
||||||
|
bytes32 newRoot = roots[currentRootIndex];
|
||||||
|
|
||||||
|
uint256 id = depositCount++;
|
||||||
|
emit Deposited(id, msg.sender, commitment, travelRuleHash, complianceProvider, travelRuleUri, leafIndex, newRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ========================== association set publish ====================== */
|
||||||
|
|
||||||
|
function proposeAssociationRoot(bytes32 root) external onlyFoundation {
|
||||||
|
if (associationRootPublishedAt[root] != 0) return;
|
||||||
|
if (associationRootProposedAt[root] == 0) {
|
||||||
|
associationRootProposedAt[root] = uint64(block.timestamp);
|
||||||
|
associationRootChallenged[root] = false;
|
||||||
|
emit AssociationRootProposed(root, uint64(block.timestamp) + ASSOCIATION_ROOT_CHALLENGE_WINDOW);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function challengeAssociationRoot(bytes32 root, string calldata reason) external {
|
||||||
|
if (associationRootProposedAt[root] == 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootPublishedAt[root] != 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootChallenged[root]) revert UnknownAssociationRoot(); // already challenged — wait for dismissal
|
||||||
|
if (associationRootDismissCount[root] >= MAX_DISMISSALS_PER_ROOT) revert MaxDismissalsReached();
|
||||||
|
// AUDIT FIX R5 (HIGH-2): require slashable CHALLENGE_BOND so a griefer
|
||||||
|
// can no longer freeze withdrawals at ~30k gas per 24h cycle.
|
||||||
|
if (!BOND_TOKEN.transferFrom(msg.sender, address(this), CHALLENGE_BOND)) revert ChallengeBondTransferFailed();
|
||||||
|
associationRootChallenged[root] = true;
|
||||||
|
associationRootChallenger[root] = msg.sender;
|
||||||
|
emit AssociationRootChallenged(root, msg.sender, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dismissAssociationRootChallenge(bytes32 root) external onlyFoundation {
|
||||||
|
if (!associationRootChallenged[root]) revert UnknownAssociationRoot();
|
||||||
|
associationRootChallenged[root] = false;
|
||||||
|
associationRootDismissCount[root] += 1;
|
||||||
|
// AUDIT FIX R6 (CRITICAL): reset window on dismiss. Combined with
|
||||||
|
// MAX_DISMISSALS_PER_ROOT=2 this caps the worst-case Foundation+
|
||||||
|
// sockpuppet bypass at 48h (vs R5's 0h instant publish). Each
|
||||||
|
// dismissal genuinely costs Foundation 24h delay AND burns the
|
||||||
|
// challenger's bond.
|
||||||
|
associationRootProposedAt[root] = uint64(block.timestamp);
|
||||||
|
address challenger = associationRootChallenger[root];
|
||||||
|
delete associationRootChallenger[root];
|
||||||
|
if (challenger != address(0)) {
|
||||||
|
// best-effort burn
|
||||||
|
BOND_TOKEN.transfer(CHALLENGE_BOND_BURN, CHALLENGE_BOND);
|
||||||
|
}
|
||||||
|
emit AssociationRootChallengeDismissed(root, challenger, associationRootDismissCount[root]);
|
||||||
|
emit AssociationRootProposed(root, uint64(block.timestamp) + ASSOCIATION_ROOT_CHALLENGE_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
function publishAssociationRoot(bytes32 root) external {
|
||||||
|
if (associationRootPublishedAt[root] != 0) return;
|
||||||
|
uint64 proposed = associationRootProposedAt[root];
|
||||||
|
if (proposed == 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootChallenged[root]) revert UnknownAssociationRoot();
|
||||||
|
if (block.timestamp < uint256(proposed) + ASSOCIATION_ROOT_CHALLENGE_WINDOW) {
|
||||||
|
revert UnknownAssociationRoot();
|
||||||
|
}
|
||||||
|
associationRootPublishedAt[root] = uint64(block.timestamp);
|
||||||
|
emit AssociationRootPublished(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== withdraw path ============================ */
|
||||||
|
|
||||||
|
function withdraw(
|
||||||
|
bytes calldata proof,
|
||||||
|
bytes32 depositRoot,
|
||||||
|
bytes32 associationRoot,
|
||||||
|
bytes32 nullifierHash,
|
||||||
|
address recipient,
|
||||||
|
address feeRecipient,
|
||||||
|
uint256 fee,
|
||||||
|
uint256 refund
|
||||||
|
) external nonReentrant {
|
||||||
|
if (spentNullifiers[nullifierHash]) revert AlreadySpent();
|
||||||
|
if (associationRootPublishedAt[associationRoot] == 0) revert UnknownAssociationRoot();
|
||||||
|
// AUDIT FIX (HIGH #28): the depositRoot must be one of the last 64
|
||||||
|
// on-chain-computed roots — there is no Foundation override.
|
||||||
|
if (!isKnownRoot(depositRoot)) revert UnknownDepositRoot();
|
||||||
|
if (fee + refund > DENOMINATION) revert FeeTooLarge();
|
||||||
|
|
||||||
|
uint256[] memory pubs = new uint256[](8);
|
||||||
|
pubs[0] = uint256(POOL_ID);
|
||||||
|
pubs[1] = uint256(depositRoot);
|
||||||
|
pubs[2] = uint256(associationRoot);
|
||||||
|
pubs[3] = uint256(nullifierHash);
|
||||||
|
pubs[4] = uint256(uint160(recipient));
|
||||||
|
pubs[5] = uint256(uint160(feeRecipient));
|
||||||
|
pubs[6] = refund;
|
||||||
|
pubs[7] = fee;
|
||||||
|
|
||||||
|
if (!VERIFIER.verify(proof, pubs)) revert InvalidProof();
|
||||||
|
|
||||||
|
spentNullifiers[nullifierHash] = true;
|
||||||
|
|
||||||
|
// AUDIT FIX R6 (HIGH): refund is paid out to msg.sender (the relayer
|
||||||
|
// or sponsor) as a gas-reimbursement kickback — the standard
|
||||||
|
// zk-mixer relayer pattern. Previously refund was subtracted from
|
||||||
|
// recipient amount but NEVER paid out — pool accounting was unbalanced.
|
||||||
|
uint256 toRecipient = DENOMINATION - fee - refund;
|
||||||
|
if (toRecipient > 0 && !TOKEN.transfer(recipient, toRecipient)) revert TransferFailed();
|
||||||
|
if (fee > 0 && !TOKEN.transfer(feeRecipient, fee)) revert TransferFailed();
|
||||||
|
if (refund > 0 && !TOKEN.transfer(msg.sender, refund)) revert TransferFailed();
|
||||||
|
|
||||||
|
emit Withdrawn(nullifierHash, recipient, feeRecipient, fee, refund, depositRoot, associationRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= views ================================= */
|
||||||
|
|
||||||
|
function complianceProviders() external view returns (address[] memory) {
|
||||||
|
return complianceProviderList;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAssociationRootValid(bytes32 root) external view returns (bool) {
|
||||||
|
return associationRootPublishedAt[root] != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Compatibility alias for older indexers/clients that expect a
|
||||||
|
/// `latestDepositRoot()` getter. Returns the current on-chain Merkle root.
|
||||||
|
function latestDepositRoot() external view returns (bytes32) {
|
||||||
|
return roots[currentRootIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "../zkverify/ISP1Verifier.sol";
|
||||||
|
|
||||||
|
/// @title AereCompliancePoolSP1Verifier
|
||||||
|
/// @notice SP1-backed verifier adapter for AereCompliancePool. Bridges the
|
||||||
|
/// pool's `IPrivacyPoolVerifier.verify(bytes proof, uint256[] pubs)`
|
||||||
|
/// interface to the Succinct Labs SP1 verifier gateway.
|
||||||
|
///
|
||||||
|
/// The off-chain prover is the Rust SP1 program at
|
||||||
|
/// `zk-circuits/compliance-pool/program`. Its compiled VKEY is
|
||||||
|
/// stored as a constructor-immutable here. The 8 public inputs
|
||||||
|
/// the pool passes (poolId, depositRoot, associationRoot,
|
||||||
|
/// nullifierHash, recipient, feeRecipient, refund, fee) are
|
||||||
|
/// abi-encoded into the same struct the program commits to.
|
||||||
|
///
|
||||||
|
/// @dev Drop-in replacement for `MockPrivacyPoolVerifier` in production
|
||||||
|
/// deploys. Test deploys may continue to use the mock to avoid
|
||||||
|
/// needing a real SP1 proof per test.
|
||||||
|
contract AereCompliancePoolSP1Verifier {
|
||||||
|
ISP1Verifier public immutable SP1;
|
||||||
|
bytes32 public immutable PROGRAM_VKEY;
|
||||||
|
|
||||||
|
error InvalidPublicInputCount();
|
||||||
|
error InvalidPublicValues();
|
||||||
|
|
||||||
|
constructor(ISP1Verifier sp1, bytes32 programVKey) {
|
||||||
|
require(address(sp1) != address(0) && programVKey != bytes32(0), "zero");
|
||||||
|
SP1 = sp1;
|
||||||
|
PROGRAM_VKEY = programVKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Verify a withdraw proof.
|
||||||
|
/// @param proof SP1-encoded proof bytes (Groth16 or PLONK over SP1 zkVM)
|
||||||
|
/// @param pubs [poolId, depositRoot, associationRoot, nullifierHash,
|
||||||
|
/// recipient, feeRecipient, refund, fee]
|
||||||
|
/// @return ok True iff SP1 verifier accepts the proof against the
|
||||||
|
/// ABI-encoded public-values struct.
|
||||||
|
function verify(bytes calldata proof, uint256[] calldata pubs) external view returns (bool ok) {
|
||||||
|
if (pubs.length != 8) revert InvalidPublicInputCount();
|
||||||
|
|
||||||
|
// The Rust program commits PublicValues = (bytes32 pool_id,
|
||||||
|
// bytes32 deposit_root, bytes32 association_root,
|
||||||
|
// bytes32 nullifier_hash, address recipient, address fee_recipient,
|
||||||
|
// uint256 refund, uint256 fee).
|
||||||
|
bytes memory publicValues = abi.encode(
|
||||||
|
bytes32(pubs[0]),
|
||||||
|
bytes32(pubs[1]),
|
||||||
|
bytes32(pubs[2]),
|
||||||
|
bytes32(pubs[3]),
|
||||||
|
address(uint160(pubs[4])),
|
||||||
|
address(uint160(pubs[5])),
|
||||||
|
pubs[6],
|
||||||
|
pubs[7]
|
||||||
|
);
|
||||||
|
|
||||||
|
// SP1Verifier.verifyProof reverts on failure. Wrap in a low-level
|
||||||
|
// staticcall so we can return bool to fit the existing pool
|
||||||
|
// interface.
|
||||||
|
(bool success, ) = address(SP1).staticcall(
|
||||||
|
abi.encodeCall(ISP1Verifier.verifyProof, (PROGRAM_VKEY, publicValues, proof))
|
||||||
|
);
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereCompliancePoolV2 — Privacy Pools + Travel Rule hybrid (bug-fixed challenge bond)
|
||||||
|
* @notice Bug-fix redeploy of AereCompliancePool
|
||||||
|
* (0x79735c31F289F7A4d6Be3E02aaB70B544796D41d, 0 deposits). The
|
||||||
|
* Privacy-Pools construction, on-chain append-only Merkle tree, rolling
|
||||||
|
* root history, SP1 verifier reference, and Travel-Rule deposit path are
|
||||||
|
* BYTE-FOR-BYTE identical to V1. The SAME deployed SP1 verifier is
|
||||||
|
* reused, so the existing off-chain circuit still matches this pool's
|
||||||
|
* tree (TREE_DEPTH, ZERO_VALUE and keccak hashing are unchanged).
|
||||||
|
*
|
||||||
|
* ─────────────────────────── WHY V2 ───────────────────────────
|
||||||
|
* F8 (challenge bond unrecoverable). V1's challengeAssociationRoot pulled
|
||||||
|
* a 100-token CHALLENGE_BOND but there was NO path to return it to an
|
||||||
|
* HONEST challenger:
|
||||||
|
* - if the Foundation dismissed the challenge, the bond was BURNED;
|
||||||
|
* - if the Foundation simply never dismissed, the root stayed
|
||||||
|
* "challenged" forever, the bond sat locked in the contract, and no
|
||||||
|
* refund function existed.
|
||||||
|
* So an honest challenger who was RIGHT always lost 100 tokens.
|
||||||
|
*
|
||||||
|
* V2 fix. A challenge now resolves one of two ways:
|
||||||
|
* - DISMISSED (provably-bad challenge): the Foundation calls
|
||||||
|
* dismissAssociationRootChallenge WITHIN the dismissal window
|
||||||
|
* (== ASSOCIATION_ROOT_CHALLENGE_WINDOW after the challenge). The
|
||||||
|
* bond is BURNED to dEaD, exactly as V1. This preserves V1's
|
||||||
|
* anti-grief property: griefing a valid root still costs the bond.
|
||||||
|
* - UPHELD (Foundation failed to dismiss in time): after the dismissal
|
||||||
|
* window passes with the challenge still standing, anyone can call
|
||||||
|
* reclaimUpheldChallenge — the bond is REFUNDED to the challenger and
|
||||||
|
* the root is PERMANENTLY REJECTED (it can never publish). An honest
|
||||||
|
* challenger is made whole; a questionable association set is not
|
||||||
|
* published (the safe default for a compliance pool).
|
||||||
|
*
|
||||||
|
* The dismissal window is bounded by ASSOCIATION_ROOT_CHALLENGE_WINDOW,
|
||||||
|
* which is now a constructor IMMUTABLE (was a constant) so a deployer-
|
||||||
|
* owned demo twin can exercise the full lifecycle quickly while the
|
||||||
|
* canonical pool keeps the production 24h value. No other behaviour
|
||||||
|
* changes.
|
||||||
|
*/
|
||||||
|
interface IPrivacyPoolVerifier {
|
||||||
|
/// @param publicInputs [poolId, depositRoot, associationRoot, nullifierHash,
|
||||||
|
/// recipientWord, feeRecipientWord, refundWord, feeWord]
|
||||||
|
function verify(bytes calldata proof, uint256[] calldata publicInputs) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Append-only zk-mixer Merkle tree with rolling-history root cache.
|
||||||
|
/// IDENTICAL to AereCompliancePool V1 (circuit compatibility).
|
||||||
|
abstract contract MerkleTreeWithHistoryV2 {
|
||||||
|
uint32 public constant TREE_DEPTH = 20;
|
||||||
|
uint32 public constant ROOT_HISTORY_SIZE = 256;
|
||||||
|
|
||||||
|
bytes32 public constant ZERO_VALUE = keccak256("aere.compliance-pool.v1.empty-leaf");
|
||||||
|
|
||||||
|
bytes32[TREE_DEPTH] public filledSubtrees;
|
||||||
|
bytes32[TREE_DEPTH] public zeros;
|
||||||
|
bytes32[ROOT_HISTORY_SIZE] public roots;
|
||||||
|
uint32 public currentRootIndex;
|
||||||
|
uint32 public nextLeafIndex;
|
||||||
|
|
||||||
|
error TreeFull();
|
||||||
|
|
||||||
|
event TreeNearCapacity(uint32 indexed leaves, uint32 capacity);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
bytes32 z = ZERO_VALUE;
|
||||||
|
for (uint32 i = 0; i < TREE_DEPTH; i++) {
|
||||||
|
zeros[i] = z;
|
||||||
|
filledSubtrees[i] = z;
|
||||||
|
z = keccak256(abi.encodePacked(z, z));
|
||||||
|
}
|
||||||
|
// history intentionally left as zeros.
|
||||||
|
}
|
||||||
|
|
||||||
|
function _insert(bytes32 leaf) internal returns (uint32 idx) {
|
||||||
|
idx = nextLeafIndex;
|
||||||
|
if (idx >= uint32(1 << TREE_DEPTH)) revert TreeFull();
|
||||||
|
nextLeafIndex = idx + 1;
|
||||||
|
|
||||||
|
uint32 cur = idx;
|
||||||
|
bytes32 left;
|
||||||
|
bytes32 right;
|
||||||
|
bytes32 node = leaf;
|
||||||
|
for (uint32 i = 0; i < TREE_DEPTH; i++) {
|
||||||
|
if (cur & 1 == 0) {
|
||||||
|
left = node;
|
||||||
|
right = zeros[i];
|
||||||
|
filledSubtrees[i] = node;
|
||||||
|
} else {
|
||||||
|
left = filledSubtrees[i];
|
||||||
|
right = node;
|
||||||
|
}
|
||||||
|
node = keccak256(abi.encodePacked(left, right));
|
||||||
|
cur >>= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32 newRootIdx = (currentRootIndex + 1) % ROOT_HISTORY_SIZE;
|
||||||
|
currentRootIndex = newRootIdx;
|
||||||
|
roots[newRootIdx] = node;
|
||||||
|
|
||||||
|
uint32 cap = uint32(1 << TREE_DEPTH);
|
||||||
|
uint32 leaves = nextLeafIndex;
|
||||||
|
if (leaves == (cap * 90) / 100 || leaves == (cap * 99) / 100) {
|
||||||
|
emit TreeNearCapacity(leaves, cap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isKnownRoot(bytes32 root) public view returns (bool) {
|
||||||
|
if (root == bytes32(0)) return false;
|
||||||
|
uint32 i = currentRootIndex;
|
||||||
|
do {
|
||||||
|
if (roots[i] == root) return true;
|
||||||
|
if (i == 0) i = ROOT_HISTORY_SIZE;
|
||||||
|
i--;
|
||||||
|
} while (i != currentRootIndex);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLastRoot() external view returns (bytes32) {
|
||||||
|
return roots[currentRootIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
contract AereCompliancePoolV2 is MerkleTreeWithHistoryV2, ReentrancyGuard {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
IERC20 public immutable TOKEN;
|
||||||
|
uint256 public immutable DENOMINATION;
|
||||||
|
address public immutable FOUNDATION;
|
||||||
|
IPrivacyPoolVerifier public immutable VERIFIER;
|
||||||
|
bytes32 public immutable POOL_ID;
|
||||||
|
|
||||||
|
/* ================================= state ================================= */
|
||||||
|
|
||||||
|
/// association roots go through a challenge window.
|
||||||
|
mapping(bytes32 => uint64) public associationRootPublishedAt;
|
||||||
|
mapping(bytes32 => uint64) public associationRootProposedAt;
|
||||||
|
mapping(bytes32 => bool) public associationRootChallenged;
|
||||||
|
/// F8: timestamp of the CURRENT active challenge (dismissal-window anchor).
|
||||||
|
mapping(bytes32 => uint64) public associationRootChallengedAt;
|
||||||
|
/// F8: a root permanently killed by an UPHELD challenge — can never publish.
|
||||||
|
mapping(bytes32 => bool) public associationRootRejected;
|
||||||
|
mapping(bytes32 => uint8) public associationRootDismissCount;
|
||||||
|
mapping(bytes32 => address) public associationRootChallenger;
|
||||||
|
uint8 public constant MAX_DISMISSALS_PER_ROOT = 2;
|
||||||
|
uint256 public constant CHALLENGE_BOND = 100 ether; // 100 tokens
|
||||||
|
address public constant CHALLENGE_BOND_BURN = 0x000000000000000000000000000000000000dEaD;
|
||||||
|
IERC20 public immutable BOND_TOKEN; // bond paid in same TOKEN as DENOMINATION
|
||||||
|
/// V2: immutable (was a 24h constant) so a demo twin can use a short window.
|
||||||
|
uint64 public immutable ASSOCIATION_ROOT_CHALLENGE_WINDOW;
|
||||||
|
|
||||||
|
mapping(bytes32 => bool) public spentNullifiers;
|
||||||
|
mapping(bytes32 => bool) public commitmentSeen; // prevents duplicate commitment deposits
|
||||||
|
uint256 public depositCount;
|
||||||
|
|
||||||
|
mapping(address => bool) public isComplianceProvider;
|
||||||
|
address[] public complianceProviderList;
|
||||||
|
|
||||||
|
/* ================================= events ================================= */
|
||||||
|
|
||||||
|
event Deposited(
|
||||||
|
uint256 indexed depositId,
|
||||||
|
address indexed sender,
|
||||||
|
bytes32 commitment,
|
||||||
|
bytes32 travelRuleHash,
|
||||||
|
address indexed complianceProvider,
|
||||||
|
string travelRuleUri,
|
||||||
|
uint32 leafIndex,
|
||||||
|
bytes32 newRoot
|
||||||
|
);
|
||||||
|
event AssociationRootProposed(bytes32 indexed root, uint64 challengeEndsAt);
|
||||||
|
event AssociationRootChallenged(bytes32 indexed root, address indexed challenger, string reason);
|
||||||
|
event AssociationRootChallengeDismissed(bytes32 indexed root, address indexed challenger, uint8 dismissCount);
|
||||||
|
/// F8: bond refunded to an honest challenger; root permanently rejected.
|
||||||
|
event AssociationRootChallengeUpheld(bytes32 indexed root, address indexed challenger, uint256 bondRefunded);
|
||||||
|
event AssociationRootRejected(bytes32 indexed root);
|
||||||
|
event AssociationRootPublished(bytes32 indexed root);
|
||||||
|
event Withdrawn(
|
||||||
|
bytes32 indexed nullifierHash,
|
||||||
|
address indexed recipient,
|
||||||
|
address indexed feeRecipient,
|
||||||
|
uint256 fee,
|
||||||
|
uint256 refund,
|
||||||
|
bytes32 depositRoot,
|
||||||
|
bytes32 associationRoot
|
||||||
|
);
|
||||||
|
event ComplianceProviderSet(address indexed provider, bool allowed);
|
||||||
|
|
||||||
|
/* ================================= errors ================================= */
|
||||||
|
|
||||||
|
error NotFoundation();
|
||||||
|
error ZeroAddr();
|
||||||
|
error NotAComplianceProvider();
|
||||||
|
error AlreadySpent();
|
||||||
|
error UnknownAssociationRoot();
|
||||||
|
error UnknownDepositRoot();
|
||||||
|
error InvalidProof();
|
||||||
|
error WrongDenomination();
|
||||||
|
error TransferFailed();
|
||||||
|
error FeeTooLarge();
|
||||||
|
error CommitmentReused();
|
||||||
|
error ChallengeBondTransferFailed();
|
||||||
|
error MaxDismissalsReached();
|
||||||
|
error DismissalWindowClosed(); // F8: Foundation dismissed too late (challenge upheld)
|
||||||
|
error DismissalWindowOpen(); // F8: reclaim attempted before the window elapsed
|
||||||
|
error NotChallenged(); // F8
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert NotFoundation();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
IERC20 token,
|
||||||
|
uint256 denomination,
|
||||||
|
address foundation,
|
||||||
|
IPrivacyPoolVerifier verifier,
|
||||||
|
uint64 challengeWindow
|
||||||
|
) MerkleTreeWithHistoryV2() {
|
||||||
|
if (address(token) == address(0) || foundation == address(0) || address(verifier) == address(0)) {
|
||||||
|
revert ZeroAddr();
|
||||||
|
}
|
||||||
|
require(denomination > 0, "zero-denom");
|
||||||
|
require(challengeWindow > 0, "zero-window");
|
||||||
|
TOKEN = token;
|
||||||
|
BOND_TOKEN = token;
|
||||||
|
DENOMINATION = denomination;
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
VERIFIER = verifier;
|
||||||
|
ASSOCIATION_ROOT_CHALLENGE_WINDOW = challengeWindow;
|
||||||
|
POOL_ID = keccak256(abi.encodePacked(address(this), block.chainid));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ compliance provider ========================= */
|
||||||
|
|
||||||
|
function setComplianceProvider(address provider, bool allowed) external onlyFoundation {
|
||||||
|
if (provider == address(0)) revert ZeroAddr();
|
||||||
|
bool prev = isComplianceProvider[provider];
|
||||||
|
isComplianceProvider[provider] = allowed;
|
||||||
|
if (!prev && allowed) complianceProviderList.push(provider);
|
||||||
|
emit ComplianceProviderSet(provider, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== deposit path ============================= */
|
||||||
|
/* IDENTICAL to V1. */
|
||||||
|
|
||||||
|
function deposit(
|
||||||
|
bytes32 commitment,
|
||||||
|
bytes32 travelRuleHash,
|
||||||
|
address complianceProvider,
|
||||||
|
string calldata travelRuleUri
|
||||||
|
) external nonReentrant {
|
||||||
|
if (!isComplianceProvider[complianceProvider]) revert NotAComplianceProvider();
|
||||||
|
if (commitment == bytes32(0) || commitment == ZERO_VALUE) revert CommitmentReused();
|
||||||
|
bytes32 actualLeaf = keccak256(abi.encodePacked(commitment, msg.sender));
|
||||||
|
if (commitmentSeen[actualLeaf]) revert CommitmentReused();
|
||||||
|
commitmentSeen[actualLeaf] = true;
|
||||||
|
|
||||||
|
if (!TOKEN.transferFrom(msg.sender, address(this), DENOMINATION)) revert TransferFailed();
|
||||||
|
|
||||||
|
uint32 leafIndex = _insert(actualLeaf);
|
||||||
|
bytes32 newRoot = roots[currentRootIndex];
|
||||||
|
|
||||||
|
uint256 id = depositCount++;
|
||||||
|
emit Deposited(id, msg.sender, commitment, travelRuleHash, complianceProvider, travelRuleUri, leafIndex, newRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ========================== association set publish ====================== */
|
||||||
|
|
||||||
|
function proposeAssociationRoot(bytes32 root) external onlyFoundation {
|
||||||
|
if (associationRootPublishedAt[root] != 0) return;
|
||||||
|
if (associationRootRejected[root]) return; // permanently killed by an upheld challenge
|
||||||
|
if (associationRootProposedAt[root] == 0) {
|
||||||
|
associationRootProposedAt[root] = uint64(block.timestamp);
|
||||||
|
associationRootChallenged[root] = false;
|
||||||
|
emit AssociationRootProposed(root, uint64(block.timestamp) + ASSOCIATION_ROOT_CHALLENGE_WINDOW);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function challengeAssociationRoot(bytes32 root, string calldata reason) external {
|
||||||
|
if (associationRootProposedAt[root] == 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootPublishedAt[root] != 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootRejected[root]) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootChallenged[root]) revert UnknownAssociationRoot(); // already challenged
|
||||||
|
if (associationRootDismissCount[root] >= MAX_DISMISSALS_PER_ROOT) revert MaxDismissalsReached();
|
||||||
|
if (!BOND_TOKEN.transferFrom(msg.sender, address(this), CHALLENGE_BOND)) revert ChallengeBondTransferFailed();
|
||||||
|
associationRootChallenged[root] = true;
|
||||||
|
associationRootChallenger[root] = msg.sender;
|
||||||
|
associationRootChallengedAt[root] = uint64(block.timestamp);
|
||||||
|
emit AssociationRootChallenged(root, msg.sender, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Foundation dismisses a PROVABLY-BAD challenge. Must be called
|
||||||
|
/// within ASSOCIATION_ROOT_CHALLENGE_WINDOW of the challenge; after
|
||||||
|
/// that the challenge is deemed UPHELD and can only be reclaimed.
|
||||||
|
/// Burns the bond (unchanged from V1) and restarts the publish
|
||||||
|
/// window so an honest Foundation can still publish a valid root.
|
||||||
|
function dismissAssociationRootChallenge(bytes32 root) external onlyFoundation {
|
||||||
|
if (!associationRootChallenged[root]) revert UnknownAssociationRoot();
|
||||||
|
if (block.timestamp >= uint256(associationRootChallengedAt[root]) + ASSOCIATION_ROOT_CHALLENGE_WINDOW) {
|
||||||
|
revert DismissalWindowClosed();
|
||||||
|
}
|
||||||
|
associationRootChallenged[root] = false;
|
||||||
|
associationRootDismissCount[root] += 1;
|
||||||
|
associationRootProposedAt[root] = uint64(block.timestamp); // reset publish window
|
||||||
|
address challenger = associationRootChallenger[root];
|
||||||
|
delete associationRootChallenger[root];
|
||||||
|
delete associationRootChallengedAt[root];
|
||||||
|
if (challenger != address(0)) {
|
||||||
|
// burn the provably-bad challenger's bond (best-effort)
|
||||||
|
BOND_TOKEN.transfer(CHALLENGE_BOND_BURN, CHALLENGE_BOND);
|
||||||
|
}
|
||||||
|
emit AssociationRootChallengeDismissed(root, challenger, associationRootDismissCount[root]);
|
||||||
|
emit AssociationRootProposed(root, uint64(block.timestamp) + ASSOCIATION_ROOT_CHALLENGE_WINDOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice F8: if the Foundation did NOT dismiss within the window, the
|
||||||
|
/// challenge stands (UPHELD). Anyone can finalise it: the honest
|
||||||
|
/// challenger's bond is REFUNDED and the root is permanently
|
||||||
|
/// rejected (safe default — a questioned set is not published).
|
||||||
|
function reclaimUpheldChallenge(bytes32 root) external nonReentrant {
|
||||||
|
if (!associationRootChallenged[root]) revert NotChallenged();
|
||||||
|
if (block.timestamp < uint256(associationRootChallengedAt[root]) + ASSOCIATION_ROOT_CHALLENGE_WINDOW) {
|
||||||
|
revert DismissalWindowOpen();
|
||||||
|
}
|
||||||
|
address challenger = associationRootChallenger[root];
|
||||||
|
associationRootChallenged[root] = false;
|
||||||
|
associationRootRejected[root] = true;
|
||||||
|
delete associationRootChallenger[root];
|
||||||
|
delete associationRootChallengedAt[root];
|
||||||
|
if (challenger != address(0)) {
|
||||||
|
if (!BOND_TOKEN.transfer(challenger, CHALLENGE_BOND)) revert TransferFailed();
|
||||||
|
}
|
||||||
|
emit AssociationRootChallengeUpheld(root, challenger, CHALLENGE_BOND);
|
||||||
|
emit AssociationRootRejected(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
function publishAssociationRoot(bytes32 root) external {
|
||||||
|
if (associationRootPublishedAt[root] != 0) return;
|
||||||
|
if (associationRootRejected[root]) revert UnknownAssociationRoot();
|
||||||
|
uint64 proposed = associationRootProposedAt[root];
|
||||||
|
if (proposed == 0) revert UnknownAssociationRoot();
|
||||||
|
if (associationRootChallenged[root]) revert UnknownAssociationRoot();
|
||||||
|
if (block.timestamp < uint256(proposed) + ASSOCIATION_ROOT_CHALLENGE_WINDOW) {
|
||||||
|
revert UnknownAssociationRoot();
|
||||||
|
}
|
||||||
|
associationRootPublishedAt[root] = uint64(block.timestamp);
|
||||||
|
emit AssociationRootPublished(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== withdraw path ============================ */
|
||||||
|
/* IDENTICAL to V1. */
|
||||||
|
|
||||||
|
function withdraw(
|
||||||
|
bytes calldata proof,
|
||||||
|
bytes32 depositRoot,
|
||||||
|
bytes32 associationRoot,
|
||||||
|
bytes32 nullifierHash,
|
||||||
|
address recipient,
|
||||||
|
address feeRecipient,
|
||||||
|
uint256 fee,
|
||||||
|
uint256 refund
|
||||||
|
) external nonReentrant {
|
||||||
|
if (spentNullifiers[nullifierHash]) revert AlreadySpent();
|
||||||
|
if (associationRootPublishedAt[associationRoot] == 0) revert UnknownAssociationRoot();
|
||||||
|
if (!isKnownRoot(depositRoot)) revert UnknownDepositRoot();
|
||||||
|
if (fee + refund > DENOMINATION) revert FeeTooLarge();
|
||||||
|
|
||||||
|
uint256[] memory pubs = new uint256[](8);
|
||||||
|
pubs[0] = uint256(POOL_ID);
|
||||||
|
pubs[1] = uint256(depositRoot);
|
||||||
|
pubs[2] = uint256(associationRoot);
|
||||||
|
pubs[3] = uint256(nullifierHash);
|
||||||
|
pubs[4] = uint256(uint160(recipient));
|
||||||
|
pubs[5] = uint256(uint160(feeRecipient));
|
||||||
|
pubs[6] = refund;
|
||||||
|
pubs[7] = fee;
|
||||||
|
|
||||||
|
if (!VERIFIER.verify(proof, pubs)) revert InvalidProof();
|
||||||
|
|
||||||
|
spentNullifiers[nullifierHash] = true;
|
||||||
|
|
||||||
|
uint256 toRecipient = DENOMINATION - fee - refund;
|
||||||
|
if (toRecipient > 0 && !TOKEN.transfer(recipient, toRecipient)) revert TransferFailed();
|
||||||
|
if (fee > 0 && !TOKEN.transfer(feeRecipient, fee)) revert TransferFailed();
|
||||||
|
if (refund > 0 && !TOKEN.transfer(msg.sender, refund)) revert TransferFailed();
|
||||||
|
|
||||||
|
emit Withdrawn(nullifierHash, recipient, feeRecipient, fee, refund, depositRoot, associationRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================= views ================================= */
|
||||||
|
|
||||||
|
function complianceProviders() external view returns (address[] memory) {
|
||||||
|
return complianceProviderList;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAssociationRootValid(bytes32 root) external view returns (bool) {
|
||||||
|
return associationRootPublishedAt[root] != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function latestDepositRoot() external view returns (bytes32) {
|
||||||
|
return roots[currentRootIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereForensicEventRegistry — Forta-style detection bot output
|
||||||
|
* registry for Chain 2800
|
||||||
|
* @notice Open registry where third-party detection bots (mirror of the
|
||||||
|
* Forta Network ecosystem) post structured alerts about
|
||||||
|
* suspicious on-chain activity. Bots register first via
|
||||||
|
* registerBot(); they then submit alert events tagged with a
|
||||||
|
* severity and an alert type. Consumer dApps (lending markets,
|
||||||
|
* settlement venues) query the registry to gate counterparty
|
||||||
|
* actions when a high-severity recent alert flags an address.
|
||||||
|
*
|
||||||
|
* AERE Foundation operates a small initial bot fleet (anomalous-
|
||||||
|
* flow detection, sandwich-tx detection, sanctioned-flow
|
||||||
|
* detection); third-party operators are welcomed via
|
||||||
|
* permissionless self-registration.
|
||||||
|
*
|
||||||
|
* No asset custody. No transaction interception. Read-only audit
|
||||||
|
* surface.
|
||||||
|
*
|
||||||
|
* @dev LISTING + RANKING:
|
||||||
|
* - Each bot has an immutable owner-set stakeRequirement (default
|
||||||
|
* 0 in Phase 1 — purely reputational). Phase 2 (Q2 2027) will
|
||||||
|
* require an AERE bond + Foundation gating for high-severity
|
||||||
|
* alerts.
|
||||||
|
* - Per-bot reputation accrues from confirmed alerts (Foundation
|
||||||
|
* confirms in Phase 1; community-staked in Phase 2).
|
||||||
|
*
|
||||||
|
* ALERT TAXONOMY (initial; bots can extend):
|
||||||
|
* 0 = unknown / catch-all
|
||||||
|
* 1 = sanctioned-flow detected (counterparty matches Sanctions
|
||||||
|
* Registry)
|
||||||
|
* 2 = sandwich-tx / MEV pattern
|
||||||
|
* 3 = anomalous-flow (sudden TVL drain, unusual contract)
|
||||||
|
* 4 = oracle deviation
|
||||||
|
* 5 = bridge exploit pattern
|
||||||
|
* 6 = phishing contract pattern
|
||||||
|
* 7 = governance vote-buying pattern
|
||||||
|
* 8 = honeypot pattern
|
||||||
|
* 9 = rug-pull pattern
|
||||||
|
*
|
||||||
|
* SEVERITY:
|
||||||
|
* 1 = info
|
||||||
|
* 2 = low
|
||||||
|
* 3 = medium
|
||||||
|
* 4 = high
|
||||||
|
* 5 = critical
|
||||||
|
*/
|
||||||
|
contract AereForensicEventRegistry is Ownable {
|
||||||
|
|
||||||
|
struct Bot {
|
||||||
|
bool registered;
|
||||||
|
bool active;
|
||||||
|
address owner;
|
||||||
|
string name;
|
||||||
|
string metadataUri; // ipfs / https pointer to bot metadata
|
||||||
|
uint256 stakeRequirement;
|
||||||
|
uint256 alertCount;
|
||||||
|
uint256 confirmedCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Alert {
|
||||||
|
uint256 botId;
|
||||||
|
address subject; // the address the alert is about
|
||||||
|
uint8 alertType;
|
||||||
|
uint8 severity;
|
||||||
|
uint64 timestamp;
|
||||||
|
string detailUri; // off-chain pointer (e.g. ipfs) with full details
|
||||||
|
bool confirmed; // Foundation confirmation in Phase 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice botId → Bot
|
||||||
|
mapping(uint256 => Bot) public bots;
|
||||||
|
uint256 public nextBotId;
|
||||||
|
|
||||||
|
/// @notice alertId → Alert
|
||||||
|
mapping(uint256 => Alert) public alerts;
|
||||||
|
uint256 public nextAlertId;
|
||||||
|
|
||||||
|
/// @notice subject → recent alert ids (most recent first; capped at
|
||||||
|
/// RECENT_ALERTS_CAP per address by the off-chain indexer).
|
||||||
|
mapping(address => uint256[]) public subjectAlerts;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event BotRegistered(uint256 indexed botId, address indexed owner, string name, string metadataUri);
|
||||||
|
event BotUpdated(uint256 indexed botId, string newMetadataUri, bool active);
|
||||||
|
event AlertEmitted(uint256 indexed alertId, uint256 indexed botId, address indexed subject, uint8 alertType, uint8 severity, string detailUri);
|
||||||
|
event AlertConfirmed(uint256 indexed alertId, uint256 indexed botId);
|
||||||
|
event AlertRejected(uint256 indexed alertId, uint256 indexed botId, string reason);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error NotBotOwner();
|
||||||
|
error UnknownBot();
|
||||||
|
error UnknownAlert();
|
||||||
|
error BotInactive();
|
||||||
|
error ZeroSubject();
|
||||||
|
|
||||||
|
/* ----------------------------- bot registration ------------------------- */
|
||||||
|
|
||||||
|
function registerBot(string calldata name, string calldata metadataUri) external returns (uint256 botId) {
|
||||||
|
botId = nextBotId++;
|
||||||
|
bots[botId] = Bot({
|
||||||
|
registered: true,
|
||||||
|
active: true,
|
||||||
|
owner: msg.sender,
|
||||||
|
name: name,
|
||||||
|
metadataUri: metadataUri,
|
||||||
|
stakeRequirement: 0,
|
||||||
|
alertCount: 0,
|
||||||
|
confirmedCount: 0
|
||||||
|
});
|
||||||
|
emit BotRegistered(botId, msg.sender, name, metadataUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateBot(uint256 botId, string calldata newMetadataUri, bool active) external {
|
||||||
|
Bot storage b = bots[botId];
|
||||||
|
if (!b.registered) revert UnknownBot();
|
||||||
|
if (msg.sender != b.owner) revert NotBotOwner();
|
||||||
|
b.metadataUri = newMetadataUri;
|
||||||
|
b.active = active;
|
||||||
|
emit BotUpdated(botId, newMetadataUri, active);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------- alert emission --------------------------- */
|
||||||
|
|
||||||
|
function emitAlert(
|
||||||
|
uint256 botId,
|
||||||
|
address subject,
|
||||||
|
uint8 alertType,
|
||||||
|
uint8 severity,
|
||||||
|
string calldata detailUri
|
||||||
|
) external returns (uint256 alertId) {
|
||||||
|
Bot storage b = bots[botId];
|
||||||
|
if (!b.registered) revert UnknownBot();
|
||||||
|
if (!b.active) revert BotInactive();
|
||||||
|
if (msg.sender != b.owner) revert NotBotOwner();
|
||||||
|
if (subject == address(0)) revert ZeroSubject();
|
||||||
|
|
||||||
|
alertId = nextAlertId++;
|
||||||
|
alerts[alertId] = Alert({
|
||||||
|
botId: botId,
|
||||||
|
subject: subject,
|
||||||
|
alertType: alertType,
|
||||||
|
severity: severity,
|
||||||
|
timestamp: uint64(block.timestamp),
|
||||||
|
detailUri: detailUri,
|
||||||
|
confirmed: false
|
||||||
|
});
|
||||||
|
subjectAlerts[subject].push(alertId);
|
||||||
|
b.alertCount++;
|
||||||
|
emit AlertEmitted(alertId, botId, subject, alertType, severity, detailUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- confirmation --------------------------- */
|
||||||
|
|
||||||
|
/// @notice Phase 1: Foundation reviews + confirms valid alerts. Phase 2
|
||||||
|
/// replaces with staked-community confirmation.
|
||||||
|
function confirmAlert(uint256 alertId) external onlyOwner {
|
||||||
|
Alert storage a = alerts[alertId];
|
||||||
|
if (a.timestamp == 0) revert UnknownAlert();
|
||||||
|
if (a.confirmed) return;
|
||||||
|
a.confirmed = true;
|
||||||
|
bots[a.botId].confirmedCount++;
|
||||||
|
emit AlertConfirmed(alertId, a.botId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function rejectAlert(uint256 alertId, string calldata reason) external onlyOwner {
|
||||||
|
Alert storage a = alerts[alertId];
|
||||||
|
if (a.timestamp == 0) revert UnknownAlert();
|
||||||
|
emit AlertRejected(alertId, a.botId, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- views ------------------------------ */
|
||||||
|
|
||||||
|
/// @notice ROUND-3 FIX: cap maximum iterations to prevent griefable DoS
|
||||||
|
/// when an attacker spams a target subject with alerts. Consumers
|
||||||
|
/// (lending markets, etc.) that query this view in a transaction
|
||||||
|
/// path would otherwise be reverted by an attacker who emitted
|
||||||
|
/// millions of low-severity alerts against the subject.
|
||||||
|
uint256 public constant MAX_RECENT_ITERATIONS = 256;
|
||||||
|
|
||||||
|
/// @notice Returns the count of CONFIRMED alerts of `minSeverity` or
|
||||||
|
/// higher emitted within the last `windowSeconds` against the
|
||||||
|
/// given subject. Bounded at MAX_RECENT_ITERATIONS — for subjects
|
||||||
|
/// with > 256 recent alerts, only the most-recent 256 are
|
||||||
|
/// counted (still a useful signal; spam pushes older legit
|
||||||
|
/// alerts out of the window).
|
||||||
|
function recentConfirmedAlertCount(
|
||||||
|
address subject,
|
||||||
|
uint8 minSeverity,
|
||||||
|
uint256 windowSeconds
|
||||||
|
) external view returns (uint256 count) {
|
||||||
|
uint256[] storage ids = subjectAlerts[subject];
|
||||||
|
uint256 cutoff = block.timestamp > windowSeconds ? block.timestamp - windowSeconds : 0;
|
||||||
|
uint256 iter = 0;
|
||||||
|
for (uint256 i = ids.length; i > 0 && iter < MAX_RECENT_ITERATIONS; i--) {
|
||||||
|
Alert storage a = alerts[ids[i - 1]];
|
||||||
|
if (a.timestamp < cutoff) break;
|
||||||
|
if (a.confirmed && a.severity >= minSeverity) count++;
|
||||||
|
unchecked { iter++; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function subjectAlertCount(address subject) external view returns (uint256) {
|
||||||
|
return subjectAlerts[subject].length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSanctionsRegistry — read-only OFAC SDN sanctions registry
|
||||||
|
* @notice Foundation publishes a Merkle root of OFAC Specially Designated
|
||||||
|
* Nationals (SDN) addresses each epoch (24h cron). Any consumer
|
||||||
|
* contract can verify whether a specific address is sanctioned at
|
||||||
|
* a given epoch by submitting a Merkle inclusion proof.
|
||||||
|
*
|
||||||
|
* Source of truth: the official OFAC SDN list at
|
||||||
|
* https://www.treasury.gov/ofac/downloads/sdnlist.txt
|
||||||
|
* An off-chain ingester running on a Hostinger VPS (#2) reads the
|
||||||
|
* official list nightly, extracts crypto addresses where present,
|
||||||
|
* builds the Merkle tree, and publishes the root via the
|
||||||
|
* Foundation 2-of-3 multisig (Ledger-signed).
|
||||||
|
*
|
||||||
|
* Designed as a PUBLIC GOOD. Anyone — institutional integrator,
|
||||||
|
* dApp, EOA — calls `isSanctioned(...)` to gate or screen a
|
||||||
|
* counterparty. There is no fee. No discretionary interception.
|
||||||
|
*
|
||||||
|
* @dev Lifecycle: Proposed → (Challenged?) → Attested (mirror of
|
||||||
|
* AereNavOracle pattern). Optimistic 24h window.
|
||||||
|
*
|
||||||
|
* Leaf format: keccak256(abi.encode(address evmAddress, uint16 listId))
|
||||||
|
* where listId distinguishes the source list (1 = OFAC SDN,
|
||||||
|
* 2 = OFAC SSI, 3 = EU consolidated, etc.). Phase 1 ships with
|
||||||
|
* OFAC SDN only.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - CHALLENGE_WINDOW constant
|
||||||
|
* - History append-only; attested epochs cannot be rewritten
|
||||||
|
* - Owner can only propose / dismiss / attest
|
||||||
|
* - There is NO "deSanction" path on chain — that would suggest
|
||||||
|
* AERE Foundation is making a sanctions decision, which it is
|
||||||
|
* NOT. The Foundation only mirrors the canonical OFAC list.
|
||||||
|
*/
|
||||||
|
contract AereSanctionsRegistry is Ownable {
|
||||||
|
|
||||||
|
uint256 public constant CHALLENGE_WINDOW = 24 hours;
|
||||||
|
|
||||||
|
/// @notice OFAC SDN list id, used as the prefix in the leaf hash.
|
||||||
|
uint16 public constant LIST_OFAC_SDN = 1;
|
||||||
|
uint16 public constant LIST_OFAC_SSI = 2;
|
||||||
|
uint16 public constant LIST_EU_CONSOLIDATED = 3;
|
||||||
|
uint16 public constant LIST_UK_HMT = 4;
|
||||||
|
uint16 public constant LIST_UN_CONSOLIDATED = 5;
|
||||||
|
|
||||||
|
enum State { Proposed, Challenged, Attested }
|
||||||
|
|
||||||
|
struct Snapshot {
|
||||||
|
bytes32 root;
|
||||||
|
uint64 proposedAt;
|
||||||
|
uint64 attestedAt;
|
||||||
|
State state;
|
||||||
|
string sourceUrl; // canonical OFAC URL the root was built from
|
||||||
|
string ipfsCid; // optional: pin the full list
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice epoch → Snapshot
|
||||||
|
mapping(uint256 => Snapshot) public snapshots;
|
||||||
|
|
||||||
|
/// @notice epoch → open-challenge count
|
||||||
|
mapping(uint256 => uint256) public openChallenges;
|
||||||
|
mapping(uint256 => Challenge[]) public epochChallenges;
|
||||||
|
|
||||||
|
struct Challenge {
|
||||||
|
address challenger;
|
||||||
|
uint64 timestamp;
|
||||||
|
string reason;
|
||||||
|
bool dismissed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice monotonic latest epoch counter.
|
||||||
|
uint256 public latestEpoch;
|
||||||
|
|
||||||
|
event SnapshotProposed(uint256 indexed epoch, bytes32 root, string sourceUrl, string ipfsCid);
|
||||||
|
event SnapshotChallenged(uint256 indexed epoch, uint256 challengeId, address challenger, string reason);
|
||||||
|
event ChallengeDismissed(uint256 indexed epoch, uint256 challengeId, string response);
|
||||||
|
event SnapshotAttested(uint256 indexed epoch, bytes32 root);
|
||||||
|
|
||||||
|
error WrongState(State got, State want);
|
||||||
|
error UnknownEpoch();
|
||||||
|
error UnknownChallenge();
|
||||||
|
error EpochAlreadyExists();
|
||||||
|
error TimelockNotElapsed(uint256 nowTs, uint256 earliest);
|
||||||
|
|
||||||
|
/* -------------------------------- propose -------------------------------- */
|
||||||
|
|
||||||
|
function proposeSnapshot(
|
||||||
|
uint256 epoch,
|
||||||
|
bytes32 root,
|
||||||
|
string calldata sourceUrl,
|
||||||
|
string calldata ipfsCid
|
||||||
|
) external onlyOwner {
|
||||||
|
if (snapshots[epoch].proposedAt != 0) revert EpochAlreadyExists();
|
||||||
|
snapshots[epoch] = Snapshot({
|
||||||
|
root: root,
|
||||||
|
proposedAt: uint64(block.timestamp),
|
||||||
|
attestedAt: 0,
|
||||||
|
state: State.Proposed,
|
||||||
|
sourceUrl: sourceUrl,
|
||||||
|
ipfsCid: ipfsCid
|
||||||
|
});
|
||||||
|
if (epoch > latestEpoch) latestEpoch = epoch;
|
||||||
|
emit SnapshotProposed(epoch, root, sourceUrl, ipfsCid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- challenge ------------------------------ */
|
||||||
|
|
||||||
|
function challenge(uint256 epoch, string calldata reason) external returns (uint256 challengeId) {
|
||||||
|
Snapshot storage s = snapshots[epoch];
|
||||||
|
if (s.proposedAt == 0) revert UnknownEpoch();
|
||||||
|
if (s.state != State.Proposed && s.state != State.Challenged) revert WrongState(s.state, State.Proposed);
|
||||||
|
if (block.timestamp >= uint256(s.proposedAt) + CHALLENGE_WINDOW) {
|
||||||
|
revert TimelockNotElapsed(block.timestamp, uint256(s.proposedAt) + CHALLENGE_WINDOW);
|
||||||
|
}
|
||||||
|
challengeId = epochChallenges[epoch].length;
|
||||||
|
epochChallenges[epoch].push(Challenge({
|
||||||
|
challenger: msg.sender,
|
||||||
|
timestamp: uint64(block.timestamp),
|
||||||
|
reason: reason,
|
||||||
|
dismissed: false
|
||||||
|
}));
|
||||||
|
openChallenges[epoch]++;
|
||||||
|
s.state = State.Challenged;
|
||||||
|
emit SnapshotChallenged(epoch, challengeId, msg.sender, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dismissChallenge(uint256 epoch, uint256 challengeId, string calldata response) external onlyOwner {
|
||||||
|
Challenge[] storage list = epochChallenges[epoch];
|
||||||
|
if (challengeId >= list.length) revert UnknownChallenge();
|
||||||
|
Challenge storage c = list[challengeId];
|
||||||
|
if (c.dismissed) revert UnknownChallenge();
|
||||||
|
c.dismissed = true;
|
||||||
|
openChallenges[epoch]--;
|
||||||
|
if (openChallenges[epoch] == 0) snapshots[epoch].state = State.Proposed;
|
||||||
|
emit ChallengeDismissed(epoch, challengeId, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- attestation ---------------------------- */
|
||||||
|
|
||||||
|
function attest(uint256 epoch) external {
|
||||||
|
Snapshot storage s = snapshots[epoch];
|
||||||
|
if (s.proposedAt == 0) revert UnknownEpoch();
|
||||||
|
if (s.state != State.Proposed) revert WrongState(s.state, State.Proposed);
|
||||||
|
uint256 earliest = uint256(s.proposedAt) + CHALLENGE_WINDOW;
|
||||||
|
if (block.timestamp < earliest) revert TimelockNotElapsed(block.timestamp, earliest);
|
||||||
|
if (openChallenges[epoch] != 0) revert WrongState(State.Challenged, State.Proposed);
|
||||||
|
s.state = State.Attested;
|
||||||
|
s.attestedAt = uint64(block.timestamp);
|
||||||
|
emit SnapshotAttested(epoch, s.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- verify -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Verify that `evmAddress` was on `listId` at `epoch`.
|
||||||
|
/// @return sanctioned True if the proof is valid AND the snapshot is attested.
|
||||||
|
function isSanctioned(
|
||||||
|
uint256 epoch,
|
||||||
|
address evmAddress,
|
||||||
|
uint16 listId,
|
||||||
|
bytes32[] calldata proof
|
||||||
|
) external view returns (bool sanctioned) {
|
||||||
|
Snapshot storage s = snapshots[epoch];
|
||||||
|
if (s.state != State.Attested) return false;
|
||||||
|
bytes32 leaf = keccak256(abi.encode(evmAddress, listId));
|
||||||
|
return MerkleProof.verify(proof, s.root, leaf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice ROUND-3 FIX: cap iteration depth to prevent griefable DoS.
|
||||||
|
/// If Foundation proposes 1000 challenged-but-never-attested
|
||||||
|
/// snapshots, dApps calling this in-tx would have been bricked.
|
||||||
|
/// Now capped at 64 — practically: the latest 64 epochs.
|
||||||
|
uint256 public constant MAX_EPOCH_SCAN = 64;
|
||||||
|
|
||||||
|
/// @notice Same shape as isSanctioned but takes only the latest attested epoch.
|
||||||
|
function isSanctionedLatest(
|
||||||
|
address evmAddress,
|
||||||
|
uint16 listId,
|
||||||
|
bytes32[] calldata proof
|
||||||
|
) external view returns (bool sanctioned, uint256 attestedEpoch) {
|
||||||
|
uint256 scanned = 0;
|
||||||
|
for (uint256 e = latestEpoch; e > 0 && scanned < MAX_EPOCH_SCAN; e--) {
|
||||||
|
Snapshot storage s = snapshots[e];
|
||||||
|
if (s.state == State.Attested) {
|
||||||
|
bytes32 leaf = keccak256(abi.encode(evmAddress, listId));
|
||||||
|
return (MerkleProof.verify(proof, s.root, leaf), e);
|
||||||
|
}
|
||||||
|
unchecked { scanned++; }
|
||||||
|
}
|
||||||
|
return (false, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshotStatus(uint256 epoch) external view returns (
|
||||||
|
bytes32 root,
|
||||||
|
uint64 proposedAt,
|
||||||
|
uint64 attestedAt,
|
||||||
|
State state,
|
||||||
|
uint256 openChallengeCount,
|
||||||
|
string memory sourceUrl,
|
||||||
|
string memory ipfsCid
|
||||||
|
) {
|
||||||
|
Snapshot storage s = snapshots[epoch];
|
||||||
|
return (s.root, s.proposedAt, s.attestedAt, s.state, openChallenges[epoch], s.sourceUrl, s.ipfsCid);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereTravelRuleHashRegistry — on-chain anchor for FATF Travel Rule
|
||||||
|
* message exchanges (Notabene-compatible)
|
||||||
|
* @notice The FATF Travel Rule requires VASPs to exchange identity payloads
|
||||||
|
* for transfers above a jurisdiction-set threshold (typically
|
||||||
|
* USD 1,000 for the US, EUR 1,000 for the EU MiCA regime). The
|
||||||
|
* payloads themselves are confidential and exchanged off-chain via
|
||||||
|
* a message bus like Notabene IVMS-101.
|
||||||
|
*
|
||||||
|
* This contract is the on-chain ANCHOR for the off-chain exchange.
|
||||||
|
* The originating VASP commits a keccak256 hash of the IVMS-101
|
||||||
|
* payload before the transaction goes through, and the beneficiary
|
||||||
|
* VASP later verifies that hash matches what was exchanged. The
|
||||||
|
* on-chain anchor:
|
||||||
|
* 1. Proves the payload existed at a specific block.
|
||||||
|
* 2. Cannot be retroactively altered (commitments are
|
||||||
|
* append-only).
|
||||||
|
* 3. Is auditable by regulators without revealing the payload.
|
||||||
|
*
|
||||||
|
* No payload data is stored on chain. No identity is revealed.
|
||||||
|
*
|
||||||
|
* @dev PHASE 1 — minimal viable Travel Rule anchor.
|
||||||
|
* - `commit(payloadHash, beneficiaryVasp, threshold)` permissionless
|
||||||
|
* callable by the originator VASP. The VASP self-identifies via
|
||||||
|
* the msg.sender; consumers can query "did VASP X commit to a
|
||||||
|
* payload referencing this txid?" via the events index.
|
||||||
|
* - `acknowledge(commitmentId)` callable by the beneficiary VASP
|
||||||
|
* to mark receipt + verification of the off-chain payload.
|
||||||
|
* - `dispute(commitmentId, reason)` callable by the beneficiary
|
||||||
|
* if the payload doesn't match the on-chain hash.
|
||||||
|
*
|
||||||
|
* NO admin. NO Foundation interception. NO custody.
|
||||||
|
*
|
||||||
|
* INTEGRATIONS:
|
||||||
|
* - Notabene SDK: the JS SDK on each VASP calls
|
||||||
|
* contract.commit(hash, recipientVasp, threshold) automatically
|
||||||
|
* when the user initiates a > $1k transfer.
|
||||||
|
* - Compliance dashboards: index Commitments + Acknowledgements
|
||||||
|
* + Disputes by VASP address for audit trail.
|
||||||
|
*
|
||||||
|
* AERE Foundation Seychelles is registered as a VASP and uses this
|
||||||
|
* registry for its own institutional flows (e.g. via the
|
||||||
|
* SettlementHub for BUIDL/USDY/OUSG receipts).
|
||||||
|
*/
|
||||||
|
contract AereTravelRuleHashRegistry {
|
||||||
|
|
||||||
|
enum State { Committed, Acknowledged, Disputed }
|
||||||
|
|
||||||
|
struct Commitment {
|
||||||
|
bytes32 payloadHash;
|
||||||
|
address originatorVasp;
|
||||||
|
address beneficiaryVasp;
|
||||||
|
uint256 threshold; // jurisdiction threshold in USD units (cents)
|
||||||
|
uint64 committedAt;
|
||||||
|
uint64 statusUpdatedAt;
|
||||||
|
State state;
|
||||||
|
string disputeReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice commitmentId → Commitment
|
||||||
|
mapping(uint256 => Commitment) public commitments;
|
||||||
|
uint256 public nextCommitmentId;
|
||||||
|
|
||||||
|
/// @notice Per-VASP commitment index (for audit retrieval).
|
||||||
|
mapping(address => uint256[]) public vaspCommitments;
|
||||||
|
|
||||||
|
event Committed(uint256 indexed id, address indexed originator, address indexed beneficiary, bytes32 payloadHash, uint256 threshold);
|
||||||
|
event Acknowledged(uint256 indexed id, address indexed beneficiary);
|
||||||
|
event Disputed(uint256 indexed id, address indexed beneficiary, string reason);
|
||||||
|
|
||||||
|
error UnknownCommitment();
|
||||||
|
error NotBeneficiary();
|
||||||
|
error AlreadyAcknowledged();
|
||||||
|
error AlreadyDisputed();
|
||||||
|
error ZeroAddress();
|
||||||
|
|
||||||
|
function commit(bytes32 payloadHash, address beneficiaryVasp, uint256 threshold)
|
||||||
|
external
|
||||||
|
returns (uint256 id)
|
||||||
|
{
|
||||||
|
if (beneficiaryVasp == address(0)) revert ZeroAddress();
|
||||||
|
id = nextCommitmentId++;
|
||||||
|
commitments[id] = Commitment({
|
||||||
|
payloadHash: payloadHash,
|
||||||
|
originatorVasp: msg.sender,
|
||||||
|
beneficiaryVasp: beneficiaryVasp,
|
||||||
|
threshold: threshold,
|
||||||
|
committedAt: uint64(block.timestamp),
|
||||||
|
statusUpdatedAt: uint64(block.timestamp),
|
||||||
|
state: State.Committed,
|
||||||
|
disputeReason: ""
|
||||||
|
});
|
||||||
|
vaspCommitments[msg.sender].push(id);
|
||||||
|
vaspCommitments[beneficiaryVasp].push(id);
|
||||||
|
emit Committed(id, msg.sender, beneficiaryVasp, payloadHash, threshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
function acknowledge(uint256 id) external {
|
||||||
|
Commitment storage c = commitments[id];
|
||||||
|
if (c.committedAt == 0) revert UnknownCommitment();
|
||||||
|
if (msg.sender != c.beneficiaryVasp) revert NotBeneficiary();
|
||||||
|
if (c.state == State.Acknowledged) revert AlreadyAcknowledged();
|
||||||
|
if (c.state == State.Disputed) revert AlreadyDisputed();
|
||||||
|
c.state = State.Acknowledged;
|
||||||
|
c.statusUpdatedAt = uint64(block.timestamp);
|
||||||
|
emit Acknowledged(id, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispute(uint256 id, string calldata reason) external {
|
||||||
|
Commitment storage c = commitments[id];
|
||||||
|
if (c.committedAt == 0) revert UnknownCommitment();
|
||||||
|
if (msg.sender != c.beneficiaryVasp) revert NotBeneficiary();
|
||||||
|
if (c.state == State.Disputed) revert AlreadyDisputed();
|
||||||
|
c.state = State.Disputed;
|
||||||
|
c.disputeReason = reason;
|
||||||
|
c.statusUpdatedAt = uint64(block.timestamp);
|
||||||
|
emit Disputed(id, msg.sender, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- views ---------------------------------- */
|
||||||
|
|
||||||
|
function vaspCommitmentCount(address vasp) external view returns (uint256) {
|
||||||
|
return vaspCommitments[vasp].length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/// @dev The subset of the LIVE, deployed AerePQCKeyRegistry (chain 2800, 0x1eCa...3691) this registry
|
||||||
|
/// uses to verify an issuer's POST-QUANTUM attestation. verifyWithKey routes to the live native
|
||||||
|
/// precompile for the key's scheme (0x0AE1 Falcon-512) and verifies the signature IN FULL
|
||||||
|
/// on-chain, fail-closed.
|
||||||
|
interface IAerePQCKeyRegistryTrust {
|
||||||
|
function verifyWithKey(uint256 keyId, bytes32 message, bytes calldata signature) external view returns (bool);
|
||||||
|
function statusOf(uint256 keyId) external view returns (uint8);
|
||||||
|
function schemeOf(uint256 keyId) external view returns (uint8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereTrustRegistry, a federated registry of ACCREDITED credential issuers for Aere Network
|
||||||
|
*
|
||||||
|
* @notice The trust root for Aere's institution-grade compliance passport. Compliance trust is NOT
|
||||||
|
* a single Foundation key: it is a FEDERATED SET of accredited issuers, each authorized to
|
||||||
|
* issue a defined set of credential types. This mirrors, in spirit, the eIDAS 2.0 / EUDI
|
||||||
|
* "trusted list" model, in which a supervisory body maintains a machine-readable list of
|
||||||
|
* qualified trust service providers and the services they are accredited for. Here the Aere
|
||||||
|
* Foundation is the trusted-list operator (the registry owner); each entry is an accredited
|
||||||
|
* issuer with a DID, an accreditation SCOPE (the credential types it may issue), a lifecycle
|
||||||
|
* STATUS, and an OPTIONAL post-quantum (Falcon-512) key reference so the issuer's attestations
|
||||||
|
* can be PQC-signed and verified on-chain via the live precompile 0x0AE1.
|
||||||
|
*
|
||||||
|
* WHY POST-QUANTUM. Every accreditation stack in production today authenticates an issuer's
|
||||||
|
* attestation with a classical ECDSA / RSA signature, which a cryptographically relevant
|
||||||
|
* quantum computer forges. An Aere issuer additionally binds a Falcon-512 key here, so its
|
||||||
|
* attestations are verified with a NIST post-quantum signature scheme in full on-chain. That
|
||||||
|
* is the differentiator this registry exists to carry.
|
||||||
|
*
|
||||||
|
* DESIGN PRINCIPLES.
|
||||||
|
* - FAIL-CLOSED. An unknown issuer, a suspended or revoked issuer, or a credential type
|
||||||
|
* outside an issuer's scope all resolve to NOT accredited. isAccredited never returns a
|
||||||
|
* false positive.
|
||||||
|
* - APPEND-ONLY HISTORY, NO SILENT REWRITE. Every status transition and every scope change
|
||||||
|
* is pushed to an append-only history. The current status is a pointer; the record of how
|
||||||
|
* it got there is immutable and fully auditable.
|
||||||
|
* - TERMINAL REVOCATION. Accreditation revocation is terminal (a revoked issuer can never
|
||||||
|
* be reinstated). Suspension is reversible.
|
||||||
|
*
|
||||||
|
* @dev HONEST SCOPE. This is application-layer compliance tooling. It changes NOTHING about Aere
|
||||||
|
* consensus, which stays classical secp256k1 ECDSA QBFT. What is post-quantum here is the
|
||||||
|
* AUTHENTICITY of an issuer attestation, verified by the live precompile. This contract holds
|
||||||
|
* no funds. Whether any REAL institution is accredited, and whether such accreditation carries
|
||||||
|
* legal weight under eIDAS 2.0, is a partnership / regulatory matter that is external to this
|
||||||
|
* code and is NOT asserted by deploying it.
|
||||||
|
*
|
||||||
|
* @dev No PII on chain. An issuer entry stores a DID (a public identifier, not personal data) and
|
||||||
|
* opaque bytes32 credential-type tags. Reason codes on status transitions are opaque bytes32.
|
||||||
|
*/
|
||||||
|
contract AereTrustRegistry is Ownable {
|
||||||
|
/// @notice Falcon-512 scheme id in AerePQCKeyRegistry (live precompile 0x0AE1).
|
||||||
|
uint8 public constant SCHEME_FALCON512 = 1;
|
||||||
|
/// @notice AerePQCKeyRegistry.STATUS_ACTIVE (only an ACTIVE key is a current key).
|
||||||
|
uint8 internal constant KEY_STATUS_ACTIVE = 1;
|
||||||
|
/// @notice Sentinel for "no post-quantum key linked to this issuer".
|
||||||
|
uint256 public constant NO_KEY = type(uint256).max;
|
||||||
|
|
||||||
|
/// @notice Issuer accreditation lifecycle. None=never accredited; Active=may issue in scope;
|
||||||
|
/// Suspended=temporarily halted (reversible); Revoked=terminal.
|
||||||
|
enum Status {
|
||||||
|
None,
|
||||||
|
Active,
|
||||||
|
Suspended,
|
||||||
|
Revoked
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The LIVE AerePQCKeyRegistry used to verify an issuer's Falcon-512 attestations.
|
||||||
|
IAerePQCKeyRegistryTrust public immutable KEY_REGISTRY;
|
||||||
|
|
||||||
|
struct Issuer {
|
||||||
|
address controller; // the issuer id / controlling address
|
||||||
|
Status status; // current lifecycle status (history is append-only, see below)
|
||||||
|
uint256 pqcKeyId; // Falcon-512 keyId in KEY_REGISTRY, or NO_KEY
|
||||||
|
uint64 accreditedAt; // block timestamp of first accreditation
|
||||||
|
string did; // the issuer's did:aere DID (public identifier, not PII)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice One append-only record per status transition. No entry is ever rewritten.
|
||||||
|
struct StatusEvent {
|
||||||
|
Status status;
|
||||||
|
uint64 blockNumber;
|
||||||
|
uint64 timestamp;
|
||||||
|
bytes32 reason; // opaque reason code (e.g. keccak256("audit-lapsed")); never PII
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice One append-only record per scope change.
|
||||||
|
struct ScopeEvent {
|
||||||
|
bytes32 credentialType;
|
||||||
|
bool granted; // true = granted, false = removed
|
||||||
|
uint64 timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// issuerId is the index into _issuers. Index 0 is a reserved placeholder so issuerIdByAddress's
|
||||||
|
// default 0 unambiguously means "no such issuer"; real issuers have issuerId >= 1.
|
||||||
|
Issuer[] private _issuers;
|
||||||
|
mapping(address => uint256) public issuerIdByAddress; // controller => issuerId (0 = none)
|
||||||
|
mapping(uint256 => mapping(bytes32 => bool)) private _inScope; // issuerId => credentialType => granted
|
||||||
|
mapping(uint256 => bytes32[]) private _scopeList; // issuerId => append-only granted-type list (may repeat across grant/revoke cycles)
|
||||||
|
mapping(uint256 => StatusEvent[]) private _statusHistory; // issuerId => append-only status log
|
||||||
|
mapping(uint256 => ScopeEvent[]) private _scopeHistory; // issuerId => append-only scope log
|
||||||
|
|
||||||
|
event IssuerAccredited(uint256 indexed issuerId, address indexed controller, string did, uint256 pqcKeyId);
|
||||||
|
event IssuerStatusChanged(uint256 indexed issuerId, Status indexed oldStatus, Status indexed newStatus, bytes32 reason);
|
||||||
|
event IssuerScopeChanged(uint256 indexed issuerId, bytes32 indexed credentialType, bool granted);
|
||||||
|
event IssuerPqcKeySet(uint256 indexed issuerId, uint256 oldKeyId, uint256 newKeyId);
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error EmptyDid();
|
||||||
|
error AlreadyAccredited(address controller);
|
||||||
|
error UnknownIssuer(uint256 issuerId);
|
||||||
|
error NotActive(uint256 issuerId);
|
||||||
|
error NotSuspended(uint256 issuerId);
|
||||||
|
error AlreadyRevoked(uint256 issuerId);
|
||||||
|
error PqcKeyNotActiveFalcon(uint256 keyId);
|
||||||
|
error ScopeAlreadyGranted(uint256 issuerId, bytes32 credentialType);
|
||||||
|
error ScopeNotGranted(uint256 issuerId, bytes32 credentialType);
|
||||||
|
|
||||||
|
constructor(address keyRegistry_) {
|
||||||
|
if (keyRegistry_ == address(0)) revert ZeroAddress();
|
||||||
|
KEY_REGISTRY = IAerePQCKeyRegistryTrust(keyRegistry_);
|
||||||
|
// Reserve index 0 as an inert placeholder so issuerId 0 is never a real issuer.
|
||||||
|
_issuers.push(Issuer({controller: address(0), status: Status.None, pqcKeyId: NO_KEY, accreditedAt: 0, did: ""}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Accreditation (owner)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Accredit a new issuer with an initial scope and an optional Falcon-512 key reference.
|
||||||
|
* Owner-only (the Foundation as trusted-list operator). The controller address is the
|
||||||
|
* issuer id and the party that controls the linked credential-issuing keys.
|
||||||
|
* @param controller the issuer's controlling address (also its issuer id / address).
|
||||||
|
* @param did the issuer's did:aere DID (public identifier; not validated for full DID
|
||||||
|
* syntax here, that is an off-chain concern, see [VERIFY] in the docs).
|
||||||
|
* @param scopes the credential types this issuer may issue (opaque bytes32 tags).
|
||||||
|
* @param pqcKeyId a Falcon-512 keyId in KEY_REGISTRY, or NO_KEY for no post-quantum key.
|
||||||
|
* @return issuerId the assigned issuer id (>= 1).
|
||||||
|
*/
|
||||||
|
function accreditIssuer(address controller, string calldata did, bytes32[] calldata scopes, uint256 pqcKeyId)
|
||||||
|
external
|
||||||
|
onlyOwner
|
||||||
|
returns (uint256 issuerId)
|
||||||
|
{
|
||||||
|
if (controller == address(0)) revert ZeroAddress();
|
||||||
|
if (bytes(did).length == 0) revert EmptyDid();
|
||||||
|
if (issuerIdByAddress[controller] != 0) revert AlreadyAccredited(controller);
|
||||||
|
if (pqcKeyId != NO_KEY) _requireActiveFalconKey(pqcKeyId);
|
||||||
|
|
||||||
|
issuerId = _issuers.length;
|
||||||
|
_issuers.push(
|
||||||
|
Issuer({
|
||||||
|
controller: controller,
|
||||||
|
status: Status.Active,
|
||||||
|
pqcKeyId: pqcKeyId,
|
||||||
|
accreditedAt: uint64(block.timestamp),
|
||||||
|
did: did
|
||||||
|
})
|
||||||
|
);
|
||||||
|
issuerIdByAddress[controller] = issuerId;
|
||||||
|
|
||||||
|
for (uint256 i = 0; i < scopes.length; i++) {
|
||||||
|
_grantScope(issuerId, scopes[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
_statusHistory[issuerId].push(
|
||||||
|
StatusEvent({status: Status.Active, blockNumber: uint64(block.number), timestamp: uint64(block.timestamp), reason: bytes32(0)})
|
||||||
|
);
|
||||||
|
|
||||||
|
emit IssuerAccredited(issuerId, controller, did, pqcKeyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Grant an additional credential type to an issuer's accreditation scope (owner-only).
|
||||||
|
function grantScope(uint256 issuerId, bytes32 credentialType) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
_grantScope(issuerId, credentialType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Remove a credential type from an issuer's scope (owner-only). Append-only history keeps
|
||||||
|
/// the record of the grant and the removal; the current scope simply no longer includes it.
|
||||||
|
function revokeScope(uint256 issuerId, bytes32 credentialType) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
if (!_inScope[issuerId][credentialType]) revert ScopeNotGranted(issuerId, credentialType);
|
||||||
|
_inScope[issuerId][credentialType] = false;
|
||||||
|
_scopeHistory[issuerId].push(ScopeEvent({credentialType: credentialType, granted: false, timestamp: uint64(block.timestamp)}));
|
||||||
|
emit IssuerScopeChanged(issuerId, credentialType, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Suspend an active issuer (reversible). All its credentials fail verification until
|
||||||
|
/// reinstated (fail-closed). Owner-only.
|
||||||
|
function suspendIssuer(uint256 issuerId, bytes32 reason) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
if (_issuers[issuerId].status != Status.Active) revert NotActive(issuerId);
|
||||||
|
_transition(issuerId, Status.Suspended, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Reinstate a suspended issuer to Active (owner-only).
|
||||||
|
function reinstateIssuer(uint256 issuerId, bytes32 reason) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
if (_issuers[issuerId].status != Status.Suspended) revert NotSuspended(issuerId);
|
||||||
|
_transition(issuerId, Status.Active, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Permanently revoke an issuer's accreditation (terminal, not reversible). Owner-only.
|
||||||
|
function revokeIssuer(uint256 issuerId, bytes32 reason) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
if (_issuers[issuerId].status == Status.Revoked) revert AlreadyRevoked(issuerId);
|
||||||
|
_transition(issuerId, Status.Revoked, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Set or clear an issuer's Falcon-512 key reference (owner-only). Pass NO_KEY to clear.
|
||||||
|
function setIssuerPqcKey(uint256 issuerId, uint256 pqcKeyId) external onlyOwner {
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
if (pqcKeyId != NO_KEY) _requireActiveFalconKey(pqcKeyId);
|
||||||
|
uint256 old = _issuers[issuerId].pqcKeyId;
|
||||||
|
_issuers[issuerId].pqcKeyId = pqcKeyId;
|
||||||
|
emit IssuerPqcKeySet(issuerId, old, pqcKeyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Accreditation + PQC verification (views)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice True iff `issuerId` is ACTIVE and `credentialType` is currently in its scope.
|
||||||
|
/// Fail-closed for unknown / suspended / revoked issuers and out-of-scope types.
|
||||||
|
function isAccredited(uint256 issuerId, bytes32 credentialType) external view returns (bool) {
|
||||||
|
if (issuerId == 0 || issuerId >= _issuers.length) return false;
|
||||||
|
if (_issuers[issuerId].status != Status.Active) return false;
|
||||||
|
return _inScope[issuerId][credentialType];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Verify a POST-QUANTUM (Falcon-512) attestation by an issuer over a 32-byte message,
|
||||||
|
* via the live precompile 0x0AE1 through the AerePQCKeyRegistry. Fail-closed: returns
|
||||||
|
* false (never reverts) if the issuer is not Active, has no linked Falcon key, the key is
|
||||||
|
* not an ACTIVE Falcon-512 key, or the signature is invalid / tampered.
|
||||||
|
* @param issuerId the accredited issuer.
|
||||||
|
* @param message the 32-byte message the issuer's Falcon key signed.
|
||||||
|
* @param signature the Falcon-512 signature envelope (nonce(40) || esig).
|
||||||
|
*/
|
||||||
|
function verifyIssuerSignature(uint256 issuerId, bytes32 message, bytes calldata signature)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool)
|
||||||
|
{
|
||||||
|
if (issuerId == 0 || issuerId >= _issuers.length) return false;
|
||||||
|
Issuer storage iss = _issuers[issuerId];
|
||||||
|
if (iss.status != Status.Active) return false;
|
||||||
|
uint256 keyId = iss.pqcKeyId;
|
||||||
|
if (keyId == NO_KEY) return false;
|
||||||
|
if (KEY_REGISTRY.statusOf(keyId) != KEY_STATUS_ACTIVE) return false;
|
||||||
|
if (KEY_REGISTRY.schemeOf(keyId) != SCHEME_FALCON512) return false;
|
||||||
|
return KEY_REGISTRY.verifyWithKey(keyId, message, signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Reads
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Number of issuer ids ever assigned (issuerId runs 1..issuerCount, id 0 is reserved).
|
||||||
|
function issuerCount() external view returns (uint256) {
|
||||||
|
return _issuers.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The current lifecycle status of an issuer (Status.None for an unknown id).
|
||||||
|
function issuerStatus(uint256 issuerId) external view returns (Status) {
|
||||||
|
if (issuerId == 0 || issuerId >= _issuers.length) return Status.None;
|
||||||
|
return _issuers[issuerId].status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read an issuer entry. Reverts on an unknown id.
|
||||||
|
function getIssuer(uint256 issuerId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (address controller, Status status, uint256 pqcKeyId, uint64 accreditedAt, string memory did)
|
||||||
|
{
|
||||||
|
_requireIssuer(issuerId);
|
||||||
|
Issuer storage iss = _issuers[issuerId];
|
||||||
|
return (iss.controller, iss.status, iss.pqcKeyId, iss.accreditedAt, iss.did);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The Falcon-512 keyId linked to an issuer (NO_KEY if none / unknown issuer).
|
||||||
|
function pqcKeyOf(uint256 issuerId) external view returns (uint256) {
|
||||||
|
if (issuerId == 0 || issuerId >= _issuers.length) return NO_KEY;
|
||||||
|
return _issuers[issuerId].pqcKeyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The append-only status-history length for an issuer.
|
||||||
|
function statusHistoryLength(uint256 issuerId) external view returns (uint256) {
|
||||||
|
return _statusHistory[issuerId].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read one append-only status-history entry.
|
||||||
|
function statusHistoryAt(uint256 issuerId, uint256 index) external view returns (StatusEvent memory) {
|
||||||
|
return _statusHistory[issuerId][index];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The append-only scope-history length for an issuer.
|
||||||
|
function scopeHistoryLength(uint256 issuerId) external view returns (uint256) {
|
||||||
|
return _scopeHistory[issuerId].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read one append-only scope-history entry.
|
||||||
|
function scopeHistoryAt(uint256 issuerId, uint256 index) external view returns (ScopeEvent memory) {
|
||||||
|
return _scopeHistory[issuerId][index];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
function _requireIssuer(uint256 issuerId) internal view {
|
||||||
|
if (issuerId == 0 || issuerId >= _issuers.length) revert UnknownIssuer(issuerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _requireActiveFalconKey(uint256 keyId) internal view {
|
||||||
|
if (KEY_REGISTRY.statusOf(keyId) != KEY_STATUS_ACTIVE || KEY_REGISTRY.schemeOf(keyId) != SCHEME_FALCON512) {
|
||||||
|
revert PqcKeyNotActiveFalcon(keyId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _grantScope(uint256 issuerId, bytes32 credentialType) internal {
|
||||||
|
if (_inScope[issuerId][credentialType]) revert ScopeAlreadyGranted(issuerId, credentialType);
|
||||||
|
_inScope[issuerId][credentialType] = true;
|
||||||
|
_scopeList[issuerId].push(credentialType);
|
||||||
|
_scopeHistory[issuerId].push(ScopeEvent({credentialType: credentialType, granted: true, timestamp: uint64(block.timestamp)}));
|
||||||
|
emit IssuerScopeChanged(issuerId, credentialType, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _transition(uint256 issuerId, Status newStatus, bytes32 reason) internal {
|
||||||
|
Status old = _issuers[issuerId].status;
|
||||||
|
_issuers[issuerId].status = newStatus;
|
||||||
|
_statusHistory[issuerId].push(
|
||||||
|
StatusEvent({status: newStatus, blockNumber: uint64(block.number), timestamp: uint64(block.timestamp), reason: reason})
|
||||||
|
);
|
||||||
|
emit IssuerStatusChanged(issuerId, old, newStatus, reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/// @dev The AereTrustRegistry surface this contract relies on: accreditation lookups and the
|
||||||
|
/// POST-QUANTUM issuer signature verification (which routes to the live precompile 0x0AE1).
|
||||||
|
interface IAereTrustRegistryVC {
|
||||||
|
function isAccredited(uint256 issuerId, bytes32 credentialType) external view returns (bool);
|
||||||
|
function issuerStatus(uint256 issuerId) external view returns (uint8); // AereTrustRegistry.Status
|
||||||
|
function verifyIssuerSignature(uint256 issuerId, bytes32 message, bytes calldata signature)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev The AereBitstringStatusList surface used for the not-revoked check.
|
||||||
|
interface IAereStatusListVC {
|
||||||
|
function statusOf(uint256 listId, uint256 index) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereVerifiableCredential, a W3C Verifiable Credentials 2.0 style on-chain anchor + verifier
|
||||||
|
*
|
||||||
|
* @notice Anchors and verifies W3C Verifiable Credentials (VC 2.0 data model) on Aere Network with a
|
||||||
|
* POST-QUANTUM issuer signature path. A credential here binds:
|
||||||
|
* - an ISSUER, an accredited issuer id in the AereTrustRegistry;
|
||||||
|
* - a SUBJECT, identified by a did:aere DID (bound by its hash; the DID string itself is a
|
||||||
|
* public identifier carried off-chain, no PII on chain);
|
||||||
|
* - a CREDENTIAL TYPE (an opaque bytes32 tag, e.g. keccak256("KYCCredential"));
|
||||||
|
* - a VALIDITY window (validFrom / validUntil, W3C validFrom / validUntil);
|
||||||
|
* - a STATUS-LIST ENTRY (a W3C BitstringStatusListEntry: a list id + a status index);
|
||||||
|
* - a CLAIMS HASH, the keccak256 of the off-chain VC JSON claims (the credentialSubject),
|
||||||
|
* so the on-chain anchor commits to the credential content without publishing it.
|
||||||
|
*
|
||||||
|
* VERIFICATION (verifyPresented / isValid) checks, in order and fail-closed:
|
||||||
|
* 1. the issuer is ACCREDITED for this credential type in the AereTrustRegistry;
|
||||||
|
* 2. the issuer's POST-QUANTUM (Falcon-512) signature over the credential digest is valid,
|
||||||
|
* verified in full on-chain via the live precompile 0x0AE1 (through the Trust Registry);
|
||||||
|
* 3. the credential is WITHIN its validity window (not-yet-valid and expired both fail);
|
||||||
|
* 4. the credential is NOT REVOKED per its Bitstring Status List entry.
|
||||||
|
*
|
||||||
|
* DID METHOD. Subjects (and issuers) use the `did:aere` method, consistent with Aere's
|
||||||
|
* AereIdentityRegistry8004 (did:aere:<chainId>:<id>). Full DID Core syntax validation is an
|
||||||
|
* off-chain concern; anchorCredentialWithDid enforces the `did:aere:` prefix as a minimal
|
||||||
|
* on-chain guard. [VERIFY] against the finalized did:aere method registration.
|
||||||
|
*
|
||||||
|
* ANCHORING. anchorCredential verifies the FULL path (accreditation + PQC signature + validity)
|
||||||
|
* fail-closed and records the credential once. Authorship is the POST-QUANTUM signature alone,
|
||||||
|
* so anchoring may be relayed by any msg.sender (only the issuer's Falcon key can produce a
|
||||||
|
* valid signature over the contract-bound digest). A recorded anchor is then re-checked LIVE
|
||||||
|
* by isValid, which fails closed the instant the issuer is suspended / revoked or the
|
||||||
|
* credential is revoked on its status list, without needing the signature again.
|
||||||
|
*
|
||||||
|
* @dev HONEST SCOPE. Application-layer compliance tooling. Holds no funds; changes nothing about
|
||||||
|
* Aere consensus (classical secp256k1 ECDSA QBFT). What is post-quantum is the AUTHENTICITY of
|
||||||
|
* the issuer's attestation, verified by the live precompile. Whether any real institution
|
||||||
|
* issues credentials here is a partnership matter external to this code and is NOT asserted.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY] against the finalized W3C VC 2.0 serialization: this contract anchors a COMMITMENT
|
||||||
|
* to a VC (its digest + claims hash), not the JSON-LD document itself. The mapping of these
|
||||||
|
* fields to the VC JSON members (context, type, issuer, validFrom, credentialStatus) is
|
||||||
|
* defined in docs/AERE-PQ-SCREEN.md; reconcile exact JSON member names before claiming wire
|
||||||
|
* conformance.
|
||||||
|
*/
|
||||||
|
contract AereVerifiableCredential {
|
||||||
|
/// @notice AereTrustRegistry.Status.Active (an issuer must be Active to issue / stay valid).
|
||||||
|
uint8 internal constant ISSUER_STATUS_ACTIVE = 1;
|
||||||
|
|
||||||
|
/// @notice Domain separator binding a credential digest to this contract and version.
|
||||||
|
bytes32 public constant VC_DOMAIN = keccak256("AereVerifiableCredential.v2.credential");
|
||||||
|
|
||||||
|
/// @notice The DID method these credentials use for subjects and issuers.
|
||||||
|
string public constant DID_METHOD = "did:aere";
|
||||||
|
|
||||||
|
/// @notice The federated accredited-issuer trust registry.
|
||||||
|
IAereTrustRegistryVC public immutable TRUST_REGISTRY;
|
||||||
|
|
||||||
|
/// @notice The W3C Bitstring Status List used for revocation / suspension.
|
||||||
|
IAereStatusListVC public immutable STATUS_LIST;
|
||||||
|
|
||||||
|
/// @notice A W3C VC 2.0 credential binding. `subjectDidHash` is keccak256(bytes(subjectDid)); the
|
||||||
|
/// DID string is carried off-chain to keep the hot path free of variable-length data and
|
||||||
|
/// to keep identifiers off the chain. `claimsHash` is keccak256 of the off-chain VC claims.
|
||||||
|
struct Credential {
|
||||||
|
uint256 issuerId; // accredited issuer id in the AereTrustRegistry
|
||||||
|
bytes32 subjectDidHash; // keccak256(bytes(subjectDid)), subjectDid is a did:aere DID
|
||||||
|
bytes32 credentialType; // opaque type tag, e.g. keccak256("KYCCredential")
|
||||||
|
uint64 validFrom; // W3C validFrom (unix seconds, inclusive)
|
||||||
|
uint64 validUntil; // W3C validUntil (unix seconds, inclusive); 0 = no expiry
|
||||||
|
uint256 statusListId; // W3C BitstringStatusListEntry: the list
|
||||||
|
uint256 statusIndex; // W3C BitstringStatusListEntry: the index within the list
|
||||||
|
bytes32 claimsHash; // keccak256 of the off-chain credentialSubject claims (no PII on chain)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Anchor {
|
||||||
|
bool exists;
|
||||||
|
uint256 issuerId;
|
||||||
|
bytes32 credentialType;
|
||||||
|
bytes32 subjectDidHash;
|
||||||
|
uint64 validFrom;
|
||||||
|
uint64 validUntil;
|
||||||
|
uint256 statusListId;
|
||||||
|
uint256 statusIndex;
|
||||||
|
uint64 anchoredAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(bytes32 => Anchor) private _anchors; // credentialId => anchor
|
||||||
|
bytes32[] private _anchorIds; // append-only list of anchored credential ids
|
||||||
|
|
||||||
|
event CredentialAnchored(
|
||||||
|
bytes32 indexed credentialId,
|
||||||
|
uint256 indexed issuerId,
|
||||||
|
bytes32 indexed credentialType,
|
||||||
|
bytes32 subjectDidHash,
|
||||||
|
uint256 statusListId,
|
||||||
|
uint256 statusIndex
|
||||||
|
);
|
||||||
|
event CredentialAnchoredWithDid(bytes32 indexed credentialId, string subjectDid);
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error NotAccredited(uint256 issuerId, bytes32 credentialType);
|
||||||
|
error SignatureInvalid();
|
||||||
|
error NotYetValid(uint64 validFrom);
|
||||||
|
error Expired(uint64 validUntil);
|
||||||
|
error AlreadyAnchored(bytes32 credentialId);
|
||||||
|
error UnknownCredential(bytes32 credentialId);
|
||||||
|
error DidMismatch();
|
||||||
|
error NotAereDid();
|
||||||
|
|
||||||
|
constructor(address trustRegistry_, address statusList_) {
|
||||||
|
if (trustRegistry_ == address(0) || statusList_ == address(0)) revert ZeroAddress();
|
||||||
|
TRUST_REGISTRY = IAereTrustRegistryVC(trustRegistry_);
|
||||||
|
STATUS_LIST = IAereStatusListVC(statusList_);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Digest (what the issuer signs)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice The canonical 32-byte digest an issuer's Falcon-512 key signs to attest a credential.
|
||||||
|
* Binds chainId + this contract + every credential field, so a signature cannot be
|
||||||
|
* replayed against another contract, chain, subject, type, validity, or status entry.
|
||||||
|
* This value is also the credentialId used to anchor and look the credential up.
|
||||||
|
*/
|
||||||
|
function credentialDigest(Credential calldata c) public view returns (bytes32) {
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(
|
||||||
|
VC_DOMAIN,
|
||||||
|
block.chainid,
|
||||||
|
address(this),
|
||||||
|
c.issuerId,
|
||||||
|
c.subjectDidHash,
|
||||||
|
c.credentialType,
|
||||||
|
c.validFrom,
|
||||||
|
c.validUntil,
|
||||||
|
c.statusListId,
|
||||||
|
c.statusIndex,
|
||||||
|
c.claimsHash
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Alias of {credentialDigest}: the id a credential is anchored and referenced under.
|
||||||
|
function credentialId(Credential calldata c) external view returns (bytes32) {
|
||||||
|
return credentialDigest(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Helper: the subjectDidHash for a DID string (keccak256 of its UTF-8 bytes).
|
||||||
|
function hashDid(string calldata did) external pure returns (bytes32) {
|
||||||
|
return keccak256(bytes(did));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Verification (views)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice True iff the issuer is accredited for the type AND its Falcon-512 signature over the
|
||||||
|
/// credential digest verifies on-chain via 0x0AE1. Does NOT check validity or revocation.
|
||||||
|
/// Fail-closed (returns false, never reverts).
|
||||||
|
function verifyCredentialSignature(Credential calldata c, bytes calldata issuerSig) public view returns (bool) {
|
||||||
|
if (!TRUST_REGISTRY.isAccredited(c.issuerId, c.credentialType)) return false;
|
||||||
|
return TRUST_REGISTRY.verifyIssuerSignature(c.issuerId, credentialDigest(c), issuerSig);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `c` is within its validity window at the current block time.
|
||||||
|
function isWithinValidity(Credential calldata c) public view returns (bool) {
|
||||||
|
if (block.timestamp < c.validFrom) return false;
|
||||||
|
if (c.validUntil != 0 && block.timestamp > c.validUntil) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `c` is marked revoked/suspended on its Bitstring Status List entry.
|
||||||
|
function isRevoked(Credential calldata c) public view returns (bool) {
|
||||||
|
return STATUS_LIST.statusOf(c.statusListId, c.statusIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Full W3C verification of a PRESENTED credential in one call, WITHOUT requiring it to be
|
||||||
|
* anchored: accreditation + post-quantum signature + within-validity + not-revoked. Returns
|
||||||
|
* true only if all four hold. Fail-closed (never reverts), so any verifier can call it via
|
||||||
|
* eth_call to check a credential a holder presents off-chain.
|
||||||
|
*/
|
||||||
|
function verifyPresented(Credential calldata c, bytes calldata issuerSig) external view returns (bool) {
|
||||||
|
if (!verifyCredentialSignature(c, issuerSig)) return false;
|
||||||
|
if (!isWithinValidity(c)) return false;
|
||||||
|
if (isRevoked(c)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Anchor
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Anchor a credential on-chain after verifying the FULL path fail-closed: the issuer must
|
||||||
|
* be accredited for the type, the credential must be within its validity window, and the
|
||||||
|
* issuer's Falcon-512 signature over the credential digest must verify via 0x0AE1. Records
|
||||||
|
* the credential once and emits CredentialAnchored. Reverts (records nothing) on any
|
||||||
|
* failure. Relayable by anyone: authorship is the post-quantum signature.
|
||||||
|
* @return id the credentialId (== credentialDigest) the credential was anchored under.
|
||||||
|
*/
|
||||||
|
function anchorCredential(Credential calldata c, bytes calldata issuerSig) public returns (bytes32 id) {
|
||||||
|
id = credentialDigest(c);
|
||||||
|
if (_anchors[id].exists) revert AlreadyAnchored(id);
|
||||||
|
|
||||||
|
if (!TRUST_REGISTRY.isAccredited(c.issuerId, c.credentialType)) {
|
||||||
|
revert NotAccredited(c.issuerId, c.credentialType);
|
||||||
|
}
|
||||||
|
if (block.timestamp < c.validFrom) revert NotYetValid(c.validFrom);
|
||||||
|
if (c.validUntil != 0 && block.timestamp > c.validUntil) revert Expired(c.validUntil);
|
||||||
|
|
||||||
|
// Full on-chain post-quantum verification of the issuer's attestation (fail-closed).
|
||||||
|
if (!TRUST_REGISTRY.verifyIssuerSignature(c.issuerId, id, issuerSig)) revert SignatureInvalid();
|
||||||
|
|
||||||
|
_anchors[id] = Anchor({
|
||||||
|
exists: true,
|
||||||
|
issuerId: c.issuerId,
|
||||||
|
credentialType: c.credentialType,
|
||||||
|
subjectDidHash: c.subjectDidHash,
|
||||||
|
validFrom: c.validFrom,
|
||||||
|
validUntil: c.validUntil,
|
||||||
|
statusListId: c.statusListId,
|
||||||
|
statusIndex: c.statusIndex,
|
||||||
|
anchoredAt: uint64(block.timestamp)
|
||||||
|
});
|
||||||
|
_anchorIds.push(id);
|
||||||
|
|
||||||
|
emit CredentialAnchored(id, c.issuerId, c.credentialType, c.subjectDidHash, c.statusListId, c.statusIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice As {anchorCredential}, but additionally binds and emits the subject's did:aere DID
|
||||||
|
* string (enforcing keccak256(subjectDid) == c.subjectDidHash and the `did:aere:` prefix),
|
||||||
|
* so resolvers can recover the subject DID from events without any PII on chain.
|
||||||
|
*/
|
||||||
|
function anchorCredentialWithDid(Credential calldata c, string calldata subjectDid, bytes calldata issuerSig)
|
||||||
|
external
|
||||||
|
returns (bytes32 id)
|
||||||
|
{
|
||||||
|
if (keccak256(bytes(subjectDid)) != c.subjectDidHash) revert DidMismatch();
|
||||||
|
if (!_isAereDid(subjectDid)) revert NotAereDid();
|
||||||
|
id = anchorCredential(c, issuerSig);
|
||||||
|
emit CredentialAnchoredWithDid(id, subjectDid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Anchored-credential reads
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Live validity of an ANCHORED credential: the issuer must STILL be accredited for the
|
||||||
|
* type, the credential must be within its validity window, and it must not be revoked on
|
||||||
|
* its status list. Fails closed the instant the issuer is suspended / revoked (which flips
|
||||||
|
* isAccredited to false) or the credential's status bit is set. The post-quantum signature
|
||||||
|
* was verified at anchor time and cannot silently become valid again after revocation,
|
||||||
|
* because issuer suspension / key revocation both fail this check.
|
||||||
|
*/
|
||||||
|
function isValid(bytes32 id) external view returns (bool) {
|
||||||
|
Anchor storage a = _anchors[id];
|
||||||
|
if (!a.exists) return false;
|
||||||
|
if (!TRUST_REGISTRY.isAccredited(a.issuerId, a.credentialType)) return false;
|
||||||
|
if (block.timestamp < a.validFrom) return false;
|
||||||
|
if (a.validUntil != 0 && block.timestamp > a.validUntil) return false;
|
||||||
|
if (STATUS_LIST.statusOf(a.statusListId, a.statusIndex)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff a credential id has been anchored (regardless of current validity).
|
||||||
|
function isAnchored(bytes32 id) external view returns (bool) {
|
||||||
|
return _anchors[id].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read an anchored credential record. Reverts on an unknown id.
|
||||||
|
function getAnchor(bytes32 id) external view returns (Anchor memory) {
|
||||||
|
Anchor storage a = _anchors[id];
|
||||||
|
if (!a.exists) revert UnknownCredential(id);
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Total number of anchored credentials.
|
||||||
|
function anchorCount() external view returns (uint256) {
|
||||||
|
return _anchorIds.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The credential id at an index in the append-only anchor list.
|
||||||
|
function anchorIdAt(uint256 index) external view returns (bytes32) {
|
||||||
|
return _anchorIds[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @dev Minimal on-chain guard that a DID string begins with "did:aere:". Full DID Core syntax
|
||||||
|
/// validation is an off-chain concern. [VERIFY] against the finalized did:aere method.
|
||||||
|
function _isAereDid(string calldata did) internal pure returns (bool) {
|
||||||
|
bytes calldata b = bytes(did);
|
||||||
|
bytes memory prefix = bytes("did:aere:");
|
||||||
|
if (b.length < prefix.length) return false;
|
||||||
|
for (uint256 i = 0; i < prefix.length; i++) {
|
||||||
|
if (b[i] != prefix[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/// @dev Matches Succinct's canonical SP1 verifier / SP1VerifierGateway ABI:
|
||||||
|
/// verifyProof RETURNS NOTHING and REVERTS on an invalid proof. (An
|
||||||
|
/// earlier version of this interface declared `returns (bool)`, which is
|
||||||
|
/// wrong for the real gateway — decoding a bool from the gateway's empty
|
||||||
|
/// returndata reverts even for VALID proofs, so submitProof could never
|
||||||
|
/// succeed on-chain. Fixed to void + try/catch below.)
|
||||||
|
interface ISp1Verifier {
|
||||||
|
function verifyProof(
|
||||||
|
bytes32 programVKey,
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata proof
|
||||||
|
) external view;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereZKScreen — Privacy-Pools-style ZK compliance anchor
|
||||||
|
* @notice Anchors zero-knowledge proofs that a user passed an off-chain
|
||||||
|
* compliance screen WITHOUT revealing the source data. Pattern:
|
||||||
|
* user runs a screening program (sanctions check, residency
|
||||||
|
* attestation, accredited-investor proof, etc.) inside an SP1
|
||||||
|
* zkVM; the resulting proof is verified on-chain and the user's
|
||||||
|
* address is marked as "screened" against `programVKey`.
|
||||||
|
*
|
||||||
|
* dApps then gate access by reading
|
||||||
|
* `isCleared(user, programVKey, minTimestamp)` — no PII ever
|
||||||
|
* touches the chain.
|
||||||
|
*
|
||||||
|
* GOVERNANCE:
|
||||||
|
* - Foundation registers `programVKey` values (each represents a
|
||||||
|
* distinct compliance program: OFAC screen, accredited-investor
|
||||||
|
* check, EU MiCA-eligible jurisdiction proof, etc.).
|
||||||
|
* - Each program binds a Foundation-set `authorizedRoot` — see
|
||||||
|
* ROOT BINDING below.
|
||||||
|
* - Foundation can set a per-program `expirySeconds`, rotate the
|
||||||
|
* authorizedRoot (`setAuthorizedRoot`), and revoke an individual
|
||||||
|
* clearance (`revoke`).
|
||||||
|
*
|
||||||
|
* ROOT BINDING (critical soundness property):
|
||||||
|
* The proof commits an `extraDataHash` interpreted as the allowlist
|
||||||
|
* Merkle root the screen was checked against. Because the PROVER
|
||||||
|
* supplies that root inside the zkVM, a naive design would let anyone
|
||||||
|
* prove membership in a root of THEIR OWN making (an "allowlist"
|
||||||
|
* containing only themselves) — a total soundness break for the
|
||||||
|
* compliance claim. This contract closes that: each program binds a
|
||||||
|
* Foundation-set `authorizedRoot`, and `submitProof` REQUIRES the
|
||||||
|
* proof's `extraDataHash == authorizedRoot`. The Foundation rotates
|
||||||
|
* the root via `setAuthorizedRoot` as the real allowlist changes and
|
||||||
|
* can void an individual clearance via `revoke`.
|
||||||
|
*
|
||||||
|
* CONSUMER CONTRACT: dApps MUST call `isCleared` with a real
|
||||||
|
* `minTimestamp` (e.g. `block.timestamp - freshnessWindow`), never
|
||||||
|
* 0 — otherwise they accept arbitrarily old attestations. Treat
|
||||||
|
* clearance as NECESSARY-not-sufficient and AND it with a live
|
||||||
|
* sanctions check for sanctions-sensitive flows.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY:
|
||||||
|
* - SP1_VERIFIER is fixed at deploy
|
||||||
|
* - programVKey + expirySeconds are immutable PER-PROGRAM after
|
||||||
|
* registration. authorizedRoot is rotatable by the owner.
|
||||||
|
*
|
||||||
|
* PUBLIC-VALUES CONVENTION:
|
||||||
|
* bytes representing `abi.encode(uint256 chainId, address user, uint256 attestedAt, bytes32 extraDataHash)`.
|
||||||
|
*/
|
||||||
|
contract AereZKScreen is Ownable {
|
||||||
|
|
||||||
|
address public immutable SP1_VERIFIER;
|
||||||
|
|
||||||
|
struct Program {
|
||||||
|
bool registered;
|
||||||
|
uint32 expirySeconds; // 0 = no expiry
|
||||||
|
bytes32 programVKey;
|
||||||
|
bytes32 authorizedRoot; // the ONLY allowlist root proofs may attest to
|
||||||
|
string description;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice programVKey → Program
|
||||||
|
mapping(bytes32 => Program) public programs;
|
||||||
|
|
||||||
|
/// @notice user → programVKey → last cleared timestamp
|
||||||
|
mapping(address => mapping(bytes32 => uint256)) public clearedAt;
|
||||||
|
|
||||||
|
/// @notice user → programVKey → revocation watermark; a clearance whose
|
||||||
|
/// attestation timestamp is <= this value is void.
|
||||||
|
mapping(address => mapping(bytes32 => uint256)) public revokedAt;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event ProgramRegistered(bytes32 indexed programVKey, uint32 expirySeconds, bytes32 authorizedRoot, string description);
|
||||||
|
event AuthorizedRootUpdated(bytes32 indexed programVKey, bytes32 oldRoot, bytes32 newRoot);
|
||||||
|
event Screened(address indexed user, bytes32 indexed programVKey, uint256 attestedAt, bytes32 extraDataHash);
|
||||||
|
event Revoked(address indexed user, bytes32 indexed programVKey, uint256 at);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error UnknownProgram();
|
||||||
|
error InvalidProof();
|
||||||
|
error WrongChain(uint256 inProof, uint256 onChain);
|
||||||
|
error UserMismatch(address inProof, address msgSender);
|
||||||
|
error AttestationInFuture();
|
||||||
|
error AlreadyRegistered();
|
||||||
|
error ZeroAddress();
|
||||||
|
error ZeroRoot();
|
||||||
|
error BadPublicValuesLength(uint256 got);
|
||||||
|
error StaleProof(uint256 newAttestedAt, uint256 currentClearedAt);
|
||||||
|
error UnauthorizedRoot(bytes32 inProof, bytes32 authorized);
|
||||||
|
|
||||||
|
/* ----------------------------- constructor ------------------------------ */
|
||||||
|
|
||||||
|
constructor(address sp1Verifier) {
|
||||||
|
if (sp1Verifier == address(0)) revert ZeroAddress();
|
||||||
|
SP1_VERIFIER = sp1Verifier;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------- governance -------------------------------- */
|
||||||
|
|
||||||
|
function registerProgram(
|
||||||
|
bytes32 programVKey,
|
||||||
|
uint32 expirySeconds,
|
||||||
|
bytes32 authorizedRoot,
|
||||||
|
string calldata description
|
||||||
|
) external onlyOwner {
|
||||||
|
if (programs[programVKey].registered) revert AlreadyRegistered();
|
||||||
|
if (authorizedRoot == bytes32(0)) revert ZeroRoot();
|
||||||
|
programs[programVKey] = Program({
|
||||||
|
registered: true,
|
||||||
|
expirySeconds: expirySeconds,
|
||||||
|
programVKey: programVKey,
|
||||||
|
authorizedRoot: authorizedRoot,
|
||||||
|
description: description
|
||||||
|
});
|
||||||
|
emit ProgramRegistered(programVKey, expirySeconds, authorizedRoot, description);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Rotate the allowlist root a program accepts (e.g. when the
|
||||||
|
/// approved set changes). Does NOT retroactively void existing
|
||||||
|
/// clearances — use `revoke` for that.
|
||||||
|
function setAuthorizedRoot(bytes32 programVKey, bytes32 newRoot) external onlyOwner {
|
||||||
|
Program storage p = programs[programVKey];
|
||||||
|
if (!p.registered) revert UnknownProgram();
|
||||||
|
if (newRoot == bytes32(0)) revert ZeroRoot();
|
||||||
|
bytes32 old = p.authorizedRoot;
|
||||||
|
p.authorizedRoot = newRoot;
|
||||||
|
emit AuthorizedRootUpdated(programVKey, old, newRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Void a user's clearance for a program (de-listed, compromised,
|
||||||
|
/// or newly sanctioned). `isCleared` returns false until the user
|
||||||
|
/// submits a fresh proof with `attestedAt` strictly after this call.
|
||||||
|
function revoke(address user, bytes32 programVKey) external onlyOwner {
|
||||||
|
revokedAt[user][programVKey] = block.timestamp;
|
||||||
|
emit Revoked(user, programVKey, block.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ proof submit ---------------------------- */
|
||||||
|
|
||||||
|
/// @notice Submit a fresh SP1 proof attesting that `msg.sender` passed
|
||||||
|
/// the program identified by `programVKey`. publicValues MUST
|
||||||
|
/// decode to (chainId, user, attestedAt, extraDataHash) per spec,
|
||||||
|
/// and extraDataHash MUST equal the program's authorizedRoot.
|
||||||
|
function submitProof(
|
||||||
|
bytes32 programVKey,
|
||||||
|
bytes calldata publicValues,
|
||||||
|
bytes calldata proof
|
||||||
|
) external {
|
||||||
|
Program memory p = programs[programVKey];
|
||||||
|
if (!p.registered) revert UnknownProgram();
|
||||||
|
// Exact length check prevents trailing-bytes decode spoof.
|
||||||
|
// 4 × 32 = 128 bytes for (uint256, address, uint256, bytes32).
|
||||||
|
if (publicValues.length != 128) revert BadPublicValuesLength(publicValues.length);
|
||||||
|
|
||||||
|
// Real SP1 gateway reverts on an invalid proof and returns nothing on
|
||||||
|
// success. Convert its revert into our typed InvalidProof error.
|
||||||
|
try ISp1Verifier(SP1_VERIFIER).verifyProof(programVKey, publicValues, proof) {
|
||||||
|
// proof verified — did not revert
|
||||||
|
} catch {
|
||||||
|
revert InvalidProof();
|
||||||
|
}
|
||||||
|
|
||||||
|
(uint256 chainId, address user, uint256 attestedAt, bytes32 extraDataHash) =
|
||||||
|
abi.decode(publicValues, (uint256, address, uint256, bytes32));
|
||||||
|
|
||||||
|
if (chainId != block.chainid) revert WrongChain(chainId, block.chainid);
|
||||||
|
if (user != msg.sender) revert UserMismatch(user, msg.sender);
|
||||||
|
// CRITICAL soundness gate: the proof must attest to the
|
||||||
|
// Foundation-authorized allowlist root, not one the prover chose.
|
||||||
|
// Without this, anyone can self-clear by proving membership in an
|
||||||
|
// allowlist of their own making.
|
||||||
|
if (extraDataHash != p.authorizedRoot) revert UnauthorizedRoot(extraDataHash, p.authorizedRoot);
|
||||||
|
if (attestedAt > block.timestamp) revert AttestationInFuture();
|
||||||
|
// Prevent stale-proof replay from DOWNGRADING a fresher clearance.
|
||||||
|
uint256 currentTs = clearedAt[user][programVKey];
|
||||||
|
if (attestedAt <= currentTs) revert StaleProof(attestedAt, currentTs);
|
||||||
|
|
||||||
|
clearedAt[user][programVKey] = attestedAt;
|
||||||
|
emit Screened(user, programVKey, attestedAt, extraDataHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------- views ------------------------------ */
|
||||||
|
|
||||||
|
/// @notice True iff `user` has a valid, non-revoked anchor for `programVKey`
|
||||||
|
/// whose attestation timestamp is at least `minTimestamp` AND (if
|
||||||
|
/// expirySeconds > 0) not older than expirySeconds.
|
||||||
|
function isCleared(address user, bytes32 programVKey, uint256 minTimestamp) external view returns (bool) {
|
||||||
|
Program memory p = programs[programVKey];
|
||||||
|
if (!p.registered) return false;
|
||||||
|
uint256 ts = clearedAt[user][programVKey];
|
||||||
|
if (ts == 0) return false;
|
||||||
|
if (ts < minTimestamp) return false;
|
||||||
|
if (ts <= revokedAt[user][programVKey]) return false; // revoked
|
||||||
|
if (p.expirySeconds > 0 && block.timestamp > ts + uint256(p.expirySeconds)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearanceAge(address user, bytes32 programVKey) external view returns (uint256) {
|
||||||
|
uint256 ts = clearedAt[user][programVKey];
|
||||||
|
if (ts == 0) return type(uint256).max;
|
||||||
|
return block.timestamp - ts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title ChainalysisOracleWrapper — read-only proxy to Chainalysis's free
|
||||||
|
* on-chain sanctions oracle
|
||||||
|
* @notice Chainalysis publishes a free, public sanctions oracle on Ethereum
|
||||||
|
* mainnet (and other major chains) exposing `isSanctioned(address)`.
|
||||||
|
* AERE wraps that oracle on Chain 2800 by holding the deployed
|
||||||
|
* address as an immutable, providing the same interface, and
|
||||||
|
* letting AERE dApps + institutional integrators query a SINGLE
|
||||||
|
* endpoint without having to know the upstream provider's address.
|
||||||
|
*
|
||||||
|
* This contract makes a forwarding STATICCALL to the upstream
|
||||||
|
* oracle. If the upstream rejects (e.g. paused, migrated, doesn't
|
||||||
|
* exist on AERE yet), this contract returns false rather than
|
||||||
|
* reverting — failing closed but not bricking the dApp.
|
||||||
|
*
|
||||||
|
* @dev Phase 1 (Q3 2026 ship):
|
||||||
|
* - UPSTREAM_ORACLE is settable ONCE by Foundation owner via
|
||||||
|
* setUpstream() and immutable after `lockUpstream()`.
|
||||||
|
* - Foundation MUST call lockUpstream() before declaring the
|
||||||
|
* registry "production-ready". Pre-lock, the contract is
|
||||||
|
* considered configurable.
|
||||||
|
*
|
||||||
|
* Phase 2 (Q1 2027):
|
||||||
|
* - Multiple upstream oracles polled, response aggregated via
|
||||||
|
* "ANY-true" rule (sanctioned by any source ⇒ sanctioned).
|
||||||
|
* - Per-source attestation events for transparency.
|
||||||
|
*
|
||||||
|
* FORWARD INTERFACE: bool isSanctioned(address)
|
||||||
|
* (matches Chainalysis canonical SanctionsList contract)
|
||||||
|
*/
|
||||||
|
interface IChainalysisUpstream {
|
||||||
|
function isSanctioned(address account) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract ChainalysisOracleWrapper is Ownable {
|
||||||
|
|
||||||
|
address public upstreamOracle;
|
||||||
|
bool public locked;
|
||||||
|
|
||||||
|
event UpstreamSet(address oldOracle, address newOracle);
|
||||||
|
event UpstreamLocked(address finalOracle);
|
||||||
|
|
||||||
|
error AlreadyLocked();
|
||||||
|
error ZeroAddress();
|
||||||
|
|
||||||
|
function setUpstream(address newOracle) external onlyOwner {
|
||||||
|
if (locked) revert AlreadyLocked();
|
||||||
|
if (newOracle == address(0)) revert ZeroAddress();
|
||||||
|
emit UpstreamSet(upstreamOracle, newOracle);
|
||||||
|
upstreamOracle = newOracle;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lockUpstream() external onlyOwner {
|
||||||
|
if (locked) revert AlreadyLocked();
|
||||||
|
if (upstreamOracle == address(0)) revert ZeroAddress();
|
||||||
|
locked = true;
|
||||||
|
emit UpstreamLocked(upstreamOracle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Returns true if the upstream Chainalysis oracle reports
|
||||||
|
/// `account` as sanctioned. Returns false on any upstream
|
||||||
|
/// error (failing closed but never reverting the consumer).
|
||||||
|
function isSanctioned(address account) external view returns (bool sanctioned) {
|
||||||
|
address up = upstreamOracle;
|
||||||
|
if (up == address(0)) return false;
|
||||||
|
try IChainalysisUpstream(up).isSanctioned(account) returns (bool s) {
|
||||||
|
return s;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereConfidentialCompute, on-chain verifier for the AERE threshold-MPC
|
||||||
|
* confidential-compute layer (chain 2800).
|
||||||
|
*
|
||||||
|
* @notice HONEST SCOPE. This contract does NOT run any MPC. The confidential
|
||||||
|
* computation happens OFF chain, in a committee of reference nodes that
|
||||||
|
* jointly evaluate an agreed arithmetic circuit over the parties' PRIVATE
|
||||||
|
* inputs using real Shamir secret sharing and a real BGW multiplication
|
||||||
|
* gate (see foundation-ops/mpc-committee). No single node, and no
|
||||||
|
* colluding minority below the reconstruction threshold, ever learns any
|
||||||
|
* party's input; only the agreed public outputs are revealed. This
|
||||||
|
* contract's job is narrow and verifiable: it records a session's public
|
||||||
|
* outputs only if a quorum of the REGISTERED committee members has
|
||||||
|
* ECDSA-signed the canonical result. The chain does NOT re-execute the
|
||||||
|
* MPC and does NOT verify the confidentiality of the inputs; the
|
||||||
|
* confidentiality is provided by the secret sharing off chain. The chain
|
||||||
|
* verifies committee agreement on the output.
|
||||||
|
*
|
||||||
|
* THREAT MODEL of the off-chain MPC: SEMI-HONEST (honest but curious),
|
||||||
|
* secure against a colluding minority of nodes. It is NOT malicious
|
||||||
|
* secure: there is no SPDX-MAC / cheater detection, so a deviating node
|
||||||
|
* is not cryptographically caught by the protocol. The on-chain quorum of
|
||||||
|
* signatures is the trust anchor: a result is accepted only if at least
|
||||||
|
* `signatureThreshold` distinct registered members signed it.
|
||||||
|
*
|
||||||
|
* CENTRALIZATION. The committee is Foundation-run initially, so it is as
|
||||||
|
* centralized as AERE consensus is today, and it decentralizes as the
|
||||||
|
* committee grows. The owner can register or remove committee signing
|
||||||
|
* keys and set the quorum threshold. The owner CANNOT forge a session
|
||||||
|
* result: there is no function that records outputs without a real quorum
|
||||||
|
* of committee signatures, and the owner cannot produce those signatures
|
||||||
|
* for keys it does not hold. Once recorded, a session result is immutable.
|
||||||
|
*
|
||||||
|
* SUPPORTED CIRCUITS. This is a confidential-compute PRIMITIVE (private
|
||||||
|
* arithmetic tally over a fixed agreed circuit, for example a confidential
|
||||||
|
* quadratic-voting / funding tally that reveals only sum(v) and sum(v^2)).
|
||||||
|
* It is NOT a general-purpose confidential VM or fhEVM. `circuitId` binds
|
||||||
|
* the signed result to the exact circuit that was computed.
|
||||||
|
*
|
||||||
|
* TEE PATH NOT BUILT. A hardware-attested (SEV-SNP / TDX / SGX) execution
|
||||||
|
* path was intentionally not built: the AERE server is an AMD EPYC-Rome
|
||||||
|
* cloud guest with no usable trusted-execution attestation. The security
|
||||||
|
* here is pure-software secret-sharing MPC, which needs no trusted
|
||||||
|
* hardware.
|
||||||
|
*/
|
||||||
|
contract AereConfidentialCompute {
|
||||||
|
using ECDSA for bytes32;
|
||||||
|
|
||||||
|
// ----- ownership -----
|
||||||
|
address public owner;
|
||||||
|
|
||||||
|
// ----- committee registry -----
|
||||||
|
uint256 public committeeCount;
|
||||||
|
mapping(address => bool) public isCommittee;
|
||||||
|
address[] private committeeList;
|
||||||
|
|
||||||
|
// Minimum number of distinct registered committee signatures required to
|
||||||
|
// finalize a session. Set by the owner; must satisfy 1 <= threshold <= count.
|
||||||
|
uint256 public signatureThreshold;
|
||||||
|
|
||||||
|
// ----- EIP-712 -----
|
||||||
|
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||||
|
bytes32 public constant EIP712DOMAIN_TYPEHASH =
|
||||||
|
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
|
||||||
|
bytes32 public constant SESSIONRESULT_TYPEHASH =
|
||||||
|
keccak256("SessionResult(uint256 sessionId,bytes32 circuitId,uint256[] outputs)");
|
||||||
|
|
||||||
|
// ----- session results -----
|
||||||
|
struct Session {
|
||||||
|
bool exists;
|
||||||
|
bytes32 circuitId;
|
||||||
|
bytes32 outputsHash; // keccak256(abi.encodePacked(outputs))
|
||||||
|
uint32 numOutputs;
|
||||||
|
uint32 numSigners;
|
||||||
|
uint256 finalizedAtBlock;
|
||||||
|
}
|
||||||
|
mapping(uint256 => Session) public sessions;
|
||||||
|
mapping(uint256 => uint256[]) private sessionOutputs;
|
||||||
|
|
||||||
|
// ----- optional input commitments (audit trail, inputs stay private) -----
|
||||||
|
// sessionId => partyId => commitment (e.g. keccak256(input || salt)). A party
|
||||||
|
// may post its commitment BEFORE the result is finalized, so the flow is
|
||||||
|
// tamper-evident without revealing the input. Commitments are write-once.
|
||||||
|
mapping(uint256 => mapping(bytes32 => bytes32)) public inputCommitment;
|
||||||
|
mapping(uint256 => uint256) public inputCommitmentCount;
|
||||||
|
|
||||||
|
// ----- events -----
|
||||||
|
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
||||||
|
event CommitteeMemberRegistered(address indexed member, uint256 committeeCount);
|
||||||
|
event CommitteeMemberRemoved(address indexed member, uint256 committeeCount);
|
||||||
|
event SignatureThresholdSet(uint256 threshold, uint256 committeeCount);
|
||||||
|
event InputCommitted(uint256 indexed sessionId, bytes32 indexed partyId, address indexed committer, bytes32 commitment);
|
||||||
|
event SessionFinalized(
|
||||||
|
uint256 indexed sessionId,
|
||||||
|
bytes32 indexed circuitId,
|
||||||
|
bytes32 outputsHash,
|
||||||
|
uint256 numOutputs,
|
||||||
|
uint256 numSigners,
|
||||||
|
uint256 threshold
|
||||||
|
);
|
||||||
|
|
||||||
|
modifier onlyOwner() {
|
||||||
|
require(msg.sender == owner, "not owner");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
owner = msg.sender;
|
||||||
|
emit OwnershipTransferred(address(0), msg.sender);
|
||||||
|
DOMAIN_SEPARATOR = keccak256(
|
||||||
|
abi.encode(
|
||||||
|
EIP712DOMAIN_TYPEHASH,
|
||||||
|
keccak256(bytes("AereConfidentialCompute")),
|
||||||
|
keccak256(bytes("1")),
|
||||||
|
block.chainid,
|
||||||
|
address(this)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Foundation: committee registry
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
function registerCommitteeMember(address member) public onlyOwner {
|
||||||
|
require(member != address(0), "member=0");
|
||||||
|
require(!isCommittee[member], "already registered");
|
||||||
|
isCommittee[member] = true;
|
||||||
|
committeeList.push(member);
|
||||||
|
committeeCount += 1;
|
||||||
|
emit CommitteeMemberRegistered(member, committeeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerCommittee(address[] calldata members) external onlyOwner {
|
||||||
|
for (uint256 i = 0; i < members.length; i++) {
|
||||||
|
registerCommitteeMember(members[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeCommitteeMember(address member) external onlyOwner {
|
||||||
|
require(isCommittee[member], "not registered");
|
||||||
|
isCommittee[member] = false;
|
||||||
|
committeeCount -= 1;
|
||||||
|
// compact the enumeration array
|
||||||
|
uint256 len = committeeList.length;
|
||||||
|
for (uint256 i = 0; i < len; i++) {
|
||||||
|
if (committeeList[i] == member) {
|
||||||
|
committeeList[i] = committeeList[len - 1];
|
||||||
|
committeeList.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (signatureThreshold > committeeCount) signatureThreshold = committeeCount;
|
||||||
|
emit CommitteeMemberRemoved(member, committeeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Set the quorum: how many distinct registered committee signatures a
|
||||||
|
/// session result must carry. Must be at least 1 and at most the
|
||||||
|
/// committee size. For a t-of-n MPC committee a sensible quorum is the
|
||||||
|
/// reconstruction threshold or higher.
|
||||||
|
function setSignatureThreshold(uint256 threshold) external onlyOwner {
|
||||||
|
require(threshold >= 1, "threshold < 1");
|
||||||
|
require(threshold <= committeeCount, "threshold > committee");
|
||||||
|
signatureThreshold = threshold;
|
||||||
|
emit SignatureThresholdSet(threshold, committeeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferOwnership(address newOwner) external onlyOwner {
|
||||||
|
require(newOwner != address(0), "newOwner=0");
|
||||||
|
emit OwnershipTransferred(owner, newOwner);
|
||||||
|
owner = newOwner;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Parties: optional input commitments
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Post a write-once commitment to a private input before the session
|
||||||
|
/// is finalized. The input itself is never revealed on chain; the
|
||||||
|
/// commitment gives a tamper-evident audit trail. Permissionless: any
|
||||||
|
/// party may commit for its own partyId.
|
||||||
|
function commitInput(uint256 sessionId, bytes32 partyId, bytes32 commitment) external {
|
||||||
|
require(!sessions[sessionId].exists, "session finalized");
|
||||||
|
require(commitment != bytes32(0), "commitment=0");
|
||||||
|
require(inputCommitment[sessionId][partyId] == bytes32(0), "already committed");
|
||||||
|
inputCommitment[sessionId][partyId] = commitment;
|
||||||
|
inputCommitmentCount[sessionId] += 1;
|
||||||
|
emit InputCommitted(sessionId, partyId, msg.sender, commitment);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Anyone (relayer): submit a signed result
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Finalize a confidential-compute session. Records `outputs` for
|
||||||
|
/// `sessionId` iff at least `signatureThreshold` DISTINCT registered
|
||||||
|
/// committee members signed the canonical EIP-712 SessionResult over
|
||||||
|
/// (sessionId, circuitId, outputs). msg.sender is only a gas-paying
|
||||||
|
/// relayer and gains no authority: it cannot forge committee
|
||||||
|
/// signatures, and there is no owner backdoor that records a result
|
||||||
|
/// without them.
|
||||||
|
/// @param signatures 65-byte ECDSA signatures, ORDERED BY SIGNER ADDRESS
|
||||||
|
/// STRICTLY ASCENDING (this both de-duplicates signers cheaply and
|
||||||
|
/// makes the quorum count unambiguous).
|
||||||
|
function submitSession(
|
||||||
|
uint256 sessionId,
|
||||||
|
bytes32 circuitId,
|
||||||
|
uint256[] calldata outputs,
|
||||||
|
bytes[] calldata signatures
|
||||||
|
) external {
|
||||||
|
require(committeeCount > 0, "no committee");
|
||||||
|
require(signatureThreshold > 0, "threshold unset");
|
||||||
|
require(!sessions[sessionId].exists, "already finalized");
|
||||||
|
require(signatures.length >= signatureThreshold, "insufficient signatures");
|
||||||
|
require(outputs.length <= type(uint32).max, "too many outputs");
|
||||||
|
|
||||||
|
bytes32 outputsHash = keccak256(abi.encodePacked(outputs));
|
||||||
|
bytes32 structHash = keccak256(
|
||||||
|
abi.encode(SESSIONRESULT_TYPEHASH, sessionId, circuitId, outputsHash)
|
||||||
|
);
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
|
||||||
|
// Count distinct registered signers. Requiring strictly ascending signer
|
||||||
|
// addresses rejects duplicates (a repeated key cannot inflate the quorum)
|
||||||
|
// and any non-committee (forged) signature fails the isCommittee check.
|
||||||
|
address last = address(0);
|
||||||
|
uint256 valid = 0;
|
||||||
|
for (uint256 i = 0; i < signatures.length; i++) {
|
||||||
|
address signer = digest.recover(signatures[i]);
|
||||||
|
require(signer > last, "sigs unsorted or duplicate");
|
||||||
|
require(isCommittee[signer], "signer not committee");
|
||||||
|
last = signer;
|
||||||
|
valid += 1;
|
||||||
|
}
|
||||||
|
require(valid >= signatureThreshold, "quorum not met");
|
||||||
|
|
||||||
|
sessions[sessionId] = Session({
|
||||||
|
exists: true,
|
||||||
|
circuitId: circuitId,
|
||||||
|
outputsHash: outputsHash,
|
||||||
|
numOutputs: uint32(outputs.length),
|
||||||
|
numSigners: uint32(valid),
|
||||||
|
finalizedAtBlock: block.number
|
||||||
|
});
|
||||||
|
sessionOutputs[sessionId] = outputs;
|
||||||
|
|
||||||
|
emit SessionFinalized(sessionId, circuitId, outputsHash, outputs.length, valid, signatureThreshold);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice The EIP-712 digest for a result (handy for off-chain signers/tests).
|
||||||
|
function digestFor(uint256 sessionId, bytes32 circuitId, uint256[] calldata outputs)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
bytes32 outputsHash = keccak256(abi.encodePacked(outputs));
|
||||||
|
bytes32 structHash = keccak256(
|
||||||
|
abi.encode(SESSIONRESULT_TYPEHASH, sessionId, circuitId, outputsHash)
|
||||||
|
);
|
||||||
|
return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isFinalized(uint256 sessionId) external view returns (bool) {
|
||||||
|
return sessions[sessionId].exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOutputs(uint256 sessionId) external view returns (uint256[] memory) {
|
||||||
|
require(sessions[sessionId].exists, "not finalized");
|
||||||
|
return sessionOutputs[sessionId];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCommittee() external view returns (address[] memory) {
|
||||||
|
return committeeList;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Recover the signer of a signature over a session digest. View
|
||||||
|
/// helper used by the adversarial harness to show forged (non
|
||||||
|
/// committee) signatures are rejected.
|
||||||
|
function recoverSigner(
|
||||||
|
uint256 sessionId,
|
||||||
|
bytes32 circuitId,
|
||||||
|
uint256[] calldata outputs,
|
||||||
|
bytes calldata signature
|
||||||
|
) external view returns (address) {
|
||||||
|
bytes32 outputsHash = keccak256(abi.encodePacked(outputs));
|
||||||
|
bytes32 structHash = keccak256(
|
||||||
|
abi.encode(SESSIONRESULT_TYPEHASH, sessionId, circuitId, outputsHash)
|
||||||
|
);
|
||||||
|
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
|
||||||
|
return digest.recover(signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereDelegate7702 — EIP-7702 delegation target for native AERE EOAs
|
||||||
|
* @notice This is the contract code that an AERE EOA points its 7702
|
||||||
|
* delegation tuple at. When a user signs the EIP-7702 authorisation
|
||||||
|
* tuple and includes it in a transaction, their EOA's code becomes
|
||||||
|
* the *deployed* bytecode of this contract for the lifetime of
|
||||||
|
* that authorisation. Their EOA can then expose all the smart-
|
||||||
|
* account functionality below — batched calls, session keys,
|
||||||
|
* passkey signature verification — while remaining controllable
|
||||||
|
* by the original secp256k1 EOA key.
|
||||||
|
*
|
||||||
|
* @dev PHASE 1 surface (Q3 2026 ship):
|
||||||
|
*
|
||||||
|
* 1. executeBatch(Call[]) — atomic multi-call from the EOA. The
|
||||||
|
* EOA's own ECDSA signature on the surrounding transaction is
|
||||||
|
* the authorisation; no additional signature is needed inside.
|
||||||
|
*
|
||||||
|
* 2. executeWithPasskey(Call, P256Signature, bytes challenge)
|
||||||
|
* — for users who have ALSO registered a WebAuthn passkey
|
||||||
|
* (registerPasskey() below). The transaction itself is paid
|
||||||
|
* by a relayer (Foundation paymaster), the passkey signature
|
||||||
|
* authorises the inner call. This is the bridge between
|
||||||
|
* "I have MetaMask" and "I have Touch ID / Face ID".
|
||||||
|
*
|
||||||
|
* 3. addSessionKey(address key, uint48 expiry, bytes4[] allowedSelectors)
|
||||||
|
* — register a secondary key with a narrow scope (e.g. swap
|
||||||
|
* router only) and a short expiry (e.g. 24h). Used for
|
||||||
|
* dApp UX flows where you want to skip the wallet popup
|
||||||
|
* for a defined set of low-risk operations.
|
||||||
|
*
|
||||||
|
* 4. revokeSessionKey(address key) — kill switch.
|
||||||
|
*
|
||||||
|
* 5. setPasskey(bytes32 pubkeyX, bytes32 pubkeyY) — add a single
|
||||||
|
* WebAuthn passkey. Phase 1 supports one key; Phase 2 (Q4
|
||||||
|
* 2026) extends to a MultiOwnable-style set via the same
|
||||||
|
* pattern as AerePasskeyAccountFactoryV2.
|
||||||
|
*
|
||||||
|
* STORAGE LAYOUT (7702-safe):
|
||||||
|
* 7702 transmits ONLY code, not storage. Every read of state
|
||||||
|
* below happens at the EOA's account storage. That means
|
||||||
|
* different EOAs delegating to this same code get independent
|
||||||
|
* storage. No upgrade migration needed; the EOA can re-point
|
||||||
|
* its delegation tuple at a new code address at any time.
|
||||||
|
*
|
||||||
|
* REENTRANCY:
|
||||||
|
* Calls are external; the contract sets a transient _entered
|
||||||
|
* flag for the executeBatch path. Session-key invocation goes
|
||||||
|
* through the same path.
|
||||||
|
*
|
||||||
|
* GAS:
|
||||||
|
* Phase 1 verifies P-256 via the RIP-7951 precompile at 0x100
|
||||||
|
* (~6,900 gas per signature). The chain has supported this
|
||||||
|
* since the Tier 1.15 deploy (block 2,157,502).
|
||||||
|
*/
|
||||||
|
contract AereDelegate7702 {
|
||||||
|
|
||||||
|
/* --------------------------------- types --------------------------------- */
|
||||||
|
|
||||||
|
struct Call {
|
||||||
|
address target;
|
||||||
|
uint256 value;
|
||||||
|
bytes data;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SessionKey {
|
||||||
|
uint48 expiry; // unix seconds; 0 = revoked
|
||||||
|
bool active;
|
||||||
|
mapping(bytes4 => bool) allowedSelectors;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct P256Signature {
|
||||||
|
bytes32 r;
|
||||||
|
bytes32 s;
|
||||||
|
bytes authenticatorData;
|
||||||
|
bytes clientDataJSON;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- storage ------------------------------- */
|
||||||
|
|
||||||
|
/// @notice One WebAuthn (P-256) public key per delegating EOA. Phase 1
|
||||||
|
/// supports a single key; Phase 2 extends to a set.
|
||||||
|
bytes32 public passkeyPubX;
|
||||||
|
bytes32 public passkeyPubY;
|
||||||
|
|
||||||
|
/// @notice Anti-replay nonce for passkey-authorised calls.
|
||||||
|
uint256 public passkeyNonce;
|
||||||
|
|
||||||
|
mapping(address => SessionKey) internal _sessionKeys;
|
||||||
|
|
||||||
|
/// @dev Transient reentrancy guard.
|
||||||
|
bool private _entered;
|
||||||
|
|
||||||
|
/// @notice RIP-7951 P256Verify precompile address on AERE.
|
||||||
|
address internal constant P256_VERIFY = 0x0000000000000000000000000000000000000100;
|
||||||
|
|
||||||
|
/* ---------------------------------- events --------------------------------- */
|
||||||
|
|
||||||
|
event BatchExecuted(uint256 callCount);
|
||||||
|
event SessionKeyAdded(address indexed key, uint48 expiry);
|
||||||
|
event SessionKeyRevoked(address indexed key);
|
||||||
|
event PasskeySet(bytes32 indexed pubX, bytes32 indexed pubY);
|
||||||
|
event PasskeyExecuted(uint256 nonce, address indexed target, uint256 value);
|
||||||
|
|
||||||
|
/* ---------------------------------- errors -------------------------------- */
|
||||||
|
|
||||||
|
error Reentrant();
|
||||||
|
error NotEoaOwner();
|
||||||
|
error SessionKeyExpired();
|
||||||
|
error SelectorNotAllowed();
|
||||||
|
error CallFailed(uint256 idx, bytes reason);
|
||||||
|
error InvalidPasskeySignature();
|
||||||
|
error PasskeyNotConfigured();
|
||||||
|
error InvalidChallenge();
|
||||||
|
|
||||||
|
/* -------------------------------- modifiers ------------------------------- */
|
||||||
|
|
||||||
|
modifier nonReentrant() {
|
||||||
|
if (_entered) revert Reentrant();
|
||||||
|
_entered = true;
|
||||||
|
_;
|
||||||
|
_entered = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev The EOA itself is identified by address(this) under EIP-7702. So
|
||||||
|
* msg.sender == address(this) (i.e. the EOA owner sending a
|
||||||
|
* directly-signed tx to themselves) is the canonical owner check.
|
||||||
|
*/
|
||||||
|
modifier onlyOwner() {
|
||||||
|
if (msg.sender != address(this)) revert NotEoaOwner();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- core: batch ---------------------------- */
|
||||||
|
|
||||||
|
/// @notice Atomic batched-call entrypoint. Authorised by the EOA's own
|
||||||
|
/// ECDSA signature (the tx is signed by the EOA).
|
||||||
|
function executeBatch(Call[] calldata calls) external payable nonReentrant onlyOwner {
|
||||||
|
for (uint256 i = 0; i < calls.length; i++) {
|
||||||
|
(bool ok, bytes memory ret) = calls[i].target.call{value: calls[i].value}(calls[i].data);
|
||||||
|
if (!ok) revert CallFailed(i, ret);
|
||||||
|
}
|
||||||
|
emit BatchExecuted(calls.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- session keys ----------------------------- */
|
||||||
|
|
||||||
|
function addSessionKey(
|
||||||
|
address key,
|
||||||
|
uint48 expiry,
|
||||||
|
bytes4[] calldata allowedSelectors
|
||||||
|
) external onlyOwner {
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
sk.expiry = expiry;
|
||||||
|
sk.active = true;
|
||||||
|
for (uint256 i = 0; i < allowedSelectors.length; i++) {
|
||||||
|
sk.allowedSelectors[allowedSelectors[i]] = true;
|
||||||
|
}
|
||||||
|
emit SessionKeyAdded(key, expiry);
|
||||||
|
}
|
||||||
|
|
||||||
|
function revokeSessionKey(address key) external onlyOwner {
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
sk.active = false;
|
||||||
|
emit SessionKeyRevoked(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Public read for dashboards.
|
||||||
|
function sessionKeyInfo(address key, bytes4 selector) external view returns (bool active, uint48 expiry, bool selectorAllowed) {
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
return (sk.active, sk.expiry, sk.allowedSelectors[selector]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice A session key invokes itself as msg.sender. Verifies the key
|
||||||
|
/// is active and the call's selector is allowed.
|
||||||
|
function executeWithSessionKey(Call calldata callItem) external payable nonReentrant {
|
||||||
|
SessionKey storage sk = _sessionKeys[msg.sender];
|
||||||
|
if (!sk.active || sk.expiry < block.timestamp) revert SessionKeyExpired();
|
||||||
|
if (callItem.data.length < 4) revert SelectorNotAllowed();
|
||||||
|
bytes4 selector;
|
||||||
|
bytes calldata d = callItem.data;
|
||||||
|
assembly { selector := calldataload(d.offset) }
|
||||||
|
if (!sk.allowedSelectors[selector]) revert SelectorNotAllowed();
|
||||||
|
|
||||||
|
(bool ok, bytes memory ret) = callItem.target.call{value: callItem.value}(callItem.data);
|
||||||
|
if (!ok) revert CallFailed(0, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- passkeys ------------------------------- */
|
||||||
|
|
||||||
|
function setPasskey(bytes32 pubX, bytes32 pubY) external onlyOwner {
|
||||||
|
passkeyPubX = pubX;
|
||||||
|
passkeyPubY = pubY;
|
||||||
|
emit PasskeySet(pubX, pubY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Execute a single call authorised by a WebAuthn (P-256) signature.
|
||||||
|
* @param callItem The call to perform.
|
||||||
|
* @param sig The P-256 signature components.
|
||||||
|
* @dev The signed challenge is computed from the current passkeyNonce
|
||||||
|
* and the call payload. After verification, nonce is incremented
|
||||||
|
* (replay-protection).
|
||||||
|
*/
|
||||||
|
function executeWithPasskey(Call calldata callItem, P256Signature calldata sig) external payable nonReentrant {
|
||||||
|
if (passkeyPubX == bytes32(0) && passkeyPubY == bytes32(0)) revert PasskeyNotConfigured();
|
||||||
|
|
||||||
|
// Build the WebAuthn signed digest: SHA256(authenticatorData || SHA256(clientDataJSON))
|
||||||
|
bytes32 clientDataHash = sha256(sig.clientDataJSON);
|
||||||
|
bytes32 digest = sha256(abi.encodePacked(sig.authenticatorData, clientDataHash));
|
||||||
|
|
||||||
|
// ROUND-3 FIX: previously the contract verified the P-256 signature
|
||||||
|
// over the WebAuthn digest but NEVER bound the signed clientDataJSON
|
||||||
|
// to the call payload. That allowed any valid WebAuthn signature from
|
||||||
|
// this passkey (e.g. an unrelated dApp login) to be replayed here as
|
||||||
|
// authorisation for arbitrary calls. We now compute the expected
|
||||||
|
// challenge (keccak256(this, nonce, call)) base64url-encoded and
|
||||||
|
// require clientDataJSON to contain the canonical
|
||||||
|
// `"challenge":"<expected>"` substring.
|
||||||
|
bytes32 expectedChallenge = keccak256(abi.encode(address(this), passkeyNonce, callItem));
|
||||||
|
if (!_clientDataBindsChallenge(sig.clientDataJSON, expectedChallenge)) {
|
||||||
|
revert InvalidChallenge();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify via RIP-7951 P256Verify at 0x100.
|
||||||
|
// Calldata layout: 160 bytes — msgHash || r || s || qx || qy.
|
||||||
|
bytes memory input = abi.encodePacked(digest, sig.r, sig.s, passkeyPubX, passkeyPubY);
|
||||||
|
(bool ok, bytes memory ret) = P256_VERIFY.staticcall(input);
|
||||||
|
if (!ok || ret.length == 0 || ret[31] != 0x01) revert InvalidPasskeySignature();
|
||||||
|
|
||||||
|
// Replay-protect.
|
||||||
|
uint256 nonce = passkeyNonce++;
|
||||||
|
|
||||||
|
// Perform the call.
|
||||||
|
(bool ok2, bytes memory r2) = callItem.target.call{value: callItem.value}(callItem.data);
|
||||||
|
if (!ok2) revert CallFailed(0, r2);
|
||||||
|
|
||||||
|
emit PasskeyExecuted(nonce, callItem.target, callItem.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience for relayers / dApps: recover the expected
|
||||||
|
/// challenge bytes32 for the NEXT passkey-authorised call.
|
||||||
|
function nextPasskeyChallenge(Call calldata callItem) external view returns (bytes32) {
|
||||||
|
return keccak256(abi.encode(address(this), passkeyNonce, callItem));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------- challenge-binding helpers ---------------------- */
|
||||||
|
|
||||||
|
/// @dev base64url alphabet (RFC 4648 §5, no padding).
|
||||||
|
bytes internal constant B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||||
|
|
||||||
|
/// @dev Encode a 32-byte value as 43 chars of base64url (no padding).
|
||||||
|
function _b64url32(bytes32 v) internal pure returns (bytes memory out) {
|
||||||
|
out = new bytes(43);
|
||||||
|
bytes memory tbl = B64URL;
|
||||||
|
uint256 j = 0;
|
||||||
|
for (uint256 i = 0; i + 3 <= 30; i += 3) {
|
||||||
|
uint256 a = uint256(uint8(v[i]));
|
||||||
|
uint256 b = uint256(uint8(v[i + 1]));
|
||||||
|
uint256 c = uint256(uint8(v[i + 2]));
|
||||||
|
out[j++] = tbl[a >> 2];
|
||||||
|
out[j++] = tbl[((a & 0x03) << 4) | (b >> 4)];
|
||||||
|
out[j++] = tbl[((b & 0x0f) << 2) | (c >> 6)];
|
||||||
|
out[j++] = tbl[c & 0x3f];
|
||||||
|
}
|
||||||
|
// bytes 30, 31 → 3 b64url chars
|
||||||
|
uint256 a2 = uint256(uint8(v[30]));
|
||||||
|
uint256 b2 = uint256(uint8(v[31]));
|
||||||
|
out[j++] = tbl[a2 >> 2];
|
||||||
|
out[j++] = tbl[((a2 & 0x03) << 4) | (b2 >> 4)];
|
||||||
|
out[j++] = tbl[(b2 & 0x0f) << 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Check that `clientDataJSON` contains the canonical substring
|
||||||
|
/// `"challenge":"<base64url(expected)>"`. Webauthn's CollectedClientData
|
||||||
|
/// always encodes the challenge as base64url without padding (W3C spec).
|
||||||
|
function _clientDataBindsChallenge(bytes calldata clientDataJSON, bytes32 expected) internal pure returns (bool) {
|
||||||
|
bytes memory enc = _b64url32(expected);
|
||||||
|
// Build the literal pattern `"challenge":"<enc>"` — 14 fixed chars + 43.
|
||||||
|
bytes memory needle = new bytes(14 + 43);
|
||||||
|
bytes memory prefix = bytes('"challenge":"');
|
||||||
|
for (uint256 i = 0; i < 13; i++) needle[i] = prefix[i];
|
||||||
|
for (uint256 i = 0; i < 43; i++) needle[13 + i] = enc[i];
|
||||||
|
needle[56] = bytes1('"');
|
||||||
|
return _contains(clientDataJSON, needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Naive substring search; clientDataJSON is small (<512 bytes typical)
|
||||||
|
/// and needle is fixed 57 bytes → bounded gas.
|
||||||
|
function _contains(bytes calldata hay, bytes memory needle) internal pure returns (bool) {
|
||||||
|
uint256 hLen = hay.length;
|
||||||
|
uint256 nLen = needle.length;
|
||||||
|
if (nLen == 0 || hLen < nLen) return false;
|
||||||
|
uint256 last = hLen - nLen;
|
||||||
|
for (uint256 i = 0; i <= last; i++) {
|
||||||
|
bool match_ = true;
|
||||||
|
for (uint256 j = 0; j < nLen; j++) {
|
||||||
|
if (hay[i + j] != needle[j]) { match_ = false; break; }
|
||||||
|
}
|
||||||
|
if (match_) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------- receive ------------------------------- */
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereDelegate7702V2 — scope-hardened EIP-7702 delegation target
|
||||||
|
* @notice Drop-in successor to AereDelegate7702. Same owner and passkey
|
||||||
|
* surface, but session keys are now properly SCOPED so a delegated
|
||||||
|
* key can no longer exceed the authority the owner intended.
|
||||||
|
*
|
||||||
|
* @dev WHY V2 (two closed session-key escapes vs the original):
|
||||||
|
*
|
||||||
|
* FACET 1 - unbounded target + unbounded value. The original bound a
|
||||||
|
* session key ONLY by a 4-byte selector allow-list. There was no
|
||||||
|
* target allow-list and no value cap, so a key granted selector S
|
||||||
|
* could point `target` at ANY contract exposing S and set `value` to
|
||||||
|
* the account's ENTIRE native balance, draining it to an arbitrary
|
||||||
|
* address. V2 requires (a) the target to be in a per-key target
|
||||||
|
* allow-list and (b) the cumulative native value moved by the key to
|
||||||
|
* stay within a per-key spend cap (cap defaults to 0, i.e. a key can
|
||||||
|
* move NO native value unless the owner explicitly grants a cap).
|
||||||
|
*
|
||||||
|
* FACET 2 - self-call privilege escalation. onlyOwner is
|
||||||
|
* msg.sender == address(this), and executeWithSessionKey performs its
|
||||||
|
* outbound call with msg.sender == address(this). A key granted a
|
||||||
|
* selector colliding with an owner-only function (setPasskey /
|
||||||
|
* addSessionKey / revokeSessionKey) could therefore target the account
|
||||||
|
* itself and pass onlyOwner, taking the account over. V2 forbids
|
||||||
|
* target == address(this) for every session-key call, so a session key
|
||||||
|
* can never invoke the account's own owner-gated functions. The owner
|
||||||
|
* (a real EIP-7702 self-transaction) is unaffected.
|
||||||
|
*
|
||||||
|
* STORAGE LAYOUT (7702-safe): as with V1, 7702 transmits only code;
|
||||||
|
* all state reads/writes hit the delegating EOA's own account storage.
|
||||||
|
* This is a FRESH code address; delegating EOAs opt in by re-pointing
|
||||||
|
* their own 7702 tuple (owner-supervised), never migrated for them.
|
||||||
|
*/
|
||||||
|
contract AereDelegate7702V2 {
|
||||||
|
|
||||||
|
/* --------------------------------- types --------------------------------- */
|
||||||
|
|
||||||
|
struct Call {
|
||||||
|
address target;
|
||||||
|
uint256 value;
|
||||||
|
bytes data;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SessionKey {
|
||||||
|
uint48 expiry; // unix seconds; key inactive once expiry < now
|
||||||
|
bool active; // owner kill switch; false = revoked
|
||||||
|
uint256 scopeEpoch; // current scope generation; bumped on every add + revoke
|
||||||
|
uint256 spendCap; // cumulative native-value ceiling for this key (0 = no native value)
|
||||||
|
uint256 spent; // cumulative native value already moved by this key (current grant)
|
||||||
|
// Scope is keyed by scopeEpoch so a revoke + re-grant starts a FRESH,
|
||||||
|
// empty scope: only the newly-listed selectors/targets are live and no
|
||||||
|
// historical grant can ever be reactivated (the union-escape fix).
|
||||||
|
mapping(uint256 => mapping(bytes4 => bool)) allowedSelectorsAt;
|
||||||
|
mapping(uint256 => mapping(address => bool)) allowedTargetsAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct P256Signature {
|
||||||
|
bytes32 r;
|
||||||
|
bytes32 s;
|
||||||
|
bytes authenticatorData;
|
||||||
|
bytes clientDataJSON;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- storage ------------------------------- */
|
||||||
|
|
||||||
|
/// @notice One WebAuthn (P-256) public key per delegating EOA.
|
||||||
|
bytes32 public passkeyPubX;
|
||||||
|
bytes32 public passkeyPubY;
|
||||||
|
|
||||||
|
/// @notice Anti-replay nonce for passkey-authorised calls.
|
||||||
|
uint256 public passkeyNonce;
|
||||||
|
|
||||||
|
mapping(address => SessionKey) internal _sessionKeys;
|
||||||
|
|
||||||
|
/// @dev Reentrancy guard shared by executeBatch and executeWithSessionKey.
|
||||||
|
bool private _entered;
|
||||||
|
|
||||||
|
/// @notice RIP-7951 P256Verify precompile address on AERE.
|
||||||
|
address internal constant P256_VERIFY = 0x0000000000000000000000000000000000000100;
|
||||||
|
|
||||||
|
/* ---------------------------------- events --------------------------------- */
|
||||||
|
|
||||||
|
event BatchExecuted(uint256 callCount);
|
||||||
|
event SessionKeyAdded(address indexed key, uint48 expiry, uint256 spendCap);
|
||||||
|
event SessionKeyRevoked(address indexed key);
|
||||||
|
event PasskeySet(bytes32 indexed pubX, bytes32 indexed pubY);
|
||||||
|
event PasskeyExecuted(uint256 nonce, address indexed target, uint256 value);
|
||||||
|
|
||||||
|
/* ---------------------------------- errors -------------------------------- */
|
||||||
|
|
||||||
|
error Reentrant();
|
||||||
|
error NotEoaOwner();
|
||||||
|
error SessionKeyExpired();
|
||||||
|
error SelectorNotAllowed();
|
||||||
|
error TargetNotAllowed();
|
||||||
|
error SpendCapExceeded();
|
||||||
|
error CallFailed(uint256 idx, bytes reason);
|
||||||
|
error InvalidPasskeySignature();
|
||||||
|
error PasskeyNotConfigured();
|
||||||
|
error InvalidChallenge();
|
||||||
|
|
||||||
|
/* -------------------------------- modifiers ------------------------------- */
|
||||||
|
|
||||||
|
modifier nonReentrant() {
|
||||||
|
if (_entered) revert Reentrant();
|
||||||
|
_entered = true;
|
||||||
|
_;
|
||||||
|
_entered = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @dev Under EIP-7702 the EOA is identified by address(this), so the owner
|
||||||
|
* check is msg.sender == address(this) (the EOA owner sending a
|
||||||
|
* self-signed tx). Session keys are explicitly barred from targeting
|
||||||
|
* address(this), so they can never satisfy this modifier by self-call.
|
||||||
|
*/
|
||||||
|
modifier onlyOwner() {
|
||||||
|
if (msg.sender != address(this)) revert NotEoaOwner();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- core: batch ---------------------------- */
|
||||||
|
|
||||||
|
/// @notice Atomic batched-call entrypoint. Authorised by the EOA's own
|
||||||
|
/// ECDSA signature (the tx is signed by the EOA).
|
||||||
|
function executeBatch(Call[] calldata calls) external payable nonReentrant onlyOwner {
|
||||||
|
for (uint256 i = 0; i < calls.length; i++) {
|
||||||
|
(bool ok, bytes memory ret) = calls[i].target.call{value: calls[i].value}(calls[i].data);
|
||||||
|
if (!ok) revert CallFailed(i, ret);
|
||||||
|
}
|
||||||
|
emit BatchExecuted(calls.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------- session keys ----------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Register / re-grant a scoped session key.
|
||||||
|
* @param key The session-key address.
|
||||||
|
* @param expiry Unix seconds after which the key cannot act.
|
||||||
|
* @param spendCap Cumulative native-value ceiling for this key. Pass
|
||||||
|
* 0 to forbid the key from moving any native value.
|
||||||
|
* @param allowedSelectors 4-byte selectors the key may invoke.
|
||||||
|
* @param allowedTargets Contract addresses the key may call. address(this)
|
||||||
|
* is rejected: a session key can never call the
|
||||||
|
* account itself.
|
||||||
|
* @dev Each grant is AUTHORITATIVE: it bumps the key's scopeEpoch and writes
|
||||||
|
* the selectors/targets under the fresh epoch, so a re-grant does NOT
|
||||||
|
* accumulate the union of past scopes. Only the newly-listed selectors
|
||||||
|
* and targets are live; expiry, active and spendCap are overwritten, and
|
||||||
|
* the spent counter resets so a re-grant issues a fresh native budget.
|
||||||
|
*/
|
||||||
|
function addSessionKey(
|
||||||
|
address key,
|
||||||
|
uint48 expiry,
|
||||||
|
uint256 spendCap,
|
||||||
|
bytes4[] calldata allowedSelectors,
|
||||||
|
address[] calldata allowedTargets
|
||||||
|
) external onlyOwner {
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
// Fresh scope generation: everything written below lives ONLY at this
|
||||||
|
// epoch, so no selector/target from any prior grant carries over.
|
||||||
|
uint256 epoch = ++sk.scopeEpoch;
|
||||||
|
sk.expiry = expiry;
|
||||||
|
sk.active = true;
|
||||||
|
sk.spendCap = spendCap;
|
||||||
|
sk.spent = 0;
|
||||||
|
for (uint256 i = 0; i < allowedSelectors.length; i++) {
|
||||||
|
sk.allowedSelectorsAt[epoch][allowedSelectors[i]] = true;
|
||||||
|
}
|
||||||
|
for (uint256 i = 0; i < allowedTargets.length; i++) {
|
||||||
|
// A session key may never target the account itself (escalation guard).
|
||||||
|
if (allowedTargets[i] == address(this)) revert TargetNotAllowed();
|
||||||
|
sk.allowedTargetsAt[epoch][allowedTargets[i]] = true;
|
||||||
|
}
|
||||||
|
emit SessionKeyAdded(key, expiry, spendCap);
|
||||||
|
}
|
||||||
|
|
||||||
|
function revokeSessionKey(address key) external onlyOwner {
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
sk.active = false;
|
||||||
|
// Advance the scope generation so the just-revoked scope is orphaned
|
||||||
|
// immediately and can never be read again, even on a later re-grant.
|
||||||
|
sk.scopeEpoch++;
|
||||||
|
emit SessionKeyRevoked(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Public read for dashboards: selector-level view (V1-compatible).
|
||||||
|
function sessionKeyInfo(address key, bytes4 selector)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (bool active, uint48 expiry, bool selectorAllowed)
|
||||||
|
{
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
return (sk.active, sk.expiry, sk.allowedSelectorsAt[sk.scopeEpoch][selector]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Full per-key scope view: selector + target + native budget.
|
||||||
|
function sessionKeyScope(address key, bytes4 selector, address target)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
bool active,
|
||||||
|
uint48 expiry,
|
||||||
|
bool selectorAllowed,
|
||||||
|
bool targetAllowed,
|
||||||
|
uint256 spendCap,
|
||||||
|
uint256 spent
|
||||||
|
)
|
||||||
|
{
|
||||||
|
SessionKey storage sk = _sessionKeys[key];
|
||||||
|
uint256 epoch = sk.scopeEpoch;
|
||||||
|
return (
|
||||||
|
sk.active,
|
||||||
|
sk.expiry,
|
||||||
|
sk.allowedSelectorsAt[epoch][selector],
|
||||||
|
sk.allowedTargetsAt[epoch][target],
|
||||||
|
sk.spendCap,
|
||||||
|
sk.spent
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice A session key invokes itself as msg.sender. The call is allowed
|
||||||
|
/// only if the key is active, unexpired, the target is in the key's
|
||||||
|
/// target allow-list (and is NOT the account itself), the selector
|
||||||
|
/// is in the key's selector allow-list, and the cumulative native
|
||||||
|
/// value stays within the key's spend cap.
|
||||||
|
function executeWithSessionKey(Call calldata callItem) external payable nonReentrant {
|
||||||
|
SessionKey storage sk = _sessionKeys[msg.sender];
|
||||||
|
if (!sk.active || sk.expiry < block.timestamp) revert SessionKeyExpired();
|
||||||
|
|
||||||
|
// Only the key's CURRENT scope generation authorizes; any target/selector
|
||||||
|
// from a prior (revoked or superseded) grant lives at a stale epoch and
|
||||||
|
// is unreachable here.
|
||||||
|
uint256 epoch = sk.scopeEpoch;
|
||||||
|
|
||||||
|
// FACET 2 guard: a session key can never call the account itself, so it
|
||||||
|
// can never reach an owner-only function via msg.sender == address(this).
|
||||||
|
if (callItem.target == address(this)) revert TargetNotAllowed();
|
||||||
|
|
||||||
|
// FACET 1 guard (target): the target must be explicitly allow-listed.
|
||||||
|
if (!sk.allowedTargetsAt[epoch][callItem.target]) revert TargetNotAllowed();
|
||||||
|
|
||||||
|
if (callItem.data.length < 4) revert SelectorNotAllowed();
|
||||||
|
bytes4 selector;
|
||||||
|
bytes calldata d = callItem.data;
|
||||||
|
assembly { selector := calldataload(d.offset) }
|
||||||
|
if (!sk.allowedSelectorsAt[epoch][selector]) revert SelectorNotAllowed();
|
||||||
|
|
||||||
|
// FACET 1 guard (value): cumulative native spend may not exceed the cap.
|
||||||
|
if (callItem.value != 0) {
|
||||||
|
uint256 newSpent = sk.spent + callItem.value;
|
||||||
|
if (newSpent > sk.spendCap) revert SpendCapExceeded();
|
||||||
|
sk.spent = newSpent;
|
||||||
|
}
|
||||||
|
|
||||||
|
(bool ok, bytes memory ret) = callItem.target.call{value: callItem.value}(callItem.data);
|
||||||
|
if (!ok) revert CallFailed(0, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- passkeys ------------------------------- */
|
||||||
|
|
||||||
|
function setPasskey(bytes32 pubX, bytes32 pubY) external onlyOwner {
|
||||||
|
passkeyPubX = pubX;
|
||||||
|
passkeyPubY = pubY;
|
||||||
|
emit PasskeySet(pubX, pubY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Execute a single call authorised by a WebAuthn (P-256) signature.
|
||||||
|
* @param callItem The call to perform.
|
||||||
|
* @param sig The P-256 signature components.
|
||||||
|
* @dev The signed challenge is computed from the current passkeyNonce
|
||||||
|
* and the call payload. After verification, nonce is incremented
|
||||||
|
* (replay-protection). Unchanged from V1.
|
||||||
|
*/
|
||||||
|
function executeWithPasskey(Call calldata callItem, P256Signature calldata sig) external payable nonReentrant {
|
||||||
|
if (passkeyPubX == bytes32(0) && passkeyPubY == bytes32(0)) revert PasskeyNotConfigured();
|
||||||
|
|
||||||
|
// Build the WebAuthn signed digest: SHA256(authenticatorData || SHA256(clientDataJSON))
|
||||||
|
bytes32 clientDataHash = sha256(sig.clientDataJSON);
|
||||||
|
bytes32 digest = sha256(abi.encodePacked(sig.authenticatorData, clientDataHash));
|
||||||
|
|
||||||
|
// Bind the signed clientDataJSON to (this, nonce, call) so an unrelated
|
||||||
|
// WebAuthn signature cannot be replayed as authorisation for a call.
|
||||||
|
bytes32 expectedChallenge = keccak256(abi.encode(address(this), passkeyNonce, callItem));
|
||||||
|
if (!_clientDataBindsChallenge(sig.clientDataJSON, expectedChallenge)) {
|
||||||
|
revert InvalidChallenge();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify via RIP-7951 P256Verify at 0x100.
|
||||||
|
// Calldata layout: 160 bytes — msgHash || r || s || qx || qy.
|
||||||
|
bytes memory input = abi.encodePacked(digest, sig.r, sig.s, passkeyPubX, passkeyPubY);
|
||||||
|
(bool ok, bytes memory ret) = P256_VERIFY.staticcall(input);
|
||||||
|
if (!ok || ret.length == 0 || ret[31] != 0x01) revert InvalidPasskeySignature();
|
||||||
|
|
||||||
|
// Replay-protect.
|
||||||
|
uint256 nonce = passkeyNonce++;
|
||||||
|
|
||||||
|
// Perform the call.
|
||||||
|
(bool ok2, bytes memory r2) = callItem.target.call{value: callItem.value}(callItem.data);
|
||||||
|
if (!ok2) revert CallFailed(0, r2);
|
||||||
|
|
||||||
|
emit PasskeyExecuted(nonce, callItem.target, callItem.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Convenience for relayers / dApps: recover the expected
|
||||||
|
/// challenge bytes32 for the NEXT passkey-authorised call.
|
||||||
|
function nextPasskeyChallenge(Call calldata callItem) external view returns (bytes32) {
|
||||||
|
return keccak256(abi.encode(address(this), passkeyNonce, callItem));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------- challenge-binding helpers ---------------------- */
|
||||||
|
|
||||||
|
/// @dev base64url alphabet (RFC 4648 §5, no padding).
|
||||||
|
bytes internal constant B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||||
|
|
||||||
|
/// @dev Encode a 32-byte value as 43 chars of base64url (no padding).
|
||||||
|
function _b64url32(bytes32 v) internal pure returns (bytes memory out) {
|
||||||
|
out = new bytes(43);
|
||||||
|
bytes memory tbl = B64URL;
|
||||||
|
uint256 j = 0;
|
||||||
|
for (uint256 i = 0; i + 3 <= 30; i += 3) {
|
||||||
|
uint256 a = uint256(uint8(v[i]));
|
||||||
|
uint256 b = uint256(uint8(v[i + 1]));
|
||||||
|
uint256 c = uint256(uint8(v[i + 2]));
|
||||||
|
out[j++] = tbl[a >> 2];
|
||||||
|
out[j++] = tbl[((a & 0x03) << 4) | (b >> 4)];
|
||||||
|
out[j++] = tbl[((b & 0x0f) << 2) | (c >> 6)];
|
||||||
|
out[j++] = tbl[c & 0x3f];
|
||||||
|
}
|
||||||
|
// bytes 30, 31 → 3 b64url chars
|
||||||
|
uint256 a2 = uint256(uint8(v[30]));
|
||||||
|
uint256 b2 = uint256(uint8(v[31]));
|
||||||
|
out[j++] = tbl[a2 >> 2];
|
||||||
|
out[j++] = tbl[((a2 & 0x03) << 4) | (b2 >> 4)];
|
||||||
|
out[j++] = tbl[(b2 & 0x0f) << 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Check that `clientDataJSON` contains the canonical substring
|
||||||
|
/// `"challenge":"<base64url(expected)>"`.
|
||||||
|
function _clientDataBindsChallenge(bytes calldata clientDataJSON, bytes32 expected) internal pure returns (bool) {
|
||||||
|
bytes memory enc = _b64url32(expected);
|
||||||
|
// Build the literal pattern `"challenge":"<enc>"` — 14 fixed chars + 43.
|
||||||
|
bytes memory needle = new bytes(14 + 43);
|
||||||
|
bytes memory prefix = bytes('"challenge":"');
|
||||||
|
for (uint256 i = 0; i < 13; i++) needle[i] = prefix[i];
|
||||||
|
for (uint256 i = 0; i < 43; i++) needle[13 + i] = enc[i];
|
||||||
|
needle[56] = bytes1('"');
|
||||||
|
return _contains(clientDataJSON, needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Naive substring search; clientDataJSON is small and needle is fixed
|
||||||
|
/// 57 bytes so gas is bounded.
|
||||||
|
function _contains(bytes calldata hay, bytes memory needle) internal pure returns (bool) {
|
||||||
|
uint256 hLen = hay.length;
|
||||||
|
uint256 nLen = needle.length;
|
||||||
|
if (nLen == 0 || hLen < nLen) return false;
|
||||||
|
uint256 last = hLen - nLen;
|
||||||
|
for (uint256 i = 0; i <= last; i++) {
|
||||||
|
bool match_ = true;
|
||||||
|
for (uint256 j = 0; j < nLen; j++) {
|
||||||
|
if (hay[i + j] != needle[j]) { match_ = false; break; }
|
||||||
|
}
|
||||||
|
if (match_) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------- receive ------------------------------- */
|
||||||
|
|
||||||
|
receive() external payable {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereDelegationRegistry — public index of EIP-7702 delegated EOAs
|
||||||
|
* @notice Permissionless registry that records which EOAs have delegated
|
||||||
|
* to the AereDelegate7702 implementation. dApps query this to:
|
||||||
|
* - Render the "smart-wallet enabled" badge in UI
|
||||||
|
* - Discover EOAs eligible for batch execution
|
||||||
|
* - Coordinate paymaster eligibility checks
|
||||||
|
*
|
||||||
|
* Each registered account stores:
|
||||||
|
* - delegationCodeHash (EIP-7702 designator hash for cross-check)
|
||||||
|
* - registeredAt timestamp
|
||||||
|
* - lastSeenNonce (for indexers; updated by the account itself or
|
||||||
|
* permissionless `notifyNonce`)
|
||||||
|
*
|
||||||
|
* REGISTRATION is permissionless: any EOA can self-register via
|
||||||
|
* `register()`. UNREGISTRATION is also permissionless to the
|
||||||
|
* account itself (e.g. before reverting their EIP-7702 delegation).
|
||||||
|
*
|
||||||
|
* @dev The registry is purely INFORMATIONAL — no funds custody, no
|
||||||
|
* access control over the account. Wrong registration data hurts
|
||||||
|
* only the registrant's UX.
|
||||||
|
*/
|
||||||
|
contract AereDelegationRegistry {
|
||||||
|
|
||||||
|
struct Entry {
|
||||||
|
bool registered;
|
||||||
|
bytes32 delegationCodeHash; // hash of msg.sender's delegated code at registration time
|
||||||
|
uint64 registeredAt;
|
||||||
|
uint64 lastSeenAt;
|
||||||
|
uint256 lastSeenNonce;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice account → entry
|
||||||
|
mapping(address => Entry) public entries;
|
||||||
|
/// @notice paged listing for indexers
|
||||||
|
address[] public registered;
|
||||||
|
/// @notice account → index in `registered` array (1-based; 0 = not in list)
|
||||||
|
mapping(address => uint256) internal _registeredIndex;
|
||||||
|
|
||||||
|
/* --------------------------------- events ------------------------------- */
|
||||||
|
|
||||||
|
event Registered(address indexed account, bytes32 delegationCodeHash, uint64 registeredAt);
|
||||||
|
event Unregistered(address indexed account);
|
||||||
|
event NonceSeen(address indexed account, uint256 nonce, uint64 timestamp);
|
||||||
|
|
||||||
|
/* --------------------------------- errors ------------------------------- */
|
||||||
|
|
||||||
|
error AlreadyRegistered();
|
||||||
|
error NotRegistered();
|
||||||
|
|
||||||
|
/* ------------------------------ registration ---------------------------- */
|
||||||
|
|
||||||
|
/// @notice Self-register the caller. The contract reads `msg.sender`'s
|
||||||
|
/// current code hash via `extcodehash` — if the EOA has
|
||||||
|
/// delegated under EIP-7702, this returns the designated
|
||||||
|
/// implementation's code hash. If the EOA has NOT delegated,
|
||||||
|
/// the hash will be the empty-account hash and the registration
|
||||||
|
/// is still allowed (with that empty hash recorded) — front-end
|
||||||
|
/// filters can ignore entries with the empty hash.
|
||||||
|
function register() external {
|
||||||
|
if (entries[msg.sender].registered) revert AlreadyRegistered();
|
||||||
|
bytes32 codeHash;
|
||||||
|
assembly { codeHash := extcodehash(caller()) }
|
||||||
|
entries[msg.sender] = Entry({
|
||||||
|
registered: true,
|
||||||
|
delegationCodeHash: codeHash,
|
||||||
|
registeredAt: uint64(block.timestamp),
|
||||||
|
lastSeenAt: uint64(block.timestamp),
|
||||||
|
lastSeenNonce: 0
|
||||||
|
});
|
||||||
|
registered.push(msg.sender);
|
||||||
|
_registeredIndex[msg.sender] = registered.length; // 1-based
|
||||||
|
emit Registered(msg.sender, codeHash, uint64(block.timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
function unregister() external {
|
||||||
|
if (!entries[msg.sender].registered) revert NotRegistered();
|
||||||
|
delete entries[msg.sender];
|
||||||
|
uint256 idx = _registeredIndex[msg.sender];
|
||||||
|
if (idx != 0) {
|
||||||
|
uint256 lastIdx = registered.length;
|
||||||
|
if (idx != lastIdx) {
|
||||||
|
address swapped = registered[lastIdx - 1];
|
||||||
|
registered[idx - 1] = swapped;
|
||||||
|
_registeredIndex[swapped] = idx;
|
||||||
|
}
|
||||||
|
registered.pop();
|
||||||
|
delete _registeredIndex[msg.sender];
|
||||||
|
}
|
||||||
|
emit Unregistered(msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Anyone may call to update `lastSeenNonce` for an account.
|
||||||
|
/// Indexers + paymasters call this after observing a tx from
|
||||||
|
/// the account so the registry reflects fresh activity.
|
||||||
|
function notifyNonce(address account, uint256 nonce) external {
|
||||||
|
Entry storage e = entries[account];
|
||||||
|
if (!e.registered) revert NotRegistered();
|
||||||
|
if (nonce > e.lastSeenNonce) {
|
||||||
|
e.lastSeenNonce = nonce;
|
||||||
|
e.lastSeenAt = uint64(block.timestamp);
|
||||||
|
emit NonceSeen(account, nonce, uint64(block.timestamp));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------- views -------------------------------- */
|
||||||
|
|
||||||
|
function registeredCount() external view returns (uint256) { return registered.length; }
|
||||||
|
|
||||||
|
function isRegistered(address account) external view returns (bool) {
|
||||||
|
return entries[account].registered;
|
||||||
|
}
|
||||||
|
|
||||||
|
function page(uint256 start, uint256 count) external view returns (address[] memory out) {
|
||||||
|
uint256 n = registered.length;
|
||||||
|
if (start >= n) return new address[](0);
|
||||||
|
uint256 end = start + count;
|
||||||
|
if (end > n) end = n;
|
||||||
|
out = new address[](end - start);
|
||||||
|
for (uint256 i = start; i < end; i++) {
|
||||||
|
out[i - start] = registered[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereComputeMarket — DePIN compute coordination layer
|
||||||
|
* @notice The ON-CHAIN coordination + settlement layer for a decentralized
|
||||||
|
* compute marketplace (DePIN-for-AI). Providers stake native AERE and
|
||||||
|
* advertise capacity; requesters escrow AERE for a job; the provider
|
||||||
|
* does the work OFF-CHAIN and submits a result hash; the requester
|
||||||
|
* confirms (or a timeout auto-confirms) and payment is released. A
|
||||||
|
* dispute window lets the requester challenge, with Foundation
|
||||||
|
* arbitration and provider-stake slashing.
|
||||||
|
*
|
||||||
|
* SCOPE (honest): this contract is the trust/settlement rail. The actual
|
||||||
|
* GPU/compute supply is off-chain and requires real hardware providers —
|
||||||
|
* the network is only as real as the providers who join. No new token:
|
||||||
|
* staking, escrow and payment are all in native AERE.
|
||||||
|
*/
|
||||||
|
contract AereComputeMarket is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
uint256 public constant MIN_STAKE = 10 ether; // 10 AERE to be a provider
|
||||||
|
uint64 public constant CONFIRM_WINDOW = 3 days; // requester confirm/dispute window
|
||||||
|
uint16 public constant SLASH_BPS = 5000; // 50% of stake slashed on lost dispute
|
||||||
|
|
||||||
|
address public immutable FOUNDATION; // dispute arbiter
|
||||||
|
|
||||||
|
struct Provider {
|
||||||
|
bool active;
|
||||||
|
uint256 stake;
|
||||||
|
uint32 pricePerUnit; // informational, AERE-wei per compute unit
|
||||||
|
uint32 activeJobs; // outstanding claimed/submitted jobs
|
||||||
|
string endpoint; // provider API endpoint (off-chain)
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Status { None, Open, Claimed, Submitted, Paid, Refunded, Slashed }
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
address requester;
|
||||||
|
address provider;
|
||||||
|
uint256 payment; // escrowed AERE
|
||||||
|
bytes32 specHash; // hash of the off-chain job spec
|
||||||
|
bytes32 resultHash; // hash of the off-chain result
|
||||||
|
Status status;
|
||||||
|
uint64 submittedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(address => Provider) public providers;
|
||||||
|
mapping(uint256 => Job) public jobs;
|
||||||
|
uint256 public jobCount;
|
||||||
|
uint256 public slashPool; // slashed stake, sweepable by Foundation to the sink/treasury
|
||||||
|
|
||||||
|
event ProviderRegistered(address indexed provider, uint256 stake, uint32 pricePerUnit, string endpoint);
|
||||||
|
event ProviderDeregistered(address indexed provider, uint256 stakeReturned);
|
||||||
|
event JobPosted(uint256 indexed id, address indexed requester, uint256 payment, bytes32 specHash);
|
||||||
|
event JobClaimed(uint256 indexed id, address indexed provider);
|
||||||
|
event JobSubmitted(uint256 indexed id, bytes32 resultHash);
|
||||||
|
event JobPaid(uint256 indexed id, address indexed provider, uint256 payment);
|
||||||
|
event JobRefunded(uint256 indexed id, address indexed requester, uint256 payment);
|
||||||
|
event JobDisputed(uint256 indexed id);
|
||||||
|
event DisputeResolved(uint256 indexed id, bool providerWon);
|
||||||
|
|
||||||
|
error BadStake();
|
||||||
|
error NotProvider();
|
||||||
|
error HasActiveJobs();
|
||||||
|
error ZeroPayment();
|
||||||
|
error WrongStatus();
|
||||||
|
error NotRequester();
|
||||||
|
error NotJobProvider();
|
||||||
|
error WindowOpen();
|
||||||
|
error WindowClosed();
|
||||||
|
error ZeroAddress();
|
||||||
|
|
||||||
|
constructor(address foundation) {
|
||||||
|
if (foundation == address(0)) revert ZeroAddress();
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert("not foundation");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ providers ------------------------------- */
|
||||||
|
|
||||||
|
function registerProvider(uint32 pricePerUnit, string calldata endpoint) external payable {
|
||||||
|
if (msg.value < MIN_STAKE) revert BadStake();
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
p.active = true;
|
||||||
|
p.stake += msg.value;
|
||||||
|
p.pricePerUnit = pricePerUnit;
|
||||||
|
p.endpoint = endpoint;
|
||||||
|
emit ProviderRegistered(msg.sender, p.stake, pricePerUnit, endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deregisterProvider() external nonReentrant {
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
if (!p.active) revert NotProvider();
|
||||||
|
if (p.activeJobs != 0) revert HasActiveJobs();
|
||||||
|
uint256 amt = p.stake;
|
||||||
|
p.active = false;
|
||||||
|
p.stake = 0;
|
||||||
|
(bool ok, ) = msg.sender.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit ProviderDeregistered(msg.sender, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- jobs ---------------------------------- */
|
||||||
|
|
||||||
|
function postJob(bytes32 specHash) external payable returns (uint256 id) {
|
||||||
|
if (msg.value == 0) revert ZeroPayment();
|
||||||
|
id = jobCount++;
|
||||||
|
jobs[id] = Job({
|
||||||
|
requester: msg.sender, provider: address(0), payment: msg.value,
|
||||||
|
specHash: specHash, resultHash: bytes32(0), status: Status.Open, submittedAt: 0
|
||||||
|
});
|
||||||
|
emit JobPosted(id, msg.sender, msg.value, specHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Requester cancels an unclaimed job and reclaims the escrow.
|
||||||
|
function cancelJob(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
j.status = Status.Refunded;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
(bool ok, ) = msg.sender.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobRefunded(id, msg.sender, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function claimJob(uint256 id) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
if (!p.active || p.stake < MIN_STAKE) revert NotProvider();
|
||||||
|
j.provider = msg.sender;
|
||||||
|
j.status = Status.Claimed;
|
||||||
|
p.activeJobs += 1;
|
||||||
|
emit JobClaimed(id, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitResult(uint256 id, bytes32 resultHash) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.provider != msg.sender) revert NotJobProvider();
|
||||||
|
if (j.status != Status.Claimed) revert WrongStatus();
|
||||||
|
j.resultHash = resultHash;
|
||||||
|
j.status = Status.Submitted;
|
||||||
|
j.submittedAt = uint64(block.timestamp);
|
||||||
|
emit JobSubmitted(id, resultHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Requester accepts the result → pay the provider immediately.
|
||||||
|
function confirmJob(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
_pay(id, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice After the confirm window with no dispute, anyone can settle → pay provider.
|
||||||
|
function autoConfirm(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp < j.submittedAt + CONFIRM_WINDOW) revert WindowOpen();
|
||||||
|
_pay(id, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _pay(uint256 id, Job storage j) internal {
|
||||||
|
j.status = Status.Paid;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
providers[j.provider].activeJobs -= 1;
|
||||||
|
(bool ok, ) = j.provider.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobPaid(id, j.provider, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ disputes -------------------------------- */
|
||||||
|
|
||||||
|
function disputeJob(uint256 id) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp >= j.submittedAt + CONFIRM_WINDOW) revert WindowClosed();
|
||||||
|
j.status = Status.Claimed; // parked pending arbitration; marker below via event
|
||||||
|
// Re-mark to Submitted-disputed is avoided; we keep Claimed + emit; Foundation resolves.
|
||||||
|
emit JobDisputed(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Foundation arbitrates a disputed job. providerWon → provider paid;
|
||||||
|
/// else requester refunded AND provider stake slashed by SLASH_BPS.
|
||||||
|
function resolveDispute(uint256 id, bool providerWon) external onlyFoundation nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Claimed || j.provider == address(0) || j.submittedAt == 0) revert WrongStatus();
|
||||||
|
Provider storage p = providers[j.provider];
|
||||||
|
p.activeJobs -= 1;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
if (providerWon) {
|
||||||
|
j.status = Status.Paid;
|
||||||
|
(bool ok, ) = j.provider.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobPaid(id, j.provider, amt);
|
||||||
|
} else {
|
||||||
|
j.status = Status.Slashed;
|
||||||
|
uint256 slash = (p.stake * SLASH_BPS) / 10_000;
|
||||||
|
p.stake -= slash;
|
||||||
|
slashPool += slash;
|
||||||
|
(bool ok, ) = j.requester.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobRefunded(id, j.requester, amt);
|
||||||
|
}
|
||||||
|
emit DisputeResolved(id, providerWon);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweepSlashPool(address to) external onlyFoundation nonReentrant {
|
||||||
|
uint256 amt = slashPool;
|
||||||
|
slashPool = 0;
|
||||||
|
(bool ok, ) = to.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereComputeMarketV2 - DePIN compute coordination + settlement rail
|
||||||
|
* @notice The ON-CHAIN coordination and settlement layer for a decentralized
|
||||||
|
* compute marketplace (DePIN for AI and verifiable compute). Providers
|
||||||
|
* stake native AERE and advertise capacity; requesters escrow AERE for a
|
||||||
|
* job; the provider runs the work OFF-CHAIN and submits a result; the
|
||||||
|
* requester confirms (or a timeout auto-confirms) and payment releases.
|
||||||
|
* A dispute window lets the requester challenge, with Foundation
|
||||||
|
* arbitration and provider-stake slashing.
|
||||||
|
*
|
||||||
|
* WHAT V2 ADDS OVER V1 (0xf0c8178a5d9feb0f70C5f184e79edeEDaddcF350):
|
||||||
|
* 1. Self-contained jobs. `postJob` takes the FULL workload spec as
|
||||||
|
* bytes and emits it in the JobPosted event, so ANY provider daemon
|
||||||
|
* watching the chain learns exactly what to compute with no off-chain
|
||||||
|
* channel. The contract stores only keccak256(spec) as the anchor.
|
||||||
|
* 2. Verifiable determinism. `submitResult` takes the FULL result bytes
|
||||||
|
* and emits them; the contract stores keccak256(result). The requester
|
||||||
|
* (or anyone) re-runs the deterministic workload from the on-chain
|
||||||
|
* spec and checks keccak256(localResult) == the on-chain resultHash.
|
||||||
|
* 3. A distinct Disputed status. Once a job is disputed it can no longer
|
||||||
|
* be re-submitted by the provider to dodge arbitration (a V1 flaw);
|
||||||
|
* only the Foundation can resolve it.
|
||||||
|
* 4. Bootstrap-configurable MIN_STAKE (constructor immutable) so the
|
||||||
|
* stake floor is a governance parameter rather than a hardcode.
|
||||||
|
*
|
||||||
|
* SCOPE (honest): this contract is the trust and settlement RAIL. The
|
||||||
|
* actual GPU/compute supply is off-chain and requires real hardware
|
||||||
|
* providers. The rail is fully operational (anyone can stake and run the
|
||||||
|
* reference provider daemon to earn), but large-scale supply is adoption,
|
||||||
|
* exactly like validator decentralization. No new token: staking, escrow
|
||||||
|
* and payment are all in native AERE.
|
||||||
|
*/
|
||||||
|
contract AereComputeMarketV2 is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
uint256 public immutable MIN_STAKE; // stake floor to be a provider (set at deploy)
|
||||||
|
uint64 public constant CONFIRM_WINDOW = 3 days; // requester confirm/dispute window
|
||||||
|
uint16 public constant SLASH_BPS = 5000; // 50% of stake slashed on a lost dispute
|
||||||
|
|
||||||
|
address public immutable FOUNDATION; // dispute arbiter
|
||||||
|
|
||||||
|
struct Provider {
|
||||||
|
bool active;
|
||||||
|
uint256 stake;
|
||||||
|
uint32 pricePerUnit; // informational, AERE-wei per compute unit
|
||||||
|
uint32 activeJobs; // outstanding claimed/submitted/disputed jobs
|
||||||
|
string endpoint; // provider API endpoint (off-chain, optional)
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Status { None, Open, Claimed, Submitted, Disputed, Paid, Refunded, Slashed }
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
address requester;
|
||||||
|
address provider;
|
||||||
|
uint256 payment; // escrowed AERE
|
||||||
|
bytes32 specHash; // keccak256 of the workload spec (spec bytes emitted in event)
|
||||||
|
bytes32 resultHash; // keccak256 of the result (result bytes emitted in event)
|
||||||
|
Status status;
|
||||||
|
uint64 submittedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(address => Provider) public providers;
|
||||||
|
mapping(uint256 => Job) public jobs;
|
||||||
|
uint256 public jobCount;
|
||||||
|
uint256 public slashPool; // slashed stake, sweepable by Foundation to the sink/treasury
|
||||||
|
|
||||||
|
event ProviderRegistered(address indexed provider, uint256 stake, uint32 pricePerUnit, string endpoint);
|
||||||
|
event ProviderDeregistered(address indexed provider, uint256 stakeReturned);
|
||||||
|
// spec bytes are emitted (non-indexed) so any watcher can reconstruct the workload.
|
||||||
|
event JobPosted(uint256 indexed id, address indexed requester, uint256 payment, bytes32 specHash, bytes spec);
|
||||||
|
event JobClaimed(uint256 indexed id, address indexed provider);
|
||||||
|
// result bytes are emitted so the requester can verify determinism against specHash off-chain.
|
||||||
|
event JobSubmitted(uint256 indexed id, bytes32 resultHash, bytes result);
|
||||||
|
event JobPaid(uint256 indexed id, address indexed provider, uint256 payment);
|
||||||
|
event JobRefunded(uint256 indexed id, address indexed requester, uint256 payment);
|
||||||
|
event JobDisputed(uint256 indexed id);
|
||||||
|
event DisputeResolved(uint256 indexed id, bool providerWon);
|
||||||
|
|
||||||
|
error BadStake();
|
||||||
|
error NotProvider();
|
||||||
|
error HasActiveJobs();
|
||||||
|
error ZeroPayment();
|
||||||
|
error WrongStatus();
|
||||||
|
error NotRequester();
|
||||||
|
error NotJobProvider();
|
||||||
|
error WindowOpen();
|
||||||
|
error WindowClosed();
|
||||||
|
error ZeroAddress();
|
||||||
|
error EmptySpec();
|
||||||
|
|
||||||
|
constructor(address foundation, uint256 minStake) {
|
||||||
|
if (foundation == address(0)) revert ZeroAddress();
|
||||||
|
if (minStake == 0) revert BadStake();
|
||||||
|
FOUNDATION = foundation;
|
||||||
|
MIN_STAKE = minStake;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier onlyFoundation() {
|
||||||
|
if (msg.sender != FOUNDATION) revert("not foundation");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ providers ------------------------------- */
|
||||||
|
|
||||||
|
function registerProvider(uint32 pricePerUnit, string calldata endpoint) external payable {
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
if (p.stake + msg.value < MIN_STAKE) revert BadStake();
|
||||||
|
p.active = true;
|
||||||
|
p.stake += msg.value;
|
||||||
|
p.pricePerUnit = pricePerUnit;
|
||||||
|
p.endpoint = endpoint;
|
||||||
|
emit ProviderRegistered(msg.sender, p.stake, pricePerUnit, endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deregisterProvider() external nonReentrant {
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
if (!p.active) revert NotProvider();
|
||||||
|
if (p.activeJobs != 0) revert HasActiveJobs();
|
||||||
|
uint256 amt = p.stake;
|
||||||
|
p.active = false;
|
||||||
|
p.stake = 0;
|
||||||
|
(bool ok, ) = msg.sender.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit ProviderDeregistered(msg.sender, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- jobs ---------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Post a job with its FULL workload spec. The spec bytes are emitted
|
||||||
|
/// so any provider daemon can reconstruct and run it deterministically.
|
||||||
|
function postJob(bytes calldata spec) external payable returns (uint256 id) {
|
||||||
|
if (msg.value == 0) revert ZeroPayment();
|
||||||
|
if (spec.length == 0) revert EmptySpec();
|
||||||
|
bytes32 specHash = keccak256(spec);
|
||||||
|
id = jobCount++;
|
||||||
|
jobs[id] = Job({
|
||||||
|
requester: msg.sender, provider: address(0), payment: msg.value,
|
||||||
|
specHash: specHash, resultHash: bytes32(0), status: Status.Open, submittedAt: 0
|
||||||
|
});
|
||||||
|
emit JobPosted(id, msg.sender, msg.value, specHash, spec);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Requester cancels an unclaimed job and reclaims the escrow.
|
||||||
|
function cancelJob(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
j.status = Status.Refunded;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
(bool ok, ) = msg.sender.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobRefunded(id, msg.sender, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function claimJob(uint256 id) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
Provider storage p = providers[msg.sender];
|
||||||
|
if (!p.active || p.stake < MIN_STAKE) revert NotProvider();
|
||||||
|
j.provider = msg.sender;
|
||||||
|
j.status = Status.Claimed;
|
||||||
|
p.activeJobs += 1;
|
||||||
|
emit JobClaimed(id, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Provider submits the FULL result bytes. keccak256(result) is stored
|
||||||
|
/// on-chain as the verifiable anchor; the bytes are emitted for re-run.
|
||||||
|
function submitResult(uint256 id, bytes calldata result) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.provider != msg.sender) revert NotJobProvider();
|
||||||
|
if (j.status != Status.Claimed) revert WrongStatus();
|
||||||
|
bytes32 resultHash = keccak256(result);
|
||||||
|
j.resultHash = resultHash;
|
||||||
|
j.status = Status.Submitted;
|
||||||
|
j.submittedAt = uint64(block.timestamp);
|
||||||
|
emit JobSubmitted(id, resultHash, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Requester accepts the result, pay the provider immediately.
|
||||||
|
function confirmJob(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
_pay(id, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice After the confirm window with no dispute, anyone can settle, pay provider.
|
||||||
|
function autoConfirm(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp < j.submittedAt + CONFIRM_WINDOW) revert WindowOpen();
|
||||||
|
_pay(id, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _pay(uint256 id, Job storage j) internal {
|
||||||
|
j.status = Status.Paid;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
providers[j.provider].activeJobs -= 1;
|
||||||
|
(bool ok, ) = j.provider.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobPaid(id, j.provider, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ disputes -------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Requester challenges a submitted result within the confirm window.
|
||||||
|
/// The job moves to Disputed and can no longer be re-submitted; only
|
||||||
|
/// the Foundation can resolve it.
|
||||||
|
function disputeJob(uint256 id) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp >= j.submittedAt + CONFIRM_WINDOW) revert WindowClosed();
|
||||||
|
j.status = Status.Disputed;
|
||||||
|
emit JobDisputed(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Foundation arbitrates a disputed job. providerWon -> provider paid;
|
||||||
|
/// else requester refunded AND provider stake slashed by SLASH_BPS.
|
||||||
|
function resolveDispute(uint256 id, bool providerWon) external onlyFoundation nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Disputed) revert WrongStatus();
|
||||||
|
Provider storage p = providers[j.provider];
|
||||||
|
p.activeJobs -= 1;
|
||||||
|
uint256 amt = j.payment;
|
||||||
|
j.payment = 0;
|
||||||
|
if (providerWon) {
|
||||||
|
j.status = Status.Paid;
|
||||||
|
(bool ok, ) = j.provider.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobPaid(id, j.provider, amt);
|
||||||
|
} else {
|
||||||
|
j.status = Status.Slashed;
|
||||||
|
uint256 slash = (p.stake * SLASH_BPS) / 10_000;
|
||||||
|
p.stake -= slash;
|
||||||
|
slashPool += slash;
|
||||||
|
(bool ok, ) = j.requester.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
emit JobRefunded(id, j.requester, amt);
|
||||||
|
}
|
||||||
|
emit DisputeResolved(id, providerWon);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sweepSlashPool(address to) external onlyFoundation nonReentrant {
|
||||||
|
if (to == address(0)) revert ZeroAddress();
|
||||||
|
uint256 amt = slashPool;
|
||||||
|
slashPool = 0;
|
||||||
|
(bool ok, ) = to.call{value: amt}("");
|
||||||
|
require(ok, "xfer");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------- views --------------------------------- */
|
||||||
|
|
||||||
|
/// @notice Convenience getter for off-chain daemons.
|
||||||
|
function getJob(uint256 id) external view returns (Job memory) {
|
||||||
|
return jobs[id];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,606 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import {ISP1Verifier} from "../zkverify/ISP1Verifier.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereComputeMarketV3, the proof-carrying DePIN compute marketplace for Aere Network
|
||||||
|
*
|
||||||
|
* @notice The unified verification and settlement rail for decentralized compute (DePIN for AI
|
||||||
|
* and verifiable compute). A REQUESTER posts a job (a spec-hash commitment, a reward held
|
||||||
|
* in escrow, a deadline, and a required VERIFICATION MODE); a PROVIDER claims it, runs the
|
||||||
|
* work OFF-CHAIN, and submits a result whose acceptance depends on the job's mode. A
|
||||||
|
* provider is paid only against verifiable evidence, never on trust alone.
|
||||||
|
*
|
||||||
|
* WHAT V3 UNIFIES OVER V1 / V2 (V2 = the coordination layer with a single optimistic +
|
||||||
|
* Foundation-arbitration path). V3 makes the VERIFICATION RAIL a first-class, per-job
|
||||||
|
* choice and adds a post-quantum settlement gate.
|
||||||
|
*
|
||||||
|
* THREE VERIFICATION MODES (per job, chosen by the requester).
|
||||||
|
* REPLAY. The result is a deterministic function of the input. The full result bytes are
|
||||||
|
* emitted on submission so any watcher can re-run the spec and check keccak256(localResult)
|
||||||
|
* against the on-chain resultHash. Accepted after a challenge window unless a challenger
|
||||||
|
* posts a matching bond and disputes; the dispute (with the challenger's recomputed
|
||||||
|
* resultHash on record) is resolved by the configured arbiter.
|
||||||
|
* ZK_VERIFIED. The result carries a zero-knowledge proof verified ON-CHAIN through the
|
||||||
|
* existing deployed SP1 gateway verifier. Payment is released in the SAME transaction as
|
||||||
|
* the proof, and ONLY if the proof verifies. There is no other code path that pays a
|
||||||
|
* ZK_VERIFIED job, so it is impossible to pay one without a valid proof.
|
||||||
|
* OPTIMISTIC. The result is accepted after a challenge window unless a challenger posts a
|
||||||
|
* bond and disputes. A successful dispute slashes the PROVIDER bond to the CHALLENGER and
|
||||||
|
* refunds the reward to the requester.
|
||||||
|
*
|
||||||
|
* POST-QUANTUM SETTLEMENT PATH (optional per job). If a job sets pqcSettlement, the final
|
||||||
|
* release of funds to the provider additionally requires a Falcon-512 signature by the job's
|
||||||
|
* registered settlement key over a domain-separated settlement digest (chainId, this
|
||||||
|
* contract, jobId, provider, token, amount, resultHash), verified IN FULL on-chain by the
|
||||||
|
* live native precompile at 0x0AE1. The payout authorization is therefore post-quantum: a
|
||||||
|
* quantum adversary who forged the classical tx sender still cannot authorize the payout
|
||||||
|
* without the Falcon private key. Fail-closed: a tampered or missing signature reverts the
|
||||||
|
* release and nothing is paid.
|
||||||
|
*
|
||||||
|
* SETTLEMENT ASSET. Rewards settle in native AERE (token == address(0)) or an allowlisted
|
||||||
|
* ERC-20. No new token is introduced. Provider and challenger BONDS are always native AERE
|
||||||
|
* (the chain staking asset). Solvency is tracked per asset.
|
||||||
|
*
|
||||||
|
* FAIL-CLOSED GUARANTEES.
|
||||||
|
* - No double-pay: every job reaches a terminal status (Paid / Refunded / Slashed) exactly
|
||||||
|
* once; all fund-moving entrypoints are reentrancy-guarded and follow checks-effects-
|
||||||
|
* interactions.
|
||||||
|
* - No pay-without-proof in ZK_VERIFIED: settlement is inside submitResultZK, after the SP1
|
||||||
|
* gateway verifyProof call (which reverts on an invalid proof).
|
||||||
|
* - Escrow solvency invariant: for every asset, the contract balance is always at least the
|
||||||
|
* sum of open job rewards plus posted bonds in that asset (totalLiabilities). See isSolvent.
|
||||||
|
* - No admin drain: there is no owner and no sweep. The arbiter can only route a DISPUTED
|
||||||
|
* job's escrow between its requester, provider and challenger; governance can only flip a
|
||||||
|
* token allowlist bool. Neither can withdraw escrowed funds.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. This contract is the on-chain verification and settlement RAIL. Real GPU /
|
||||||
|
* accelerator supply, the off-chain provers, and the real SP1 proving are EXTERNAL and are
|
||||||
|
* adoption, not code (see the accompanying doc, marked [MEASURE]). The post-quantum settlement
|
||||||
|
* gate authorizes PAYOUTS; it does NOT make Aere consensus post-quantum (blocks remain Besu
|
||||||
|
* QBFT with classical secp256k1). The zk verifier is the existing deployed SP1 gateway; this
|
||||||
|
* contract references its interface and calls it, it does not reimplement it.
|
||||||
|
*/
|
||||||
|
contract AereComputeMarketV3 is ReentrancyGuard {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
// ----------------------------- verification modes ----------------------------
|
||||||
|
enum Mode {
|
||||||
|
REPLAY, // 0 deterministic recompute, optimistic challenge window
|
||||||
|
ZK_VERIFIED, // 1 on-chain SP1 proof, pay only on a valid proof
|
||||||
|
OPTIMISTIC // 2 general optimistic, challenge window with provider bond slashing
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------- job lifecycle ---------------------------------
|
||||||
|
enum Status {
|
||||||
|
None, // 0 never posted
|
||||||
|
Open, // 1 posted, escrowed, unclaimed
|
||||||
|
Claimed, // 2 claimed by a provider, running off-chain
|
||||||
|
Submitted, // 3 result submitted (REPLAY / OPTIMISTIC), in the challenge window
|
||||||
|
Disputed, // 4 challenged, awaiting arbiter resolution
|
||||||
|
Paid, // 5 terminal, provider paid
|
||||||
|
Refunded, // 6 terminal, requester refunded
|
||||||
|
Slashed // 7 terminal, dispute upheld, provider bond slashed to challenger
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------- live precompile -------------------------------
|
||||||
|
/// @notice Live Falcon-512 verification precompile on Aere mainnet 2800 (activated block 9,189,161).
|
||||||
|
address public constant FALCON512_PRECOMPILE = address(0x0AE1);
|
||||||
|
uint256 internal constant FALCON512_PK_LEN = 897;
|
||||||
|
uint8 internal constant FALCON512_PK_HEADER = 0x09; // 0x00 | logn=9
|
||||||
|
uint256 internal constant FALCON_NONCE_LEN = 40;
|
||||||
|
|
||||||
|
/// @notice Domain separator for the Falcon settlement authorization digest.
|
||||||
|
bytes32 public constant SETTLEMENT_DOMAIN = keccak256("AereComputeMarketV3.v1.settlement");
|
||||||
|
|
||||||
|
// ----------------------------- immutable wiring ------------------------------
|
||||||
|
/// @notice The deployed SP1 gateway verifier used to check ZK_VERIFIED proofs on-chain.
|
||||||
|
ISP1Verifier public immutable ZK_VERIFIER;
|
||||||
|
/// @notice Resolves DISPUTED jobs. Can only route a disputed job's escrow; cannot drain.
|
||||||
|
address public immutable ARBITER;
|
||||||
|
/// @notice Can flip the ERC-20 reward-token allowlist. Cannot move funds. Native AERE is always allowed.
|
||||||
|
address public immutable GOVERNANCE;
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
address requester;
|
||||||
|
address provider;
|
||||||
|
address token; // address(0) = native AERE, else an allowlisted ERC-20
|
||||||
|
uint256 reward; // escrowed reward, zeroed on terminal settlement
|
||||||
|
uint256 providerBond; // native AERE bond posted by the provider (REPLAY / OPTIMISTIC)
|
||||||
|
bytes32 specHash; // keccak256 of the workload spec
|
||||||
|
bytes32 resultHash; // keccak256 of the result (set on submission)
|
||||||
|
bytes32 zkProgramVKey; // ZK_VERIFIED: the pinned SP1 program verification key
|
||||||
|
Mode mode;
|
||||||
|
Status status;
|
||||||
|
bool pqcSettlement; // require a Falcon-512 authorization to release the payout
|
||||||
|
uint64 deadline; // submission deadline
|
||||||
|
uint64 challengeWindow; // REPLAY / OPTIMISTIC challenge window (seconds)
|
||||||
|
uint64 submittedAt; // timestamp of result submission
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Parameters for posting a job. A struct keeps the postJob stack shallow.
|
||||||
|
struct JobParams {
|
||||||
|
address token; // address(0) native AERE, else an allowlisted ERC-20
|
||||||
|
uint256 reward; // reward amount (must equal msg.value when token is native)
|
||||||
|
uint256 providerBond; // required provider bond for REPLAY / OPTIMISTIC (native AERE)
|
||||||
|
bytes32 specHash; // keccak256 of the workload spec
|
||||||
|
bytes32 zkProgramVKey; // ZK_VERIFIED only: the SP1 program vkey to verify against
|
||||||
|
Mode mode;
|
||||||
|
uint64 deadline; // absolute unix time by which a result must be submitted
|
||||||
|
uint64 challengeWindow; // REPLAY / OPTIMISTIC challenge window (seconds)
|
||||||
|
bool pqcSettlement; // require a Falcon-512 payout authorization
|
||||||
|
bytes falconPubKey; // 897-byte Falcon-512 settlement key (required iff pqcSettlement)
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(uint256 => Job) public jobs;
|
||||||
|
mapping(uint256 => bytes) public falconPubKeyOf; // jobId => Falcon-512 settlement key (pqc jobs)
|
||||||
|
mapping(uint256 => uint256) public requiredBondOf; // jobId => native-AERE bond a provider must post to claim
|
||||||
|
mapping(uint256 => address) public challengerOf; // jobId => active challenger
|
||||||
|
mapping(uint256 => uint256) public challengerBondOf; // jobId => challenger bond (native AERE)
|
||||||
|
mapping(uint256 => bytes32) public challengeResultHashOf; // jobId => challenger's recomputed resultHash (REPLAY)
|
||||||
|
uint256 public jobCount;
|
||||||
|
|
||||||
|
/// @notice ERC-20 reward tokens the requester may escrow (native AERE is always allowed).
|
||||||
|
mapping(address => bool) public tokenAllowed;
|
||||||
|
|
||||||
|
/// @notice Total open obligations per asset: sum of open job rewards plus posted bonds. The
|
||||||
|
/// contract balance in each asset is always at least this (see isSolvent).
|
||||||
|
mapping(address => uint256) public totalLiabilities;
|
||||||
|
|
||||||
|
// -------------------------------- events -------------------------------------
|
||||||
|
event TokenAllowed(address indexed token, bool allowed);
|
||||||
|
event JobPosted(
|
||||||
|
uint256 indexed id,
|
||||||
|
address indexed requester,
|
||||||
|
address indexed token,
|
||||||
|
uint256 reward,
|
||||||
|
Mode mode,
|
||||||
|
bytes32 specHash,
|
||||||
|
uint64 deadline,
|
||||||
|
bool pqcSettlement
|
||||||
|
);
|
||||||
|
event JobClaimed(uint256 indexed id, address indexed provider, uint256 providerBond);
|
||||||
|
// Result bytes emitted for REPLAY / OPTIMISTIC so challengers can re-run and check determinism.
|
||||||
|
event ResultSubmitted(uint256 indexed id, bytes32 resultHash, bytes result);
|
||||||
|
event ResultVerifiedZK(uint256 indexed id, bytes32 resultHash, bytes32 zkProgramVKey);
|
||||||
|
event JobDisputed(uint256 indexed id, address indexed challenger, uint256 bond, bytes32 recomputedResultHash);
|
||||||
|
event DisputeResolved(uint256 indexed id, bool providerWon);
|
||||||
|
event JobPaid(uint256 indexed id, address indexed provider, address indexed token, uint256 reward, uint256 bondReturned);
|
||||||
|
event JobRefunded(uint256 indexed id, address indexed requester, address indexed token, uint256 reward);
|
||||||
|
event JobSlashed(uint256 indexed id, address indexed challenger, uint256 slashedProviderBond);
|
||||||
|
event PQCSettlementAuthorized(uint256 indexed id, bytes32 settlementDigest);
|
||||||
|
|
||||||
|
// -------------------------------- errors -------------------------------------
|
||||||
|
error ZeroAddress();
|
||||||
|
error VerifierHasNoCode();
|
||||||
|
error NotArbiter();
|
||||||
|
error NotGovernance();
|
||||||
|
error TokenNotAllowed(address token);
|
||||||
|
error BadReward();
|
||||||
|
error BadValue(); // msg.value mismatch
|
||||||
|
error BadSpec();
|
||||||
|
error BadDeadline();
|
||||||
|
error BadWindow();
|
||||||
|
error BadBond();
|
||||||
|
error BadVKey();
|
||||||
|
error BadFalconKey();
|
||||||
|
error WrongStatus();
|
||||||
|
error NotRequester();
|
||||||
|
error NotJobProvider();
|
||||||
|
error DeadlinePassed();
|
||||||
|
error DeadlineNotPassed();
|
||||||
|
error WindowOpen();
|
||||||
|
error WindowClosed();
|
||||||
|
error BadPublicValues();
|
||||||
|
error ResultMismatch();
|
||||||
|
error NotPQCAuthorized();
|
||||||
|
error PQCSigNotAllowed(); // pqc signature supplied for a non-pqc job
|
||||||
|
error TransferFailed();
|
||||||
|
|
||||||
|
modifier onlyArbiter() {
|
||||||
|
if (msg.sender != ARBITER) revert NotArbiter();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
modifier onlyGovernance() {
|
||||||
|
if (msg.sender != GOVERNANCE) revert NotGovernance();
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(address zkVerifier, address arbiter, address governance) {
|
||||||
|
if (zkVerifier == address(0) || arbiter == address(0) || governance == address(0)) revert ZeroAddress();
|
||||||
|
// A code-less ZK verifier would make verifyProof (which returns no data) succeed silently, so a
|
||||||
|
// ZK_VERIFIED job would pay the provider with NO valid proof. Guard it exactly as the sibling
|
||||||
|
// AereFinalityCertificateVerifier does. The deployed value must be the live SP1 gateway.
|
||||||
|
if (zkVerifier.code.length == 0) revert VerifierHasNoCode();
|
||||||
|
ZK_VERIFIER = ISP1Verifier(zkVerifier);
|
||||||
|
ARBITER = arbiter;
|
||||||
|
GOVERNANCE = governance;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Token allowlist (governance)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice Allow or disallow an ERC-20 as a reward asset. Governance-only. Cannot move funds.
|
||||||
|
/// Native AERE (address(0)) is always allowed and is not tracked here.
|
||||||
|
function setTokenAllowed(address token, bool allowed) external onlyGovernance {
|
||||||
|
if (token == address(0)) revert ZeroAddress();
|
||||||
|
tokenAllowed[token] = allowed;
|
||||||
|
emit TokenAllowed(token, allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Post a job
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice Post a job and escrow its reward. Native AERE requires msg.value == reward; an
|
||||||
|
/// allowlisted ERC-20 requires msg.value == 0 and a prior approval to this contract.
|
||||||
|
function postJob(JobParams calldata p) external payable nonReentrant returns (uint256 id) {
|
||||||
|
if (p.reward == 0) revert BadReward();
|
||||||
|
if (p.specHash == bytes32(0)) revert BadSpec();
|
||||||
|
if (p.deadline <= block.timestamp) revert BadDeadline();
|
||||||
|
|
||||||
|
// Mode-specific validation.
|
||||||
|
if (p.mode == Mode.ZK_VERIFIED) {
|
||||||
|
if (p.zkProgramVKey == bytes32(0)) revert BadVKey();
|
||||||
|
// ZK jobs carry no provider bond: the proof is the guarantee.
|
||||||
|
if (p.providerBond != 0) revert BadBond();
|
||||||
|
} else {
|
||||||
|
// REPLAY / OPTIMISTIC need a challenge window and a non-zero provider bond to slash.
|
||||||
|
if (p.challengeWindow == 0) revert BadWindow();
|
||||||
|
if (p.providerBond == 0) revert BadBond();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Post-quantum settlement key validation.
|
||||||
|
if (p.pqcSettlement) {
|
||||||
|
if (p.falconPubKey.length != FALCON512_PK_LEN || uint8(p.falconPubKey[0]) != FALCON512_PK_HEADER) {
|
||||||
|
revert BadFalconKey();
|
||||||
|
}
|
||||||
|
} else if (p.falconPubKey.length != 0) {
|
||||||
|
revert BadFalconKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escrow the reward (interaction before state so a fee-on-transfer token cannot under-fund).
|
||||||
|
if (p.token == address(0)) {
|
||||||
|
if (msg.value != p.reward) revert BadValue();
|
||||||
|
} else {
|
||||||
|
if (!tokenAllowed[p.token]) revert TokenNotAllowed(p.token);
|
||||||
|
if (msg.value != 0) revert BadValue();
|
||||||
|
uint256 balBefore = IERC20(p.token).balanceOf(address(this));
|
||||||
|
IERC20(p.token).safeTransferFrom(msg.sender, address(this), p.reward);
|
||||||
|
uint256 received = IERC20(p.token).balanceOf(address(this)) - balBefore;
|
||||||
|
if (received != p.reward) revert BadReward(); // reject fee-on-transfer / rebasing tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
id = jobCount++;
|
||||||
|
jobs[id] = Job({
|
||||||
|
requester: msg.sender,
|
||||||
|
provider: address(0),
|
||||||
|
token: p.token,
|
||||||
|
reward: p.reward,
|
||||||
|
providerBond: 0,
|
||||||
|
specHash: p.specHash,
|
||||||
|
resultHash: bytes32(0),
|
||||||
|
zkProgramVKey: p.zkProgramVKey,
|
||||||
|
mode: p.mode,
|
||||||
|
status: Status.Open,
|
||||||
|
pqcSettlement: p.pqcSettlement,
|
||||||
|
deadline: p.deadline,
|
||||||
|
challengeWindow: p.challengeWindow,
|
||||||
|
submittedAt: 0
|
||||||
|
});
|
||||||
|
totalLiabilities[p.token] += p.reward;
|
||||||
|
if (p.mode != Mode.ZK_VERIFIED) requiredBondOf[id] = p.providerBond;
|
||||||
|
if (p.pqcSettlement) falconPubKeyOf[id] = p.falconPubKey;
|
||||||
|
|
||||||
|
emit JobPosted(id, msg.sender, p.token, p.reward, p.mode, p.specHash, p.deadline, p.pqcSettlement);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Requester reclaims the escrow of an unclaimed job at any time.
|
||||||
|
function cancelJob(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
j.status = Status.Refunded;
|
||||||
|
uint256 amt = j.reward;
|
||||||
|
j.reward = 0;
|
||||||
|
totalLiabilities[j.token] -= amt;
|
||||||
|
_payout(j.token, msg.sender, amt);
|
||||||
|
emit JobRefunded(id, msg.sender, j.token, amt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Claim a job
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice A provider claims an open job. For REPLAY / OPTIMISTIC the provider must post exactly
|
||||||
|
/// the job's required native-AERE bond (msg.value). For ZK_VERIFIED, msg.value must be 0.
|
||||||
|
function claimJob(uint256 id) external payable nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Open) revert WrongStatus();
|
||||||
|
if (block.timestamp > j.deadline) revert DeadlinePassed();
|
||||||
|
|
||||||
|
uint256 requiredBond = j.mode == Mode.ZK_VERIFIED ? 0 : requiredBondOf[id];
|
||||||
|
if (msg.value != requiredBond) revert BadValue();
|
||||||
|
|
||||||
|
j.provider = msg.sender;
|
||||||
|
j.providerBond = msg.value;
|
||||||
|
j.status = Status.Claimed;
|
||||||
|
if (msg.value != 0) totalLiabilities[address(0)] += msg.value;
|
||||||
|
|
||||||
|
emit JobClaimed(id, msg.sender, msg.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Submit a result (REPLAY / OPTIMISTIC)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice Provider submits the full result bytes for a REPLAY or OPTIMISTIC job. keccak256(result)
|
||||||
|
/// is stored as the on-chain anchor and the bytes are emitted so anyone can re-run (REPLAY)
|
||||||
|
/// or check (OPTIMISTIC) the work. The challenge window starts now.
|
||||||
|
function submitResult(uint256 id, bytes calldata result) external {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.provider != msg.sender) revert NotJobProvider();
|
||||||
|
if (j.status != Status.Claimed) revert WrongStatus();
|
||||||
|
if (j.mode == Mode.ZK_VERIFIED) revert WrongStatus(); // ZK jobs settle via submitResultZK
|
||||||
|
if (block.timestamp > j.deadline) revert DeadlinePassed();
|
||||||
|
|
||||||
|
bytes32 resultHash = keccak256(result);
|
||||||
|
j.resultHash = resultHash;
|
||||||
|
j.status = Status.Submitted;
|
||||||
|
j.submittedAt = uint64(block.timestamp);
|
||||||
|
emit ResultSubmitted(id, resultHash, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Submit a result (ZK_VERIFIED, pay on valid proof)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice Provider submits a ZK_VERIFIED result with an SP1 proof. The proof is verified on-chain
|
||||||
|
/// through the deployed SP1 gateway; the reward is released to the provider in THIS
|
||||||
|
/// transaction and ONLY if the proof verifies. There is no other path that pays a
|
||||||
|
/// ZK_VERIFIED job, so payment without a valid proof is impossible.
|
||||||
|
/// @param id the job id.
|
||||||
|
/// @param publicValues the SP1 public values, ABI-encoded as (bytes32 specHash, bytes32 resultHash).
|
||||||
|
/// specHash must equal the job's committed spec; resultHash is recorded.
|
||||||
|
/// @param proofBytes the SP1 proof; the first 4 bytes select the gateway route.
|
||||||
|
/// @param pqcSig Falcon-512 settlement authorization (only if the job set pqcSettlement; empty otherwise).
|
||||||
|
function submitResultZK(uint256 id, bytes calldata publicValues, bytes calldata proofBytes, bytes calldata pqcSig)
|
||||||
|
external
|
||||||
|
nonReentrant
|
||||||
|
{
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.provider != msg.sender) revert NotJobProvider();
|
||||||
|
if (j.status != Status.Claimed) revert WrongStatus();
|
||||||
|
if (j.mode != Mode.ZK_VERIFIED) revert WrongStatus();
|
||||||
|
if (block.timestamp > j.deadline) revert DeadlinePassed();
|
||||||
|
|
||||||
|
// Bind the proof's public values to THIS job's spec, and record the proven result.
|
||||||
|
if (publicValues.length != 64) revert BadPublicValues();
|
||||||
|
(bytes32 provenSpecHash, bytes32 provenResultHash) = abi.decode(publicValues, (bytes32, bytes32));
|
||||||
|
if (provenSpecHash != j.specHash) revert BadPublicValues();
|
||||||
|
j.resultHash = provenResultHash;
|
||||||
|
|
||||||
|
// On-chain verification through the deployed SP1 gateway. Reverts on an invalid proof, so a
|
||||||
|
// rejected proof reverts the whole transaction and pays nothing (fail-closed).
|
||||||
|
ZK_VERIFIER.verifyProof(j.zkProgramVKey, publicValues, proofBytes);
|
||||||
|
|
||||||
|
emit ResultVerifiedZK(id, provenResultHash, j.zkProgramVKey);
|
||||||
|
|
||||||
|
// Settle immediately: pay only now that the proof has verified.
|
||||||
|
_settleToProvider(id, j, pqcSig);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Accept / finalize (REPLAY / OPTIMISTIC)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice Requester accepts a submitted result early (before the window closes) and pays the provider.
|
||||||
|
function acceptResult(uint256 id, bytes calldata pqcSig) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
_settleToProvider(id, j, pqcSig);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice After the challenge window closes with no dispute, anyone can finalize and pay the provider.
|
||||||
|
function finalize(uint256 id, bytes calldata pqcSig) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp < uint256(j.submittedAt) + j.challengeWindow) revert WindowOpen();
|
||||||
|
_settleToProvider(id, j, pqcSig);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice If a claimed job blows its deadline without a submission, the requester reclaims the
|
||||||
|
/// reward and the provider bond is slashed to the requester (provider fault).
|
||||||
|
function reclaimExpired(uint256 id) external nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.requester != msg.sender) revert NotRequester();
|
||||||
|
if (j.status != Status.Claimed) revert WrongStatus();
|
||||||
|
if (block.timestamp <= j.deadline) revert DeadlineNotPassed();
|
||||||
|
|
||||||
|
j.status = Status.Refunded;
|
||||||
|
uint256 reward = j.reward;
|
||||||
|
uint256 bond = j.providerBond;
|
||||||
|
j.reward = 0;
|
||||||
|
j.providerBond = 0;
|
||||||
|
totalLiabilities[j.token] -= reward;
|
||||||
|
if (bond != 0) totalLiabilities[address(0)] -= bond;
|
||||||
|
|
||||||
|
_payout(j.token, msg.sender, reward);
|
||||||
|
if (bond != 0) _payout(address(0), msg.sender, bond); // provider bond slashed to requester
|
||||||
|
emit JobRefunded(id, msg.sender, j.token, reward);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Disputes
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice A challenger disputes a submitted REPLAY / OPTIMISTIC result within the window, posting
|
||||||
|
/// a native-AERE bond equal to the provider bond. For REPLAY the challenger records the
|
||||||
|
/// resultHash they recomputed, so the arbiter (and any observer) can verify determinism.
|
||||||
|
function dispute(uint256 id, bytes32 recomputedResultHash) external payable nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Submitted) revert WrongStatus();
|
||||||
|
if (block.timestamp >= uint256(j.submittedAt) + j.challengeWindow) revert WindowClosed();
|
||||||
|
if (msg.value != j.providerBond) revert BadValue();
|
||||||
|
|
||||||
|
j.status = Status.Disputed;
|
||||||
|
challengerOf[id] = msg.sender;
|
||||||
|
challengerBondOf[id] = msg.value;
|
||||||
|
challengeResultHashOf[id] = recomputedResultHash;
|
||||||
|
totalLiabilities[address(0)] += msg.value;
|
||||||
|
|
||||||
|
emit JobDisputed(id, msg.sender, msg.value, recomputedResultHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The arbiter resolves a disputed job. It may only route the escrow between the job's
|
||||||
|
/// requester, provider and challenger; it can never withdraw funds elsewhere.
|
||||||
|
/// providerWon == true : result upheld. Provider takes the reward, its bond back, and the
|
||||||
|
/// challenger's forfeited bond.
|
||||||
|
/// providerWon == false: dispute upheld. Reward refunded to the requester; the PROVIDER
|
||||||
|
/// bond is slashed to the challenger, who also gets its own bond back.
|
||||||
|
function resolveDispute(uint256 id, bool providerWon) external onlyArbiter nonReentrant {
|
||||||
|
Job storage j = jobs[id];
|
||||||
|
if (j.status != Status.Disputed) revert WrongStatus();
|
||||||
|
|
||||||
|
address challenger = challengerOf[id];
|
||||||
|
uint256 chBond = challengerBondOf[id];
|
||||||
|
uint256 reward = j.reward;
|
||||||
|
uint256 pBond = j.providerBond;
|
||||||
|
address token = j.token;
|
||||||
|
address provider = j.provider;
|
||||||
|
address requester = j.requester;
|
||||||
|
|
||||||
|
// Effects first.
|
||||||
|
j.reward = 0;
|
||||||
|
j.providerBond = 0;
|
||||||
|
challengerBondOf[id] = 0;
|
||||||
|
totalLiabilities[token] -= reward;
|
||||||
|
totalLiabilities[address(0)] -= (pBond + chBond);
|
||||||
|
|
||||||
|
if (providerWon) {
|
||||||
|
j.status = Status.Paid;
|
||||||
|
_payout(token, provider, reward);
|
||||||
|
if (pBond != 0) _payout(address(0), provider, pBond); // bond returned
|
||||||
|
if (chBond != 0) _payout(address(0), provider, chBond); // challenger forfeits
|
||||||
|
emit JobPaid(id, provider, token, reward, pBond);
|
||||||
|
} else {
|
||||||
|
j.status = Status.Slashed;
|
||||||
|
_payout(token, requester, reward); // reward refunded
|
||||||
|
if (chBond != 0) _payout(address(0), challenger, chBond); // challenger bond returned
|
||||||
|
if (pBond != 0) _payout(address(0), challenger, pBond); // provider bond slashed to challenger
|
||||||
|
emit JobSlashed(id, challenger, pBond);
|
||||||
|
}
|
||||||
|
emit DisputeResolved(id, providerWon);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Settlement (shared internal)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @dev Release a job's reward (and return the provider bond) to the provider. If the job requires
|
||||||
|
/// a post-quantum settlement authorization, a valid Falcon-512 signature by the job's
|
||||||
|
/// settlement key over the settlement digest is required; a tampered or missing signature
|
||||||
|
/// reverts and nothing is paid (fail-closed). Sets the terminal status before any transfer.
|
||||||
|
function _settleToProvider(uint256 id, Job storage j, bytes calldata pqcSig) internal {
|
||||||
|
address provider = j.provider;
|
||||||
|
address token = j.token;
|
||||||
|
uint256 reward = j.reward;
|
||||||
|
uint256 bond = j.providerBond;
|
||||||
|
|
||||||
|
if (j.pqcSettlement) {
|
||||||
|
bytes32 digest = settlementDigest(id, provider, token, reward, j.resultHash);
|
||||||
|
if (!_falconVerify(falconPubKeyOf[id], digest, pqcSig)) revert NotPQCAuthorized();
|
||||||
|
emit PQCSettlementAuthorized(id, digest);
|
||||||
|
} else if (pqcSig.length != 0) {
|
||||||
|
revert PQCSigNotAllowed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effects.
|
||||||
|
j.status = Status.Paid;
|
||||||
|
j.reward = 0;
|
||||||
|
j.providerBond = 0;
|
||||||
|
totalLiabilities[token] -= reward;
|
||||||
|
if (bond != 0) totalLiabilities[address(0)] -= bond;
|
||||||
|
|
||||||
|
// Interactions.
|
||||||
|
_payout(token, provider, reward);
|
||||||
|
if (bond != 0) _payout(address(0), provider, bond);
|
||||||
|
emit JobPaid(id, provider, token, reward, bond);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Transfer `amt` of `token` (address(0) = native AERE) to `to`. No-op on a zero amount.
|
||||||
|
function _payout(address token, address to, uint256 amt) internal {
|
||||||
|
if (amt == 0) return;
|
||||||
|
if (token == address(0)) {
|
||||||
|
(bool ok,) = to.call{value: amt}("");
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
} else {
|
||||||
|
IERC20(token).safeTransfer(to, amt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Post-quantum settlement authorization
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice The 32-byte digest a settlement key must Falcon-512-sign to authorize a payout. Binds
|
||||||
|
/// chainId + this contract + the job id + provider + token + amount + resultHash, so an
|
||||||
|
/// authorization can never be replayed to another job, chain, contract, or payout figure.
|
||||||
|
function settlementDigest(uint256 id, address provider, address token, uint256 amount, bytes32 resultHash)
|
||||||
|
public
|
||||||
|
view
|
||||||
|
returns (bytes32)
|
||||||
|
{
|
||||||
|
return keccak256(abi.encode(SETTLEMENT_DOMAIN, block.chainid, address(this), id, provider, token, amount, resultHash));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev Verify a Falcon-512 signature by `pubKey` over the 32-byte `message` through the live
|
||||||
|
/// precompile at 0x0AE1. Byte-identical input encoding to AerePQCMessageVerifier
|
||||||
|
/// (input = pk || sm, sm = sigLen(2, big-endian) || nonce(40) || message || esig). Fail-closed:
|
||||||
|
/// returns false (never reverts) on any malformed input or an empty / zero precompile return.
|
||||||
|
function _falconVerify(bytes memory pubKey, bytes32 message, bytes memory signature) internal view returns (bool) {
|
||||||
|
if (pubKey.length != FALCON512_PK_LEN) return false;
|
||||||
|
if (signature.length <= FALCON_NONCE_LEN) return false;
|
||||||
|
uint256 sigLen = signature.length - FALCON_NONCE_LEN; // esig length
|
||||||
|
if (sigLen > type(uint16).max) return false;
|
||||||
|
|
||||||
|
bytes memory nonce = _slice(signature, 0, FALCON_NONCE_LEN);
|
||||||
|
bytes memory esig = _slice(signature, FALCON_NONCE_LEN, sigLen);
|
||||||
|
bytes memory msgBytes = abi.encodePacked(message); // 32 bytes
|
||||||
|
bytes memory sm = abi.encodePacked(uint16(sigLen), nonce, msgBytes, esig);
|
||||||
|
bytes memory input = abi.encodePacked(pubKey, sm);
|
||||||
|
|
||||||
|
(bool ok, bytes memory ret) = FALCON512_PRECOMPILE.staticcall(input);
|
||||||
|
return ok && ret.length >= 32 && ret[31] == 0x01;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _slice(bytes memory data, uint256 start, uint256 len) internal pure returns (bytes memory out) {
|
||||||
|
out = new bytes(len);
|
||||||
|
for (uint256 i = 0; i < len; i++) {
|
||||||
|
out[i] = data[start + i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Views
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
/// @notice The escrow-solvency invariant for an asset (address(0) = native AERE): the contract
|
||||||
|
/// balance is at least the sum of open job rewards plus posted bonds in that asset.
|
||||||
|
function isSolvent(address token) public view returns (bool) {
|
||||||
|
uint256 bal = token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this));
|
||||||
|
return bal >= totalLiabilities[token];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Read a full job record.
|
||||||
|
function getJob(uint256 id) external view returns (Job memory) {
|
||||||
|
return jobs[id];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
|
||||||
|
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
|
||||||
|
import "./AereVaultRelayer.sol";
|
||||||
|
import "./AereSolverRegistry.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSettlement
|
||||||
|
* @notice Batch-auction MEV-resistant DEX for AERE.
|
||||||
|
*
|
||||||
|
* Users sign EIP-712 orders off-chain (no gas). An authorised solver collects
|
||||||
|
* open orders, finds a uniform clearing price per token pair, and submits the
|
||||||
|
* whole batch atomically via `settle()`. The contract:
|
||||||
|
* 1. Verifies each user's EIP-712 signature.
|
||||||
|
* 2. Checks each order's deadline and per-token cap.
|
||||||
|
* 3. Pulls each order's sellAmount via AereVaultRelayer (users approved that contract).
|
||||||
|
* 4. Routes the inter-order trades atomically — coincidence-of-wants matches
|
||||||
|
* at the uniform price.
|
||||||
|
* 5. Pays each user their executedBuyAmount (which must be ≥ minBuyAmount).
|
||||||
|
*
|
||||||
|
* MEV protection comes from atomicity: the whole batch executes in one transaction,
|
||||||
|
* so no actor can insert a sandwich tx between two orders in the batch.
|
||||||
|
*
|
||||||
|
* Permissioned solvers in Phase 1 (AereSolverRegistry-controlled). Phase 2 adds
|
||||||
|
* permissionless bonded-solver entry.
|
||||||
|
*
|
||||||
|
* This is a simplified port of CoW Protocol's GPv2Settlement — captures the core
|
||||||
|
* batch-atomic-clearing primitive without the full feature set (partial fills,
|
||||||
|
* ERC-1271, balance modes, dynamic fees). Audit-grade hardening deferred to Phase 2.
|
||||||
|
*/
|
||||||
|
contract AereSettlement is Ownable, ReentrancyGuard, EIP712 {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
AereVaultRelayer public immutable vaultRelayer;
|
||||||
|
AereSolverRegistry public immutable solverRegistry;
|
||||||
|
|
||||||
|
/// EIP-712 order struct.
|
||||||
|
/// Buy/sell tokens, amounts, deadline, salt (for replay protection).
|
||||||
|
struct Order {
|
||||||
|
address user;
|
||||||
|
IERC20 sellToken;
|
||||||
|
IERC20 buyToken;
|
||||||
|
uint256 sellAmount; // exact sell amount (fill-or-kill in v1)
|
||||||
|
uint256 minBuyAmount; // user-specified slippage floor
|
||||||
|
uint64 validTo; // unix deadline
|
||||||
|
uint256 salt; // unique-per-user replay nonce
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the solver claims it will execute for this order, given the batch's
|
||||||
|
/// uniform clearing price. Must satisfy executedBuyAmount >= order.minBuyAmount.
|
||||||
|
struct Execution {
|
||||||
|
uint256 executedBuyAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes32 private constant ORDER_TYPEHASH = keccak256(
|
||||||
|
"Order(address user,address sellToken,address buyToken,uint256 sellAmount,uint256 minBuyAmount,uint64 validTo,uint256 salt)"
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Replay protection: orderHash → consumed.
|
||||||
|
mapping(bytes32 => bool) public filled;
|
||||||
|
|
||||||
|
event Settled(address indexed solver, uint256 orderCount, uint256 timestamp);
|
||||||
|
event OrderFilled(
|
||||||
|
bytes32 indexed orderHash,
|
||||||
|
address indexed user,
|
||||||
|
address sellToken,
|
||||||
|
address buyToken,
|
||||||
|
uint256 sellAmount,
|
||||||
|
uint256 buyAmount
|
||||||
|
);
|
||||||
|
|
||||||
|
modifier onlySolver() {
|
||||||
|
require(solverRegistry.isSolver(msg.sender), "Settlement: not a solver");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(AereVaultRelayer _vault, AereSolverRegistry _registry) EIP712("AereSettlement", "1") {
|
||||||
|
vaultRelayer = _vault;
|
||||||
|
solverRegistry = _registry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute the canonical hash of an order for EIP-712 verification.
|
||||||
|
function orderHash(Order calldata o) public view returns (bytes32) {
|
||||||
|
bytes32 structHash = keccak256(abi.encode(
|
||||||
|
ORDER_TYPEHASH,
|
||||||
|
o.user,
|
||||||
|
address(o.sellToken),
|
||||||
|
address(o.buyToken),
|
||||||
|
o.sellAmount,
|
||||||
|
o.minBuyAmount,
|
||||||
|
o.validTo,
|
||||||
|
o.salt
|
||||||
|
));
|
||||||
|
return _hashTypedDataV4(structHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Settle a batch of orders atomically.
|
||||||
|
* @dev Solver must provide one signature per order and one execution amount per order.
|
||||||
|
* The solver is responsible for sourcing buyToken liquidity (via internal CoW
|
||||||
|
* matching between orders, or by interacting with AereSwap, or by holding its
|
||||||
|
* own inventory). After the batch, every user must have received at least their
|
||||||
|
* minBuyAmount of buyToken.
|
||||||
|
*
|
||||||
|
* Implementation: this contract pulls sellTokens FROM each user TO the solver
|
||||||
|
* via the VaultRelayer, then expects the solver to push buyTokens to each user.
|
||||||
|
* Solver supplies buyTokens from its working capital + post-batch arbitrage.
|
||||||
|
*/
|
||||||
|
function settle(
|
||||||
|
Order[] calldata orders,
|
||||||
|
bytes[] calldata signatures,
|
||||||
|
Execution[] calldata executions
|
||||||
|
) external onlySolver nonReentrant {
|
||||||
|
require(orders.length == signatures.length && orders.length == executions.length,
|
||||||
|
"Settlement: length mismatch");
|
||||||
|
require(orders.length > 0, "Settlement: empty batch");
|
||||||
|
|
||||||
|
for (uint256 i = 0; i < orders.length; i++) {
|
||||||
|
Order calldata o = orders[i];
|
||||||
|
require(block.timestamp <= o.validTo, "Settlement: order expired");
|
||||||
|
require(executions[i].executedBuyAmount >= o.minBuyAmount, "Settlement: below minBuy");
|
||||||
|
|
||||||
|
bytes32 h = orderHash(o);
|
||||||
|
require(!filled[h], "Settlement: already filled");
|
||||||
|
|
||||||
|
// Verify EIP-712 signature.
|
||||||
|
address signer = ECDSA.recover(h, signatures[i]);
|
||||||
|
require(signer == o.user, "Settlement: bad signature");
|
||||||
|
|
||||||
|
filled[h] = true;
|
||||||
|
|
||||||
|
// 1. Pull sellAmount from user → solver. (VaultRelayer has approval.)
|
||||||
|
vaultRelayer.transferFromUser(o.sellToken, o.user, msg.sender, o.sellAmount);
|
||||||
|
|
||||||
|
// 2. Solver MUST push executedBuyAmount of buyToken to user.
|
||||||
|
// The settlement contract orchestrates by pulling from solver and pushing to user.
|
||||||
|
// Solver must approve THIS contract for buyToken first (or use internal CoW match
|
||||||
|
// where the buyToken flows from another order's sellToken — handled outside this loop).
|
||||||
|
o.buyToken.safeTransferFrom(msg.sender, o.user, executions[i].executedBuyAmount);
|
||||||
|
|
||||||
|
emit OrderFilled(h, o.user, address(o.sellToken), address(o.buyToken), o.sellAmount, executions[i].executedBuyAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit Settled(msg.sender, orders.length, block.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User can cancel an open order on-chain (rare; mostly orders expire naturally).
|
||||||
|
function cancelOrder(Order calldata o) external {
|
||||||
|
require(msg.sender == o.user, "Settlement: not order owner");
|
||||||
|
filled[orderHash(o)] = true; // mark consumed → solver can't fill
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether an order is still openable.
|
||||||
|
function isOrderFillable(Order calldata o) external view returns (bool) {
|
||||||
|
return !filled[orderHash(o)] && block.timestamp <= o.validTo;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereSolverRegistry
|
||||||
|
* @notice Allowlist of solvers permitted to call AereSettlement.settle().
|
||||||
|
*
|
||||||
|
* Phase 1 (current): owner-curated allowlist. Foundation adds vetted solvers.
|
||||||
|
* Phase 2 (later): permissionless solver entry with bonded stake — anyone
|
||||||
|
* can become a solver by posting an AERE bond; the bond is slashable for
|
||||||
|
* misbehavior (settling at unfavorable clearing prices, censoring orders,
|
||||||
|
* etc). Slashing logic deferred to Phase 2 audit.
|
||||||
|
*
|
||||||
|
* Mirror of CoW Protocol's GPv2AllowListAuthentication pattern.
|
||||||
|
*/
|
||||||
|
contract AereSolverRegistry is Ownable {
|
||||||
|
mapping(address => bool) public isSolver;
|
||||||
|
address[] public solvers;
|
||||||
|
|
||||||
|
event SolverAdded(address indexed solver);
|
||||||
|
event SolverRemoved(address indexed solver);
|
||||||
|
|
||||||
|
function addSolver(address solver) external onlyOwner {
|
||||||
|
require(solver != address(0), "Registry: zero address");
|
||||||
|
require(!isSolver[solver], "Registry: already a solver");
|
||||||
|
isSolver[solver] = true;
|
||||||
|
solvers.push(solver);
|
||||||
|
emit SolverAdded(solver);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSolver(address solver) external onlyOwner {
|
||||||
|
require(isSolver[solver], "Registry: not a solver");
|
||||||
|
isSolver[solver] = false;
|
||||||
|
for (uint256 i = 0; i < solvers.length; i++) {
|
||||||
|
if (solvers[i] == solver) {
|
||||||
|
solvers[i] = solvers[solvers.length - 1];
|
||||||
|
solvers.pop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit SolverRemoved(solver);
|
||||||
|
}
|
||||||
|
|
||||||
|
function solverCount() external view returns (uint256) {
|
||||||
|
return solvers.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereVaultRelayer
|
||||||
|
* @notice Token allowance proxy for the AereSettlement batch DEX.
|
||||||
|
* Users approve THIS contract once for each token they intend to trade
|
||||||
|
* (typically MaxUint256). AereSettlement calls into the relayer to pull
|
||||||
|
* tokens during batch settlement.
|
||||||
|
*
|
||||||
|
* Following CoW Protocol's GPv2VaultRelayer pattern — separates token
|
||||||
|
* allowances from the settlement contract so the settlement contract
|
||||||
|
* can be upgraded without users having to re-approve.
|
||||||
|
*/
|
||||||
|
contract AereVaultRelayer is Ownable {
|
||||||
|
using SafeERC20 for IERC20;
|
||||||
|
|
||||||
|
/// The single authorised caller (AereSettlement). Owner can rotate it.
|
||||||
|
address public settlement;
|
||||||
|
|
||||||
|
event SettlementChanged(address indexed previousSettlement, address indexed newSettlement);
|
||||||
|
|
||||||
|
modifier onlySettlement() {
|
||||||
|
require(msg.sender == settlement, "Relayer: caller not settlement");
|
||||||
|
_;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSettlement(address _settlement) external onlyOwner {
|
||||||
|
emit SettlementChanged(settlement, _settlement);
|
||||||
|
settlement = _settlement;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pull `amount` of `token` from `from` to `to`. Only callable by the settlement contract.
|
||||||
|
function transferFromUser(IERC20 token, address from, address to, uint256 amount) external onlySettlement {
|
||||||
|
token.safeTransferFrom(from, to, amount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/// @dev The one AerePQCKeyRegistry read used to verify a mandate's post-quantum signature. Live at
|
||||||
|
/// 0x1eCa…3691 on chain 2800; verifyWithKey routes to the native precompile for the key's
|
||||||
|
/// scheme (0x0AE1 Falcon-512) and verifies in full on-chain, fail-closed.
|
||||||
|
interface IAerePQCKeyRegistryMandate {
|
||||||
|
function verifyWithKey(uint256 keyId, bytes32 message, bytes calldata signature) external view returns (bool);
|
||||||
|
function statusOf(uint256 keyId) external view returns (uint8);
|
||||||
|
function schemeOf(uint256 keyId) external view returns (uint8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereAP2MandateVerifier, a post-quantum x402 / AP2 payment-mandate verifier
|
||||||
|
*
|
||||||
|
* @notice A minimal verifier for AP2-style payment MANDATES whose authorizing signature is
|
||||||
|
* POST-QUANTUM (Falcon-512), verified in full on-chain by Aere Network's LIVE native
|
||||||
|
* precompile (0x0AE1) through the already-deployed AerePQCKeyRegistry. Settlement of the
|
||||||
|
* authorized spend is routed through the EXISTING AERE402 rail (AERE402FacilitatorPQC /
|
||||||
|
* AERE402FacilitatorV2), which is NOT redeployed or modified here.
|
||||||
|
*
|
||||||
|
* WHAT AN AP2 / x402 MANDATE IS. A signed, standing authorization of the form
|
||||||
|
* "agent X may spend up to N of token T per period P for purpose Q". In AP2 (Google) and
|
||||||
|
* x402 (Coinbase) today that authorization is an ECDSA signature, which a quantum computer
|
||||||
|
* forges. Here the authorizing key is a Falcon-512 key in AerePQCKeyRegistry, so the mandate
|
||||||
|
* is quantum-durable. The struct and the verify path are below.
|
||||||
|
*
|
||||||
|
* THE STRUCT. A Mandate binds the paying agent's Falcon key, the token, the spend cap, the
|
||||||
|
* validity window, an opaque purpose tag, and a mandate nonce (so an agent can issue several
|
||||||
|
* independent standing mandates). Its `mandateHash` binds chainId + this contract so a
|
||||||
|
* signed mandate cannot be replayed against another verifier or chain.
|
||||||
|
*
|
||||||
|
* THE VERIFY PATH.
|
||||||
|
* - verifyMandate(m, falconSig): pure on-chain PQC check that the agent's Falcon key
|
||||||
|
* signed `m` (view; anyone can check for free via eth_call).
|
||||||
|
* - authorizeSpend(m, amount, falconSig): the enforced path. Verifies the Falcon mandate
|
||||||
|
* signature via the live precompile, checks the validity window and the cumulative cap,
|
||||||
|
* records the spend against the mandate, and emits MandateAuthorized. Reverts fail-closed
|
||||||
|
* on an invalid / tampered signature, an out-of-window mandate, or a cap overflow.
|
||||||
|
*
|
||||||
|
* SETTLEMENT ROUTING. authorizeSpend records that `amount` is authorized under the mandate;
|
||||||
|
* the actual token movement + 25-bps fee to AereSink is performed by the live AERE402 rail.
|
||||||
|
* To keep the mandate's cumulative cap honest (only real settlements should consume it),
|
||||||
|
* authorizeSpend is gated to an immutable SETTLEMENT_EXECUTOR when one is configured (the
|
||||||
|
* AERE402 facilitator, which calls authorizeSpend atomically with settlement). When
|
||||||
|
* SETTLEMENT_EXECUTOR is the zero address the accounting path is open (for verification and
|
||||||
|
* testing); the pure PQC check verifyMandate is always open.
|
||||||
|
*
|
||||||
|
* [DEPLOY CONSTRAINT, accepted-and-documented risk] A Falcon mandate signature is a STANDING
|
||||||
|
* authorization by design: one signature authorizes repeated spends up to the cap, and the
|
||||||
|
* signature is public. So in the OPEN accounting path (SETTLEMENT_EXECUTOR == address(0)) ANY
|
||||||
|
* address that observes the signature can replay authorizeSpend to consume the mandate's
|
||||||
|
* remaining cap WITHOUT a real settlement (cap-exhaustion griefing; no custody, no theft, since
|
||||||
|
* this contract moves no funds). The mitigation is built in and MUST be used in production: set
|
||||||
|
* SETTLEMENT_EXECUTOR to the AERE402 facilitator so cap consumption only ever happens ALONGSIDE
|
||||||
|
* a real settlement (the gate is enforced in authorizeSpend and proven in the tests). The open
|
||||||
|
* path is intended ONLY for eth_call verification and unit testing and MUST NOT be used for a
|
||||||
|
* production deployment. A per-authorization nonce is deliberately NOT added here because it
|
||||||
|
* would break the intended standing-mandate ("sign once, spend repeatedly up to the cap")
|
||||||
|
* semantics; the executor gate closes the vector without that trade-off.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY: confirm against the finalized x402 / AP2 mandate schema] The x402 and AP2 mandate
|
||||||
|
* field sets are still evolving (AP2 distinguishes Intent vs Cart mandates; x402 carries an
|
||||||
|
* HTTP-402 payment payload). This struct captures the common "spend up to N per period for
|
||||||
|
* purpose Q" authorization; reconcile the exact field set and encoding with the final specs
|
||||||
|
* before claiming wire-level conformance.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer payment authorization only. Does NOT change AERE consensus
|
||||||
|
* (still Besu QBFT classical ECDSA). Holds NO funds (the cap is accounting, not custody; the
|
||||||
|
* AERE402 rail custodies and moves value). No admin.
|
||||||
|
*/
|
||||||
|
contract AereAP2MandateVerifier {
|
||||||
|
/// @notice Falcon-512 is the mandate signing scheme (live precompile 0x0AE1).
|
||||||
|
uint8 public constant SCHEME_FALCON512 = 1;
|
||||||
|
uint8 internal constant REGISTRY_STATUS_ACTIVE = 1;
|
||||||
|
|
||||||
|
/// @notice Domain separator binding a mandate hash to this verifier.
|
||||||
|
bytes32 public constant MANDATE_DOMAIN = keccak256("AereAP2MandateVerifier.v1.mandate");
|
||||||
|
|
||||||
|
/// @notice The LIVE AerePQCKeyRegistry that verifies the Falcon mandate signature via 0x0AE1.
|
||||||
|
IAerePQCKeyRegistryMandate public immutable KEY_REGISTRY;
|
||||||
|
|
||||||
|
/// @notice The AERE402 settlement executor allowed to consume a mandate's cap. Zero = open path.
|
||||||
|
address public immutable SETTLEMENT_EXECUTOR;
|
||||||
|
|
||||||
|
/// @notice An AP2 / x402 payment mandate: "agentKey may spend up to maxAmount of token per the
|
||||||
|
/// [periodStart, periodEnd] window for `purpose`". mandateNonce distinguishes an agent's
|
||||||
|
/// several standing mandates.
|
||||||
|
struct Mandate {
|
||||||
|
uint256 agentKeyId; // the paying agent's Falcon-512 key in AerePQCKeyRegistry
|
||||||
|
address token; // the settlement token the cap is denominated in
|
||||||
|
uint256 maxAmount; // cumulative spend cap over the window
|
||||||
|
uint64 periodStart; // unix seconds, inclusive
|
||||||
|
uint64 periodEnd; // unix seconds, inclusive (>= periodStart)
|
||||||
|
bytes32 purpose; // opaque purpose tag, e.g. keccak256("inference:anthropic")
|
||||||
|
uint256 mandateNonce; // per-agent mandate index (lets an agent hold several mandates)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice mandateHash => cumulative amount already authorized under that mandate.
|
||||||
|
mapping(bytes32 => uint256) public spentUnder;
|
||||||
|
|
||||||
|
event MandateAuthorized(
|
||||||
|
bytes32 indexed mandateHash,
|
||||||
|
uint256 indexed agentKeyId,
|
||||||
|
address indexed token,
|
||||||
|
uint256 amount,
|
||||||
|
uint256 cumulative,
|
||||||
|
bytes32 purpose
|
||||||
|
);
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error NotSettlementExecutor();
|
||||||
|
error AgentKeyNotActiveFalcon(uint256 agentKeyId);
|
||||||
|
error InvalidMandateWindow(uint64 periodStart, uint64 periodEnd);
|
||||||
|
error MandateNotYetValid(uint64 periodStart);
|
||||||
|
error MandateExpired(uint64 periodEnd);
|
||||||
|
error ZeroAmount();
|
||||||
|
error MandateCapExceeded(uint256 cap, uint256 attempted);
|
||||||
|
error MandateSignatureInvalid();
|
||||||
|
|
||||||
|
constructor(address keyRegistry_, address settlementExecutor_) {
|
||||||
|
if (keyRegistry_ == address(0)) revert ZeroAddress();
|
||||||
|
KEY_REGISTRY = IAerePQCKeyRegistryMandate(keyRegistry_);
|
||||||
|
SETTLEMENT_EXECUTOR = settlementExecutor_; // zero allowed = open accounting path
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Mandate hash + pure verify
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice The canonical hash a Falcon mandate signature must sign. Binds chainId + this
|
||||||
|
/// verifier so a mandate cannot be replayed against another verifier or chain.
|
||||||
|
function mandateHash(Mandate calldata m) public view returns (bytes32) {
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(
|
||||||
|
MANDATE_DOMAIN,
|
||||||
|
block.chainid,
|
||||||
|
address(this),
|
||||||
|
m.agentKeyId,
|
||||||
|
m.token,
|
||||||
|
m.maxAmount,
|
||||||
|
m.periodStart,
|
||||||
|
m.periodEnd,
|
||||||
|
m.purpose,
|
||||||
|
m.mandateNonce
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Pure on-chain post-quantum check that the agent's Falcon key signed this mandate.
|
||||||
|
/// View, permissionless: anyone can verify a mandate via eth_call for free. Returns
|
||||||
|
/// false (never reverts) if the key is not an ACTIVE Falcon key or the signature is
|
||||||
|
/// invalid.
|
||||||
|
function verifyMandate(Mandate calldata m, bytes calldata falconSig) external view returns (bool) {
|
||||||
|
if (KEY_REGISTRY.statusOf(m.agentKeyId) != REGISTRY_STATUS_ACTIVE) return false;
|
||||||
|
if (KEY_REGISTRY.schemeOf(m.agentKeyId) != SCHEME_FALCON512) return false;
|
||||||
|
return KEY_REGISTRY.verifyWithKey(m.agentKeyId, mandateHash(m), falconSig);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Authorize (enforced path)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Authorize `amount` of spend under a Falcon-signed mandate. Verifies the post-quantum
|
||||||
|
* mandate signature on-chain via the live precompile, enforces the validity window and
|
||||||
|
* the cumulative cap, records the spend, and emits MandateAuthorized. Fail-closed on any
|
||||||
|
* invalid / tampered signature, an out-of-window mandate, or a cap overflow.
|
||||||
|
*
|
||||||
|
* Gated to SETTLEMENT_EXECUTOR when one is configured, so a mandate's cap is only ever
|
||||||
|
* consumed alongside a real AERE402 settlement (the executor calls this atomically).
|
||||||
|
* PRODUCTION MUST configure SETTLEMENT_EXECUTOR: in the open path (executor == 0) the public
|
||||||
|
* standing signature is replayable by anyone to exhaust the cap (see the contract-level
|
||||||
|
* DEPLOY CONSTRAINT note). The open path is verification / test only.
|
||||||
|
*
|
||||||
|
* @param m the mandate being drawn against.
|
||||||
|
* @param amount the spend to authorize now (charged against the mandate's cumulative cap).
|
||||||
|
* @param falconSig the agent's Falcon-512 signature over mandateHash(m).
|
||||||
|
* @return mh the mandate hash the spend was recorded under.
|
||||||
|
*/
|
||||||
|
function authorizeSpend(Mandate calldata m, uint256 amount, bytes calldata falconSig)
|
||||||
|
external
|
||||||
|
returns (bytes32 mh)
|
||||||
|
{
|
||||||
|
if (SETTLEMENT_EXECUTOR != address(0) && msg.sender != SETTLEMENT_EXECUTOR) revert NotSettlementExecutor();
|
||||||
|
if (amount == 0) revert ZeroAmount();
|
||||||
|
|
||||||
|
// Window checks.
|
||||||
|
if (m.periodEnd < m.periodStart) revert InvalidMandateWindow(m.periodStart, m.periodEnd);
|
||||||
|
if (block.timestamp < m.periodStart) revert MandateNotYetValid(m.periodStart);
|
||||||
|
if (block.timestamp > m.periodEnd) revert MandateExpired(m.periodEnd);
|
||||||
|
|
||||||
|
// The mandate signer must be an ACTIVE Falcon key (rotating / revoking it halts the mandate).
|
||||||
|
if (
|
||||||
|
KEY_REGISTRY.statusOf(m.agentKeyId) != REGISTRY_STATUS_ACTIVE
|
||||||
|
|| KEY_REGISTRY.schemeOf(m.agentKeyId) != SCHEME_FALCON512
|
||||||
|
) revert AgentKeyNotActiveFalcon(m.agentKeyId);
|
||||||
|
|
||||||
|
mh = mandateHash(m);
|
||||||
|
|
||||||
|
// Full on-chain post-quantum verification of the mandate authorization.
|
||||||
|
if (!KEY_REGISTRY.verifyWithKey(m.agentKeyId, mh, falconSig)) revert MandateSignatureInvalid();
|
||||||
|
|
||||||
|
// Cap check (overflow-safe) then record.
|
||||||
|
uint256 already = spentUnder[mh];
|
||||||
|
uint256 next = already + amount;
|
||||||
|
if (next < already || next > m.maxAmount) revert MandateCapExceeded(m.maxAmount, next);
|
||||||
|
spentUnder[mh] = next;
|
||||||
|
|
||||||
|
emit MandateAuthorized(mh, m.agentKeyId, m.token, amount, next, m.purpose);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Remaining spendable amount under a mandate (0 if exhausted). Does NOT check the
|
||||||
|
/// time window or signature; use verifyMandate / authorizeSpend for the full gate.
|
||||||
|
function remainingUnder(Mandate calldata m) external view returns (uint256) {
|
||||||
|
uint256 already = spentUnder[mandateHash(m)];
|
||||||
|
return already >= m.maxAmount ? 0 : m.maxAmount - already;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `m` is within its validity window at the current block time.
|
||||||
|
function isWithinWindow(Mandate calldata m) external view returns (bool) {
|
||||||
|
return block.timestamp >= m.periodStart && block.timestamp <= m.periodEnd && m.periodEnd >= m.periodStart;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/utils/Strings.sol";
|
||||||
|
import "./IERC8004.sol";
|
||||||
|
|
||||||
|
/// @dev The subset of the LIVE, deployed AereAgentDID (chain 2800, 0xce64…22C5) this adapter reads.
|
||||||
|
/// The DID is the Aere-native agent identity: an agent whose ROOT authority is a Falcon key in
|
||||||
|
/// AerePQCKeyRegistry. This adapter never writes to the DID and never redeploys it.
|
||||||
|
interface IAereAgentDIDIdentity {
|
||||||
|
function agentExists(uint256 rootKeyId) external view returns (bool);
|
||||||
|
|
||||||
|
function getAgent(uint256 rootKeyId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (address controller, uint64 createdBlock, uint64 sessionNonce, uint256 sessionCountForAgent);
|
||||||
|
|
||||||
|
function keyRegistry() external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev The one AerePQCKeyRegistry read used to resolve an agent's CURRENT controller.
|
||||||
|
interface IAerePQCKeyRegistryOwner {
|
||||||
|
function ownerOf(uint256 keyId) external view returns (address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereIdentityRegistry8004, an ERC-8004 Identity adapter over the deployed AereAgentDID
|
||||||
|
*
|
||||||
|
* @notice Exposes the ERC-8004 Identity registry surface (register / resolve an agent with a DID
|
||||||
|
* plus an AgentCard metadata URI) over Aere Network's ALREADY-DEPLOYED agent identity
|
||||||
|
* primitive, AereAgentDID. It does NOT redeploy or modify the live DID: it reads the live
|
||||||
|
* DID for agent existence and control, and stores only the ERC-8004 metadata (domain +
|
||||||
|
* AgentCard URI) that the DID itself does not carry.
|
||||||
|
*
|
||||||
|
* IDENTITY ANCHOR. The ERC-8004 agentId IS the AereAgentDID agent id, which is the Falcon
|
||||||
|
* ROOT key id in AerePQCKeyRegistry (agentId == rootKeyId). So an ERC-8004 resolve is a
|
||||||
|
* direct, honest pass-through to the live DID: the agent's on-chain root of authority is a
|
||||||
|
* quantum-durable Falcon key, not a bare secp256k1 address. The DID string is
|
||||||
|
* "did:aere:<chainId>:<agentId>".
|
||||||
|
*
|
||||||
|
* REGISTER = BIND METADATA TO AN EXISTING DID AGENT. `register` does not mint a new
|
||||||
|
* identity (the identity already exists in the live DID). It binds an ERC-8004 AgentCard
|
||||||
|
* URI + domain to an existing DID agent, and is gated to that agent's CURRENT controller
|
||||||
|
* (the registry owner of the Falcon root key), so only the party who proved Falcon
|
||||||
|
* possession can publish the agent's ERC-8004 metadata.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY: confirm against the finalized ERC-8004 interface] The newer ERC-8004 Identity
|
||||||
|
* draft leans on an ERC-721 registration (register(tokenURI) minting a sequential id). Aere
|
||||||
|
* anchors the ERC-8004 identity to the pre-existing Falcon-rooted DID id instead of minting
|
||||||
|
* a fresh sequential id, because the trust root is the on-chain Falcon key, not a token.
|
||||||
|
* The resolve / getAgent / AgentCard-URI SEMANTICS match ERC-8004; the id-minting selector
|
||||||
|
* differs by design and is documented here.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer identity only. This does NOT change AERE consensus (blocks
|
||||||
|
* are still Besu QBFT with classical secp256k1 ECDSA). It holds no funds and has no admin.
|
||||||
|
*/
|
||||||
|
contract AereIdentityRegistry8004 is IERC8004Identity {
|
||||||
|
using Strings for uint256;
|
||||||
|
|
||||||
|
/// @notice The LIVE, deployed AereAgentDID this adapter presents an ERC-8004 face over.
|
||||||
|
IAereAgentDIDIdentity public immutable DID;
|
||||||
|
|
||||||
|
/// @notice The AerePQCKeyRegistry the DID roots into (read from the DID at construction). Used
|
||||||
|
/// only to resolve an agent's current controller (the registry owner of the root key).
|
||||||
|
IAerePQCKeyRegistryOwner public immutable KEY_REGISTRY;
|
||||||
|
|
||||||
|
struct Record {
|
||||||
|
bool registered;
|
||||||
|
string agentDomain;
|
||||||
|
string agentCardURI;
|
||||||
|
address boundController; // controller captured at registration (immutable per Falcon root key)
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(uint256 => Record) private _records; // agentId (== rootKeyId) => ERC-8004 metadata
|
||||||
|
mapping(bytes32 => uint256) private _domainToAgentPlus1; // keccak(domain) => agentId + 1 (0 = unset)
|
||||||
|
mapping(address => uint256[]) private _agentsOfAddress; // controller => agentIds it registered
|
||||||
|
uint256[] private _registeredAgentIds; // append-only list of all registered agentIds
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error UnknownAgent(uint256 agentId);
|
||||||
|
error NotController(uint256 agentId);
|
||||||
|
error AlreadyRegistered(uint256 agentId);
|
||||||
|
error NotRegistered(uint256 agentId);
|
||||||
|
error EmptyDomain();
|
||||||
|
error DomainTaken(string agentDomain);
|
||||||
|
|
||||||
|
constructor(address did) {
|
||||||
|
if (did == address(0)) revert ZeroAddress();
|
||||||
|
DID = IAereAgentDIDIdentity(did);
|
||||||
|
address reg = IAereAgentDIDIdentity(did).keyRegistry();
|
||||||
|
if (reg == address(0)) revert ZeroAddress();
|
||||||
|
KEY_REGISTRY = IAerePQCKeyRegistryOwner(reg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Registration (metadata binding)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Bind ERC-8004 metadata (domain + AgentCard URI) to an existing AereAgentDID agent.
|
||||||
|
* Gated to the agent's CURRENT controller (the registry owner of the Falcon root key).
|
||||||
|
* Does not mint a new identity: the identity already lives in the live DID.
|
||||||
|
* @param agentId the AereAgentDID agent id (== the Falcon root key id).
|
||||||
|
* @param agentDomain the agent's domain (non-empty, unique across this adapter).
|
||||||
|
* @param agentCardURI the AgentCard / registration metadata document URI.
|
||||||
|
*/
|
||||||
|
function register(uint256 agentId, string calldata agentDomain, string calldata agentCardURI) external {
|
||||||
|
if (!DID.agentExists(agentId)) revert UnknownAgent(agentId);
|
||||||
|
address controller = KEY_REGISTRY.ownerOf(agentId);
|
||||||
|
if (controller == address(0) || msg.sender != controller) revert NotController(agentId);
|
||||||
|
if (_records[agentId].registered) revert AlreadyRegistered(agentId);
|
||||||
|
if (bytes(agentDomain).length == 0) revert EmptyDomain();
|
||||||
|
|
||||||
|
bytes32 dk = keccak256(bytes(agentDomain));
|
||||||
|
if (_domainToAgentPlus1[dk] != 0) revert DomainTaken(agentDomain);
|
||||||
|
|
||||||
|
_records[agentId] =
|
||||||
|
Record({registered: true, agentDomain: agentDomain, agentCardURI: agentCardURI, boundController: controller});
|
||||||
|
_domainToAgentPlus1[dk] = agentId + 1;
|
||||||
|
_agentsOfAddress[controller].push(agentId);
|
||||||
|
_registeredAgentIds.push(agentId);
|
||||||
|
|
||||||
|
emit AgentRegistered(agentId, agentDomain, agentCardURI, controller);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Update the ERC-8004 metadata for an already-registered agent. Controller-gated.
|
||||||
|
* Re-indexes the domain (the new domain must be free unless unchanged).
|
||||||
|
*/
|
||||||
|
function updateAgent(uint256 agentId, string calldata newDomain, string calldata newCardURI) external {
|
||||||
|
Record storage r = _records[agentId];
|
||||||
|
if (!r.registered) revert NotRegistered(agentId);
|
||||||
|
address controller = KEY_REGISTRY.ownerOf(agentId);
|
||||||
|
if (controller == address(0) || msg.sender != controller) revert NotController(agentId);
|
||||||
|
if (bytes(newDomain).length == 0) revert EmptyDomain();
|
||||||
|
|
||||||
|
bytes32 oldKey = keccak256(bytes(r.agentDomain));
|
||||||
|
bytes32 newKey = keccak256(bytes(newDomain));
|
||||||
|
if (newKey != oldKey) {
|
||||||
|
if (_domainToAgentPlus1[newKey] != 0) revert DomainTaken(newDomain);
|
||||||
|
delete _domainToAgentPlus1[oldKey];
|
||||||
|
_domainToAgentPlus1[newKey] = agentId + 1;
|
||||||
|
r.agentDomain = newDomain;
|
||||||
|
}
|
||||||
|
r.agentCardURI = newCardURI;
|
||||||
|
|
||||||
|
emit AgentUpdated(agentId, newDomain, newCardURI, controller);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Resolve
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Identity
|
||||||
|
function getAgent(uint256 agentId) public view returns (AgentInfo memory) {
|
||||||
|
Record storage r = _records[agentId];
|
||||||
|
if (!r.registered) revert NotRegistered(agentId);
|
||||||
|
return AgentInfo({
|
||||||
|
agentId: agentId,
|
||||||
|
did: didString(agentId),
|
||||||
|
agentDomain: r.agentDomain,
|
||||||
|
agentCardURI: r.agentCardURI,
|
||||||
|
agentAddress: KEY_REGISTRY.ownerOf(agentId), // current controller, read live
|
||||||
|
registered: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Identity
|
||||||
|
function resolveByDomain(string calldata agentDomain) external view returns (AgentInfo memory) {
|
||||||
|
uint256 plus1 = _domainToAgentPlus1[keccak256(bytes(agentDomain))];
|
||||||
|
if (plus1 == 0) revert NotRegistered(0);
|
||||||
|
return getAgent(plus1 - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Identity
|
||||||
|
/// @dev Returns the MOST RECENT agent registered by `agentAddress`. Use agentsOf() for the full set.
|
||||||
|
function resolveByAddress(address agentAddress) external view returns (AgentInfo memory) {
|
||||||
|
uint256[] storage ids = _agentsOfAddress[agentAddress];
|
||||||
|
if (ids.length == 0) revert NotRegistered(0);
|
||||||
|
return getAgent(ids[ids.length - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Identity
|
||||||
|
function agentCount() external view returns (uint256) {
|
||||||
|
return _registeredAgentIds.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice True iff ERC-8004 metadata has been bound for `agentId` (and the DID agent exists).
|
||||||
|
function isRegistered(uint256 agentId) external view returns (bool) {
|
||||||
|
return _records[agentId].registered && DID.agentExists(agentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice All agentIds registered by a controller (append-only; ids are stable Falcon roots).
|
||||||
|
function agentsOf(address controller) external view returns (uint256[] memory) {
|
||||||
|
return _agentsOfAddress[controller];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The full list of registered agentIds (append-only).
|
||||||
|
function registeredAgentIds() external view returns (uint256[] memory) {
|
||||||
|
return _registeredAgentIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The DID string for an agent: "did:aere:<chainId>:<agentId>".
|
||||||
|
function didString(uint256 agentId) public view returns (string memory) {
|
||||||
|
return string.concat("did:aere:", block.chainid.toString(), ":", agentId.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "./IERC8004.sol";
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
|
||||||
|
/// @dev The subset of the LIVE, deployed AereAIReputation (chain 2800, 0x781e…feBF) this adapter
|
||||||
|
/// uses. Reputation there is keyed by (operator address, bytes32 agentId): `attest` is gated
|
||||||
|
/// to a registered attestor set fixed at deploy, and `scoreOf` / `statsOf` are public reads.
|
||||||
|
interface IAereAIReputationLive {
|
||||||
|
function attest(address operator, bytes32 agentId, int8 delta, bytes32 evidenceHash, string calldata evidenceUri)
|
||||||
|
external;
|
||||||
|
|
||||||
|
function scoreOf(address operator, bytes32 agentId) external view returns (uint256);
|
||||||
|
|
||||||
|
function statsOf(address operator, bytes32 agentId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (uint256 positiveCount, uint256 disputeCount, uint256 lifetimeSlashed);
|
||||||
|
|
||||||
|
function isAttestor(address who) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev The one Identity-adapter read used to resolve an ERC-8004 agentId to its Aere operator
|
||||||
|
/// (the agent's controller), which is the operator address the live reputation is keyed by.
|
||||||
|
interface IAereIdentity8004 {
|
||||||
|
function isRegistered(uint256 agentId) external view returns (bool);
|
||||||
|
function getAgent(uint256 agentId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (IERC8004Identity.AgentInfo memory);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereReputationRegistry8004, an ERC-8004 Reputation adapter over the deployed AereAIReputation
|
||||||
|
*
|
||||||
|
* @notice Exposes the ERC-8004 Reputation surface (attest / read feedback) over Aere Network's
|
||||||
|
* ALREADY-DEPLOYED composable reputation primitive, AereAIReputation. It does NOT redeploy
|
||||||
|
* or modify the live reputation contract.
|
||||||
|
*
|
||||||
|
* READ (adapts the deployed contract directly). `getScore` and `getStats` map an ERC-8004
|
||||||
|
* agentId to the live reputation's (operator, agentId) key and read `scoreOf` / `statsOf`
|
||||||
|
* straight from the deployed AereAIReputation. This works against the currently-live
|
||||||
|
* instance as-is, with no change to it.
|
||||||
|
*
|
||||||
|
* WRITE (forwards feedback to the live contract). `giveFeedback` maps an ERC-8004 feedback
|
||||||
|
* signal to the live `attest(operator, agentId, delta, evidenceHash, uri)` and forwards it.
|
||||||
|
*
|
||||||
|
* @dev KEY MAPPING. The live reputation is keyed by (operator address, bytes32 agentId). This
|
||||||
|
* adapter derives:
|
||||||
|
* operator = the agent's current controller, resolved from the Identity adapter.
|
||||||
|
* agentKey = bytes32(agentId) (the ERC-8004 / DID agent id, left-padded).
|
||||||
|
* So an ERC-8004 read/write addresses exactly one live reputation slot, deterministically.
|
||||||
|
*
|
||||||
|
* @dev HONEST WRITE CONSTRAINT. AereAIReputation's attestor set is fixed at its deploy and has
|
||||||
|
* no add path. For `giveFeedback` to land in the live score, THIS adapter must be a
|
||||||
|
* registered attestor on the reputation instance it is constructed with. The currently-live
|
||||||
|
* AereAIReputation lists the Foundation attestor only (immutable), so pairing this adapter
|
||||||
|
* for WRITE-THROUGH is a Foundation governance decision, external to this contract and
|
||||||
|
* founder-gated. [VERIFY: on mainnet, register this adapter as an attestor before relying on
|
||||||
|
* giveFeedback, or have the Foundation attestor call the live attest directly.] The READ
|
||||||
|
* path needs no such authorization and works against the live instance today.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY: confirm against the finalized ERC-8004 interface] ERC-8004 reputation feedback in
|
||||||
|
* later drafts carries a richer payload (score, tag, response URI). Here the feedback signal
|
||||||
|
* is normalized to the live model's delta in {-1, 0, +1} (+1 positive, -1 dispute, 0
|
||||||
|
* neutral) so no information is invented beyond what the deployed contract records.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer reputation only. Does NOT change AERE consensus, holds no
|
||||||
|
* funds.
|
||||||
|
*
|
||||||
|
* @dev CALLER GATE (feedback authorization). Because every caller collapses into ONE on-chain
|
||||||
|
* attestor identity (this adapter) on the live AereAIReputation, an ungated write path would
|
||||||
|
* let ANY address inflate or tank any agent's reputation, defeating the live contract's
|
||||||
|
* curated-attestor model and its (attestor, evidenceHash) dedup. To mirror that curated model,
|
||||||
|
* `giveFeedback` is gated to an owner-managed allowlist of authorized feedback authors
|
||||||
|
* (`isAuthorizedFeedbackAuthor`). The owner curates WHO may submit feedback; it CANNOT set a
|
||||||
|
* reputation value directly, cannot bypass the {-1, 0, +1} delta clamp every author is held to,
|
||||||
|
* and holds no funds. This is the least-surprising design that closes the "anyone can write"
|
||||||
|
* hole while keeping the score honest and the read path fully permissionless.
|
||||||
|
*/
|
||||||
|
contract AereReputationRegistry8004 is IERC8004Reputation, Ownable {
|
||||||
|
/// @notice The LIVE, deployed AereAIReputation this adapter presents an ERC-8004 face over.
|
||||||
|
IAereAIReputationLive public immutable REPUTATION;
|
||||||
|
|
||||||
|
/// @notice The Aere ERC-8004 Identity adapter, used to resolve agentId -> operator (controller).
|
||||||
|
IAereIdentity8004 public immutable IDENTITY;
|
||||||
|
|
||||||
|
/// @notice Owner-curated set of addresses allowed to submit feedback through this adapter. Mirrors
|
||||||
|
/// the live AereAIReputation curated-attestor model at the adapter boundary: only an
|
||||||
|
/// authorized author may drive an agent's live reputation via `giveFeedback`.
|
||||||
|
mapping(address => bool) public isAuthorizedFeedbackAuthor;
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error AgentNotRegistered(uint256 agentId);
|
||||||
|
error InvalidDelta(int8 delta);
|
||||||
|
error AdapterNotAttestor();
|
||||||
|
error NotAuthorizedFeedbackAuthor(address caller);
|
||||||
|
|
||||||
|
/// @notice Emitted when the owner adds or removes an authorized feedback author.
|
||||||
|
event FeedbackAuthorSet(address indexed author, bool authorized);
|
||||||
|
|
||||||
|
constructor(address reputation, address identity) {
|
||||||
|
if (reputation == address(0) || identity == address(0)) revert ZeroAddress();
|
||||||
|
REPUTATION = IAereAIReputationLive(reputation);
|
||||||
|
IDENTITY = IAereIdentity8004(identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Feedback-author administration
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Authorize `author` to submit feedback through this adapter. Owner-only. This power is
|
||||||
|
/// scoped to feedback AUTHORIZATION only: it cannot set a reputation value, cannot exceed
|
||||||
|
/// the {-1, 0, +1} delta clamp, and moves no funds.
|
||||||
|
function addFeedbackAuthor(address author) external onlyOwner {
|
||||||
|
if (author == address(0)) revert ZeroAddress();
|
||||||
|
isAuthorizedFeedbackAuthor[author] = true;
|
||||||
|
emit FeedbackAuthorSet(author, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Revoke `author`'s authorization to submit feedback through this adapter. Owner-only.
|
||||||
|
function removeFeedbackAuthor(address author) external onlyOwner {
|
||||||
|
isAuthorizedFeedbackAuthor[author] = false;
|
||||||
|
emit FeedbackAuthorSet(author, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Write
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Record ERC-8004 feedback about an agent, forwarding it to the live AereAIReputation.
|
||||||
|
* The feedback signal is `delta` in {-1, 0, +1}. Resolves the live operator from the
|
||||||
|
* Identity adapter and calls the deployed `attest`. Reverts fail-closed if this adapter
|
||||||
|
* is not an authorized attestor on the live reputation (see contract NatSpec).
|
||||||
|
* @dev Gated to the owner-curated `isAuthorizedFeedbackAuthor` set: an unauthorized caller
|
||||||
|
* reverts NotAuthorizedFeedbackAuthor, so this adapter cannot act as an open reputation
|
||||||
|
* firehose once it is a live attestor. Every authorized author is still bound by the
|
||||||
|
* {-1, 0, +1} delta clamp, so authorization cannot forge an arbitrary score.
|
||||||
|
* @param agentId the ERC-8004 / DID agent id.
|
||||||
|
* @param delta +1 positive, -1 dispute, 0 neutral (audit-trail only).
|
||||||
|
* @param evidenceHash a 32-byte commitment to the off-chain evidence (non-zero on the live path).
|
||||||
|
* @param evidenceURI an optional public URI for the evidence.
|
||||||
|
*/
|
||||||
|
function giveFeedback(uint256 agentId, int8 delta, bytes32 evidenceHash, string calldata evidenceURI) external {
|
||||||
|
if (!isAuthorizedFeedbackAuthor[msg.sender]) revert NotAuthorizedFeedbackAuthor(msg.sender);
|
||||||
|
if (!IDENTITY.isRegistered(agentId)) revert AgentNotRegistered(agentId);
|
||||||
|
if (delta < -1 || delta > 1) revert InvalidDelta(delta);
|
||||||
|
// Surface the missing-authorization case with a clear adapter-level error rather than an
|
||||||
|
// opaque revert bubbling up from the live contract.
|
||||||
|
if (!REPUTATION.isAttestor(address(this))) revert AdapterNotAttestor();
|
||||||
|
|
||||||
|
address operator = _operatorOf(agentId);
|
||||||
|
REPUTATION.attest(operator, _agentKey(agentId), delta, evidenceHash, evidenceURI);
|
||||||
|
|
||||||
|
emit NewFeedback(agentId, msg.sender, delta, evidenceHash, evidenceURI);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Read
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Reputation
|
||||||
|
/// @notice The agent's live reputation score (0..10000), read straight from AereAIReputation.
|
||||||
|
function getScore(uint256 agentId) external view returns (uint256) {
|
||||||
|
return REPUTATION.scoreOf(_operatorOf(agentId), _agentKey(agentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The raw live reputation counters for an agent (positive / dispute / lifetime slashed).
|
||||||
|
function getStats(uint256 agentId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (uint256 positiveCount, uint256 disputeCount, uint256 lifetimeSlashed)
|
||||||
|
{
|
||||||
|
return REPUTATION.statsOf(_operatorOf(agentId), _agentKey(agentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff this adapter is authorized to write feedback into the live reputation.
|
||||||
|
function canWriteThrough() external view returns (bool) {
|
||||||
|
return REPUTATION.isAttestor(address(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The (operator, agentKey) pair this adapter maps an ERC-8004 agentId to on the live contract.
|
||||||
|
function liveKeyOf(uint256 agentId) external view returns (address operator, bytes32 agentKey) {
|
||||||
|
return (_operatorOf(agentId), _agentKey(agentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
function _operatorOf(uint256 agentId) internal view returns (address) {
|
||||||
|
return IDENTITY.getAgent(agentId).agentAddress; // current controller
|
||||||
|
}
|
||||||
|
|
||||||
|
function _agentKey(uint256 agentId) internal pure returns (bytes32) {
|
||||||
|
return bytes32(agentId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "./IERC8004.sol";
|
||||||
|
|
||||||
|
/// @dev The subset of the LIVE, deployed AerePQCKeyRegistry (chain 2800, 0x1eCa…3691) this adapter
|
||||||
|
/// uses. verifyWithKey routes to the live native precompile for the key's scheme (0x0AE1
|
||||||
|
/// Falcon-512, 0x0AE3 ML-DSA-44) and verifies the signature IN FULL on-chain, fail-closed.
|
||||||
|
interface IAerePQCKeyRegistryValidation {
|
||||||
|
function verifyWithKey(uint256 keyId, bytes32 message, bytes calldata signature) external view returns (bool);
|
||||||
|
function statusOf(uint256 keyId) external view returns (uint8);
|
||||||
|
function schemeOf(uint256 keyId) external view returns (uint8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @dev The one AereAgentDID read used to confirm the server agent being validated actually exists.
|
||||||
|
interface IAereAgentDIDValidation {
|
||||||
|
function agentExists(uint256 rootKeyId) external view returns (bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereValidationRegistry8004, the post-quantum ERC-8004 Validation registry
|
||||||
|
*
|
||||||
|
* @notice The differentiator. Exposes the ERC-8004 Validation surface (request / respond with a
|
||||||
|
* proof) where the validator's RESPONSE proof is a POST-QUANTUM signature, Falcon-512 or
|
||||||
|
* ML-DSA-44, verified in full ON-CHAIN by Aere Network's LIVE native precompiles
|
||||||
|
* (0x0AE1 Falcon-512, 0x0AE3 ML-DSA-44) through the already-deployed AerePQCKeyRegistry.
|
||||||
|
* Every other agent-validation stack in the ecosystem authenticates validator responses
|
||||||
|
* with ECDSA, which a quantum computer forges; this one does not.
|
||||||
|
*
|
||||||
|
* FLOW.
|
||||||
|
* 1. requestValidation(validatorKeyId, serverAgentId, dataHash): anyone records a request
|
||||||
|
* that the PQC validator identified by `validatorKeyId` validate the work the server
|
||||||
|
* agent committed to via `dataHash`. The validator key must be an ACTIVE Falcon-512 or
|
||||||
|
* ML-DSA-44 key in the registry; the server agent must exist in the live AereAgentDID.
|
||||||
|
* 2. respondValidation(requestId, response, pqcProof): the validator answers with a score
|
||||||
|
* (0..100, the ERC-8004 convention) and a PQC signature over this contract's
|
||||||
|
* domain-separated challenge binding (requestId, dataHash, serverAgentId,
|
||||||
|
* validatorKeyId, response). The signature is verified on-chain via the live
|
||||||
|
* precompile. On success the response is recorded once; on any invalid or tampered
|
||||||
|
* proof the call REVERTS and records nothing (FAIL-CLOSED).
|
||||||
|
*
|
||||||
|
* @dev NON-REPLAYABLE / NON-FORGEABLE. The challenge binds chainId + this contract + the exact
|
||||||
|
* request tuple + the response, so a proof for one (request, response) can never be reused
|
||||||
|
* for another, another contract, or another chain. A request completes exactly once
|
||||||
|
* (respond reverts once Status != Pending). Authorship is the PQC signature alone: respond
|
||||||
|
* may be relayed by any msg.sender, since only the validator private key can produce a valid
|
||||||
|
* signature over the contract-bound challenge. An empty / zero precompile return (a stale,
|
||||||
|
* un-activated chain) is treated as INVALID.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY: confirm against the finalized ERC-8004 interface] ERC-8004 validation in the base
|
||||||
|
* draft identifies the validator by an agent id and carries an opaque response byte. Aere
|
||||||
|
* keeps request/respond SEMANTICS but binds the validator to a REGISTERED POST-QUANTUM KEY
|
||||||
|
* (so the response is cryptographically authenticated on-chain, not merely emitted) and
|
||||||
|
* keeps the response in the ERC-8004 0..100 range. Reconcile exact selectors with the final
|
||||||
|
* ERC before claiming selector-level conformance.
|
||||||
|
*
|
||||||
|
* HONEST SCOPE. Application-layer validation only. This does NOT make AERE consensus
|
||||||
|
* post-quantum (blocks are still Besu QBFT with classical secp256k1 ECDSA). It holds no
|
||||||
|
* funds and has no admin. What is post-quantum here is the AUTHENTICITY of a validator's
|
||||||
|
* response, verified by the live precompiles.
|
||||||
|
*/
|
||||||
|
contract AereValidationRegistry8004 is IERC8004Validation {
|
||||||
|
/// @notice PQC schemes accepted for a validator key (match AerePQCKeyRegistry scheme ids).
|
||||||
|
uint8 public constant SCHEME_FALCON512 = 1; // live precompile 0x0AE1
|
||||||
|
uint8 public constant SCHEME_MLDSA44 = 3; // live precompile 0x0AE3
|
||||||
|
uint8 internal constant REGISTRY_STATUS_ACTIVE = 1;
|
||||||
|
uint8 public constant MAX_RESPONSE = 100; // ERC-8004 response score range 0..100
|
||||||
|
|
||||||
|
/// @notice Domain separator for the response challenge the validator PQC-signs.
|
||||||
|
bytes32 public constant VALIDATION_DOMAIN = keccak256("AereValidationRegistry8004.v1.response");
|
||||||
|
|
||||||
|
/// @notice The LIVE AerePQCKeyRegistry that verifies validator PQC signatures via the precompiles.
|
||||||
|
IAerePQCKeyRegistryValidation public immutable KEY_REGISTRY;
|
||||||
|
|
||||||
|
/// @notice The LIVE AereAgentDID used to confirm the server agent under validation exists.
|
||||||
|
IAereAgentDIDValidation public immutable DID;
|
||||||
|
|
||||||
|
struct Request {
|
||||||
|
uint256 validatorKeyId;
|
||||||
|
uint256 serverAgentId;
|
||||||
|
bytes32 dataHash;
|
||||||
|
Status status;
|
||||||
|
uint8 response; // valid only once status == Completed
|
||||||
|
uint8 pqcScheme; // the validator key's scheme at response time
|
||||||
|
uint64 requestedBlock;
|
||||||
|
uint64 respondedBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping(bytes32 => Request) private _requests; // requestId => request
|
||||||
|
mapping(uint256 => uint256) public requestNonce; // validatorKeyId => monotonic request counter
|
||||||
|
bytes32[] private _requestIds; // append-only list of every requestId
|
||||||
|
|
||||||
|
error ZeroAddress();
|
||||||
|
error ValidatorKeyNotActive(uint256 validatorKeyId);
|
||||||
|
error ValidatorSchemeUnsupported(uint256 validatorKeyId, uint8 scheme);
|
||||||
|
error ServerAgentUnknown(uint256 serverAgentId);
|
||||||
|
error UnknownRequest(bytes32 requestId);
|
||||||
|
error RequestNotPending(bytes32 requestId);
|
||||||
|
error ResponseOutOfRange(uint8 response);
|
||||||
|
error PQCValidationFailed();
|
||||||
|
|
||||||
|
constructor(address keyRegistry_, address did_) {
|
||||||
|
if (keyRegistry_ == address(0) || did_ == address(0)) revert ZeroAddress();
|
||||||
|
KEY_REGISTRY = IAerePQCKeyRegistryValidation(keyRegistry_);
|
||||||
|
DID = IAereAgentDIDValidation(did_);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Request
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Validation
|
||||||
|
function requestValidation(uint256 validatorKeyId, uint256 serverAgentId, bytes32 dataHash)
|
||||||
|
external
|
||||||
|
returns (bytes32 requestId)
|
||||||
|
{
|
||||||
|
uint8 scheme = _requireActivePQCValidator(validatorKeyId);
|
||||||
|
if (!DID.agentExists(serverAgentId)) revert ServerAgentUnknown(serverAgentId);
|
||||||
|
|
||||||
|
uint256 n = requestNonce[validatorKeyId];
|
||||||
|
requestNonce[validatorKeyId] = n + 1;
|
||||||
|
requestId = keccak256(
|
||||||
|
abi.encode(VALIDATION_DOMAIN, block.chainid, address(this), validatorKeyId, serverAgentId, dataHash, n)
|
||||||
|
);
|
||||||
|
|
||||||
|
_requests[requestId] = Request({
|
||||||
|
validatorKeyId: validatorKeyId,
|
||||||
|
serverAgentId: serverAgentId,
|
||||||
|
dataHash: dataHash,
|
||||||
|
status: Status.Pending,
|
||||||
|
response: 0,
|
||||||
|
pqcScheme: scheme,
|
||||||
|
requestedBlock: uint64(block.number),
|
||||||
|
respondedBlock: 0
|
||||||
|
});
|
||||||
|
_requestIds.push(requestId);
|
||||||
|
|
||||||
|
emit ValidationRequest(requestId, validatorKeyId, serverAgentId, dataHash);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Respond (PQC-verified)
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @inheritdoc IERC8004Validation
|
||||||
|
/// @notice Respond to a pending validation with a score and a POST-QUANTUM proof. The proof is a
|
||||||
|
/// Falcon-512 or ML-DSA-44 signature by the validator key over this contract's challenge,
|
||||||
|
/// verified in full on-chain by the live precompile. Reverts (records nothing) on an
|
||||||
|
/// invalid or tampered proof (FAIL-CLOSED).
|
||||||
|
/// @param requestId the pending request being answered.
|
||||||
|
/// @param response the validation score, 0..100 (ERC-8004 convention).
|
||||||
|
/// @param pqcProof the validator's PQC signature envelope for the key's scheme.
|
||||||
|
function respondValidation(bytes32 requestId, uint8 response, bytes calldata pqcProof) external {
|
||||||
|
Request storage r = _requests[requestId];
|
||||||
|
if (r.status == Status.None) revert UnknownRequest(requestId);
|
||||||
|
if (r.status != Status.Pending) revert RequestNotPending(requestId);
|
||||||
|
if (response > MAX_RESPONSE) revert ResponseOutOfRange(response);
|
||||||
|
|
||||||
|
// The validator key must still be an ACTIVE Falcon-512 / ML-DSA-44 key (it could have been
|
||||||
|
// rotated or revoked between request and response).
|
||||||
|
uint8 scheme = _requireActivePQCValidator(r.validatorKeyId);
|
||||||
|
|
||||||
|
bytes32 challenge = responseChallenge(requestId, response);
|
||||||
|
// Full on-chain post-quantum verification via the live precompile through the registry.
|
||||||
|
if (!KEY_REGISTRY.verifyWithKey(r.validatorKeyId, challenge, pqcProof)) revert PQCValidationFailed();
|
||||||
|
|
||||||
|
// Effects: record exactly once.
|
||||||
|
r.status = Status.Completed;
|
||||||
|
r.response = response;
|
||||||
|
r.pqcScheme = scheme;
|
||||||
|
r.respondedBlock = uint64(block.number);
|
||||||
|
|
||||||
|
emit ValidationResponse(requestId, r.validatorKeyId, r.serverAgentId, response, scheme);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice The exact 32-byte challenge a validator must PQC-sign to answer `requestId` with
|
||||||
|
* `response`. Off-chain validators query this to know what to sign; the contract binds
|
||||||
|
* the request tuple so a proof cannot be moved to a different request or response.
|
||||||
|
*/
|
||||||
|
function responseChallenge(bytes32 requestId, uint8 response) public view returns (bytes32) {
|
||||||
|
Request storage r = _requests[requestId];
|
||||||
|
return keccak256(
|
||||||
|
abi.encode(
|
||||||
|
VALIDATION_DOMAIN,
|
||||||
|
block.chainid,
|
||||||
|
address(this),
|
||||||
|
requestId,
|
||||||
|
r.dataHash,
|
||||||
|
r.serverAgentId,
|
||||||
|
r.validatorKeyId,
|
||||||
|
response
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Views
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @notice Read a validation request/response by id.
|
||||||
|
function getValidation(bytes32 requestId)
|
||||||
|
external
|
||||||
|
view
|
||||||
|
returns (
|
||||||
|
uint256 validatorKeyId,
|
||||||
|
uint256 serverAgentId,
|
||||||
|
bytes32 dataHash,
|
||||||
|
Status status,
|
||||||
|
uint8 response,
|
||||||
|
uint8 pqcScheme,
|
||||||
|
uint64 requestedBlock,
|
||||||
|
uint64 respondedBlock
|
||||||
|
)
|
||||||
|
{
|
||||||
|
Request storage r = _requests[requestId];
|
||||||
|
if (r.status == Status.None) revert UnknownRequest(requestId);
|
||||||
|
return (
|
||||||
|
r.validatorKeyId,
|
||||||
|
r.serverAgentId,
|
||||||
|
r.dataHash,
|
||||||
|
r.status,
|
||||||
|
r.response,
|
||||||
|
r.pqcScheme,
|
||||||
|
r.requestedBlock,
|
||||||
|
r.respondedBlock
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice True iff `requestId` has a recorded, PQC-verified validation response.
|
||||||
|
function isValidated(bytes32 requestId) external view returns (bool) {
|
||||||
|
return _requests[requestId].status == Status.Completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Total number of validation requests ever recorded.
|
||||||
|
function requestCount() external view returns (uint256) {
|
||||||
|
return _requestIds.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The requestId at an index in the append-only list.
|
||||||
|
function requestIdAt(uint256 index) external view returns (bytes32) {
|
||||||
|
return _requestIds[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice The live precompile address that verifies a validator key's scheme (informational).
|
||||||
|
function precompileFor(uint8 scheme) external pure returns (address) {
|
||||||
|
if (scheme == SCHEME_FALCON512) return address(0x0AE1);
|
||||||
|
if (scheme == SCHEME_MLDSA44) return address(0x0AE3);
|
||||||
|
return address(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================================
|
||||||
|
// Internal
|
||||||
|
// ==========================================================================
|
||||||
|
|
||||||
|
/// @dev Require `keyId` is an ACTIVE Falcon-512 or ML-DSA-44 key in the live registry. Returns
|
||||||
|
/// the scheme.
|
||||||
|
function _requireActivePQCValidator(uint256 keyId) internal view returns (uint8 scheme) {
|
||||||
|
if (KEY_REGISTRY.statusOf(keyId) != REGISTRY_STATUS_ACTIVE) revert ValidatorKeyNotActive(keyId);
|
||||||
|
scheme = KEY_REGISTRY.schemeOf(keyId);
|
||||||
|
if (scheme != SCHEME_FALCON512 && scheme != SCHEME_MLDSA44) {
|
||||||
|
revert ValidatorSchemeUnsupported(keyId, scheme);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title IERC8004, the ERC-8004 "Trustless Agents" registry surface AS MODELED for Aere Network
|
||||||
|
*
|
||||||
|
* @notice ERC-8004 defines three on-chain registries that give autonomous / AI agents a
|
||||||
|
* portable, verifiable trust layer on top of the A2A (Agent-to-Agent) protocol:
|
||||||
|
* - IDENTITY : a unique on-chain agent id resolving to an off-chain AgentCard
|
||||||
|
* (a metadata document, e.g. "/.well-known/agent-card.json").
|
||||||
|
* - REPUTATION : client feedback / attestations about an agent, readable on-chain.
|
||||||
|
* - VALIDATION : independent validators requesting and responding to proofs about
|
||||||
|
* an agent's work.
|
||||||
|
*
|
||||||
|
* These interfaces capture the DOCUMENTED request / resolve / attest / validate
|
||||||
|
* SEMANTICS of ERC-8004 so Aere's already-deployed agent primitives can expose a
|
||||||
|
* standards-shaped surface over them.
|
||||||
|
*
|
||||||
|
* @dev [VERIFY: confirm against the finalized ERC-8004 interface]
|
||||||
|
* ERC-8004 is a live, evolving draft. Between draft revisions the Identity registry
|
||||||
|
* has moved toward an ERC-721 registration model (register / tokenURI), and the
|
||||||
|
* Reputation and Validation function names and argument orders are still settling.
|
||||||
|
* The shapes below are the semantic model the Aere adapters implement; the exact
|
||||||
|
* function selectors and event topics MUST be reconciled with the final ERC text
|
||||||
|
* before any byte-level selector-conformance claim is made. Where the model departs
|
||||||
|
* from a specific draft, the adapter NatSpec says so.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/// @notice ERC-8004 Identity registry: register / resolve an agent with a DID + metadata URI.
|
||||||
|
interface IERC8004Identity {
|
||||||
|
struct AgentInfo {
|
||||||
|
uint256 agentId; // the ERC-8004 agent id
|
||||||
|
string did; // decentralized identifier, e.g. "did:aere:2800:<agentId>"
|
||||||
|
string agentDomain; // the agent's domain, e.g. "agent.example.com"
|
||||||
|
string agentCardURI; // AgentCard / registration metadata document URI
|
||||||
|
address agentAddress; // the address that controls / acts as the agent
|
||||||
|
bool registered; // whether ERC-8004 metadata has been bound for this agent
|
||||||
|
}
|
||||||
|
|
||||||
|
event AgentRegistered(
|
||||||
|
uint256 indexed agentId, string agentDomain, string agentCardURI, address indexed agentAddress
|
||||||
|
);
|
||||||
|
event AgentUpdated(
|
||||||
|
uint256 indexed agentId, string agentDomain, string agentCardURI, address indexed agentAddress
|
||||||
|
);
|
||||||
|
|
||||||
|
function getAgent(uint256 agentId) external view returns (AgentInfo memory);
|
||||||
|
function resolveByDomain(string calldata agentDomain) external view returns (AgentInfo memory);
|
||||||
|
function resolveByAddress(address agentAddress) external view returns (AgentInfo memory);
|
||||||
|
function agentCount() external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice ERC-8004 Reputation registry: attest / read feedback about an agent.
|
||||||
|
interface IERC8004Reputation {
|
||||||
|
/// @param delta the feedback signal, normalized to {-1, 0, +1}: +1 positive, -1 dispute, 0 neutral.
|
||||||
|
event NewFeedback(
|
||||||
|
uint256 indexed agentId, address indexed attestor, int8 delta, bytes32 evidenceHash, string evidenceURI
|
||||||
|
);
|
||||||
|
|
||||||
|
function giveFeedback(uint256 agentId, int8 delta, bytes32 evidenceHash, string calldata evidenceURI) external;
|
||||||
|
function getScore(uint256 agentId) external view returns (uint256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice ERC-8004 Validation registry: request / respond with a proof.
|
||||||
|
interface IERC8004Validation {
|
||||||
|
enum Status {
|
||||||
|
None, // no such request
|
||||||
|
Pending, // requested, awaiting a validator response
|
||||||
|
Completed // validator responded with a proof
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
event ValidationRequest(
|
||||||
|
bytes32 indexed requestId, uint256 indexed validatorKeyId, uint256 indexed serverAgentId, bytes32 dataHash
|
||||||
|
);
|
||||||
|
event ValidationResponse(
|
||||||
|
bytes32 indexed requestId,
|
||||||
|
uint256 indexed validatorKeyId,
|
||||||
|
uint256 indexed serverAgentId,
|
||||||
|
uint8 response,
|
||||||
|
uint8 pqcScheme
|
||||||
|
);
|
||||||
|
|
||||||
|
function requestValidation(uint256 validatorKeyId, uint256 serverAgentId, bytes32 dataHash)
|
||||||
|
external
|
||||||
|
returns (bytes32 requestId);
|
||||||
|
function respondValidation(bytes32 requestId, uint8 response, bytes calldata pqcProof) external;
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereFaucetV2 — testnet faucet with optional anonymous claim path
|
||||||
|
* @notice Two claim paths:
|
||||||
|
*
|
||||||
|
* 1. claim() — per-address cooldown (existing AereFaucet pattern,
|
||||||
|
* preserved for compatibility).
|
||||||
|
*
|
||||||
|
* 2. claimAnonymous(commitment, recipient, validUntil, sig) —
|
||||||
|
* Foundation off-chain issues a one-time claim ticket. The
|
||||||
|
* ticket commits to a fresh commitment value generated by
|
||||||
|
* the user; the on-chain side burns the commitment after
|
||||||
|
* first use. Different (commitment, recipient) pairs are
|
||||||
|
* independent — a user can claim N times by getting N
|
||||||
|
* tickets, but each ticket is one-shot.
|
||||||
|
*
|
||||||
|
* The anonymous path is useful for:
|
||||||
|
* - developer testing with throwaway addresses
|
||||||
|
* - integration tests in CI
|
||||||
|
* - hackathon onboarding where the founder doesn't want
|
||||||
|
* to expose participant wallet trails
|
||||||
|
*
|
||||||
|
* CIRCULATION CONTROL: anonymous claim drains the same balance
|
||||||
|
* as regular claim; both share `dripAmount`. The Foundation gates
|
||||||
|
* issuance volume by deciding how many tickets to mint off-chain.
|
||||||
|
*
|
||||||
|
* IMMUTABILITY: SIGNER is set at deploy and cannot be replaced.
|
||||||
|
* To rotate, redeploy. (Faucets are cheap; live ones can be
|
||||||
|
* retired by setting dripAmount to 0.)
|
||||||
|
*
|
||||||
|
* GOTCHAS:
|
||||||
|
* - Tickets are ECDSA-signed (EIP-191) by SIGNER.
|
||||||
|
* - validUntil prevents indefinite ticket hoarding.
|
||||||
|
* - Commitment is the unique replay key; collisions are
|
||||||
|
* improbable with 32-byte randomness.
|
||||||
|
* - recipient is bound in the signed message — a ticket cannot
|
||||||
|
* be redirected after signing.
|
||||||
|
*/
|
||||||
|
contract AereFaucetV2 is Ownable, ReentrancyGuard {
|
||||||
|
|
||||||
|
/* ================================ config ================================ */
|
||||||
|
|
||||||
|
/// @notice Off-chain ticket signer for anonymous-mode claims.
|
||||||
|
address public immutable SIGNER;
|
||||||
|
|
||||||
|
uint256 public dripAmount = 0.05 ether;
|
||||||
|
uint64 public cooldown = 1 days;
|
||||||
|
|
||||||
|
/* ================================= state ================================ */
|
||||||
|
|
||||||
|
mapping(address => uint64) public lastClaim;
|
||||||
|
/// @notice commitment → spent. One-shot per commitment.
|
||||||
|
mapping(bytes32 => bool) public spentCommitments;
|
||||||
|
|
||||||
|
/* ================================= events ================================ */
|
||||||
|
|
||||||
|
event Dripped(address indexed to, uint256 amount);
|
||||||
|
event AnonymousDripped(address indexed to, bytes32 indexed commitment, uint256 amount);
|
||||||
|
event Funded(address indexed from, uint256 amount);
|
||||||
|
event ConfigUpdated(uint256 dripAmount, uint64 cooldown);
|
||||||
|
|
||||||
|
/* ================================= errors ================================ */
|
||||||
|
|
||||||
|
error InCooldown();
|
||||||
|
error Dry();
|
||||||
|
error TransferFailed();
|
||||||
|
error TicketExpired();
|
||||||
|
error TicketSignerMismatch();
|
||||||
|
error CommitmentSpent();
|
||||||
|
error BadParams();
|
||||||
|
|
||||||
|
/* ============================== constructor ============================= */
|
||||||
|
|
||||||
|
constructor(address signer_) {
|
||||||
|
require(signer_ != address(0), "zero-signer");
|
||||||
|
SIGNER = signer_;
|
||||||
|
}
|
||||||
|
|
||||||
|
receive() external payable { emit Funded(msg.sender, msg.value); }
|
||||||
|
|
||||||
|
/* ============================== regular claim ============================ */
|
||||||
|
|
||||||
|
function claim() external nonReentrant {
|
||||||
|
if (block.timestamp - lastClaim[msg.sender] < cooldown) revert InCooldown();
|
||||||
|
if (address(this).balance < dripAmount) revert Dry();
|
||||||
|
lastClaim[msg.sender] = uint64(block.timestamp);
|
||||||
|
(bool ok, ) = msg.sender.call{value: dripAmount}("");
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit Dripped(msg.sender, dripAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =========================== anonymous claim ============================= */
|
||||||
|
|
||||||
|
/// @notice Burn a one-time ticket and drip to `recipient`. The ticket
|
||||||
|
/// is an EIP-191 signature by SIGNER over
|
||||||
|
/// keccak256(abi.encode("AereFaucetV2", chainid, address(this),
|
||||||
|
/// commitment, recipient, validUntil))
|
||||||
|
/// msg.sender doesn't matter for permission — anyone can submit
|
||||||
|
/// (typical relayer pattern). Useful for gasless onboarding.
|
||||||
|
function claimAnonymous(
|
||||||
|
bytes32 commitment,
|
||||||
|
address recipient,
|
||||||
|
uint64 validUntil,
|
||||||
|
bytes calldata sig
|
||||||
|
) external nonReentrant {
|
||||||
|
if (recipient == address(0) || commitment == bytes32(0)) revert BadParams();
|
||||||
|
if (block.timestamp > validUntil) revert TicketExpired();
|
||||||
|
if (spentCommitments[commitment]) revert CommitmentSpent();
|
||||||
|
if (address(this).balance < dripAmount) revert Dry();
|
||||||
|
|
||||||
|
bytes32 inner = keccak256(abi.encode(
|
||||||
|
"AereFaucetV2", block.chainid, address(this), commitment, recipient, validUntil
|
||||||
|
));
|
||||||
|
bytes32 ethSigned = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inner));
|
||||||
|
address recovered = _recover(ethSigned, sig);
|
||||||
|
if (recovered != SIGNER) revert TicketSignerMismatch();
|
||||||
|
|
||||||
|
spentCommitments[commitment] = true;
|
||||||
|
(bool ok, ) = recipient.call{value: dripAmount}("");
|
||||||
|
if (!ok) revert TransferFailed();
|
||||||
|
emit AnonymousDripped(recipient, commitment, dripAmount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== owner ops ============================== */
|
||||||
|
|
||||||
|
function setConfig(uint256 _drip, uint64 _cooldown) external onlyOwner {
|
||||||
|
if (_cooldown < 1 hours) revert BadParams();
|
||||||
|
dripAmount = _drip;
|
||||||
|
cooldown = _cooldown;
|
||||||
|
emit ConfigUpdated(_drip, _cooldown);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ views ================================ */
|
||||||
|
|
||||||
|
function nextClaimAt(address user) external view returns (uint64) {
|
||||||
|
return lastClaim[user] + cooldown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ================================ internal ============================== */
|
||||||
|
|
||||||
|
function _recover(bytes32 hash, bytes calldata sig) internal pure returns (address) {
|
||||||
|
if (sig.length != 65) return address(0);
|
||||||
|
bytes32 r; bytes32 s; uint8 v;
|
||||||
|
assembly {
|
||||||
|
r := calldataload(sig.offset)
|
||||||
|
s := calldataload(add(sig.offset, 0x20))
|
||||||
|
v := byte(0, calldataload(add(sig.offset, 0x40)))
|
||||||
|
}
|
||||||
|
if (v < 27) v += 27;
|
||||||
|
return ecrecover(hash, v, r, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity 0.8.23;
|
||||||
|
|
||||||
|
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
|
||||||
|
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title AereGovLock
|
||||||
|
* @notice A self-contained, non-transferable, CHECKPOINTED ERC20Votes governance
|
||||||
|
* vote source built on a CUSTODY-LOCK (veToken-style) model. It is a
|
||||||
|
* drop-in IVotes source for the existing AereGovernor
|
||||||
|
* (0xd16C2551Bf4f3d0DDF961282078917b2e8679999) and its TimelockController
|
||||||
|
* (0xf95738Cf366Dd2ea76fBa1b2736163BDc11D2e55).
|
||||||
|
*
|
||||||
|
* WHY THIS EXISTS. The previous vote source, AereStakedGovVotes (gAERE
|
||||||
|
* 0xD7575795A055cb093957B86f0607871A2D37805C), was a LAZY PULL-BASED
|
||||||
|
* MIRROR of external staking contracts. It had a fatal class of bug:
|
||||||
|
* voting power could DETACH from the capital that was supposed to back
|
||||||
|
* it. Concretely, AereLockedStaking.earlyExit() returns a user's
|
||||||
|
* principal instantly WITHOUT burning any mirrored gAERE, and sync() is
|
||||||
|
* opt-in, so a single unit of never-truly-locked AERE could be recycled
|
||||||
|
* through many accounts (sybils) to manufacture N-fold voting power.
|
||||||
|
* Worse, quorum was measured off an OPT-IN synced total supply, so the
|
||||||
|
* denominator was meaningless.
|
||||||
|
*
|
||||||
|
* THE FIX (this contract). Power CANNOT detach from capital because the
|
||||||
|
* capital lives HERE, in custody, for the whole life of the vote:
|
||||||
|
* - lock() is the ONLY way votes are minted, and it requires native
|
||||||
|
* AERE to be transferred INTO this contract in the same call
|
||||||
|
* (payable). Votes minted == principal deposited, exactly 1:1.
|
||||||
|
* - withdraw() is the ONLY way votes are burned, and it is the ONLY
|
||||||
|
* way principal leaves. It is gated by unlockTime, burns the votes
|
||||||
|
* FIRST, then returns the exact principal. There is NO earlyExit,
|
||||||
|
* NO admin drain, NO detached-claim path.
|
||||||
|
* - Therefore, at ALL times and at EVERY historical snapshot:
|
||||||
|
* totalSupply() == sum of all live locks == this contract's
|
||||||
|
* native balance credited through lock().
|
||||||
|
* One unit of capital yields AT MOST one unit of votes. Recycling is
|
||||||
|
* impossible: to give capital to a sybil you must withdraw, which
|
||||||
|
* burns the votes before the capital can move.
|
||||||
|
*
|
||||||
|
* NON-TRANSFERABLE, DELEGATABLE. Balances represent a custody claim, not
|
||||||
|
* a spendable asset, so transfer / transferFrom / approve REVERT. Vote
|
||||||
|
* DELEGATION works normally via ERC20Votes.delegate() (it moves voting
|
||||||
|
* units, never the underlying custody claim), so holders can delegate to
|
||||||
|
* a representative without ever detaching capital.
|
||||||
|
*
|
||||||
|
* CLOCK. Block-number clock (OpenZeppelin default), matching AereGovernor,
|
||||||
|
* so getPastVotes / getPastTotalSupply are snapshot-fixed at a proposal's
|
||||||
|
* past block and cannot be retroactively entered. Lock expiry uses wall
|
||||||
|
* clock (block.timestamp); vote accounting uses block number. This split
|
||||||
|
* is the standard veToken pattern.
|
||||||
|
*
|
||||||
|
* MEANINGFUL QUORUM. Because totalSupply() == total locked capital,
|
||||||
|
* GovernorVotesQuorumFraction computes quorum as a real fraction of real
|
||||||
|
* locked capital, not of an opt-in mirror.
|
||||||
|
*/
|
||||||
|
contract AereGovLock is ERC20Votes, ReentrancyGuard {
|
||||||
|
/// @notice One custody lock per account. `amount` is the native AERE held in
|
||||||
|
/// custody for this account; `unlockTime` is the earliest wall-clock
|
||||||
|
/// time at which it (and the votes it backs) may be withdrawn.
|
||||||
|
struct Lock {
|
||||||
|
uint256 amount;
|
||||||
|
uint256 unlockTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice account => its single custody lock position.
|
||||||
|
mapping(address => Lock) private _locks;
|
||||||
|
|
||||||
|
/// @notice Minimum lock duration enforced on every lock / extension, in
|
||||||
|
/// seconds. Set once at deployment. May be 0 (no minimum).
|
||||||
|
uint256 public immutable minLockDuration;
|
||||||
|
|
||||||
|
/// @notice Sanity cap on how far in the future a lock may be set, to prevent
|
||||||
|
/// fat-finger effectively-permanent locks and timestamp overflow.
|
||||||
|
uint256 public constant MAX_LOCK_DURATION = 1460 days; // ~4 years
|
||||||
|
|
||||||
|
event Locked(address indexed account, uint256 addedAmount, uint256 newAmount, uint256 unlockTime);
|
||||||
|
event Withdrawn(address indexed account, uint256 amount);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param _minLockDuration Minimum seconds a deposit must stay locked. Pass 0
|
||||||
|
* to disable the minimum. Must be <= MAX_LOCK_DURATION.
|
||||||
|
*/
|
||||||
|
constructor(uint256 _minLockDuration)
|
||||||
|
ERC20("AERE Governance Lock", "govAERE")
|
||||||
|
ERC20Permit("AERE Governance Lock")
|
||||||
|
{
|
||||||
|
require(_minLockDuration <= MAX_LOCK_DURATION, "govAERE: min > max");
|
||||||
|
minLockDuration = _minLockDuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Custody lock: capital IN -> votes minted 1:1.
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Lock native AERE into custody and mint an equal amount of
|
||||||
|
* non-transferable, checkpointed votes. This is the ONLY mint path.
|
||||||
|
*
|
||||||
|
* `amount` MUST equal msg.value; it is an explicit argument purely so
|
||||||
|
* the deposited quantity is unambiguous in calldata and events. The
|
||||||
|
* real transfer of value is msg.value (native AERE) into this
|
||||||
|
* contract, so the votes are always fully backed by custody here.
|
||||||
|
*
|
||||||
|
* If the caller already has a lock, this ADDS to it and the position
|
||||||
|
* adopts the new (later or equal) unlock time. The unlock time can
|
||||||
|
* only move FORWARD, never be shortened by a subsequent lock, so
|
||||||
|
* capital already committed cannot be released early by re-locking.
|
||||||
|
*
|
||||||
|
* @param amount Quantity of native AERE to lock. Must equal msg.value and be > 0.
|
||||||
|
* @param unlockTime Wall-clock timestamp when withdrawal becomes allowed.
|
||||||
|
*/
|
||||||
|
function lock(uint256 amount, uint256 unlockTime) external payable nonReentrant {
|
||||||
|
require(amount > 0, "govAERE: zero amount");
|
||||||
|
require(msg.value == amount, "govAERE: value != amount");
|
||||||
|
|
||||||
|
Lock storage position = _locks[msg.sender];
|
||||||
|
|
||||||
|
// Enforce the minimum duration from now, and never allow shortening an
|
||||||
|
// existing commitment.
|
||||||
|
uint256 minUnlock = block.timestamp + minLockDuration;
|
||||||
|
require(unlockTime >= minUnlock, "govAERE: below min duration");
|
||||||
|
require(unlockTime <= block.timestamp + MAX_LOCK_DURATION, "govAERE: above max duration");
|
||||||
|
require(unlockTime >= position.unlockTime, "govAERE: cannot shorten lock");
|
||||||
|
|
||||||
|
position.amount += amount;
|
||||||
|
position.unlockTime = unlockTime;
|
||||||
|
|
||||||
|
// Mint votes 1:1 with the deposited capital. _mint writes an ERC20Votes
|
||||||
|
// checkpoint, making the new weight snapshot-safe.
|
||||||
|
_mint(msg.sender, amount);
|
||||||
|
|
||||||
|
emit Locked(msg.sender, amount, position.amount, unlockTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Extend an existing lock's unlock time WITHOUT adding capital. Votes
|
||||||
|
* are unchanged (they are already 1:1 with the locked capital). Only
|
||||||
|
* allowed to move the unlock time forward.
|
||||||
|
*/
|
||||||
|
function extendLock(uint256 newUnlockTime) external {
|
||||||
|
Lock storage position = _locks[msg.sender];
|
||||||
|
require(position.amount > 0, "govAERE: no lock");
|
||||||
|
require(newUnlockTime > position.unlockTime, "govAERE: not later");
|
||||||
|
require(newUnlockTime >= block.timestamp + minLockDuration, "govAERE: below min duration");
|
||||||
|
require(newUnlockTime <= block.timestamp + MAX_LOCK_DURATION, "govAERE: above max duration");
|
||||||
|
position.unlockTime = newUnlockTime;
|
||||||
|
emit Locked(msg.sender, 0, position.amount, newUnlockTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Custody release: votes burned FIRST -> capital OUT. The only exit.
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Withdraw the full locked principal AFTER unlockTime, burning the
|
||||||
|
* backing votes in the same call. This is the ONLY burn path and the
|
||||||
|
* ONLY way capital leaves the contract. Votes are burned BEFORE the
|
||||||
|
* native transfer (checks-effects-interactions), so at no instant can
|
||||||
|
* an account hold votes whose capital has already left.
|
||||||
|
*/
|
||||||
|
function withdraw() external nonReentrant {
|
||||||
|
Lock storage position = _locks[msg.sender];
|
||||||
|
uint256 amount = position.amount;
|
||||||
|
require(amount > 0, "govAERE: no lock");
|
||||||
|
require(block.timestamp >= position.unlockTime, "govAERE: still locked");
|
||||||
|
|
||||||
|
// EFFECTS: clear the position and burn the votes before moving value.
|
||||||
|
position.amount = 0;
|
||||||
|
position.unlockTime = 0;
|
||||||
|
_burn(msg.sender, amount);
|
||||||
|
|
||||||
|
// INTERACTION: return the exact principal.
|
||||||
|
(bool ok, ) = payable(msg.sender).call{value: amount}("");
|
||||||
|
require(ok, "govAERE: native transfer failed");
|
||||||
|
|
||||||
|
emit Withdrawn(msg.sender, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Views.
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// @notice The custody lock (amount, unlockTime) for `account`.
|
||||||
|
function locks(address account) external view returns (uint256 amount, uint256 unlockTime) {
|
||||||
|
Lock storage position = _locks[account];
|
||||||
|
return (position.amount, position.unlockTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Principal currently held in custody for `account` (== its votes balance).
|
||||||
|
function lockedBalanceOf(address account) external view returns (uint256) {
|
||||||
|
return _locks[account].amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @notice Unlock timestamp for `account`'s lock (0 if none).
|
||||||
|
function unlockTimeOf(address account) external view returns (uint256) {
|
||||||
|
return _locks[account].unlockTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @notice Total native AERE held in custody through lock(). Under normal use
|
||||||
|
* this equals totalSupply(). It is exposed so anyone can verify the
|
||||||
|
* backing invariant on-chain. (A forced native send via selfdestruct
|
||||||
|
* could push the raw contract balance above this figure; such surplus
|
||||||
|
* is never counted as votes and is never withdrawable, so it cannot
|
||||||
|
* inflate voting power.)
|
||||||
|
*/
|
||||||
|
function totalLocked() external view returns (uint256) {
|
||||||
|
return totalSupply();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Non-transferability. Balances are custody claims, not spendable tokens.
|
||||||
|
// Mint (from == 0) and burn (to == 0) are allowed; everything else reverts.
|
||||||
|
// Vote delegation is unaffected (it moves voting units, not balances).
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
|
||||||
|
require(from == address(0) || to == address(0), "govAERE: non-transferable");
|
||||||
|
super._beforeTokenTransfer(from, to, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function transfer(address, uint256) public pure override returns (bool) {
|
||||||
|
revert("govAERE: non-transferable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferFrom(address, address, uint256) public pure override returns (bool) {
|
||||||
|
revert("govAERE: non-transferable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function approve(address, uint256) public pure override returns (bool) {
|
||||||
|
revert("govAERE: non-transferable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function increaseAllowance(address, uint256) public pure override returns (bool) {
|
||||||
|
revert("govAERE: non-transferable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function decreaseAllowance(address, uint256) public pure override returns (bool) {
|
||||||
|
revert("govAERE: non-transferable");
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 459 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user