diff --git a/.github/workflows/circuits-ci.yml b/.github/workflows/circuits-ci.yml new file mode 100644 index 0000000..5c3421d --- /dev/null +++ b/.github/workflows/circuits-ci.yml @@ -0,0 +1,43 @@ +name: Circuits CI + +on: + pull_request: + push: + branches: + - main + - canary + - dev + +jobs: + circuits-test: + name: Circuits Witness Tests + runs-on: ubuntu-latest + permissions: + contents: read + defaults: + run: + working-directory: circuits + + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: '22' + + - name: Install circom + run: | + CIRCOM_VERSION="v2.2.3" + CIRCOM_URL="https://github.com/iden3/circom/releases/download/${CIRCOM_VERSION}/circom-linux-amd64" + curl -L "$CIRCOM_URL" -o circom + chmod +x circom + sudo mv circom /usr/local/bin/circom + circom --version + + - name: Install dependencies + run: npm ci + + - name: Run witness tests + run: npm test diff --git a/LICENSE b/LICENSE index f5ab6aa..98af169 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ (The MIT License) -Copyright 2020-2025 Optimism +Copyright 2026 Trade Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/circuits/.gitignore b/circuits/.gitignore new file mode 100644 index 0000000..f412b0c --- /dev/null +++ b/circuits/.gitignore @@ -0,0 +1,9 @@ +build/ +node_modules/ +*.zkey +*.ptau +witness.wtns + +# Prototype files (superseded by circuits/mark/MARKPool.circom) +utxo/ +setup.js diff --git a/circuits/mark/MARKPool.circom b/circuits/mark/MARKPool.circom new file mode 100644 index 0000000..fee49c9 --- /dev/null +++ b/circuits/mark/MARKPool.circom @@ -0,0 +1,229 @@ +pragma circom 2.0.0; + +include "circomlib/circuits/poseidon.circom"; +include "circomlib/circuits/comparators.circom"; +include "circomlib/circuits/switcher.circom"; +include "circomlib/circuits/bitify.circom"; + +template MARKPool(depth, nIn, nOut) { + // Domain separation constants — PERMANENT. Never change after first deployment. + // These values are protocol-specific to MARK and must remain stable across upgrades + // to prevent cross-version commitment and nullifier reuse. + // DOMAIN_VERSION: 1 — protocol version tag + // DOMAIN_NOTE_COMMITMENT: 11 — note commitment hash domain + // DOMAIN_NULLIFIER: 12 — nullifier hash domain + var DOMAIN_VERSION = 1; + var DOMAIN_NOTE_COMMITMENT = 11; + var DOMAIN_NULLIFIER = 12; + + // Private inputs (notes to spend) + signal input inAmount[nIn]; + signal input inSecret[nIn]; + signal input inBlinding[nIn]; + signal input inPathElements[nIn][depth]; + signal input inPathIndices[nIn][depth]; + + // Private outputs (new notes) + signal input outAmount[nOut]; + signal input outSecret[nOut]; + signal input outBlinding[nOut]; + + // Public inputs. + // IMPORTANT: snarkjs publicSignals ordering follows signal declaration order. + // Canonical verifier order (13 signals): + // [merkleRoot, chainId, dstChainId, protocolEpoch, fee, relayer, + // nullifier[0], nullifier[1], outCommitment[0], outCommitment[1], + // withdrawOwner, withdrawRecipient, withdrawAmount] + signal input merkleRoot; + signal input chainId; + signal input dstChainId; + signal input protocolEpoch; + signal input fee; + signal input relayer; + signal input nullifier[nIn]; + signal input outCommitment[nOut]; + signal input withdrawOwner; + signal input withdrawRecipient; + signal input withdrawAmount; + + signal computedNullifier[nIn]; + signal computedOutCommitment[nOut]; + + // 1) Input commitments + nullifiers + component inCommitment[nIn]; + component inNullifier[nIn]; + var i; + for (i = 0; i < nIn; i++) { + inCommitment[i] = Poseidon(4); + inCommitment[i].inputs[0] <== DOMAIN_VERSION * 100 + DOMAIN_NOTE_COMMITMENT; + inCommitment[i].inputs[1] <== inAmount[i]; + inCommitment[i].inputs[2] <== inSecret[i]; + inCommitment[i].inputs[3] <== inBlinding[i]; + + inNullifier[i] = Poseidon(4); + inNullifier[i].inputs[0] <== DOMAIN_VERSION * 100 + DOMAIN_NULLIFIER; + inNullifier[i].inputs[1] <== inSecret[i]; + inNullifier[i].inputs[2] <== inCommitment[i].out; + inNullifier[i].inputs[3] <== chainId; + computedNullifier[i] <== inNullifier[i].out; + computedNullifier[i] === nullifier[i]; + } + + // Prevent zero nullifiers (double-spend protection) + component nullifierNonZero[nIn]; + for (i = 0; i < nIn; i++) { + nullifierNonZero[i] = IsZero(); + nullifierNonZero[i].in <== nullifier[i]; + nullifierNonZero[i].out === 0; + } + + // Prevent duplicate nullifiers within the same proof + component sameNullifier[nIn * (nIn - 1) / 2]; + var pairIndex = 0; + for (i = 0; i < nIn; i++) { + for (var j = i + 1; j < nIn; j++) { + sameNullifier[pairIndex] = IsEqual(); + sameNullifier[pairIndex].in[0] <== nullifier[i]; + sameNullifier[pairIndex].in[1] <== nullifier[j]; + sameNullifier[pairIndex].out === 0; + pairIndex++; + } + } + + // 2) Merkle inclusion for each input + signal cur[nIn][depth + 1]; + component sw[nIn][depth]; + component h[nIn][depth]; + var j; + for (i = 0; i < nIn; i++) { + cur[i][0] <== inCommitment[i].out; + for (j = 0; j < depth; j++) { + inPathIndices[i][j] * (inPathIndices[i][j] - 1) === 0; + sw[i][j] = Switcher(); + sw[i][j].sel <== inPathIndices[i][j]; + sw[i][j].L <== cur[i][j]; + sw[i][j].R <== inPathElements[i][j]; + h[i][j] = Poseidon(2); + h[i][j].inputs[0] <== sw[i][j].outL; + h[i][j].inputs[1] <== sw[i][j].outR; + cur[i][j + 1] <== h[i][j].out; + } + cur[i][depth] === merkleRoot; + } + + // Ensure merkle root is non-zero + component merkleRootNonZero = IsZero(); + merkleRootNonZero.in <== merkleRoot; + merkleRootNonZero.out === 0; + + // 3) Output commitments — bound to dstChainId to prevent cross-chain replay + component outCommit[nOut]; + for (i = 0; i < nOut; i++) { + outCommit[i] = Poseidon(4); + outCommit[i].inputs[0] <== DOMAIN_VERSION * 100 + DOMAIN_NOTE_COMMITMENT; + outCommit[i].inputs[1] <== outAmount[i]; + outCommit[i].inputs[2] <== outSecret[i]; + outCommit[i].inputs[3] <== outBlinding[i] + dstChainId; + computedOutCommitment[i] <== outCommit[i].out; + computedOutCommitment[i] === outCommitment[i]; + } + + // Prevent duplicate output commitments within the same proof + component sameOutCommitment[nOut * (nOut - 1) / 2]; + pairIndex = 0; + for (i = 0; i < nOut; i++) { + for (j = i + 1; j < nOut; j++) { + sameOutCommitment[pairIndex] = IsEqual(); + sameOutCommitment[pairIndex].in[0] <== outCommitment[i]; + sameOutCommitment[pairIndex].in[1] <== outCommitment[j]; + sameOutCommitment[pairIndex].out === 0; + pairIndex++; + } + } + + // 4) Range constraints + component inAmountBits[nIn]; + component inAmountPositive[nIn]; + for (i = 0; i < nIn; i++) { + inAmountBits[i] = Num2Bits(64); + inAmountBits[i].in <== inAmount[i]; + + inAmountPositive[i] = GreaterThan(64); + inAmountPositive[i].in[0] <== inAmount[i]; + inAmountPositive[i].in[1] <== 0; + inAmountPositive[i].out === 1; + } + + component outAmountBits[nOut]; + for (i = 0; i < nOut; i++) { + outAmountBits[i] = Num2Bits(64); + outAmountBits[i].in <== outAmount[i]; + // Output amounts may be zero (change outputs) + } + + component feeBits = Num2Bits(64); + feeBits.in <== fee; + + component relayerBits = Num2Bits(160); + relayerBits.in <== relayer; + + component withdrawRecipientBits = Num2Bits(160); + withdrawRecipientBits.in <== withdrawRecipient; + + component withdrawOwnerBits = Num2Bits(160); + withdrawOwnerBits.in <== withdrawOwner; + + component withdrawAmountBits = Num2Bits(64); + withdrawAmountBits.in <== withdrawAmount; + + component dstChainBits = Num2Bits(64); + dstChainBits.in <== dstChainId; + + component protocolEpochBits = Num2Bits(32); + protocolEpochBits.in <== protocolEpoch; + + // 5) Balance equation: sum(inputs) = sum(outputs) + fee + withdrawAmount + // Fee rate policy is enforced at the contract level (Pool.feeBurnBps), not here. + signal sumIn[nIn + 1]; + signal sumOut[nOut + 1]; + sumIn[0] <== 0; + sumOut[0] <== 0; + for (i = 0; i < nIn; i++) { + sumIn[i + 1] <== sumIn[i] + inAmount[i]; + } + for (i = 0; i < nOut; i++) { + sumOut[i + 1] <== sumOut[i] + outAmount[i]; + } + sumIn[nIn] === sumOut[nOut] + fee + withdrawAmount; + + // Withdraw binding: if withdrawAmount is zero, owner and recipient must be zero. + // If withdrawAmount is non-zero, owner and recipient must both be non-zero. + component withdrawAmountIsZero = IsZero(); + withdrawAmountIsZero.in <== withdrawAmount; + withdrawOwner * withdrawAmountIsZero.out === 0; + withdrawRecipient * withdrawAmountIsZero.out === 0; + + component withdrawOwnerIsZero = IsZero(); + withdrawOwnerIsZero.in <== withdrawOwner; + withdrawOwnerIsZero.out * (1 - withdrawAmountIsZero.out) === 0; + + component withdrawRecipientIsZero = IsZero(); + withdrawRecipientIsZero.in <== withdrawRecipient; + withdrawRecipientIsZero.out * (1 - withdrawAmountIsZero.out) === 0; +} + +// Public signal order (13 signals): +// [0] merkleRoot +// [1] chainId +// [2] dstChainId +// [3] protocolEpoch +// [4] fee +// [5] relayer +// [6] nullifier[0] +// [7] nullifier[1] +// [8] outCommitment[0] +// [9] outCommitment[1] +// [10] withdrawOwner +// [11] withdrawRecipient +// [12] withdrawAmount +component main {public [merkleRoot, chainId, dstChainId, protocolEpoch, fee, relayer, nullifier, outCommitment, withdrawOwner, withdrawRecipient, withdrawAmount]} = MARKPool(20, 2, 2); diff --git a/circuits/package-lock.json b/circuits/package-lock.json new file mode 100644 index 0000000..9d1d623 --- /dev/null +++ b/circuits/package-lock.json @@ -0,0 +1,1466 @@ +{ + "name": "@mark/circuits", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@mark/circuits", + "version": "0.1.0", + "dependencies": { + "circomlib": "2.0.5" + }, + "devDependencies": { + "circomlibjs": "^0.1.7", + "snarkjs": "0.7.5" + } + }, + "node_modules/@ethersproject/abi": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/abi/-/abi-5.8.0.tgz", + "integrity": "sha512-b9YS/43ObplgyV6SlyQsG53/vkSal0MNA1fskSC4mbnCMi8R+NkcH8K9FPYNESf6jUefBUniE4SOKms0E/KK1Q==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/address": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/hash": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/strings": "^5.8.0" + } + }, + "node_modules/@ethersproject/abstract-provider": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/abstract-provider/-/abstract-provider-5.8.0.tgz", + "integrity": "sha512-wC9SFcmh4UK0oKuLJQItoQdzS/qZ51EJegK6EmAWlh+OptpQ/npECOR3QqECd8iGHC0RJb4WKbVdSfif4ammrg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/networks": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/transactions": "^5.8.0", + "@ethersproject/web": "^5.8.0" + } + }, + "node_modules/@ethersproject/abstract-signer": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/abstract-signer/-/abstract-signer-5.8.0.tgz", + "integrity": "sha512-N0XhZTswXcmIZQdYtUnd79VJzvEwXQw6PK0dTl9VoYrEBxxCPXqS0Eod7q5TNKRxe1/5WUMuR0u0nqTF/avdCA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-provider": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0" + } + }, + "node_modules/@ethersproject/address": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/address/-/address-5.8.0.tgz", + "integrity": "sha512-GhH/abcC46LJwshoN+uBNoKVFPxUuZm6dA257z0vZkKmU1+t8xTn8oK7B9qrj8W2rFRMch4gbJl6PmVxjxBEBA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/rlp": "^5.8.0" + } + }, + "node_modules/@ethersproject/base64": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/base64/-/base64-5.8.0.tgz", + "integrity": "sha512-lN0oIwfkYj9LbPx4xEkie6rAMJtySbpOAFXSDVQaBnAzYfB4X2Qr+FXJGxMoc3Bxp2Sm8OwvzMrywxyw0gLjIQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0" + } + }, + "node_modules/@ethersproject/basex": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/basex/-/basex-5.8.0.tgz", + "integrity": "sha512-PIgTszMlDRmNwW9nhS6iqtVfdTAKosA7llYXNmGPw4YAI1PUyMv28988wAb41/gHF/WqGdoLv0erHaRcHRKW2Q==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/properties": "^5.8.0" + } + }, + "node_modules/@ethersproject/bignumber": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/bignumber/-/bignumber-5.8.0.tgz", + "integrity": "sha512-ZyaT24bHaSeJon2tGPKIiHszWjD/54Sz8t57Toch475lCLljC6MgPmxk7Gtzz+ddNN5LuHea9qhAe0x3D+uYPA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "bn.js": "^5.2.1" + } + }, + "node_modules/@ethersproject/bytes": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/bytes/-/bytes-5.8.0.tgz", + "integrity": "sha512-vTkeohgJVCPVHu5c25XWaWQOZ4v+DkGoC42/TS2ond+PARCxTJvgTFUNDZovyQ/uAQ4EcpqqowKydcdmRKjg7A==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/constants": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/constants/-/constants-5.8.0.tgz", + "integrity": "sha512-wigX4lrf5Vu+axVTIvNsuL6YrV4O5AXl5ubcURKMEME5TnWBouUh0CDTWxZ2GpnRn1kcCgE7l8O5+VbV9QTTcg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bignumber": "^5.8.0" + } + }, + "node_modules/@ethersproject/contracts": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/contracts/-/contracts-5.8.0.tgz", + "integrity": "sha512-0eFjGz9GtuAi6MZwhb4uvUM216F38xiuR0yYCjKJpNfSEy4HUM8hvqqBj9Jmm0IUz8l0xKEhWwLIhPgxNY0yvQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abi": "^5.8.0", + "@ethersproject/abstract-provider": "^5.8.0", + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/address": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/transactions": "^5.8.0" + } + }, + "node_modules/@ethersproject/hash": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/hash/-/hash-5.8.0.tgz", + "integrity": "sha512-ac/lBcTbEWW/VGJij0CNSw/wPcw9bSRgCB0AIBz8CvED/jfvDoV9hsIIiWfvWmFEi8RcXtlNwp2jv6ozWOsooA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/address": "^5.8.0", + "@ethersproject/base64": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/strings": "^5.8.0" + } + }, + "node_modules/@ethersproject/hdnode": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/hdnode/-/hdnode-5.8.0.tgz", + "integrity": "sha512-4bK1VF6E83/3/Im0ERnnUeWOY3P1BZml4ZD3wcH8Ys0/d1h1xaFt6Zc+Dh9zXf9TapGro0T4wvO71UTCp3/uoA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/basex": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/pbkdf2": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/sha2": "^5.8.0", + "@ethersproject/signing-key": "^5.8.0", + "@ethersproject/strings": "^5.8.0", + "@ethersproject/transactions": "^5.8.0", + "@ethersproject/wordlists": "^5.8.0" + } + }, + "node_modules/@ethersproject/json-wallets": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/json-wallets/-/json-wallets-5.8.0.tgz", + "integrity": "sha512-HxblNck8FVUtNxS3VTEYJAcwiKYsBIF77W15HufqlBF9gGfhmYOJtYZp8fSDZtn9y5EaXTE87zDwzxRoTFk11w==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/address": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/hdnode": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/pbkdf2": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/random": "^5.8.0", + "@ethersproject/strings": "^5.8.0", + "@ethersproject/transactions": "^5.8.0", + "aes-js": "3.0.0", + "scrypt-js": "3.0.1" + } + }, + "node_modules/@ethersproject/keccak256": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/keccak256/-/keccak256-5.8.0.tgz", + "integrity": "sha512-A1pkKLZSz8pDaQ1ftutZoaN46I6+jvuqugx5KYNeQOPqq+JZ0Txm7dlWesCHB5cndJSu5vP2VKptKf7cksERng==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "js-sha3": "0.8.0" + } + }, + "node_modules/@ethersproject/logger": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/logger/-/logger-5.8.0.tgz", + "integrity": "sha512-Qe6knGmY+zPPWTC+wQrpitodgBfH7XoceCGL5bJVejmH+yCS3R8jJm8iiWuvWbG76RUmyEG53oqv6GMVWqunjA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT" + }, + "node_modules/@ethersproject/networks": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/networks/-/networks-5.8.0.tgz", + "integrity": "sha512-egPJh3aPVAzbHwq8DD7Po53J4OUSsA1MjQp8Vf/OZPav5rlmWUaFLiq8cvQiGK0Z5K6LYzm29+VA/p4RL1FzNg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/pbkdf2": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/pbkdf2/-/pbkdf2-5.8.0.tgz", + "integrity": "sha512-wuHiv97BrzCmfEaPbUFpMjlVg/IDkZThp9Ri88BpjRleg4iePJaj2SW8AIyE8cXn5V1tuAaMj6lzvsGJkGWskg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/sha2": "^5.8.0" + } + }, + "node_modules/@ethersproject/properties": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/properties/-/properties-5.8.0.tgz", + "integrity": "sha512-PYuiEoQ+FMaZZNGrStmN7+lWjlsoufGIHdww7454FIaGdbe/p5rnaCXTr5MtBYl3NkeoVhHZuyzChPeGeKIpQw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/providers": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/providers/-/providers-5.8.0.tgz", + "integrity": "sha512-3Il3oTzEx3o6kzcg9ZzbE+oCZYyY+3Zh83sKkn4s1DZfTUjIegHnN2Cm0kbn9YFy45FDVcuCLLONhU7ny0SsCw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-provider": "^5.8.0", + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/address": "^5.8.0", + "@ethersproject/base64": "^5.8.0", + "@ethersproject/basex": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/hash": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/networks": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/random": "^5.8.0", + "@ethersproject/rlp": "^5.8.0", + "@ethersproject/sha2": "^5.8.0", + "@ethersproject/strings": "^5.8.0", + "@ethersproject/transactions": "^5.8.0", + "@ethersproject/web": "^5.8.0", + "bech32": "1.1.4", + "ws": "8.18.0" + } + }, + "node_modules/@ethersproject/random": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/random/-/random-5.8.0.tgz", + "integrity": "sha512-E4I5TDl7SVqyg4/kkA/qTfuLWAQGXmSOgYyO01So8hLfwgKvYK5snIlzxJMk72IFdG/7oh8yuSqY2KX7MMwg+A==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/rlp": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/rlp/-/rlp-5.8.0.tgz", + "integrity": "sha512-LqZgAznqDbiEunaUvykH2JAoXTT9NV0Atqk8rQN9nx9SEgThA/WMx5DnW8a9FOufo//6FZOCHZ+XiClzgbqV9Q==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/sha2": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/sha2/-/sha2-5.8.0.tgz", + "integrity": "sha512-dDOUrXr9wF/YFltgTBYS0tKslPEKr6AekjqDW2dbn1L1xmjGR+9GiKu4ajxovnrDbwxAKdHjW8jNcwfz8PAz4A==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "hash.js": "1.1.7" + } + }, + "node_modules/@ethersproject/signing-key": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/signing-key/-/signing-key-5.8.0.tgz", + "integrity": "sha512-LrPW2ZxoigFi6U6aVkFN/fa9Yx/+4AtIUe4/HACTvKJdhm0eeb107EVCIQcrLZkxaSIgc/eCrX8Q1GtbH+9n3w==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "bn.js": "^5.2.1", + "elliptic": "6.6.1", + "hash.js": "1.1.7" + } + }, + "node_modules/@ethersproject/solidity": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/solidity/-/solidity-5.8.0.tgz", + "integrity": "sha512-4CxFeCgmIWamOHwYN9d+QWGxye9qQLilpgTU0XhYs1OahkclF+ewO+3V1U0mvpiuQxm5EHHmv8f7ClVII8EHsA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/sha2": "^5.8.0", + "@ethersproject/strings": "^5.8.0" + } + }, + "node_modules/@ethersproject/strings": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/strings/-/strings-5.8.0.tgz", + "integrity": "sha512-qWEAk0MAvl0LszjdfnZ2uC8xbR2wdv4cDabyHiBh3Cldq/T8dPH3V4BbBsAYJUeonwD+8afVXld274Ls+Y1xXg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/transactions": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/transactions/-/transactions-5.8.0.tgz", + "integrity": "sha512-UglxSDjByHG0TuU17bDfCemZ3AnKO2vYrL5/2n2oXvKzvb7Cz+W9gOWXKARjp2URVwcWlQlPOEQyAviKwT4AHg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/address": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/rlp": "^5.8.0", + "@ethersproject/signing-key": "^5.8.0" + } + }, + "node_modules/@ethersproject/units": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/units/-/units-5.8.0.tgz", + "integrity": "sha512-lxq0CAnc5kMGIiWW4Mr041VT8IhNM+Pn5T3haO74XZWFulk7wH1Gv64HqE96hT4a7iiNMdOCFEBgaxWuk8ETKQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/constants": "^5.8.0", + "@ethersproject/logger": "^5.8.0" + } + }, + "node_modules/@ethersproject/wallet": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/wallet/-/wallet-5.8.0.tgz", + "integrity": "sha512-G+jnzmgg6UxurVKRKvw27h0kvG75YKXZKdlLYmAHeF32TGUzHkOFd7Zn6QHOTYRFWnfjtSSFjBowKo7vfrXzPA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abstract-provider": "^5.8.0", + "@ethersproject/abstract-signer": "^5.8.0", + "@ethersproject/address": "^5.8.0", + "@ethersproject/bignumber": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/hash": "^5.8.0", + "@ethersproject/hdnode": "^5.8.0", + "@ethersproject/json-wallets": "^5.8.0", + "@ethersproject/keccak256": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/random": "^5.8.0", + "@ethersproject/signing-key": "^5.8.0", + "@ethersproject/transactions": "^5.8.0", + "@ethersproject/wordlists": "^5.8.0" + } + }, + "node_modules/@ethersproject/web": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/web/-/web-5.8.0.tgz", + "integrity": "sha512-j7+Ksi/9KfGviws6Qtf9Q7KCqRhpwrYKQPs+JBA/rKVFF/yaWLHJEH3zfVP2plVu+eys0d2DlFmhoQJayFewcw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/base64": "^5.8.0", + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/strings": "^5.8.0" + } + }, + "node_modules/@ethersproject/wordlists": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@ethersproject/wordlists/-/wordlists-5.8.0.tgz", + "integrity": "sha512-2df9bbXicZws2Sb5S6ET493uJ0Z84Fjr3pC4tu/qlnZERibZCeUVuqdtt+7Tv9xxhUxHoIekIA7avrKUWHrezg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/bytes": "^5.8.0", + "@ethersproject/hash": "^5.8.0", + "@ethersproject/logger": "^5.8.0", + "@ethersproject/properties": "^5.8.0", + "@ethersproject/strings": "^5.8.0" + } + }, + "node_modules/@iden3/bigarray": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/@iden3/bigarray/-/bigarray-0.0.2.tgz", + "integrity": "sha512-Xzdyxqm1bOFF6pdIsiHLLl3HkSLjbhqJHVyqaTxXt3RqXBEnmsUmEW47H7VOi/ak7TdkRpNkxjyK5Zbkm+y52g==", + "dev": true, + "license": "GPL-3.0" + }, + "node_modules/@iden3/binfileutils": { + "version": "0.0.12", + "resolved": "https://registry.npmjs.org/@iden3/binfileutils/-/binfileutils-0.0.12.tgz", + "integrity": "sha512-naAmzuDufRIcoNfQ1d99d7hGHufLA3wZSibtr4dMe6ZeiOPV1KwOZWTJ1YVz4HbaWlpDuzVU72dS4ATQS4PXBQ==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "fastfile": "0.0.20", + "ffjavascript": "^0.3.0" + } + }, + "node_modules/aes-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz", + "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==", + "dev": true, + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/b4a": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz", + "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==", + "dev": true, + "license": "Apache-2.0", + "peerDependencies": { + "react-native-b4a": "*" + }, + "peerDependenciesMeta": { + "react-native-b4a": { + "optional": true + } + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/bech32": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/bech32/-/bech32-1.1.4.tgz", + "integrity": "sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/bfj": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/bfj/-/bfj-7.1.0.tgz", + "integrity": "sha512-I6MMLkn+anzNdCUp9hMRyui1HaNEUCco50lxbvNS4+EyXg8lN3nJ48PjPWtbH8UVS9CuMoaKE9U2V3l29DaRQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bluebird": "^3.7.2", + "check-types": "^11.2.3", + "hoopy": "^0.1.4", + "jsonpath": "^1.1.1", + "tryer": "^1.0.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/blake-hash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/blake-hash/-/blake-hash-2.0.0.tgz", + "integrity": "sha512-Igj8YowDu1PRkRsxZA7NVkdFNxH5rKv5cpLxQ0CVXSIA77pVYwCPRQJ2sMew/oneUpfuYRyjG6r8SmmmnbZb1w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^3.0.0", + "node-gyp-build": "^4.2.2", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/blake2b": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/blake2b/-/blake2b-2.1.4.tgz", + "integrity": "sha512-AyBuuJNI64gIvwx13qiICz6H6hpmjvYS5DGkG6jbXMOT8Z3WUJ3V1X0FlhIoT1b/5JtHE3ki+xjtMvu1nn+t9A==", + "dev": true, + "license": "ISC", + "dependencies": { + "blake2b-wasm": "^2.4.0", + "nanoassert": "^2.0.0" + } + }, + "node_modules/blake2b-wasm": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/blake2b-wasm/-/blake2b-wasm-2.4.0.tgz", + "integrity": "sha512-S1kwmW2ZhZFFFOghcx73+ZajEfKBqhP82JMssxtLVMxlaPea1p9uoLiUZ5WYyHn0KddwbLc+0vh4wR0KBNoT5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "b4a": "^1.0.1", + "nanoassert": "^2.0.0" + } + }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/bn.js": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.3.tgz", + "integrity": "sha512-EAcmnPkxpntVL+DS7bO1zhcZNvCkxqtkd0ZY53h06GNQ3DEkkGZ/gKgmDv6DdZQGj9BgfSPKtJJ7Dp1GPP8f7w==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", + "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==", + "dev": true, + "license": "MIT" + }, + "node_modules/check-types": { + "version": "11.2.3", + "resolved": "https://registry.npmjs.org/check-types/-/check-types-11.2.3.tgz", + "integrity": "sha512-+67P1GkJRaxQD6PKK0Et9DhwQB+vGg3PM5+aavopCpZT1lj9jeqfvpgTLAWErNj8qApkkmXlu/Ug74kmhagkXg==", + "dev": true, + "license": "MIT" + }, + "node_modules/circom_runtime": { + "version": "0.1.28", + "resolved": "https://registry.npmjs.org/circom_runtime/-/circom_runtime-0.1.28.tgz", + "integrity": "sha512-ACagpQ7zBRLKDl5xRZ4KpmYIcZDUjOiNRuxvXLqhnnlLSVY1Dbvh73TI853nqoR0oEbihtWmMSjgc5f+pXf/jQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "ffjavascript": "0.3.1" + }, + "bin": { + "calcwit": "calcwit.js" + } + }, + "node_modules/circomlib": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/circomlib/-/circomlib-2.0.5.tgz", + "integrity": "sha512-O7NQ8OS+J4eshBuoy36z/TwQU0YHw8W3zxZcs4hVwpEll3e4hDm3mgkIPqItN8FDeLEKZFK3YeT/+k8TiLF3/A==", + "license": "GPL-3.0" + }, + "node_modules/circomlibjs": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/circomlibjs/-/circomlibjs-0.1.7.tgz", + "integrity": "sha512-GRAUoAlKAsiiTa+PA725G9RmEmJJRc8tRFxw/zKktUxlQISGznT4hH4ESvW8FNTsrGg/nNd06sGP/Wlx0LUHVg==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "blake-hash": "^2.0.0", + "blake2b": "^2.1.3", + "ethers": "^5.5.1", + "ffjavascript": "^0.2.45" + } + }, + "node_modules/circomlibjs/node_modules/ffjavascript": { + "version": "0.2.63", + "resolved": "https://registry.npmjs.org/ffjavascript/-/ffjavascript-0.2.63.tgz", + "integrity": "sha512-dBgdsfGks58b66JnUZeZpGxdMIDQ4QsD3VYlRJyFVrKQHb2kJy4R2gufx5oetrTxXPT+aEjg0dOvOLg1N0on4A==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "wasmbuilder": "0.0.16", + "wasmcurves": "0.2.2", + "web-worker": "1.2.0" + } + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/elliptic": { + "version": "6.6.1", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.6.1.tgz", + "integrity": "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "bn.js": "^4.11.9", + "brorand": "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + "inherits": "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/elliptic/node_modules/bn.js": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz", + "integrity": "sha512-fGTi3gxV/23FTYdAoUtLYp6qySe2KE3teyZitipKNRuVYcBkoP/bB3guXN/XVKUe9mxCHXnc9C4ocyz8OmgN0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/escodegen": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", + "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/escodegen/node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esprima": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-1.2.5.tgz", + "integrity": "sha512-S9VbPDU0adFErpDai3qDkjq8+G05ONtKzcyNrPKg/ZKa+tf879nX2KexNU95b31UoTJjRLInNBHHHjFPoCd7lQ==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ethers": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz", + "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@ethersproject/abi": "5.8.0", + "@ethersproject/abstract-provider": "5.8.0", + "@ethersproject/abstract-signer": "5.8.0", + "@ethersproject/address": "5.8.0", + "@ethersproject/base64": "5.8.0", + "@ethersproject/basex": "5.8.0", + "@ethersproject/bignumber": "5.8.0", + "@ethersproject/bytes": "5.8.0", + "@ethersproject/constants": "5.8.0", + "@ethersproject/contracts": "5.8.0", + "@ethersproject/hash": "5.8.0", + "@ethersproject/hdnode": "5.8.0", + "@ethersproject/json-wallets": "5.8.0", + "@ethersproject/keccak256": "5.8.0", + "@ethersproject/logger": "5.8.0", + "@ethersproject/networks": "5.8.0", + "@ethersproject/pbkdf2": "5.8.0", + "@ethersproject/properties": "5.8.0", + "@ethersproject/providers": "5.8.0", + "@ethersproject/random": "5.8.0", + "@ethersproject/rlp": "5.8.0", + "@ethersproject/sha2": "5.8.0", + "@ethersproject/signing-key": "5.8.0", + "@ethersproject/solidity": "5.8.0", + "@ethersproject/strings": "5.8.0", + "@ethersproject/transactions": "5.8.0", + "@ethersproject/units": "5.8.0", + "@ethersproject/wallet": "5.8.0", + "@ethersproject/web": "5.8.0", + "@ethersproject/wordlists": "5.8.0" + } + }, + "node_modules/fastfile": { + "version": "0.0.20", + "resolved": "https://registry.npmjs.org/fastfile/-/fastfile-0.0.20.tgz", + "integrity": "sha512-r5ZDbgImvVWCP0lA/cGNgQcZqR+aYdFx3u+CtJqUE510pBUVGMn4ulL/iRTI4tACTYsNJ736uzFxEBXesPAktA==", + "dev": true, + "license": "GPL-3.0" + }, + "node_modules/ffjavascript": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/ffjavascript/-/ffjavascript-0.3.1.tgz", + "integrity": "sha512-4PbK1WYodQtuF47D4pRI5KUg3Q392vuP5WjE1THSnceHdXwU3ijaoS0OqxTzLknCtz4Z2TtABzkBdBdMn3B/Aw==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "wasmbuilder": "0.0.16", + "wasmcurves": "0.2.2", + "web-worker": "1.2.0" + } + }, + "node_modules/filelist": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", + "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "node_modules/hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/hoopy": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/hoopy/-/hoopy-0.1.4.tgz", + "integrity": "sha512-HRcs+2mr52W0K+x8RzcLzuPPmVIKMSv97RGHy0Ea9y/mpcaK+xTrjICA04KAHi4GRzxliNqNJEFYWHghy3rSfQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonpath": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/jsonpath/-/jsonpath-1.3.0.tgz", + "integrity": "sha512-0kjkYHJBkAy50Z5QzArZ7udmvxrJzkpKYW27fiF//BrMY7TQibYLl+FYIXN2BiYmwMIVzSfD8aDRj6IzgBX2/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "esprima": "1.2.5", + "static-eval": "2.1.1", + "underscore": "1.13.6" + } + }, + "node_modules/logplease": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/logplease/-/logplease-1.2.15.tgz", + "integrity": "sha512-jLlHnlsPSJjpwUfcNyUxXCl33AYg2cHhIf9QhGL2T4iPT0XPB+xP1LRKFPgIg1M/sg9kAJvy94w9CzBNrfnstA==", + "dev": true, + "license": "MIT" + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true, + "license": "ISC" + }, + "node_modules/minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg==", + "dev": true, + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/nanoassert": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/nanoassert/-/nanoassert-2.0.0.tgz", + "integrity": "sha512-7vO7n28+aYO4J+8w96AzhmU8G+Y/xpPDJz/se19ICsqj/momRbb9mh9ZUtkoJ5X3nTnPdhEJyc0qnM6yAsHBaA==", + "dev": true, + "license": "ISC" + }, + "node_modules/node-addon-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", + "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "dev": true, + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/r1csfile": { + "version": "0.0.48", + "resolved": "https://registry.npmjs.org/r1csfile/-/r1csfile-0.0.48.tgz", + "integrity": "sha512-kHRkKUJNaor31l05f2+RFzvcH5XSa7OfEfd/l4hzjte6NL6fjRkSMfZ4BjySW9wmfdwPOtq3mXurzPvPGEf5Tw==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "@iden3/bigarray": "0.0.2", + "@iden3/binfileutils": "0.0.12", + "fastfile": "0.0.20", + "ffjavascript": "0.3.0" + } + }, + "node_modules/r1csfile/node_modules/ffjavascript": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/ffjavascript/-/ffjavascript-0.3.0.tgz", + "integrity": "sha512-l7sR5kmU3gRwDy8g0Z2tYBXy5ttmafRPFOqY7S6af5cq51JqJWt5eQ/lSR/rs2wQNbDYaYlQr5O+OSUf/oMLoQ==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "wasmbuilder": "0.0.16", + "wasmcurves": "0.2.2", + "web-worker": "1.2.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/scrypt-js": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/scrypt-js/-/scrypt-js-3.0.1.tgz", + "integrity": "sha512-cdwTTnqPu0Hyvf5in5asVdZocVDTNRmR7XEcJuIzMjJeSHybHl7vpB66AzwTaIg6CLSbtjcxc8fqcySfnTkccA==", + "dev": true, + "license": "MIT" + }, + "node_modules/snarkjs": { + "version": "0.7.5", + "resolved": "https://registry.npmjs.org/snarkjs/-/snarkjs-0.7.5.tgz", + "integrity": "sha512-h+3c4rXZKLhLuHk4LHydZCk/h5GcNvk5GjVKRRkHmfb6Ntf8gHOA9zea3g656iclRuhqQ3iKDWFgiD9ypLrKiA==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "@iden3/binfileutils": "0.0.12", + "bfj": "^7.0.2", + "blake2b-wasm": "^2.4.0", + "circom_runtime": "0.1.28", + "ejs": "^3.1.6", + "fastfile": "0.0.20", + "ffjavascript": "0.3.1", + "js-sha3": "^0.8.0", + "logplease": "^1.2.15", + "r1csfile": "0.0.48" + }, + "bin": { + "snarkjs": "build/cli.cjs" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/static-eval": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.1.1.tgz", + "integrity": "sha512-MgWpQ/ZjGieSVB3eOJVs4OA2LT/q1vx98KPCTTQPzq/aLr0YUXTsgryTXr4SLfR0ZfUUCiedM9n/ABeDIyy4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "escodegen": "^2.1.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/tryer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tryer/-/tryer-1.0.1.tgz", + "integrity": "sha512-c3zayb8/kWWpycWYg87P71E1S1ZL6b6IJxfb5fvsUgsf0S2MVGaDhDXXjDMpdCpfWXqptc+4mXwmiy1ypXqRAA==", + "dev": true, + "license": "MIT" + }, + "node_modules/underscore": { + "version": "1.13.6", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", + "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/wasmbuilder": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/wasmbuilder/-/wasmbuilder-0.0.16.tgz", + "integrity": "sha512-Qx3lEFqaVvp1cEYW7Bfi+ebRJrOiwz2Ieu7ZG2l7YyeSJIok/reEQCQCuicj/Y32ITIJuGIM9xZQppGx5LrQdA==", + "dev": true, + "license": "GPL-3.0" + }, + "node_modules/wasmcurves": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/wasmcurves/-/wasmcurves-0.2.2.tgz", + "integrity": "sha512-JRY908NkmKjFl4ytnTu5ED6AwPD+8VJ9oc94kdq7h5bIwbj0L4TDJ69mG+2aLs2SoCmGfqIesMWTEJjtYsoQXQ==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "wasmbuilder": "0.0.16" + } + }, + "node_modules/web-worker": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/circuits/package.json b/circuits/package.json new file mode 100644 index 0000000..db61542 --- /dev/null +++ b/circuits/package.json @@ -0,0 +1,17 @@ +{ + "name": "@mark/circuits", + "version": "0.1.0", + "private": true, + "description": "MARK Protocol ZK circuits (circom)", + "scripts": { + "build": "circom mark/MARKPool.circom --r1cs --wasm --sym -l node_modules --output build", + "test": "mkdir -p build && npm run build && node test/MARKPool.test.mjs" + }, + "dependencies": { + "circomlib": "2.0.5" + }, + "devDependencies": { + "circomlibjs": "^0.1.7", + "snarkjs": "0.7.5" + } +} diff --git a/circuits/setup.mjs b/circuits/setup.mjs new file mode 100644 index 0000000..0a855f6 --- /dev/null +++ b/circuits/setup.mjs @@ -0,0 +1,52 @@ +// Trusted setup for MARKPool circuit. +// Generates build/MARKPoolVerifier.sol for use in contracts/src/pool/verifier/. +// Run: node setup.mjs +// +// Powers of tau: pot15 (2^15 = 32768 >= 26387*2 wires required by MARKPool(20,2,2)) + +import { randomBytes } from 'crypto'; +import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs'; +import { fileURLToPath } from 'url'; +import { zKey, powersOfTau } from 'snarkjs'; + +mkdirSync('build', { recursive: true }); + +const entropy1 = randomBytes(32).toString('hex'); +const entropy2 = randomBytes(32).toString('hex'); + +console.log('Step 1: Powers of Tau (pot15)...'); +await powersOfTau.newAccumulator('bn128', 15, 'build/pot15_0000.ptau'); + +console.log('Step 2: Contribute to Powers of Tau...'); +await powersOfTau.contribute('build/pot15_0000.ptau', 'build/pot15_final.ptau', + 'MARK Protocol', entropy1); + +console.log('Step 3: Prepare phase 2...'); +await powersOfTau.preparePhase2('build/pot15_final.ptau', 'build/pot15_phase2.ptau'); + +// Verify compiled circuit exists before attempting trusted setup +if (!existsSync('build/MARKPool.r1cs')) { + console.error('Error: build/MARKPool.r1cs not found. Run: npm run build'); + process.exit(1); +} + +console.log('Step 4: Phase 2 setup...'); +await zKey.newZKey('build/MARKPool.r1cs', 'build/pot15_phase2.ptau', 'build/markpool_0000.zkey'); + +console.log('Step 5: Contribute to zkey...'); +await zKey.contribute('build/markpool_0000.zkey', 'build/markpool_final.zkey', + 'MARK Protocol MARKPool', entropy2); + +console.log('Step 6: Export verification key...'); +const vKey = await zKey.exportVerificationKey('build/markpool_final.zkey'); +writeFileSync('build/markpool_verification_key.json', JSON.stringify(vKey, null, 2)); + +console.log('Step 7: Export Solidity verifier...'); +const templatePath = fileURLToPath( + new URL('node_modules/snarkjs/templates/verifier_groth16.sol.ejs', import.meta.url) +); +const solidityTemplate = readFileSync(templatePath, 'utf8'); +const verifier = await zKey.exportSolidityVerifier('build/markpool_final.zkey', { groth16: solidityTemplate }); +writeFileSync('build/MARKPoolVerifier.sol', verifier); + +console.log('Done. Copy build/MARKPoolVerifier.sol to contracts/src/pool/verifier/MARKPoolVerifier.sol'); diff --git a/circuits/test/MARKPool.test.mjs b/circuits/test/MARKPool.test.mjs new file mode 100644 index 0000000..3e1b15d --- /dev/null +++ b/circuits/test/MARKPool.test.mjs @@ -0,0 +1,204 @@ +// Witness tests for MARKPool circuit. +// Run: node test/MARKPool.test.mjs + +import { buildPoseidon } from "circomlibjs"; +import { readFileSync } from "fs"; +import { createRequire } from "module"; +import { fileURLToPath } from "url"; +import path from "path"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const require = createRequire(import.meta.url); + +const poseidon = await buildPoseidon(); +const F = poseidon.F; + +function poseidonHash(...inputs) { + return F.toObject(poseidon(inputs.map(BigInt))); +} + +// Replicate MerkleTree.sol zero-value tree (depth=20, zero leaf = 0) +function buildZeroTree(depth) { + const zeros = [0n]; + for (let i = 1; i <= depth; i++) { + zeros.push(poseidonHash(zeros[i - 1], zeros[i - 1])); + } + return zeros; +} + +const wasmPath = path.join(__dirname, "../build/MARKPool_js/MARKPool.wasm"); +const WitnessCalculator = require(path.join(__dirname, "../build/MARKPool_js/witness_calculator.js")); +const wasm = readFileSync(wasmPath); +const wc = await WitnessCalculator(wasm); + +async function expectPass(label, input) { + try { + await wc.calculateWitness(input, false); + console.log(` PASS: ${label}`); + } catch (e) { + console.error(` FAIL: ${label} — ${e.message}`); + process.exit(1); + } +} + +async function expectFail(label, input) { + try { + await wc.calculateWitness(input, false); + console.error(` FAIL: ${label} — expected constraint failure`); + process.exit(1); + } catch (e) { + // Only treat constraint/assertion failures as expected. Rethrow anything else + // (malformed input, missing signal, internal error) so regressions surface. + const msg = (e?.message ?? '').toLowerCase(); + if (msg.includes('assert failed') || msg.includes('constraint') || msg.includes('error in template')) { + console.log(` PASS: ${label}`); + } else { + throw e; + } + } +} + +// Domain constants (must match MARKPool.circom) +const DOMAIN_VERSION = 1n; +const DOMAIN_NOTE_COMMITMENT = 11n; +const DOMAIN_NULLIFIER = 12n; +const DOMAIN_COMMITMENT = DOMAIN_VERSION * 100n + DOMAIN_NOTE_COMMITMENT; +const DOMAIN_NULLIFIER_TAG = DOMAIN_VERSION * 100n + DOMAIN_NULLIFIER; + +const DEPTH = 20; +const CHAIN_ID = 11155420n; // OP Sepolia + +// Build a valid note +function makeNote(amount, secret, blinding) { + const commitment = poseidonHash(DOMAIN_COMMITMENT, amount, secret, blinding); + return { amount, secret, blinding, commitment }; +} + +function makeNullifier(note, chainId) { + return poseidonHash(DOMAIN_NULLIFIER_TAG, note.secret, note.commitment, chainId); +} + +function makeOutCommitment(amount, secret, blinding, dstChainId) { + return poseidonHash(DOMAIN_COMMITMENT, amount, secret, blinding + dstChainId); +} + +// Base valid inputs: 2-in 2-out transact, no withdrawal +const in0 = makeNote(500n, 111n, 222n); +const in1 = makeNote(500n, 333n, 444n); +const out0Secret = 555n; const out0Blinding = 666n; const out0Amount = 400n; +const out1Secret = 777n; const out1Blinding = 888n; const out1Amount = 100n; +const fee = 500n; // 500 = 500 (in0+in1=1000, out0+out1=500, fee=500, withdraw=0) + +// After inserting in1 at index 1, the root changes — for simplicity use a single-leaf tree +// where in1 is also at index 0 in its own path (both share the same root for test purposes). +// Use a shared root: insert both into the same tree. +function buildTwoLeafRoot(leaf0, leaf1, depth) { + const zeros = buildZeroTree(depth); + // Level 0: leaf0 at 0, leaf1 at 1 + let cur0 = poseidonHash(leaf0, leaf1); // parent of both + let root = cur0; + for (let i = 1; i < depth; i++) { + root = poseidonHash(root, zeros[i]); + } + return { + root, + path0: { elements: [leaf1, ...zeros.slice(1, depth)], indices: Array(depth).fill(0n) }, + path1: { elements: [leaf0, ...zeros.slice(1, depth)], indices: [1n, ...Array(depth - 1).fill(0n)] }, + }; +} + +const tree = buildTwoLeafRoot(in0.commitment, in1.commitment, DEPTH); +const merkleRoot = tree.root; + +const nullifier0 = makeNullifier(in0, CHAIN_ID); +const nullifier1 = makeNullifier(in1, CHAIN_ID); +const outC0 = makeOutCommitment(out0Amount, out0Secret, out0Blinding, CHAIN_ID); +const outC1 = makeOutCommitment(out1Amount, out1Secret, out1Blinding, CHAIN_ID); + +const validBase = { + inAmount: [in0.amount, in1.amount], + inSecret: [in0.secret, in1.secret], + inBlinding: [in0.blinding, in1.blinding], + inPathElements: [tree.path0.elements, tree.path1.elements], + inPathIndices: [tree.path0.indices, tree.path1.indices], + outAmount: [out0Amount, out1Amount], + outSecret: [out0Secret, out1Secret], + outBlinding: [out0Blinding, out1Blinding], + merkleRoot, + chainId: CHAIN_ID, + dstChainId: CHAIN_ID, + protocolEpoch: 0n, + fee, + relayer: 0n, + nullifier: [nullifier0, nullifier1], + outCommitment: [outC0, outC1], + withdrawOwner: 0n, + withdrawRecipient: 0n, + withdrawAmount: 0n, +}; + +console.log("MARKPool circuit tests"); + +// Happy path +await expectPass("valid 2-in 2-out transact", validBase); + +// Balance equation +await expectFail("fee too low (balance broken)", { ...validBase, fee: fee - 1n }); +await expectFail("fee too high (balance broken)", { ...validBase, fee: fee + 1n }); + +// Withdrawal binding +const withdrawOwner = BigInt("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"); +const withdrawRecipient = BigInt("0x70997970C51812dc3A010C7d01b50e0d17dc79C8"); +const withdrawAmount = 200n; +const feeWithWithdraw = 300n; // in0+in1=1000, out0+out1=500, fee=300, withdraw=200 +const validWithWithdraw = { + ...validBase, + fee: feeWithWithdraw, + withdrawOwner, + withdrawRecipient, + withdrawAmount, +}; +await expectPass("valid transact with withdraw binding", validWithWithdraw); +await expectFail("withdraw amount non-zero but owner zero", { + ...validWithWithdraw, + withdrawOwner: 0n, +}); +await expectFail("withdraw amount non-zero but recipient zero", { + ...validWithWithdraw, + withdrawRecipient: 0n, +}); +await expectFail("withdraw amount zero but owner non-zero", { + ...validBase, + withdrawOwner, + withdrawRecipient: 0n, + withdrawAmount: 0n, +}); + +// Nullifier constraints +await expectFail("wrong nullifier (tampered)", { + ...validBase, + nullifier: [nullifier0 + 1n, nullifier1], +}); +await expectFail("duplicate nullifiers", { + ...validBase, + nullifier: [nullifier0, nullifier0], +}); + +// Merkle root +await expectFail("wrong merkle root", { ...validBase, merkleRoot: merkleRoot + 1n }); +await expectFail("zero merkle root", { ...validBase, merkleRoot: 0n }); + +// Input amount constraints +await expectFail("zero input amount", { + ...validBase, + inAmount: [0n, in1.amount], + fee: in1.amount, +}); + +// Output commitment +await expectFail("wrong output commitment", { + ...validBase, + outCommitment: [outC0 + 1n, outC1], +}); + +console.log("\nAll tests passed."); diff --git a/contracts/foundry.toml b/contracts/foundry.toml index 0bd298c..0a7de05 100644 --- a/contracts/foundry.toml +++ b/contracts/foundry.toml @@ -8,6 +8,7 @@ broadcast = "broadcast" libs = ["lib"] no_match_path = "test/integration/**" fs_permissions = [{ access = "read-write", path = "./broadcast" }] +via_ir = true remappings = [ "@interop-lib/=lib/interop-lib/src/", "@openzeppelin/=lib/createx/lib/openzeppelin-contracts/" @@ -35,3 +36,6 @@ no_match_path = "test/never/**" + + + diff --git a/contracts/script/deploy/pool/DeployMARKPool.s.sol b/contracts/script/deploy/pool/DeployMARKPool.s.sol new file mode 100644 index 0000000..d8912b1 --- /dev/null +++ b/contracts/script/deploy/pool/DeployMARKPool.s.sol @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Script, console} from "forge-std/Script.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; +import {RYLA} from "../../../src/token/RYLA.sol"; +import {MARKPool} from "../../../src/pool/MARKPool.sol"; +import {MARKWithdrawAdapter} from "../../../src/withdraw/MARKWithdrawAdapter.sol"; +import {RYLACreditLedger} from "../../../src/pool/RYLACreditLedger.sol"; + +/// @notice Deploys MARKPool, RYLACreditLedger, and MARKWithdrawAdapter. +/// @dev Deployment sequence: +/// 1. Deploy AccessManager (admin = owner) +/// 2. Deploy MARKPool (authority = AccessManager, verifier) +/// 3. Deploy RYLACreditLedger (token, pool) — pool address now known +/// 4. Deploy MARKWithdrawAdapter (authority = AccessManager, ledger, pool) +/// 5. Configure restricted selectors on pool and adapter via AccessManager +/// 6. Call pool.setAssetLedger(ledger) — wires ledger for relayer fee credits +/// 7. Grant MINTER_ROLE and BURNER_ROLE on RYLA to RYLACreditLedger +/// +/// Required env vars: +/// PRIVATE_KEY — deployer private key +/// MARK_RYLA_TOKEN — deployed RYLA address +/// MARK_POOL_VERIFIER — deployed MARKPoolVerifier address +/// +/// Optional env vars: +/// MARK_POOL_OWNER — AccessManager admin (defaults to deployer) +/// MARK_POOL_INTENT_SIGNER — initial intent signer for MARKWithdrawAdapter +contract DeployMARKPool is Script { + bytes32 private constant DEFAULT_ADMIN_ROLE = 0x00; + uint64 private constant POOL_ADMIN_ROLE = 1; + + error MissingTokenAdminForRoleGrants(); + + struct Config { + uint256 deployerKey; + address deployer; + address tokenAddress; + address verifierAddress; + address owner; + address intentSigner; + address poseidonAddress; + } + + struct Deployed { + AccessManager accessManager; + MARKPool pool; + RYLACreditLedger ledger; + MARKWithdrawAdapter adapter; + } + + function run() external returns (Deployed memory d) { + Config memory cfg = _loadConfig(); + RYLA token = RYLA(cfg.tokenAddress); + + if (!token.hasRole(DEFAULT_ADMIN_ROLE, cfg.deployer)) revert MissingTokenAdminForRoleGrants(); + + vm.startBroadcast(cfg.deployerKey); + + // 1. AccessManager — admin is owner + d.accessManager = new AccessManager(cfg.owner); + + // 2. MARKPool — no ledger needed at construction + d.pool = new MARKPool(address(d.accessManager), cfg.verifierAddress, cfg.poseidonAddress); + + // 3. RYLACreditLedger — pool address now known + d.ledger = new RYLACreditLedger(cfg.tokenAddress, address(d.pool)); + + // 4. MARKWithdrawAdapter + d.adapter = new MARKWithdrawAdapter( + address(d.accessManager), + address(d.ledger), + address(d.pool) + ); + + // Wire adapter into ledger (one-time call — breaks circular deploy dependency) + d.ledger.setAdapter(address(d.adapter)); + + // 5. Grant POOL_ADMIN_ROLE to owner and deployer (deployer needs it for setup calls below) + d.accessManager.grantRole(POOL_ADMIN_ROLE, cfg.owner, 0); + if (cfg.deployer != cfg.owner) { + d.accessManager.grantRole(POOL_ADMIN_ROLE, cfg.deployer, 0); + } + + // 6. Assign restricted selectors on MARKPool to POOL_ADMIN_ROLE + bytes4[] memory poolSelectors = new bytes4[](14); + poolSelectors[0] = MARKPool.pause.selector; + poolSelectors[1] = MARKPool.unpause.selector; + poolSelectors[2] = MARKPool.pauseWithdrawals.selector; + poolSelectors[3] = MARKPool.unpauseWithdrawals.selector; + poolSelectors[4] = MARKPool.setVerifier.selector; + poolSelectors[5] = MARKPool.setProofTypeEnabled.selector; + poolSelectors[6] = MARKPool.emergencyDisableProofType.selector; + poolSelectors[7] = MARKPool.setMaxRootAge.selector; + poolSelectors[8] = MARKPool.setFeeBurnBps.selector; + poolSelectors[9] = MARKPool.setMinFee.selector; + poolSelectors[10] = MARKPool.setProtocolEpoch.selector; + poolSelectors[11] = MARKPool.setBridgeOutEntrypoint.selector; + poolSelectors[12] = MARKPool.bridgeIn.selector; + poolSelectors[13] = MARKPool.setAssetLedger.selector; + d.accessManager.setTargetFunctionRole(address(d.pool), poolSelectors, POOL_ADMIN_ROLE); + + // 7. Assign restricted selectors on MARKWithdrawAdapter to POOL_ADMIN_ROLE + bytes4[] memory adapterSelectors = new bytes4[](4); + adapterSelectors[0] = MARKWithdrawAdapter.pause.selector; + adapterSelectors[1] = MARKWithdrawAdapter.unpause.selector; + adapterSelectors[2] = MARKWithdrawAdapter.setMaxIntentValidity.selector; + adapterSelectors[3] = MARKWithdrawAdapter.setIntentSigner.selector; + d.accessManager.setTargetFunctionRole(address(d.adapter), adapterSelectors, POOL_ADMIN_ROLE); + + // 8. Wire ledger into pool (one-time call) + d.pool.setAssetLedger(address(d.ledger)); + + // 9. Set intent signer if provided + if (cfg.intentSigner != address(0)) { + d.adapter.setIntentSigner(cfg.intentSigner, true); + } + + // 10. Grant RYLA roles to ledger + token.setMinter(address(d.ledger), true); + token.setBurner(address(d.ledger), true); + + // 11. Revoke deployer's temporary admin role if deployer != owner + if (cfg.deployer != cfg.owner) { + d.accessManager.revokeRole(POOL_ADMIN_ROLE, cfg.deployer); + } + + vm.stopBroadcast(); + + console.log("AccessManager: ", address(d.accessManager)); + console.log("MARKPool: ", address(d.pool)); + console.log("RYLACreditLedger: ", address(d.ledger)); + console.log("MARKWithdrawAdapter:", address(d.adapter)); + } + + function _loadConfig() internal view returns (Config memory cfg) { + cfg.deployerKey = vm.envUint("PRIVATE_KEY"); + cfg.deployer = vm.addr(cfg.deployerKey); + cfg.tokenAddress = vm.envAddress("MARK_RYLA_TOKEN"); + cfg.verifierAddress = vm.envAddress("MARK_POOL_VERIFIER"); + cfg.owner = vm.envOr("MARK_POOL_OWNER", cfg.deployer); + cfg.intentSigner = vm.envOr("MARK_POOL_INTENT_SIGNER", address(0)); + // Default: Semaphore PoseidonT3 (same address on all EVM networks, BN254 compatible) + cfg.poseidonAddress = vm.envOr("MARK_POOL_POSEIDON", address(0xB43122Ecb241DD50062641f089876679fd06599a)); + } +} diff --git a/contracts/script/ops/pool/ReleasePool.s.sol b/contracts/script/ops/pool/ReleasePool.s.sol new file mode 100644 index 0000000..2eff3a2 --- /dev/null +++ b/contracts/script/ops/pool/ReleasePool.s.sol @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Script, console} from "forge-std/Script.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; +import {RYLA} from "../../../src/token/RYLA.sol"; +import {MARKPool} from "../../../src/pool/MARKPool.sol"; +import {MARKWithdrawAdapter} from "../../../src/withdraw/MARKWithdrawAdapter.sol"; +import {RYLACreditLedger} from "../../../src/pool/RYLACreditLedger.sol"; +import {DeployMARKPool} from "../../deploy/pool/DeployMARKPool.s.sol"; + +/// @notice Release orchestrator for the MARKPool stack. +/// @dev Sequence: preflight checks -> deploy -> verify -> artifact. +/// +/// Required env vars: +/// PRIVATE_KEY — deployer private key +/// MARK_RYLA_TOKEN — deployed RYLA address +/// MARK_POOL_VERIFIER — deployed MARKPoolVerifier address +/// +/// Optional env vars: +/// MARK_POOL_OWNER — AccessManager admin (defaults to deployer) +/// MARK_POOL_INTENT_SIGNER — initial intent signer for MARKWithdrawAdapter +/// MARK_POOL_RELEASE_EXECUTE — set true to broadcast (default: false = dry-run) +/// MARK_POOL_RELEASE_WRITE_ARTIFACT — set true to write JSON artifact +/// MARK_POOL_RELEASE_ARTIFACT_PATH — artifact output path +/// MARK_GIT_COMMIT — git commit hash for artifact +contract ReleasePool is Script { + bytes32 private constant DEFAULT_ADMIN_ROLE = 0x00; + + error PreflightFailed(string reason); + + struct ReleaseResult { + bool execute; + address deployer; + address token; + address accessManager; + address pool; + address ledger; + address adapter; + } + + function run() external { + bool execute = vm.envOr("MARK_POOL_RELEASE_EXECUTE", false); + bool writeArtifact = vm.envOr("MARK_POOL_RELEASE_WRITE_ARTIFACT", false); + + uint256 deployerKey = vm.envUint("PRIVATE_KEY"); + address deployer = vm.addr(deployerKey); + address tokenAddress = vm.envAddress("MARK_RYLA_TOKEN"); + address verifierAddress = vm.envAddress("MARK_POOL_VERIFIER"); + + // Preflight checks + _preflight(deployer, tokenAddress, verifierAddress); + + if (!execute) { + console.log("MARK_POOL_RELEASE_EXECUTE=false. Dry-run complete (no transactions broadcast)."); + if (writeArtifact) { + _writeArtifact(ReleaseResult({ + execute: false, + deployer: deployer, + token: tokenAddress, + accessManager: address(0), + pool: address(0), + ledger: address(0), + adapter: address(0) + })); + } + return; + } + + DeployMARKPool deployPool = new DeployMARKPool(); + DeployMARKPool.Deployed memory d = deployPool.run(); + + // Post-deploy verification + _verify(tokenAddress, d); + + ReleaseResult memory result = ReleaseResult({ + execute: true, + deployer: deployer, + token: tokenAddress, + accessManager: address(d.accessManager), + pool: address(d.pool), + ledger: address(d.ledger), + adapter: address(d.adapter) + }); + + if (writeArtifact) { + _writeArtifact(result); + } else { + console.log("Artifact write disabled (MARK_POOL_RELEASE_WRITE_ARTIFACT=false)."); + } + + console.log("Pool release complete."); + console.log(" AccessManager:", address(d.accessManager)); + console.log(" MARKPool: ", address(d.pool)); + console.log(" RYLACreditLedger:", address(d.ledger)); + console.log(" MARKWithdrawAdapter:", address(d.adapter)); + } + + function _preflight(address deployer, address tokenAddress, address verifierAddress) internal view { + if (tokenAddress == address(0)) revert PreflightFailed("MARK_RYLA_TOKEN not set"); + if (verifierAddress == address(0)) revert PreflightFailed("MARK_POOL_VERIFIER not set"); + if (tokenAddress.code.length == 0) revert PreflightFailed("MARK_RYLA_TOKEN is not a contract"); + if (verifierAddress.code.length == 0) revert PreflightFailed("MARK_POOL_VERIFIER is not a contract"); + + RYLA token = RYLA(tokenAddress); + if (!token.hasRole(DEFAULT_ADMIN_ROLE, deployer)) { + revert PreflightFailed("deployer does not have DEFAULT_ADMIN_ROLE on RYLA"); + } + } + + function _verify(address tokenAddress, DeployMARKPool.Deployed memory d) internal view { + // Pool is wired to the correct ledger + require(address(d.pool.ASSET_LEDGER()) == address(d.ledger), "pool ASSET_LEDGER mismatch"); + + // Ledger is wired to pool and adapter + require(d.ledger.POOL() == address(d.pool), "ledger POOL mismatch"); + require(d.ledger.ADAPTER() == address(d.adapter), "ledger ADAPTER mismatch"); + + // Adapter is wired to ledger and pool + require(address(d.adapter.ASSET_LEDGER()) == address(d.ledger), "adapter ASSET_LEDGER mismatch"); + require(address(d.adapter.PROOF_POOL()) == address(d.pool), "adapter PROOF_POOL mismatch"); + + // RYLA roles granted to ledger + RYLA token = RYLA(tokenAddress); + bytes32 minterRole = token.MINTER_ROLE(); + bytes32 burnerRole = token.BURNER_ROLE(); + require(token.hasRole(minterRole, address(d.ledger)), "ledger missing MINTER_ROLE"); + require(token.hasRole(burnerRole, address(d.ledger)), "ledger missing BURNER_ROLE"); + + console.log("Post-deploy verification passed."); + } + + function _writeArtifact(ReleaseResult memory result) internal { + string memory path = vm.envOr( + "MARK_POOL_RELEASE_ARTIFACT_PATH", + string("broadcast/mark-pool-release-latest.json") + ); + string memory root = "pool-release"; + _ensureParentDir(path); + + vm.serializeString(root, "protocol", "MARK"); + vm.serializeString(root, "component", "pool"); + vm.serializeBool(root, "execute", result.execute); + vm.serializeAddress(root, "deployer", result.deployer); + vm.serializeAddress(root, "token", result.token); + vm.serializeAddress(root, "accessManager", result.accessManager); + vm.serializeAddress(root, "pool", result.pool); + vm.serializeAddress(root, "ledger", result.ledger); + vm.serializeAddress(root, "adapter", result.adapter); + vm.serializeUint(root, "chainId", block.chainid); + vm.serializeUint(root, "timestamp", block.timestamp); + string memory json = vm.serializeString(root, "gitCommit", vm.envOr("MARK_GIT_COMMIT", string("unknown"))); + vm.writeJson(json, path); + + console.log("Pool release artifact written:", path); + } + + function _ensureParentDir(string memory path) internal { + bytes memory raw = bytes(path); + uint256 split = type(uint256).max; + for (uint256 i = raw.length; i > 0; i--) { + if (raw[i - 1] == "/") { split = i - 1; break; } + } + if (split == type(uint256).max || split == 0) return; + bytes memory parent = new bytes(split); + for (uint256 j = 0; j < split; j++) { parent[j] = raw[j]; } + vm.createDir(string(parent), true); + } +} diff --git a/contracts/src/crypto/MerkleTree.sol b/contracts/src/crypto/MerkleTree.sol new file mode 100644 index 0000000..3c5c182 --- /dev/null +++ b/contracts/src/crypto/MerkleTree.sol @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {IPoseidonT3} from "../interfaces/IPoseidonT3.sol"; +import {PoolErrors} from "../pool/errors/PoolErrors.sol"; + +library MerkleTree { + uint256 internal constant FIELD_SIZE = + 21888242871839275222246405745257275088548364400416034343698204186575808495617; + + struct Tree { + uint256 depth; + uint256 nextLeafIndex; + bytes32 root; + address poseidon; + mapping(uint256 => bytes32) filledSubtrees; + mapping(uint256 => bytes32) zeros; + } + + function init(Tree storage tree, uint256 depth, address poseidon) internal { + if (tree.depth != 0) revert PoolErrors.TreeAlreadyInitialized(); + if (depth == 0 || depth > 32) revert PoolErrors.InvalidRoot(); + + tree.depth = depth; + tree.poseidon = poseidon; + + bytes32 current = bytes32(0); + for (uint256 i = 0; i < depth; i++) { + tree.zeros[i] = current; + tree.filledSubtrees[i] = current; + current = _hash(poseidon, current, current); + } + tree.root = current; + } + + function insert(Tree storage tree, bytes32 leaf) internal { + if (tree.depth == 0) revert PoolErrors.TreeNotInitialized(); + if (uint256(leaf) >= FIELD_SIZE) revert PoolErrors.LeafOutOfField(); + + uint256 maxLeaves = uint256(1) << tree.depth; + if (tree.nextLeafIndex >= maxLeaves) revert PoolErrors.TreeFull(); + + uint256 index = tree.nextLeafIndex; + tree.nextLeafIndex++; + + bytes32 current = leaf; + uint256 idx = index; + address poseidon = tree.poseidon; + + for (uint256 i = 0; i < tree.depth; i++) { + if (idx % 2 == 0) { + tree.filledSubtrees[i] = current; + current = _hash(poseidon, current, tree.zeros[i]); + } else { + current = _hash(poseidon, tree.filledSubtrees[i], current); + } + idx >>= 1; + } + + tree.root = current; + } + + function getRoot(Tree storage tree) internal view returns (bytes32) { + return tree.root; + } + + function _hash(address poseidon, bytes32 left, bytes32 right) private view returns (bytes32) { + uint256[2] memory inputs = [uint256(left), uint256(right)]; + return bytes32(IPoseidonT3(poseidon).hash(inputs)); + } +} diff --git a/contracts/src/crypto/ProofUtils.sol b/contracts/src/crypto/ProofUtils.sol new file mode 100644 index 0000000..c2c1a63 --- /dev/null +++ b/contracts/src/crypto/ProofUtils.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +library ProofUtils { + /** + * @dev Converts snarkjs proof format to Solidity verifier format + * Fixes G2 point coordinate ordering incompatibility + */ + function convertProof(uint256[2][2] memory bSnarkjs) + internal + pure + returns (uint256[2][2] memory) + { + // Fix G2 point coordinate ordering + uint256[2][2] memory bFixed = [ + [bSnarkjs[0][1], bSnarkjs[0][0]], // Swap coordinates + [bSnarkjs[1][1], bSnarkjs[1][0]] // Swap coordinates + ]; + + return bFixed; + } +} diff --git a/contracts/src/crypto/generated/PoseidonT3.sol b/contracts/src/crypto/generated/PoseidonT3.sol new file mode 100644 index 0000000..81c3574 --- /dev/null +++ b/contracts/src/crypto/generated/PoseidonT3.sol @@ -0,0 +1,1572 @@ +/// SPDX-License-Identifier: MIT +pragma solidity ^0.8.24; + +library PoseidonT3 { + uint256 constant M00 = + 0x109b7f411ba0e4c9b2b70caf5c36a7b194be7c11ad24378bfedb68592ba8118b; + uint256 constant M01 = + 0x2969f27eed31a480b9c36c764379dbca2cc8fdd1415c3dded62940bcde0bd771; + uint256 constant M02 = + 0x143021ec686a3f330d5f9e654638065ce6cd79e28c5b3753326244ee65a1b1a7; + uint256 constant M10 = + 0x16ed41e13bb9c0c66ae119424fddbcbc9314dc9fdbdeea55d6c64543dc4903e0; + uint256 constant M11 = + 0x2e2419f9ec02ec394c9871c832963dc1b89d743c8c7b964029b2311687b1fe23; + uint256 constant M12 = + 0x176cc029695ad02582a70eff08a6fd99d057e12e58e7d7b6b16cdfabc8ee2911; + + // See here for a simplified implementation: https://github.com/vimwitch/poseidon-solidity/blob/e57becdabb65d99fdc586fe1e1e09e7108202d53/contracts/Poseidon.sol#L40 + // Inspired by: https://github.com/iden3/circomlibjs/blob/v0.0.8/src/poseidon_slow.js + function hash(uint256[2] memory) public pure returns (uint256) { + assembly { + let F := + 21888242871839275222246405745257275088548364400416034343698204186575808495617 + let M20 := + 0x2b90bba00fca0589f617e7dcbfe82e0df706ab640ceb247b791a93b74e36736d + let M21 := + 0x101071f0032379b697315876690f053d148d4e109f5fb065c8aacc55a0f89bfa + let M22 := + 0x19a3fc0a56702bf417ba7fee3802593fa644470307043f7773279cd71d25d5e0 + + // load the inputs from memory + let state1 := + add( + mod(mload(0x80), F), + 0x00f1445235f2148c5986587169fc1bcd887b08d4d00868df5696fff40956e864 + ) + let state2 := + add( + mod(mload(0xa0), F), + 0x08dff3487e8ac99e1f29a058d0fa80b930c728730b7ab36ce879f3890ecf73f5 + ) + let scratch0 := mulmod(state1, state1, F) + state1 := mulmod(mulmod(scratch0, scratch0, F), state1, F) + scratch0 := mulmod(state2, state2, F) + state2 := mulmod(mulmod(scratch0, scratch0, F), state2, F) + scratch0 := add( + 0x2f27be690fdaee46c3ce28f7532b13c856c35342c84bda6e20966310fadc01d0, + add( + add( + 15452833169820924772166449970675545095234312153403844297388521437673434406763, + mulmod(state1, M10, F) + ), + mulmod(state2, M20, F) + ) + ) + let scratch1 := + add( + 0x2b2ae1acf68b7b8d2416bebf3d4f6234b763fe04b8043ee48b8327bebca16cf2, + add( + add( + 18674271267752038776579386132900109523609358935013267566297499497165104279117, + mulmod(state1, M11, F) + ), + mulmod(state2, M21, F) + ) + ) + let scratch2 := + add( + 0x0319d062072bef7ecca5eac06f97d4d55952c175ab6b03eae64b44c7dbf11cfa, + add( + add( + 14817777843080276494683266178512808687156649753153012854386334860566696099579, + mulmod(state1, M12, F) + ), + mulmod(state2, M22, F) + ) + ) + let state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := mulmod(scratch1, scratch1, F) + scratch1 := mulmod(mulmod(state0, state0, F), scratch1, F) + state0 := mulmod(scratch2, scratch2, F) + scratch2 := mulmod(mulmod(state0, state0, F), scratch2, F) + state0 := add( + 0x28813dcaebaeaa828a376df87af4a63bc8b7bf27ad49c6298ef7b387bf28526d, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x2727673b2ccbc903f181bf38e1c1d40d2033865200c352bc150928adddf9cb78, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x234ec45ca27727c2e74abd2b2a1494cd6efbd43e340587d6b8fb9e31e65cc632, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := mulmod(state1, state1, F) + state1 := mulmod(mulmod(scratch0, scratch0, F), state1, F) + scratch0 := mulmod(state2, state2, F) + state2 := mulmod(mulmod(scratch0, scratch0, F), state2, F) + scratch0 := add( + 0x15b52534031ae18f7f862cb2cf7cf760ab10a8150a337b1ccd99ff6e8797d428, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0dc8fad6d9e4b35f5ed9a3d186b79ce38e0e8a8d1b58b132d701d4eecf68d1f6, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x1bcd95ffc211fbca600f705fad3fb567ea4eb378f62e1fec97805518a47e4d9c, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := mulmod(scratch1, scratch1, F) + scratch1 := mulmod(mulmod(state0, state0, F), scratch1, F) + state0 := mulmod(scratch2, scratch2, F) + scratch2 := mulmod(mulmod(state0, state0, F), scratch2, F) + state0 := add( + 0x10520b0ab721cadfe9eff81b016fc34dc76da36c2578937817cb978d069de559, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1f6d48149b8e7f7d9b257d8ed5fbbaf42932498075fed0ace88a9eb81f5627f6, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1d9655f652309014d29e00ef35a2089bfff8dc1c816f0dc9ca34bdb5460c8705, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x04df5a56ff95bcafb051f7b1cd43a99ba731ff67e47032058fe3d4185697cc7d, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0672d995f8fff640151b3d290cedaf148690a10a8c8424a7f6ec282b6e4be828, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x099952b414884454b21200d7ffafdd5f0c9a9dcc06f2708e9fc1d8209b5c75b9, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x052cba2255dfd00c7c483143ba8d469448e43586a9b4cd9183fd0e843a6b9fa6, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0b8badee690adb8eb0bd74712b7999af82de55707251ad7716077cb93c464ddc, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x119b1590f13307af5a1ee651020c07c749c15d60683a8050b963d0a8e4b2bdd1, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x03150b7cd6d5d17b2529d36be0f67b832c4acfc884ef4ee5ce15be0bfb4a8d09, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2cc6182c5e14546e3cf1951f173912355374efb83d80898abe69cb317c9ea565, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x005032551e6378c450cfe129a404b3764218cadedac14e2b92d2cd73111bf0f9, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x233237e3289baa34bb147e972ebcb9516469c399fcc069fb88f9da2cc28276b5, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x05c8f4f4ebd4a6e3c980d31674bfbe6323037f21b34ae5a4e80c2d4c24d60280, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x0a7b1db13042d396ba05d818a319f25252bcf35ef3aeed91ee1f09b2590fc65b, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2a73b71f9b210cf5b14296572c9d32dbf156e2b086ff47dc5df542365a404ec0, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1ac9b0417abcc9a1935107e9ffc91dc3ec18f2c4dbe7f22976a760bb5c50c460, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x12c0339ae08374823fabb076707ef479269f3e4d6cb104349015ee046dc93fc0, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x0b7475b102a165ad7f5b18db4e1e704f52900aa3253baac68246682e56e9a28e, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x037c2849e191ca3edb1c5e49f6e8b8917c843e379366f2ea32ab3aa88d7f8448, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x05a6811f8556f014e92674661e217e9bd5206c5c93a07dc145fdb176a716346f, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x29a795e7d98028946e947b75d54e9f044076e87a7b2883b47b675ef5f38bd66e, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x20439a0c84b322eb45a3857afc18f5826e8c7382c8a1585c507be199981fd22f, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2e0ba8d94d9ecf4a94ec2050c7371ff1bb50f27799a84b6d4a2a6f2a0982c887, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x143fd115ce08fb27ca38eb7cce822b4517822cd2109048d2e6d0ddcca17d71c8, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0c64cbecb1c734b857968dbbdcf813cdf8611659323dbcbfc84323623be9caf1, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x028a305847c683f646fca925c163ff5ae74f348d62c2b670f1426cef9403da53, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2e4ef510ff0b6fda5fa940ab4c4380f26a6bcb64d89427b824d6755b5db9e30c, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0081c95bc43384e663d79270c956ce3b8925b4f6d033b078b96384f50579400e, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2ed5f0c91cbd9749187e2fade687e05ee2491b349c039a0bba8a9f4023a0bb38, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x30509991f88da3504bbf374ed5aae2f03448a22c76234c8c990f01f33a735206, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1c3f20fd55409a53221b7c4d49a356b9f0a1119fb2067b41a7529094424ec6ad, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x10b4e7f3ab5df003049514459b6e18eec46bb2213e8e131e170887b47ddcb96c, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2a1982979c3ff7f43ddd543d891c2abddd80f804c077d775039aa3502e43adef, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1c74ee64f15e1db6feddbead56d6d55dba431ebc396c9af95cad0f1315bd5c91, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x07533ec850ba7f98eab9303cace01b4b9e4f2e8b82708cfa9c2fe45a0ae146a0, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x21576b438e500449a151e4eeaf17b154285c68f42d42c1808a11abf3764c0750, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x2f17c0559b8fe79608ad5ca193d62f10bce8384c815f0906743d6930836d4a9e, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x2d477e3862d07708a79e8aae946170bc9775a4201318474ae665b0b1b7e2730e, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x162f5243967064c390e095577984f291afba2266c38f5abcd89be0f5b2747eab, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2b4cb233ede9ba48264ecd2c8ae50d1ad7a8596a87f29f8a7777a70092393311, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2c8fbcb2dd8573dc1dbaf8f4622854776db2eece6d85c4cf4254e7c35e03b07a, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x1d6f347725e4816af2ff453f0cd56b199e1b61e9f601e9ade5e88db870949da9, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x204b0c397f4ebe71ebc2d8b3df5b913df9e6ac02b68d31324cd49af5c4565529, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x0c4cb9dc3c4fd8174f1149b3c63c3c2f9ecb827cd7dc25534ff8fb75bc79c502, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x174ad61a1448c899a25416474f4930301e5c49475279e0639a616ddc45bc7b54, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1a96177bcf4d8d89f759df4ec2f3cde2eaaa28c177cc0fa13a9816d49a38d2ef, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x066d04b24331d71cd0ef8054bc60c4ff05202c126a233c1a8242ace360b8a30a, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x2a4c4fc6ec0b0cf52195782871c6dd3b381cc65f72e02ad527037a62aa1bd804, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x13ab2d136ccf37d447e9f2e14a7cedc95e727f8446f6d9d7e55afc01219fd649, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1121552fca26061619d24d843dc82769c1b04fcec26f55194c2e3e869acc6a9a, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x00ef653322b13d6c889bc81715c37d77a6cd267d595c4a8909a5546c7c97cff1, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0e25483e45a665208b261d8ba74051e6400c776d652595d9845aca35d8a397d3, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x29f536dcb9dd7682245264659e15d88e395ac3d4dde92d8c46448db979eeba89, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x2a56ef9f2c53febadfda33575dbdbd885a124e2780bbea170e456baace0fa5be, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1c8361c78eb5cf5decfb7a2d17b5c409f2ae2999a46762e8ee416240a8cb9af1, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x151aff5f38b20a0fc0473089aaf0206b83e8e68a764507bfd3d0ab4be74319c5, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x04c6187e41ed881dc1b239c88f7f9d43a9f52fc8c8b6cdd1e76e47615b51f100, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x13b37bd80f4d27fb10d84331f6fb6d534b81c61ed15776449e801b7ddc9c2967, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x01a5c536273c2d9df578bfbd32c17b7a2ce3664c2a52032c9321ceb1c4e8a8e4, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x2ab3561834ca73835ad05f5d7acb950b4a9a2c666b9726da832239065b7c3b02, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1d4d8ec291e720db200fe6d686c0d613acaf6af4e95d3bf69f7ed516a597b646, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x041294d2cc484d228f5784fe7919fd2bb925351240a04b711514c9c80b65af1d, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x154ac98e01708c611c4fa715991f004898f57939d126e392042971dd90e81fc6, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0b339d8acca7d4f83eedd84093aef51050b3684c88f8b0b04524563bc6ea4da4, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x0955e49e6610c94254a4f84cfbab344598f0e71eaff4a7dd81ed95b50839c82e, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x06746a6156eba54426b9e22206f15abca9a6f41e6f535c6f3525401ea0654626, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0f18f5a0ecd1423c496f3820c549c27838e5790e2bd0a196ac917c7ff32077fb, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x04f6eeca1751f7308ac59eff5beb261e4bb563583ede7bc92a738223d6f76e13, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2b56973364c4c4f5c1a3ec4da3cdce038811eb116fb3e45bc1768d26fc0b3758, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x123769dd49d5b054dcd76b89804b1bcb8e1392b385716a5d83feb65d437f29ef, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2147b424fc48c80a88ee52b91169aacea989f6446471150994257b2fb01c63e9, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x0fdc1f58548b85701a6c5505ea332a29647e6f34ad4243c2ea54ad897cebe54d, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x12373a8251fea004df68abcf0f7786d4bceff28c5dbbe0c3944f685cc0a0b1f2, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x21e4f4ea5f35f85bad7ea52ff742c9e8a642756b6af44203dd8a1f35c1a90035, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x16243916d69d2ca3dfb4722224d4c462b57366492f45e90d8a81934f1bc3b147, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1efbe46dd7a578b4f66f9adbc88b4378abc21566e1a0453ca13a4159cac04ac2, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x07ea5e8537cf5dd08886020e23a7f387d468d5525be66f853b672cc96a88969a, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x05a8c4f9968b8aa3b7b478a30f9a5b63650f19a75e7ce11ca9fe16c0b76c00bc, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x20f057712cc21654fbfe59bd345e8dac3f7818c701b9c7882d9d57b72a32e83f, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x04a12ededa9dfd689672f8c67fee31636dcd8e88d01d49019bd90b33eb33db69, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x27e88d8c15f37dcee44f1e5425a51decbd136ce5091a6767e49ec9544ccd101a, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2feed17b84285ed9b8a5c8c5e95a41f66e096619a7703223176c41ee433de4d1, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x1ed7cc76edf45c7c404241420f729cf394e5942911312a0d6972b8bd53aff2b8, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x15742e99b9bfa323157ff8c586f5660eac6783476144cdcadf2874be45466b1a, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1aac285387f65e82c895fc6887ddf40577107454c6ec0317284f033f27d0c785, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x25851c3c845d4790f9ddadbdb6057357832e2e7a49775f71ec75a96554d67c77, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x15a5821565cc2ec2ce78457db197edf353b7ebba2c5523370ddccc3d9f146a67, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2411d57a4813b9980efa7e31a1db5966dcf64f36044277502f15485f28c71727, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x002e6f8d6520cd4713e335b8c0b6d2e647e9a98e12f4cd2558828b5ef6cb4c9b, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x2ff7bc8f4380cde997da00b616b0fcd1af8f0e91e2fe1ed7398834609e0315d2, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x00b9831b948525595ee02724471bcd182e9521f6b7bb68f1e93be4febb0d3cbe, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x0a2f53768b8ebf6a86913b0e57c04e011ca408648a4743a87d77adbf0c9c3512, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x00248156142fd0373a479f91ff239e960f599ff7e94be69b7f2a290305e1198d, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x171d5620b87bfb1328cf8c02ab3f0c9a397196aa6a542c2350eb512a2b2bcda9, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x170a4f55536f7dc970087c7c10d6fad760c952172dd54dd99d1045e4ec34a808, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x29aba33f799fe66c2ef3134aea04336ecc37e38c1cd211ba482eca17e2dbfae1, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1e9bc179a4fdd758fdd1bb1945088d47e70d114a03f6a0e8b5ba650369e64973, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1dd269799b660fad58f7f4892dfb0b5afeaad869a9c4b44f9c9e1c43bdaf8f09, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x22cdbc8b70117ad1401181d02e15459e7ccd426fe869c7c95d1dd2cb0f24af38, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x0ef042e454771c533a9f57a55c503fcefd3150f52ed94a7cd5ba93b9c7dacefd, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x11609e06ad6c8fe2f287f3036037e8851318e8b08a0359a03b304ffca62e8284, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x1166d9e554616dba9e753eea427c17b7fecd58c076dfe42708b08f5b783aa9af, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x2de52989431a859593413026354413db177fbf4cd2ac0b56f855a888357ee466, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x3006eb4ffc7a85819a6da492f3a8ac1df51aee5b17b8e89d74bf01cf5f71e9ad, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2af41fbb61ba8a80fdcf6fff9e3f6f422993fe8f0a4639f962344c8225145086, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x119e684de476155fe5a6b41a8ebc85db8718ab27889e85e781b214bace4827c3, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x1835b786e2e8925e188bea59ae363537b51248c23828f047cff784b97b3fd800, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x28201a34c594dfa34d794996c6433a20d152bac2a7905c926c40e285ab32eeb6, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x083efd7a27d1751094e80fefaf78b000864c82eb571187724a761f88c22cc4e7, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x0b6f88a3577199526158e61ceea27be811c16df7774dd8519e079564f61fd13b, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x0ec868e6d15e51d9644f66e1d6471a94589511ca00d29e1014390e6ee4254f5b, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2af33e3f866771271ac0c9b3ed2e1142ecd3e74b939cd40d00d937ab84c98591, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x0b520211f904b5e7d09b5d961c6ace7734568c547dd6858b364ce5e47951f178, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x0b2d722d0919a1aad8db58f10062a92ea0c56ac4270e822cca228620188a1d40, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x1f790d4d7f8cf094d980ceb37c2453e957b54a9991ca38bbe0061d1ed6e562d4, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x0171eb95dfbf7d1eaea97cd385f780150885c16235a2a6a8da92ceb01e504233, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x0c2d0e3b5fd57549329bf6885da66b9b790b40defd2c8650762305381b168873, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1162fb28689c27154e5a8228b4e72b377cbcafa589e283c35d3803054407a18d, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2f1459b65dee441b64ad386a91e8310f282c5a92a89e19921623ef8249711bc0, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x1e6ff3216b688c3d996d74367d5cd4c1bc489d46754eb712c243f70d1b53cfbb, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x01ca8be73832b8d0681487d27d157802d741a6f36cdc2a0576881f9326478875, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1f7735706ffe9fc586f976d5bdf223dc680286080b10cea00b9b5de315f9650e, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2522b60f4ea3307640a0c2dce041fba921ac10a3d5f096ef4745ca838285f019, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x23f0bee001b1029d5255075ddc957f833418cad4f52b6c3f8ce16c235572575b, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2bc1ae8b8ddbb81fcaac2d44555ed5685d142633e9df905f66d9401093082d59, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x0f9406b8296564a37304507b8dba3ed162371273a07b1fc98011fcd6ad72205f, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x2360a8eb0cc7defa67b72998de90714e17e75b174a52ee4acb126c8cd995f0a8, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x15871a5cddead976804c803cbaef255eb4815a5e96df8b006dcbbc2767f88948, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x193a56766998ee9e0a8652dd2f3b1da0362f4f54f72379544f957ccdeefb420f, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x2a394a43934f86982f9be56ff4fab1703b2e63c8ad334834e4309805e777ae0f, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x1859954cfeb8695f3e8b635dcb345192892cd11223443ba7b4166e8876c0d142, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x04e1181763050e58013444dbcb99f1902b11bc25d90bbdca408d3819f4fed32b, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0fdb253dee83869d40c335ea64de8c5bb10eb82db08b5e8b1f5e5552bfd05f23, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x058cbe8a9a5027bdaa4efb623adead6275f08686f1c08984a9d7c5bae9b4f1c0, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x1382edce9971e186497eadb1aeb1f52b23b4b83bef023ab0d15228b4cceca59a, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x03464990f045c6ee0819ca51fd11b0be7f61b8eb99f14b77e1e6634601d9e8b5, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x23f7bfc8720dc296fff33b41f98ff83c6fcab4605db2eb5aaa5bc137aeb70a58, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x0a59a158e3eec2117e6e94e7f0e9decf18c3ffd5e1531a9219636158bbaf62f2, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x06ec54c80381c052b58bf23b312ffd3ce2c4eba065420af8f4c23ed0075fd07b, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x118872dc832e0eb5476b56648e867ec8b09340f7a7bcb1b4962f0ff9ed1f9d01, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x13d69fa127d834165ad5c7cba7ad59ed52e0b0f0e42d7fea95e1906b520921b1, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x169a177f63ea681270b1c6877a73d21bde143942fb71dc55fd8a49f19f10c77b, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x04ef51591c6ead97ef42f287adce40d93abeb032b922f66ffb7e9a5a7450544d, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x256e175a1dc079390ecd7ca703fb2e3b19ec61805d4f03ced5f45ee6dd0f69ec, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x30102d28636abd5fe5f2af412ff6004f75cc360d3205dd2da002813d3e2ceeb2, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x10998e42dfcd3bbf1c0714bc73eb1bf40443a3fa99bef4a31fd31be182fcc792, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x193edd8e9fcf3d7625fa7d24b598a1d89f3362eaf4d582efecad76f879e36860, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x18168afd34f2d915d0368ce80b7b3347d1c7a561ce611425f2664d7aa51f0b5d, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x29383c01ebd3b6ab0c017656ebe658b6a328ec77bc33626e29e2e95b33ea6111, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x10646d2f2603de39a1f4ae5e7771a64a702db6e86fb76ab600bf573f9010c711, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0beb5e07d1b27145f575f1395a55bf132f90c25b40da7b3864d0242dcb1117fb, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x16d685252078c133dc0d3ecad62b5c8830f95bb2e54b59abdffbf018d96fa336, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x0a6abd1d833938f33c74154e0404b4b40a555bbbec21ddfafd672dd62047f01a, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1a679f5d36eb7b5c8ea12a4c2dedc8feb12dffeec450317270a6f19b34cf1860, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x0980fb233bd456c23974d50e0ebfde4726a423eada4e8f6ffbc7592e3f1b93d6, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x161b42232e61b84cbf1810af93a38fc0cece3d5628c9282003ebacb5c312c72b, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0ada10a90c7f0520950f7d47a60d5e6a493f09787f1564e5d09203db47de1a0b, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1a730d372310ba82320345a29ac4238ed3f07a8a2b4e121bb50ddb9af407f451, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x2c8120f268ef054f817064c369dda7ea908377feaba5c4dffbda10ef58e8c556, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1c7c8824f758753fa57c00789c684217b930e95313bcb73e6e7b8649a4968f70, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x2cd9ed31f5f8691c8e39e4077a74faa0f400ad8b491eb3f7b47b27fa3fd1cf77, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x23ff4f9d46813457cf60d92f57618399a5e022ac321ca550854ae23918a22eea, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x09945a5d147a4f66ceece6405dddd9d0af5a2c5103529407dff1ea58f180426d, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x188d9c528025d4c2b67660c6b771b90f7c7da6eaa29d3f268a6dd223ec6fc630, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x3050e37996596b7f81f68311431d8734dba7d926d3633595e0c0d8ddf4f0f47f, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x15af1169396830a91600ca8102c35c426ceae5461e3f95d89d829518d30afd78, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x1da6d09885432ea9a06d9f37f873d985dae933e351466b2904284da3320d8acc, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := add( + 0x2796ea90d269af29f5f8acf33921124e4e4fad3dbe658945e546ee411ddaa9cb, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x202d7dd1da0f6b4b0325c8b3307742f01e15612ec8e9304a7cb0319e01d32d60, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x096d6790d05bb759156a952ba263d672a2d7f9c788f4c831a29dace4c0f8be5f, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := add( + 0x054efa1f65b0fce283808965275d877b438da23ce5b13e1963798cb1447d25a4, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x1b162f83d917e93edb3308c29802deb9d8aa690113b2e14864ccf6e18e4165f1, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x21e5241e12564dd6fd9f1cdd2a0de39eedfefc1466cc568ec5ceb745a0506edc, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := mulmod(scratch1, scratch1, F) + scratch1 := mulmod(mulmod(state0, state0, F), scratch1, F) + state0 := mulmod(scratch2, scratch2, F) + scratch2 := mulmod(mulmod(state0, state0, F), scratch2, F) + state0 := add( + 0x1cfb5662e8cf5ac9226a80ee17b36abecb73ab5f87e161927b4349e10e4bdf08, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x0f21177e302a771bbae6d8d1ecb373b62c99af346220ac0129c53f666eb24100, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1671522374606992affb0dd7f71b12bec4236aede6290546bcef7e1f515c2320, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := mulmod(state1, state1, F) + state1 := mulmod(mulmod(scratch0, scratch0, F), state1, F) + scratch0 := mulmod(state2, state2, F) + state2 := mulmod(mulmod(scratch0, scratch0, F), state2, F) + scratch0 := add( + 0x0fa3ec5b9488259c2eb4cf24501bfad9be2ec9e42c5cc8ccd419d2a692cad870, + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ) + ) + scratch1 := add( + 0x193c0e04e0bd298357cb266c1506080ed36edce85c648cc085e8c57b1ab54bba, + add( + add(mulmod(state0, M01, F), mulmod(state1, M11, F)), + mulmod(state2, M21, F) + ) + ) + scratch2 := add( + 0x102adf8ef74735a27e9128306dcbc3c99f6f7291cd406578ce14ea2adaba68f8, + add( + add(mulmod(state0, M02, F), mulmod(state1, M12, F)), + mulmod(state2, M22, F) + ) + ) + state0 := mulmod(scratch0, scratch0, F) + scratch0 := mulmod(mulmod(state0, state0, F), scratch0, F) + state0 := mulmod(scratch1, scratch1, F) + scratch1 := mulmod(mulmod(state0, state0, F), scratch1, F) + state0 := mulmod(scratch2, scratch2, F) + scratch2 := mulmod(mulmod(state0, state0, F), scratch2, F) + state0 := add( + 0x0fe0af7858e49859e2a54d6f1ad945b1316aa24bfbdd23ae40a6d0cb70c3eab1, + add( + add(mulmod(scratch0, M00, F), mulmod(scratch1, M10, F)), + mulmod(scratch2, M20, F) + ) + ) + state1 := add( + 0x216f6717bbc7dedb08536a2220843f4e2da5f1daa9ebdefde8a5ea7344798d22, + add( + add(mulmod(scratch0, M01, F), mulmod(scratch1, M11, F)), + mulmod(scratch2, M21, F) + ) + ) + state2 := add( + 0x1da55cc900f0d21f4a3e694391918a1b3c23b2ac773c6b3ef88e2e4228325161, + add( + add(mulmod(scratch0, M02, F), mulmod(scratch1, M12, F)), + mulmod(scratch2, M22, F) + ) + ) + scratch0 := mulmod(state0, state0, F) + state0 := mulmod(mulmod(scratch0, scratch0, F), state0, F) + scratch0 := mulmod(state1, state1, F) + state1 := mulmod(mulmod(scratch0, scratch0, F), state1, F) + scratch0 := mulmod(state2, state2, F) + state2 := mulmod(mulmod(scratch0, scratch0, F), state2, F) + + mstore( + 0x0, + mod( + add( + add(mulmod(state0, M00, F), mulmod(state1, M10, F)), + mulmod(state2, M20, F) + ), + F + ) + ) + + return(0, 0x20) + } + } +} diff --git a/contracts/src/interfaces/ICreditLedger.sol b/contracts/src/interfaces/ICreditLedger.sol new file mode 100644 index 0000000..832987b --- /dev/null +++ b/contracts/src/interfaces/ICreditLedger.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +interface ICreditLedger { + function credit(address to, uint256 amount) external; + function debit(address from, uint256 amount) external; + function creditBalanceOf(address account) external view returns (uint256); + function totalCreditsMinted() external view returns (uint256); + function totalCreditsBurned() external view returns (uint256); + function totalCreditsOutstanding() external view returns (uint256); + function maxCredits() external view returns (uint256); +} diff --git a/contracts/src/interfaces/IPoolBridge.sol b/contracts/src/interfaces/IPoolBridge.sol new file mode 100644 index 0000000..fcddc4f --- /dev/null +++ b/contracts/src/interfaces/IPoolBridge.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Minimal Pool surface required by BridgeAdapter. +interface IPoolBridge { + function bridgeOut( + bytes32 merkleRoot, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments, + uint256 fee, + address relayer, + uint256 dstChainId, + uint256[2] calldata a, + uint256[2][2] calldata bSnarkjs, + uint256[2] calldata c + ) external; + + function bridgeIn(uint256 srcChainId, bytes32[2] calldata outCommitments) + external; +} diff --git a/contracts/src/interfaces/IPoolNullifier.sol b/contracts/src/interfaces/IPoolNullifier.sol new file mode 100644 index 0000000..7c5df6e --- /dev/null +++ b/contracts/src/interfaces/IPoolNullifier.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Minimal Pool surface required by WithdrawAdapter. +interface IPoolNullifier { + function isNullifierUsedGlobal(bytes32 nullifier) + external + view + returns (bool); + + function nullifierWithdrawBinding(bytes32 nullifier) + external + view + returns (bytes32); + + function computeWithdrawBindingHash( + address owner, + address recipient, + uint256 amount + ) external view returns (bytes32); +} diff --git a/contracts/src/interfaces/IPoseidonT3.sol b/contracts/src/interfaces/IPoseidonT3.sol new file mode 100644 index 0000000..394cdef --- /dev/null +++ b/contracts/src/interfaces/IPoseidonT3.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @title IPoseidonT3 +/// @notice Interface for a deployed Poseidon T3 hash contract (BN254, t=3, 2 inputs). +/// @dev Compatible with Semaphore's deployment at 0xB43122Ecb241DD50062641f089876679fd06599a +/// (same address on Ethereum, OP Mainnet, OP Sepolia, Arbitrum, Base, and others). +interface IPoseidonT3 { + function hash(uint256[2] memory inputs) external pure returns (uint256); +} diff --git a/contracts/src/interfaces/IVerifier.sol b/contracts/src/interfaces/IVerifier.sol new file mode 100644 index 0000000..41ba676 --- /dev/null +++ b/contracts/src/interfaces/IVerifier.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +interface IVerifier { + function verifyProof( + uint256[2] calldata a, + uint256[2][2] calldata b, + uint256[2] calldata c, + uint256[13] calldata input + ) external view returns (bool); +} diff --git a/contracts/src/pool/MARKPool.sol b/contracts/src/pool/MARKPool.sol new file mode 100644 index 0000000..5f0bd61 --- /dev/null +++ b/contracts/src/pool/MARKPool.sol @@ -0,0 +1,529 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol"; +import {ICreditLedger} from "../interfaces/ICreditLedger.sol"; +import {IVerifier} from "../interfaces/IVerifier.sol"; +import {ProofUtils} from "../crypto/ProofUtils.sol"; +import {MerkleTree} from "../crypto/MerkleTree.sol"; +import {PoolFeePolicy} from "./PoolFeePolicy.sol"; +import {PoolPublicInputs} from "./PoolPublicInputs.sol"; +import {PoolValidation} from "./PoolValidation.sol"; +import {PoolErrors} from "./errors/PoolErrors.sol"; + +/// @title MARKPool +/// @notice ZK UTXO pool for private RYLA transfers with Merkle tree membership proofs. +/// @dev Withdrawal flow (burn-to-claim model): +/// Notes enter the pool via transact() or bridgeIn() — both require a valid ZK proof +/// or restricted access respectively. Notes do NOT deposit tokens into the pool; +/// the pool is a nullifier registry backed by a Merkle tree. +/// +/// To withdraw RYLA, a note owner calls transactWithWithdrawBinding(), which: +/// 1. Verifies the ZK proof (Merkle membership + balance equation) +/// 2. Marks nullifiers as spent (prevents double-spend) +/// 3. Records a withdraw binding: hash(owner, recipient, amount) per nullifier +/// 4. Does NOT transfer any tokens +/// +/// The note owner then calls MARKWithdrawAdapter.withdrawWithSig(), which: +/// 1. Verifies the withdraw binding matches the pool's recorded binding +/// 2. Verifies owner + intent signer signatures (EIP-191 personal_sign) +/// 3. Calls RYLACreditLedger.debit(owner, amount) — burns RYLA from owner +/// +/// The owner must hold RYLA tokens equal to the withdrawal amount and approve +/// RYLACreditLedger before calling withdrawWithSig. The ZK proof proves the owner +/// controls the note; the RYLA burn proves they are redeeming it. +/// +/// Relayer fees are credited via ASSET_LEDGER.credit(relayer, fee) during transact(). +/// ASSET_LEDGER must be set via setAssetLedger() after deployment. +contract MARKPool is ReentrancyGuard, AccessManaged, Pausable, PoolErrors { + using MerkleTree for MerkleTree.Tree; + + struct VerifyContext { + bytes32 merkleRoot; + uint256 dstChainId; + uint256 protocolEpoch; + uint256 fee; + address relayer; + address withdrawOwner; + address withdrawRecipient; + uint256 withdrawAmount; + } + + uint8 public constant PROOF_TYPE_TRANSFER = 1; + bytes32 public constant WITHDRAW_BINDING_DOMAIN = keccak256("MARKPool.WithdrawBinding.v1"); + uint256 public constant MAX_ALLOWED_ROOT_AGE = 30 days; + uint256 public constant MAX_FEE_BURN_BPS = 10_000; + uint256 public constant MAX_MIN_FEE = type(uint64).max; + + ICreditLedger public ASSET_LEDGER; + bool public withdrawalsPaused; + uint256 public maxRootAge; + uint256 public feeBurnBps; + uint256 public minFee; + uint256 public protocolEpoch; + address public bridgeOutEntrypoint; + + MerkleTree.Tree private tree; + mapping(uint8 => address) private verifiers; + mapping(uint8 => bool) public proofTypeEnabled; + mapping(bytes32 => bool) private usedNullifiersGlobal; + mapping(bytes32 => bool) public processedBridgeMessages; + mapping(bytes32 => bytes32) public nullifierWithdrawBinding; + mapping(bytes32 => bool) public knownRoots; + mapping(bytes32 => uint256) public rootTimestamps; + mapping(uint256 => bytes32) private rootQueue; + uint256 public rootQueueHead; + uint256 public rootQueueTail; + + event WithdrawalsPaused(address indexed account); + event WithdrawalsUnpaused(address indexed account); + event VerifierSet(uint8 indexed proofType, address indexed verifier); + event ProofTypeEnabled(uint8 indexed proofType, bool enabled); + event RootAdded(bytes32 indexed root); + event MaxRootAgeSet(uint256 maxRootAge); + event FeeBurnBpsSet(uint256 feeBurnBps); + event MinFeeSet(uint256 minFee); + event ProtocolEpochSet(uint256 previousProtocolEpoch, uint256 newProtocolEpoch); + event NoteSpent(bytes32 indexed nullifier); + event WithdrawBindingRecorded( + bytes32 indexed nullifier, + bytes32 indexed bindingHash, + address indexed owner, + address recipient, + uint256 amount + ); + event NoteCreated(bytes32 indexed commitment); + event FeePaid(address indexed relayer, uint256 fee); + event FeeBurned(uint256 amount); + event AssetLedgerSet(address indexed assetLedger); + event BridgeOutEntrypointSet(address indexed entrypoint); + event RootPruned(bytes32 indexed root); + event BridgeOut( + uint256 indexed dstChainId, + bytes32 indexed commitment0, + bytes32 indexed commitment1, + uint256 fee, + address relayer + ); + event BridgeIn( + uint256 indexed srcChainId, + bytes32 indexed commitment0, + bytes32 indexed commitment1 + ); + + constructor(address initialAuthority, address _verifier, address _poseidon) + AccessManaged(initialAuthority) + { + if (_verifier == address(0)) revert InvalidVerifier(); + if (_verifier.code.length == 0) revert VerifierMustBeContract(); + if (_poseidon == address(0)) revert InvalidPoseidon(); + if (_poseidon.code.length == 0) revert PoseidonMustBeContract(); + + verifiers[PROOF_TYPE_TRANSFER] = _verifier; + proofTypeEnabled[PROOF_TYPE_TRANSFER] = true; + + tree.init(20, _poseidon); + bytes32 initialRoot = tree.getRoot(); + knownRoots[initialRoot] = true; + rootTimestamps[initialRoot] = block.timestamp; + rootQueue[0] = initialRoot; + rootQueueHead = 0; + rootQueueTail = 1; + + emit VerifierSet(PROOF_TYPE_TRANSFER, _verifier); + emit ProofTypeEnabled(PROOF_TYPE_TRANSFER, true); + emit RootAdded(initialRoot); + } + + modifier whenWithdrawalsNotPaused() { + if (withdrawalsPaused) revert WithdrawalsArePaused(); + _; + } + + function pause() external restricted { + if (paused()) revert AlreadyPaused(); + _pause(); + // Also pause withdrawals when the contract is paused. + // Note: unpause() does NOT automatically restore withdrawals — call unpauseWithdrawals() explicitly. + if (!withdrawalsPaused) { + withdrawalsPaused = true; + emit WithdrawalsPaused(msg.sender); + } + } + + function unpause() external restricted { + if (!paused()) revert NotPaused(); + _unpause(); + } + + function pauseWithdrawals() external restricted { + if (withdrawalsPaused) revert WithdrawalsAlreadyPaused(); + withdrawalsPaused = true; + emit WithdrawalsPaused(msg.sender); + } + + function unpauseWithdrawals() external restricted { + if (!withdrawalsPaused) revert WithdrawalsNotPaused(); + withdrawalsPaused = false; + emit WithdrawalsUnpaused(msg.sender); + } + + function verifier() external view returns (address) { + return verifiers[PROOF_TYPE_TRANSFER]; + } + + function verifierForType(uint8 proofType) external view returns (address) { + return verifiers[proofType]; + } + + function setVerifier(uint8 proofType, address verifierAddr) external restricted { + if (proofType == 0) revert InvalidProofType(); + if (verifierAddr == address(0)) revert InvalidVerifier(); + if (verifierAddr.code.length == 0) revert VerifierMustBeContract(); + if (verifiers[proofType] == verifierAddr) revert NoStateChange(); + if (proofTypeEnabled[proofType] && !withdrawalsPaused) revert WithdrawalsNotPaused(); + verifiers[proofType] = verifierAddr; + emit VerifierSet(proofType, verifierAddr); + } + + function setProofTypeEnabled(uint8 proofType, bool enabled) external restricted { + if (proofType == 0) revert InvalidProofType(); + if (proofTypeEnabled[proofType] == enabled) revert NoStateChange(); + if (enabled) { + if (verifiers[proofType] == address(0)) revert VerifierNotConfigured(); + if (!withdrawalsPaused) revert WithdrawalsNotPaused(); + } + proofTypeEnabled[proofType] = enabled; + emit ProofTypeEnabled(proofType, enabled); + } + + function emergencyDisableProofType(uint8 proofType) external restricted { + if (proofType == 0) revert InvalidProofType(); + proofTypeEnabled[proofType] = false; + emit ProofTypeEnabled(proofType, false); + } + + function setMaxRootAge(uint256 newMaxRootAge) external restricted { + if (newMaxRootAge > MAX_ALLOWED_ROOT_AGE) revert RootAgeTooLarge(); + if (newMaxRootAge == maxRootAge) revert NoStateChange(); + bool tightening = (maxRootAge == 0 && newMaxRootAge != 0) + || (maxRootAge != 0 && newMaxRootAge != 0 && newMaxRootAge < maxRootAge); + if (tightening && !withdrawalsPaused) revert WithdrawalsNotPaused(); + maxRootAge = newMaxRootAge; + emit MaxRootAgeSet(newMaxRootAge); + } + + function setFeeBurnBps(uint256 newFeeBurnBps) external restricted { + if (newFeeBurnBps > MAX_FEE_BURN_BPS) revert InvalidBurnBps(); + if (newFeeBurnBps == feeBurnBps) revert NoStateChange(); + feeBurnBps = newFeeBurnBps; + emit FeeBurnBpsSet(newFeeBurnBps); + } + + function setMinFee(uint256 newMinFee) external restricted { + // Circuit enforces percentage fee; runtime floor is a narrow safety guard only. + // Allowed values are intentionally constrained to 0/1 credit unit. + if (newMinFee > 1) revert MinFeeTooLarge(); + if (newMinFee != minFee) { + minFee = newMinFee; + emit MinFeeSet(newMinFee); + } + } + + function setProtocolEpoch(uint256 newProtocolEpoch) external restricted { + if (newProtocolEpoch > type(uint32).max) revert EpochExceedsCircuitRange(); + uint256 currentProtocolEpoch = protocolEpoch; + if (newProtocolEpoch == currentProtocolEpoch) revert NoStateChange(); + if (newProtocolEpoch < currentProtocolEpoch) revert EpochCanOnlyIncrease(); + if (!withdrawalsPaused) revert WithdrawalsNotPaused(); + protocolEpoch = newProtocolEpoch; + emit ProtocolEpochSet(currentProtocolEpoch, newProtocolEpoch); + } + + function setBridgeOutEntrypoint(address entrypoint) external restricted { + if (entrypoint != address(0) && entrypoint.code.length == 0) revert EntrypointMustBeContract(); + if (entrypoint == bridgeOutEntrypoint) revert NoStateChange(); + bool tightening = (bridgeOutEntrypoint == address(0) && entrypoint != address(0)) + || (bridgeOutEntrypoint != address(0) && entrypoint != address(0) && bridgeOutEntrypoint != entrypoint); + if (tightening && !withdrawalsPaused) revert WithdrawalsNotPaused(); + bridgeOutEntrypoint = entrypoint; + emit BridgeOutEntrypointSet(entrypoint); + } + + /// @notice Sets the asset ledger used for relayer fee credits. Can only be set once. + /// @dev Separated from the constructor to break the circular dependency between + /// MARKPool and RYLACreditLedger (each needs the other's address at construction). + function setAssetLedger(address ledgerAddress) external restricted { + if (address(ASSET_LEDGER) != address(0)) revert NoStateChange(); + if (ledgerAddress == address(0)) revert InvalidAssetLedger(); + if (ledgerAddress.code.length == 0) revert AssetLedgerMustBeContract(); + ASSET_LEDGER = ICreditLedger(ledgerAddress); + emit AssetLedgerSet(ledgerAddress); + } + + function pruneRoots(uint256 maxToPrune) external returns (uint256 pruned) { + return _pruneRoots(maxToPrune); + } + + function _pruneRoots(uint256 maxToPrune) internal returns (uint256 pruned) { + if (maxRootAge == 0 || maxToPrune == 0) return 0; + // slither-disable-next-line timestamp + if (block.timestamp <= maxRootAge) return 0; + + uint256 cutoff = block.timestamp - maxRootAge; + uint256 head = rootQueueHead; + uint256 tail = rootQueueTail; + + // Keep at least one root (the newest) to preserve transaction liveness. + while (head + 1 < tail && pruned < maxToPrune) { + bytes32 root = rootQueue[head]; + // slither-disable-next-line timestamp + if (rootTimestamps[root] > cutoff) break; + delete knownRoots[root]; + delete rootTimestamps[root]; + delete rootQueue[head]; + emit RootPruned(root); + head++; + pruned++; + } + + if (head != rootQueueHead) { + rootQueueHead = head; + } + } + + function getMerkleRoot() external view returns (bytes32) { + return tree.getRoot(); + } + + function isRootUsable(bytes32 root) public view returns (bool) { + if (!knownRoots[root]) return false; + // Always allow the latest root so the system can advance even in low activity periods. + if (root == tree.getRoot()) return true; + if (maxRootAge == 0) return true; + // slither-disable-next-line timestamp + return block.timestamp <= rootTimestamps[root] + maxRootAge; + } + + function isNullifierUsedGlobal(bytes32 nullifier) external view returns (bool) { + return usedNullifiersGlobal[nullifier]; + } + + /// @notice Executes a private transfer. Permissionless — the ZK proof is the authorization. + /// @dev Any caller may submit a valid proof. Access is gated by proof validity, not by role. + /// The proof binds to merkleRoot, chainId, protocolEpoch, nullifiers, and outCommitments, + /// preventing cross-chain, cross-epoch, and replay attacks without requiring a privileged caller. + function transact( + bytes32 merkleRoot, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments, + uint256 fee, + address relayer, + uint256[2] calldata a, + uint256[2][2] calldata bSnarkjs, + uint256[2] calldata c + ) external nonReentrant whenNotPaused whenWithdrawalsNotPaused { + _verifyAndConsume(merkleRoot, block.chainid, nullifiers, outCommitments, fee, relayer, address(0), address(0), 0, a, bSnarkjs, c); + _insertCommitmentsValidated(outCommitments); + _applyFee(fee, relayer); + } + + /// @notice Executes a private transfer with a withdraw binding. Permissionless — the ZK proof is the authorization. + /// @dev Identical access model to transact. The withdraw binding additionally commits the proof + /// to a specific (withdrawOwner, withdrawRecipient, withdrawAmount) tuple, enabling + /// the WithdrawAdapter to claim the output without a second ZK proof. + function transactWithWithdrawBinding( + bytes32 merkleRoot, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments, + uint256 fee, + address relayer, + address withdrawOwner, + address withdrawRecipient, + uint256 withdrawAmount, + uint256[2] calldata a, + uint256[2][2] calldata bSnarkjs, + uint256[2] calldata c + ) external nonReentrant whenNotPaused whenWithdrawalsNotPaused { + if (withdrawAmount == 0) revert InvalidWithdrawAmount(); + _verifyAndConsume(merkleRoot, block.chainid, nullifiers, outCommitments, fee, relayer, withdrawOwner, withdrawRecipient, withdrawAmount, a, bSnarkjs, c); + _insertCommitmentsValidated(outCommitments); + _applyFee(fee, relayer); + _recordWithdrawBinding(nullifiers, withdrawOwner, withdrawRecipient, withdrawAmount); + } + + /// @notice Initiates a cross-chain transfer. Restricted to the configured bridgeOutEntrypoint. + /// @dev The proof binds to dstChainId instead of block.chainid, committing the output notes + /// to the destination chain. Only the bridgeOutEntrypoint may call this — not permissionless. + function bridgeOut( + bytes32 merkleRoot, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments, + uint256 fee, + address relayer, + uint256 dstChainId, + uint256[2] calldata a, + uint256[2][2] calldata bSnarkjs, + uint256[2] calldata c + ) external nonReentrant whenNotPaused whenWithdrawalsNotPaused { + address configuredEntrypoint = bridgeOutEntrypoint; + if (configuredEntrypoint == address(0)) revert BridgeOutDisabled(); + if (msg.sender != configuredEntrypoint) revert UnauthorizedBridgeOutCaller(); + if (dstChainId == 0) revert InvalidDestination(); + if (dstChainId == block.chainid) revert DestinationIsSource(); + _verifyAndConsume(merkleRoot, dstChainId, nullifiers, outCommitments, fee, relayer, address(0), address(0), 0, a, bSnarkjs, c); + _applyFee(fee, relayer); + emit BridgeOut(dstChainId, outCommitments[0], outCommitments[1], fee, relayer); + } + + /// @notice Inserts incoming cross-chain commitments into the Merkle tree. Restricted. + /// @dev Called by the bridge relay after a bridgeOut on the source chain is confirmed. + /// Restricted to prevent unauthorized note insertion. + /// `messageId` is a unique identifier for the source-chain message (e.g. the + /// SuperchainTokenBridge message hash) and prevents duplicate delivery. + function bridgeIn(uint256 srcChainId, bytes32 messageId, bytes32[2] calldata outCommitments) + external + restricted + whenNotPaused + { + if (srcChainId == 0) revert InvalidSource(); + if (srcChainId == block.chainid) revert SourceIsDestination(); + if (messageId == bytes32(0)) revert InvalidMessageId(); + if (processedBridgeMessages[messageId]) revert BridgeMessageAlreadyProcessed(); + processedBridgeMessages[messageId] = true; + PoolValidation.requireCommitmentsValid(outCommitments); + _insertCommitmentsValidated(outCommitments); + emit BridgeIn(srcChainId, outCommitments[0], outCommitments[1]); + } + + function _verifyAndConsume( + bytes32 merkleRoot, + uint256 dstChainId, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments, + uint256 fee, + address relayer, + address withdrawOwner, + address withdrawRecipient, + uint256 withdrawAmount, + uint256[2] calldata a, + uint256[2][2] calldata bSnarkjs, + uint256[2] calldata c + ) internal { + VerifyContext memory ctx = VerifyContext({ + merkleRoot: merkleRoot, + dstChainId: dstChainId, + protocolEpoch: protocolEpoch, + fee: fee, + relayer: relayer, + withdrawOwner: withdrawOwner, + withdrawRecipient: withdrawRecipient, + withdrawAmount: withdrawAmount + }); + + PoolValidation.requireDestEpochAndFeeWithinCircuitRange(ctx.dstChainId, ctx.protocolEpoch, ctx.fee); + PoolValidation.requireWithdrawBindingWithinCircuitRange(ctx.withdrawOwner, ctx.withdrawRecipient, ctx.withdrawAmount); + PoolValidation.requireRootWithinCircuitRange(ctx.merkleRoot); + if (!proofTypeEnabled[PROOF_TYPE_TRANSFER]) revert ProofTypeDisabled(); + if (!knownRoots[ctx.merkleRoot]) revert UnknownRoot(); + if (!isRootUsable(ctx.merkleRoot)) revert RootExpired(); + if (ctx.fee < minFee) revert FeeTooLow(); + + address verifierAddr = verifiers[PROOF_TYPE_TRANSFER]; + if (verifierAddr == address(0)) revert VerifierNotConfigured(); + + PoolValidation.requireNullifiersFresh(nullifiers, usedNullifiersGlobal); + PoolValidation.requireCommitmentsValid(outCommitments); + + uint256[13] memory publicInputs = _buildPublicInputs(ctx, nullifiers, outCommitments); + if (!_verifyProof(IVerifier(verifierAddr), publicInputs, a, bSnarkjs, c)) revert InvalidProof(); + + for (uint256 i = 0; i < nullifiers.length; i++) { + usedNullifiersGlobal[nullifiers[i]] = true; + emit NoteSpent(nullifiers[i]); + } + } + + + function _insertCommitmentsValidated(bytes32[2] calldata outCommitments) internal { + uint256 tail = rootQueueTail; + for (uint256 i = 0; i < outCommitments.length; i++) { + tree.insert(outCommitments[i]); + bytes32 newRoot = tree.getRoot(); + knownRoots[newRoot] = true; + rootTimestamps[newRoot] = block.timestamp; + rootQueue[tail] = newRoot; + tail++; + emit NoteCreated(outCommitments[i]); + emit RootAdded(newRoot); + } + { + rootQueueTail = tail; + } + } + + + function _applyFee(uint256 fee, address relayer) internal { + if (fee == 0) return; + (uint256 burnAmount, uint256 relayerAmount) = PoolFeePolicy.split(fee, feeBurnBps, MAX_FEE_BURN_BPS); + // "Burn" is applied by withholding mint; total supply increases only by relayerAmount. + if (relayerAmount > 0) { + if (relayer == address(0)) revert InvalidRelayer(); + if (address(ASSET_LEDGER) == address(0)) revert InvalidAssetLedger(); + ASSET_LEDGER.credit(relayer, relayerAmount); + emit FeePaid(relayer, relayerAmount); + } + if (burnAmount > 0) { + emit FeeBurned(burnAmount); + } + } + + function _verifyProof( + IVerifier selectedVerifier, + uint256[13] memory publicInputs, + uint256[2] memory a, + uint256[2][2] memory bSnarkjs, + uint256[2] memory c + ) internal view returns (bool) { + uint256[2][2] memory bFixed = ProofUtils.convertProof(bSnarkjs); + return selectedVerifier.verifyProof(a, bFixed, c, publicInputs); + } + + function _buildPublicInputs( + VerifyContext memory ctx, + bytes32[2] calldata nullifiers, + bytes32[2] calldata outCommitments + ) internal view returns (uint256[13] memory publicInputs) { + return PoolPublicInputs.build( + nullifiers, outCommitments, ctx.merkleRoot, block.chainid, ctx.dstChainId, + ctx.protocolEpoch, ctx.fee, ctx.relayer, + ctx.withdrawOwner, ctx.withdrawRecipient, ctx.withdrawAmount + ); + } + + function computeWithdrawBindingHash(address owner, address recipient, uint256 amount) + public + view + returns (bytes32) + { + return keccak256(abi.encode(WITHDRAW_BINDING_DOMAIN, address(this), block.chainid, owner, recipient, amount)); + } + + function _recordWithdrawBinding( + bytes32[2] calldata nullifiers, + address owner, + address recipient, + uint256 amount + ) internal { + bytes32 bindingHash = computeWithdrawBindingHash(owner, recipient, amount); + for (uint256 i = 0; i < nullifiers.length; i++) { + if (nullifierWithdrawBinding[nullifiers[i]] != bytes32(0)) revert WithdrawBindingExists(); + nullifierWithdrawBinding[nullifiers[i]] = bindingHash; + emit WithdrawBindingRecorded(nullifiers[i], bindingHash, owner, recipient, amount); + } + } + + +} diff --git a/contracts/src/pool/PoolFeePolicy.sol b/contracts/src/pool/PoolFeePolicy.sol new file mode 100644 index 0000000..fb8f773 --- /dev/null +++ b/contracts/src/pool/PoolFeePolicy.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Fee policy and split helpers for Pool. +library PoolFeePolicy { + error FeePolicyInvalidBps(); + + function split(uint256 fee, uint256 feeBurnBps, uint256 maxFeeBurnBps) + internal + pure + returns (uint256 burnAmount, uint256 relayerAmount) + { + if (maxFeeBurnBps == 0) revert FeePolicyInvalidBps(); + if (feeBurnBps > maxFeeBurnBps) revert FeePolicyInvalidBps(); + burnAmount = fee * feeBurnBps / maxFeeBurnBps; + relayerAmount = fee - burnAmount; + } +} diff --git a/contracts/src/pool/PoolPublicInputs.sol b/contracts/src/pool/PoolPublicInputs.sol new file mode 100644 index 0000000..bdfddac --- /dev/null +++ b/contracts/src/pool/PoolPublicInputs.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Canonical public input encoder for UTXO proof verification. +library PoolPublicInputs { + function build( + bytes32[2] memory nullifiers, + bytes32[2] memory outCommitments, + bytes32 merkleRoot, + uint256 chainId, + uint256 dstChainId, + uint256 protocolEpoch, + uint256 fee, + address relayer + ) internal pure returns (uint256[13] memory publicInputs) { + return build( + nullifiers, + outCommitments, + merkleRoot, + chainId, + dstChainId, + protocolEpoch, + fee, + relayer, + address(0), + address(0), + 0 + ); + } + + function build( + bytes32[2] memory nullifiers, + bytes32[2] memory outCommitments, + bytes32 merkleRoot, + uint256 chainId, + uint256 dstChainId, + uint256 protocolEpoch, + uint256 fee, + address relayer, + address withdrawOwner, + address withdrawRecipient, + uint256 withdrawAmount + ) internal pure returns (uint256[13] memory publicInputs) { + // Canonical ordering: + // [root, chainId, dstChainId, protocolEpoch, fee, relayer, nullifier0, nullifier1, outCommitment0, outCommitment1, withdrawOwner, withdrawRecipient, withdrawAmount] + publicInputs[0] = uint256(merkleRoot); + publicInputs[1] = chainId; + publicInputs[2] = dstChainId; + publicInputs[3] = protocolEpoch; + publicInputs[4] = fee; + publicInputs[5] = uint256(uint160(relayer)); + publicInputs[6] = uint256(nullifiers[0]); + publicInputs[7] = uint256(nullifiers[1]); + publicInputs[8] = uint256(outCommitments[0]); + publicInputs[9] = uint256(outCommitments[1]); + publicInputs[10] = uint256(uint160(withdrawOwner)); + publicInputs[11] = uint256(uint160(withdrawRecipient)); + publicInputs[12] = withdrawAmount; + } +} diff --git a/contracts/src/pool/PoolValidation.sol b/contracts/src/pool/PoolValidation.sol new file mode 100644 index 0000000..599fd5c --- /dev/null +++ b/contracts/src/pool/PoolValidation.sol @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {PoolErrors} from "../pool/errors/PoolErrors.sol"; + +/// @notice Shared validation helpers for Pool transaction and bridge flows. +library PoolValidation { + // BN254 scalar field used by Groth16/circom public inputs. + uint256 internal constant SNARK_SCALAR_FIELD = + 21888242871839275222246405745257275088548364400416034343698204186575808495617; + + function requireDestEpochAndFeeWithinCircuitRange( + uint256 dstChainId, + uint256 protocolEpoch, + uint256 fee + ) internal pure { + if (dstChainId > type(uint64).max) revert PoolErrors.InputExceedsCircuitRange(); + if (protocolEpoch > type(uint32).max) revert PoolErrors.EpochExceedsCircuitRange(); + if (fee > type(uint64).max) revert PoolErrors.InputExceedsCircuitRange(); + } + + function requireWithdrawBindingWithinCircuitRange( + address withdrawOwner, + address withdrawRecipient, + uint256 withdrawAmount + ) internal pure { + if (withdrawAmount > type(uint64).max) revert PoolErrors.InputExceedsCircuitRange(); + if (withdrawAmount == 0) { + if (withdrawOwner != address(0)) revert PoolErrors.InvalidWithdrawOwner(); + if (withdrawRecipient != address(0)) revert PoolErrors.InvalidWithdrawRecipient(); + } else { + if (withdrawOwner == address(0)) revert PoolErrors.InvalidWithdrawOwner(); + if (withdrawRecipient == address(0)) revert PoolErrors.InvalidWithdrawRecipient(); + } + } + + function requireRootWithinCircuitRange(bytes32 merkleRoot) internal pure { + if (uint256(merkleRoot) >= SNARK_SCALAR_FIELD) revert PoolErrors.InputExceedsCircuitRange(); + } + + function requireNullifiersFresh( + bytes32[2] calldata nullifiers, + mapping(bytes32 => bool) storage usedNullifiersGlobal + ) internal view { + // Check duplicate first so the error is precise. + if (nullifiers[0] == nullifiers[1]) revert PoolErrors.NullifierDuplicate(); + for (uint256 i = 0; i < nullifiers.length; i++) { + bytes32 nullifier = nullifiers[i]; + if (nullifier == bytes32(0)) revert PoolErrors.NullifierInvalid(); + if (uint256(nullifier) >= SNARK_SCALAR_FIELD) revert PoolErrors.InputExceedsCircuitRange(); + if (usedNullifiersGlobal[nullifier]) revert PoolErrors.NullifierUsed(); + } + } + + function requireCommitmentsValid(bytes32[2] calldata outCommitments) + internal + pure + { + for (uint256 i = 0; i < outCommitments.length; i++) { + if (outCommitments[i] == bytes32(0)) revert PoolErrors.CommitmentInvalid(); + if (uint256(outCommitments[i]) >= SNARK_SCALAR_FIELD) revert PoolErrors.InputExceedsCircuitRange(); + } + if (outCommitments[0] == outCommitments[1]) revert PoolErrors.CommitmentDuplicate(); + } +} diff --git a/contracts/src/pool/RYLACreditLedger.sol b/contracts/src/pool/RYLACreditLedger.sol new file mode 100644 index 0000000..5627fa5 --- /dev/null +++ b/contracts/src/pool/RYLACreditLedger.sol @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {IRYLA} from "../interfaces/IRYLA.sol"; +import {ICreditLedger} from "../interfaces/ICreditLedger.sol"; +import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +/// @title RYLACreditLedger +/// @notice Adapter that bridges ICreditLedger to IRYLA for MARKPool and MARKWithdrawAdapter. +/// @dev credit() is restricted to POOL — called for relayer fee payouts. +/// debit() is restricted to ADAPTER — called to burn RYLA on withdrawal. +/// ADAPTER is set post-construction via setAdapter() to break the circular deploy +/// dependency (adapter constructor requires ledger address, ledger requires adapter address). +/// This contract must hold MINTER_ROLE and BURNER_ROLE on the RYLA token. +/// `debit` requires `from` to have approved this contract for at least `amount` tokens. +contract RYLACreditLedger is ICreditLedger { + using SafeERC20 for IERC20; + + error Unauthorized(); + error ZeroAddress(); + error AdapterAlreadySet(); + error InvalidContract(); + + event AdapterSet(address indexed adapter); + event Credit(address indexed to, uint256 amount); + event Debit(address indexed from, uint256 amount); + + IRYLA public immutable TOKEN; + address public immutable POOL; + address public immutable OWNER; + address public ADAPTER; + + uint256 private _totalMinted; + uint256 private _totalBurned; + + constructor(address token_, address pool_) { + if (token_ == address(0) || pool_ == address(0)) revert ZeroAddress(); + if (token_.code.length == 0) revert InvalidContract(); + if (pool_.code.length == 0) revert InvalidContract(); + TOKEN = IRYLA(token_); + POOL = pool_; + OWNER = msg.sender; + } + + /// @notice Sets the adapter address. Can only be called once, by the deployer. + /// @dev Restricted to OWNER (the deployer) to prevent front-running between + /// deployment and the setAdapter call in the release script. + function setAdapter(address adapter_) external { + if (msg.sender != OWNER) revert Unauthorized(); + if (ADAPTER != address(0)) revert AdapterAlreadySet(); + if (adapter_ == address(0)) revert ZeroAddress(); + if (adapter_.code.length == 0) revert InvalidContract(); + ADAPTER = adapter_; + emit AdapterSet(adapter_); + } + + function credit(address to, uint256 amount) external { + if (msg.sender != POOL) revert Unauthorized(); + _totalMinted += amount; + emit Credit(to, amount); + TOKEN.mint(to, amount); + } + + function debit(address from, uint256 amount) external { + if (msg.sender != ADAPTER) revert Unauthorized(); + _totalBurned += amount; + emit Debit(from, amount); + IERC20(address(TOKEN)).safeTransferFrom(from, address(this), amount); + TOKEN.burn(amount); + } + + function creditBalanceOf(address account) external view returns (uint256) { + return TOKEN.balanceOf(account); + } + + function totalCreditsMinted() external view returns (uint256) { + return _totalMinted; + } + + function totalCreditsBurned() external view returns (uint256) { + return _totalBurned; + } + + /// @notice Returns net credits tracked by this ledger (credit() calls minus debit() calls). + /// @dev Scope is limited to flows through this contract's credit() and debit() functions + /// (_totalMinted and _totalBurned). RYLA minted or burned via other paths + /// (e.g. MARKSettlementModule, direct token burns) is not reflected here, so + /// _totalBurned may exceed _totalMinted as measured by this ledger. Returns 0 + /// in that case rather than reverting. + function totalCreditsOutstanding() external view returns (uint256) { + return _totalMinted >= _totalBurned ? _totalMinted - _totalBurned : 0; + } + + function maxCredits() external pure returns (uint256) { + return type(uint256).max; + } +} diff --git a/contracts/src/pool/errors/PoolErrors.sol b/contracts/src/pool/errors/PoolErrors.sol new file mode 100644 index 0000000..40296de --- /dev/null +++ b/contracts/src/pool/errors/PoolErrors.sol @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Custom errors for the Pool, PoolValidation, and MerkleTree contracts. +abstract contract PoolErrors { + // Verifier / asset ledger configuration + error InvalidVerifier(); + error VerifierMustBeContract(); + error InvalidPoseidon(); + error PoseidonMustBeContract(); + error VerifierNotConfigured(); + error InvalidAssetLedger(); + error AssetLedgerMustBeContract(); + error EntrypointMustBeContract(); + + // Proof type management + error InvalidProofType(); + error ProofTypeDisabled(); + + // Pause / withdrawal gate + error AlreadyPaused(); + error NotPaused(); + error WithdrawalsArePaused(); + error WithdrawalsAlreadyPaused(); + error WithdrawalsNotPaused(); + + // Fee policy + error FeeTooLow(); + /// @dev Fired when setMinFee is called with a value > 1. minFee is constrained to + /// 0 or 1 credit unit — values above 1 indicate a misconfigured fee policy. + error MinFeeTooLarge(); + error InvalidBurnBps(); + + // Merkle tree + error TreeNotInitialized(); + error TreeAlreadyInitialized(); + error TreeFull(); + error LeafOutOfField(); + + // Merkle root / epoch + error UnknownRoot(); + error RootExpired(); + error RootAlreadyKnown(); + error RootAgeTooLarge(); + error EpochCanOnlyIncrease(); + error EpochExceedsCircuitRange(); + error InputExceedsCircuitRange(); + + // Nullifier + error NullifierUsed(); + error NullifierDuplicate(); + error NullifierInvalid(); + + // Commitment + error CommitmentInvalid(); + error CommitmentDuplicate(); + + // Proof / withdraw + error InvalidProof(); + error InvalidWithdrawAmount(); + error InvalidWithdrawOwner(); + error InvalidWithdrawRecipient(); + error WithdrawBindingExists(); + + // Bridge-out + error BridgeOutDisabled(); + error UnauthorizedBridgeOutCaller(); + error InvalidSource(); + error InvalidDestination(); + error InvalidMessageId(); + error SourceIsDestination(); + error DestinationIsSource(); + error InvalidRoot(); + error BridgeMessageAlreadyProcessed(); + + // Generic + error NoStateChange(); + error InvalidRelayer(); +} diff --git a/contracts/src/pool/verifier/MARKPoolVerifier.sol b/contracts/src/pool/verifier/MARKPoolVerifier.sol new file mode 100644 index 0000000..05d9d5c --- /dev/null +++ b/contracts/src/pool/verifier/MARKPoolVerifier.sol @@ -0,0 +1,252 @@ +// SPDX-License-Identifier: GPL-3.0 +/* + Copyright 2021 0KIMS association. + + This file is generated with [snarkJS](https://github.com/iden3/snarkjs). + + snarkJS is a free software: you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + snarkJS is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with snarkJS. If not, see . +*/ + +pragma solidity ^0.8.25; + +contract MARKPoolVerifier { + // Scalar field size + uint256 constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617; + // Base field size + uint256 constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; + + // Verification Key data + uint256 constant alphax = 7690121453837064741791666285615914065043168911112024434635727450696948422155; + uint256 constant alphay = 19345384908200007096220441272874255011681315248075750381704111138335765955939; + uint256 constant betax1 = 6915934800673380020968239961322121395269172970533534101674332671678415647246; + uint256 constant betax2 = 20728849236918147024992766736188414469847245385633192207887668658686399927588; + uint256 constant betay1 = 21312787228846701455550273385994038986810827549346222493309345736711813078377; + uint256 constant betay2 = 16286369113203485455529573339382241219652132627904969020690079721408278626154; + uint256 constant gammax1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; + uint256 constant gammax2 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; + uint256 constant gammay1 = 4082367875863433681332203403145435568316851327593401208105741076214120093531; + uint256 constant gammay2 = 8495653923123431417604973247489272438418190587263600148770280649306958101930; + uint256 constant deltax1 = 18345997162799119763959895099884005794908640345221290015934691352832684803409; + uint256 constant deltax2 = 18376220675637683916789943756353088518300600925197561931224366358883175144946; + uint256 constant deltay1 = 14667787894595027688399092139120199969307647556867024352155398167389948755220; + uint256 constant deltay2 = 17402953593761902101339812066866095628747519305463643507602187887465365773563; + + + uint256 constant IC0x = 19677464199829831391143197766895170870202127014521187688146355322194167148789; + uint256 constant IC0y = 14508738950164930345796428833546353070862474607782487610541850087929116474823; + + uint256 constant IC1x = 15810506242982102758328405285766847137006576574868460171387725247110566628643; + uint256 constant IC1y = 11938198121287064712385776490568305466880644396271008528046426042839610914074; + + uint256 constant IC2x = 18060475454236239168879174600455192598240591544351300374321852531007429009260; + uint256 constant IC2y = 10296541415987206312466055552238695162994563741943336332647294514514935225702; + + uint256 constant IC3x = 3990251842151791550142883039865846292187659831760645494713083817305989709105; + uint256 constant IC3y = 1304028740140725426252032502949428173892032776255032882042899910509473360120; + + uint256 constant IC4x = 21395198740199805844451312446272709617147392380661710468534185462130281275251; + uint256 constant IC4y = 12578747072742829252091273986932145672426413050540548117821316259630037256762; + + uint256 constant IC5x = 14655361099279462571711764477264712958209045342810426112622760020406723477975; + uint256 constant IC5y = 16473077741198686033561698162265512156626032674621230865444064605841618114186; + + uint256 constant IC6x = 8339902252239795081910729652265595713879123333853824977475238292919724589513; + uint256 constant IC6y = 9820528359329116982730541353201661834578929514941329926803536170951379309866; + + uint256 constant IC7x = 9617676558640460423141383812130917145761139647874321775264012149719154634990; + uint256 constant IC7y = 19593893247410006121291214540215535963752641361334134681489375464166464502639; + + uint256 constant IC8x = 10096618593207197176611766393169319752761689442500959997102862948250829793082; + uint256 constant IC8y = 17494166304952791491504140178523726688997463801000163628380743050969222835058; + + uint256 constant IC9x = 13229071062576027181470319239919008050027368487464842689099423968901005572714; + uint256 constant IC9y = 14079217861664032079295362303322009278793429507935279509898657532006155661451; + + uint256 constant IC10x = 9870923827008178781317591932446971439112779463121740091254410422921350400337; + uint256 constant IC10y = 1219780025409560941514831026892781911586565452764231309711241768110330035679; + + uint256 constant IC11x = 18018388542095146381096718473114112195585557454998366946299555005537522886657; + uint256 constant IC11y = 9755299296218437764934573811016436707100541752064000523732170157502071982459; + + uint256 constant IC12x = 10763815019232165310646098723787191585893365403641063356783612748255221441294; + uint256 constant IC12y = 20630753604272640342314204407594751978163768046423435894514917305447912351616; + + uint256 constant IC13x = 15573237768046962222146529676543444045309562040107000847925173039157817674084; + uint256 constant IC13y = 16229429557329522323758870379600272246081875321482243209760555251354229611954; + + + // Memory data + uint16 constant pVk = 0; + uint16 constant pPairing = 128; + + uint16 constant pLastMem = 896; + + function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[13] calldata _pubSignals) public view returns (bool) { + assembly { + function checkField(v) { + if iszero(lt(v, r)) { + mstore(0, 0) + return(0, 0x20) + } + } + + // G1 function to multiply a G1 value(x,y) to value in an address + function g1_mulAccC(pR, x, y, s) { + let success + let mIn := mload(0x40) + mstore(mIn, x) + mstore(add(mIn, 32), y) + mstore(add(mIn, 64), s) + + success := staticcall(sub(gas(), 2000), 7, mIn, 96, mIn, 64) + + if iszero(success) { + mstore(0, 0) + return(0, 0x20) + } + + mstore(add(mIn, 64), mload(pR)) + mstore(add(mIn, 96), mload(add(pR, 32))) + + success := staticcall(sub(gas(), 2000), 6, mIn, 128, pR, 64) + + if iszero(success) { + mstore(0, 0) + return(0, 0x20) + } + } + + function checkPairing(pA, pB, pC, pubSignals, pMem) -> isOk { + let _pPairing := add(pMem, pPairing) + let _pVk := add(pMem, pVk) + + mstore(_pVk, IC0x) + mstore(add(_pVk, 32), IC0y) + + // Compute the linear combination vk_x + + g1_mulAccC(_pVk, IC1x, IC1y, calldataload(add(pubSignals, 0))) + + g1_mulAccC(_pVk, IC2x, IC2y, calldataload(add(pubSignals, 32))) + + g1_mulAccC(_pVk, IC3x, IC3y, calldataload(add(pubSignals, 64))) + + g1_mulAccC(_pVk, IC4x, IC4y, calldataload(add(pubSignals, 96))) + + g1_mulAccC(_pVk, IC5x, IC5y, calldataload(add(pubSignals, 128))) + + g1_mulAccC(_pVk, IC6x, IC6y, calldataload(add(pubSignals, 160))) + + g1_mulAccC(_pVk, IC7x, IC7y, calldataload(add(pubSignals, 192))) + + g1_mulAccC(_pVk, IC8x, IC8y, calldataload(add(pubSignals, 224))) + + g1_mulAccC(_pVk, IC9x, IC9y, calldataload(add(pubSignals, 256))) + + g1_mulAccC(_pVk, IC10x, IC10y, calldataload(add(pubSignals, 288))) + + g1_mulAccC(_pVk, IC11x, IC11y, calldataload(add(pubSignals, 320))) + + g1_mulAccC(_pVk, IC12x, IC12y, calldataload(add(pubSignals, 352))) + + g1_mulAccC(_pVk, IC13x, IC13y, calldataload(add(pubSignals, 384))) + + + // -A + mstore(_pPairing, calldataload(pA)) + mstore(add(_pPairing, 32), mod(sub(q, calldataload(add(pA, 32))), q)) + + // B + mstore(add(_pPairing, 64), calldataload(pB)) + mstore(add(_pPairing, 96), calldataload(add(pB, 32))) + mstore(add(_pPairing, 128), calldataload(add(pB, 64))) + mstore(add(_pPairing, 160), calldataload(add(pB, 96))) + + // alpha1 + mstore(add(_pPairing, 192), alphax) + mstore(add(_pPairing, 224), alphay) + + // beta2 + mstore(add(_pPairing, 256), betax1) + mstore(add(_pPairing, 288), betax2) + mstore(add(_pPairing, 320), betay1) + mstore(add(_pPairing, 352), betay2) + + // vk_x + mstore(add(_pPairing, 384), mload(add(pMem, pVk))) + mstore(add(_pPairing, 416), mload(add(pMem, add(pVk, 32)))) + + + // gamma2 + mstore(add(_pPairing, 448), gammax1) + mstore(add(_pPairing, 480), gammax2) + mstore(add(_pPairing, 512), gammay1) + mstore(add(_pPairing, 544), gammay2) + + // C + mstore(add(_pPairing, 576), calldataload(pC)) + mstore(add(_pPairing, 608), calldataload(add(pC, 32))) + + // delta2 + mstore(add(_pPairing, 640), deltax1) + mstore(add(_pPairing, 672), deltax2) + mstore(add(_pPairing, 704), deltay1) + mstore(add(_pPairing, 736), deltay2) + + + let success := staticcall(sub(gas(), 2000), 8, _pPairing, 768, _pPairing, 0x20) + + isOk := and(success, mload(_pPairing)) + } + + let pMem := mload(0x40) + mstore(0x40, add(pMem, pLastMem)) + + // Validate that all evaluations ∈ F + + checkField(calldataload(add(_pubSignals, 0))) + + checkField(calldataload(add(_pubSignals, 32))) + + checkField(calldataload(add(_pubSignals, 64))) + + checkField(calldataload(add(_pubSignals, 96))) + + checkField(calldataload(add(_pubSignals, 128))) + + checkField(calldataload(add(_pubSignals, 160))) + + checkField(calldataload(add(_pubSignals, 192))) + + checkField(calldataload(add(_pubSignals, 224))) + + checkField(calldataload(add(_pubSignals, 256))) + + checkField(calldataload(add(_pubSignals, 288))) + + checkField(calldataload(add(_pubSignals, 320))) + + checkField(calldataload(add(_pubSignals, 352))) + + checkField(calldataload(add(_pubSignals, 384))) + + + // Validate all evaluations + let isValid := checkPairing(_pA, _pB, _pC, _pubSignals, pMem) + + mstore(0, isValid) + return(0, 0x20) + } + } + } diff --git a/contracts/src/withdraw/MARKWithdrawAdapter.sol b/contracts/src/withdraw/MARKWithdrawAdapter.sol new file mode 100644 index 0000000..f0dd85e --- /dev/null +++ b/contracts/src/withdraw/MARKWithdrawAdapter.sol @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; +import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; +import {ICreditLedger} from "../interfaces/ICreditLedger.sol"; +import {IPoolNullifier} from "../interfaces/IPoolNullifier.sol"; +import {MARKWithdrawErrors} from "./MARKWithdrawErrors.sol"; + +/// @notice Native-token payout adapter backed by credit debits. +/// @dev Amount/recipient are bound to per-nullifier Pool withdraw bindings. +/// Owner authorization still relies on signatures; the circuit does not bind owner to note secret. +contract MARKWithdrawAdapter is AccessManaged, Pausable, ReentrancyGuard, MARKWithdrawErrors { + bytes32 public constant WITHDRAW_INTENT_DOMAIN = keccak256("MARKWithdrawAdapter.Intent.v1"); + uint256 public constant DEFAULT_MAX_INTENT_VALIDITY = 1 hours; + + ICreditLedger public immutable ASSET_LEDGER; + IPoolNullifier public immutable PROOF_POOL; + uint256 public maxIntentValidity; + uint256 public totalNativePaid; + mapping(address => uint256) public withdrawNonce; + mapping(bytes32 => bool) public claimedNullifiers; + mapping(address => bool) public intentSigners; + + event NativeReceived(address indexed from, uint256 amount, uint256 resultingBalance); + event MaxIntentValiditySet(uint256 previousMaxIntentValidity, uint256 newMaxIntentValidity); + event IntentSignerSet(address indexed signer, bool previousEnabled, bool newEnabled); + event NullifierClaimed(bytes32 indexed nullifier, address indexed owner); + event WithdrawIntentAuthorized(address indexed signer, bytes32 indexed intentHash, address indexed owner); + event WithdrawExecuted( + address indexed creditOwner, + address indexed recipient, + uint256 amount, + uint256 nonce, + bytes32 indexed intentHash, + address caller + ); + + constructor(address initialAuthority, address ledgerAddress, address poolAddress) + AccessManaged(initialAuthority) + { + if (ledgerAddress == address(0)) revert InvalidAssetLedger(); + if (poolAddress == address(0)) revert InvalidProofPool(); + if (ledgerAddress.code.length == 0) revert AssetLedgerMustBeContract(); + if (poolAddress.code.length == 0) revert ProofPoolMustBeContract(); + ASSET_LEDGER = ICreditLedger(ledgerAddress); + PROOF_POOL = IPoolNullifier(poolAddress); + maxIntentValidity = DEFAULT_MAX_INTENT_VALIDITY; + emit MaxIntentValiditySet(0, DEFAULT_MAX_INTENT_VALIDITY); + } + + receive() external payable { + emit NativeReceived(msg.sender, msg.value, address(this).balance); + } + + function pause() external restricted { + if (paused()) revert AlreadyPaused(); + _pause(); + } + + function unpause() external restricted { + if (!paused()) revert NotPaused(); + _unpause(); + } + + function setMaxIntentValidity(uint256 newMaxIntentValidity) external restricted { + if (newMaxIntentValidity == 0) revert InvalidMaxIntentValidity(); + uint256 previous = maxIntentValidity; + if (newMaxIntentValidity == previous) revert NoStateChange(); + maxIntentValidity = newMaxIntentValidity; + emit MaxIntentValiditySet(previous, newMaxIntentValidity); + } + + function setIntentSigner(address signer, bool enabled) external restricted { + if (signer == address(0)) revert InvalidSigner(); + bool previousEnabled = intentSigners[signer]; + if (enabled == previousEnabled) revert NoStateChange(); + intentSigners[signer] = enabled; + emit IntentSignerSet(signer, previousEnabled, enabled); + } + + function computeWithdrawIntentHash( + address creditOwner, + address recipient, + uint256 amount, + bytes32[2] memory nullifiers, + uint256 nonce, + uint256 deadline + ) public view returns (bytes32) { + return keccak256( + abi.encode( + WITHDRAW_INTENT_DOMAIN, + address(this), + block.chainid, + address(ASSET_LEDGER), + address(PROOF_POOL), + creditOwner, + recipient, + amount, + nullifiers[0], + nullifiers[1], + nonce, + deadline + ) + ); + } + + /// @notice Returns the EIP-191 personal_sign digest for a withdraw intent. + /// @dev Uses toEthSignedMessageHash (personal_sign) intentionally — signers use + /// eth_sign or personal_sign, not eth_signTypedData. The intent hash is a + /// structured keccak256 hash; wrapping it in EIP-191 prevents raw-hash signing + /// attacks while keeping wallet compatibility broad. + function computeWithdrawIntentDigest( + address creditOwner, + address recipient, + uint256 amount, + bytes32[2] calldata nullifiers, + uint256 nonce, + uint256 deadline + ) external view returns (bytes32) { + bytes32 intentHash = computeWithdrawIntentHash(creditOwner, recipient, amount, nullifiers, nonce, deadline); + return MessageHashUtils.toEthSignedMessageHash(intentHash); + } + + function withdrawWithSig( + address creditOwner, + address recipient, + uint256 amount, + bytes32[2] calldata nullifiers, + uint256 nonce, + uint256 deadline, + bytes calldata ownerSignature, + bytes calldata intentSignature + ) external nonReentrant whenNotPaused { + _validateWithdrawRequest(creditOwner, recipient, amount, nonce, deadline, ownerSignature, intentSignature); + _validateNullifierState(nullifiers); + _requireWithdrawBindingMatch(nullifiers, creditOwner, recipient, amount); + + (bytes32 intentHash, address intentSigner) = _requireSignatures( + creditOwner, recipient, amount, nullifiers, nonce, deadline, ownerSignature, intentSignature + ); + + withdrawNonce[creditOwner] = nonce + 1; + claimedNullifiers[nullifiers[0]] = true; + claimedNullifiers[nullifiers[1]] = true; + emit WithdrawIntentAuthorized(intentSigner, intentHash, creditOwner); + emit NullifierClaimed(nullifiers[0], creditOwner); + emit NullifierClaimed(nullifiers[1], creditOwner); + totalNativePaid += amount; + + // Transfer ETH before burning RYLA — if the transfer fails, RYLA is not burned. + (bool ok,) = payable(recipient).call{value: amount}(""); + if (!ok) revert NativeTransferFailed(); + + ASSET_LEDGER.debit(creditOwner, amount); + + emit WithdrawExecuted(creditOwner, recipient, amount, nonce, intentHash, msg.sender); + } + + function _validateWithdrawRequest( + address creditOwner, + address recipient, + uint256 amount, + uint256 nonce, + uint256 deadline, + bytes calldata ownerSignature, + bytes calldata intentSignature + ) internal view { + if (creditOwner == address(0)) revert InvalidCreditOwner(); + if (recipient == address(0)) revert InvalidRecipient(); + if (amount == 0) revert InvalidAmount(); + if (ownerSignature.length == 0) revert MissingOwnerSignature(); + if (intentSignature.length == 0) revert MissingIntentSignature(); + if (deadline == 0) revert InvalidIntentDeadline(); + if (deadline < block.timestamp) revert IntentExpired(); + if (deadline - block.timestamp > maxIntentValidity) revert IntentExceedsMaxValidity(); + if (address(this).balance < amount) revert InsufficientLiquidity(); + if (nonce != withdrawNonce[creditOwner]) revert NonceMismatch(); + } + + function _validateNullifierState(bytes32[2] calldata nullifiers) internal view { + if (nullifiers[0] == bytes32(0)) revert NullifierInvalid(); + if (nullifiers[1] == bytes32(0)) revert NullifierInvalid(); + if (nullifiers[0] == nullifiers[1]) revert NullifierDuplicate(); + if (!PROOF_POOL.isNullifierUsedGlobal(nullifiers[0])) revert NullifierNotConsumed(); + if (!PROOF_POOL.isNullifierUsedGlobal(nullifiers[1])) revert NullifierNotConsumed(); + if (claimedNullifiers[nullifiers[0]]) revert NullifierAlreadyClaimed(); + if (claimedNullifiers[nullifiers[1]]) revert NullifierAlreadyClaimed(); + } + + function _requireWithdrawBindingMatch( + bytes32[2] calldata nullifiers, + address owner, + address recipient, + uint256 amount + ) internal view { + bytes32 expectedBinding = PROOF_POOL.computeWithdrawBindingHash(owner, recipient, amount); + if (PROOF_POOL.nullifierWithdrawBinding(nullifiers[0]) != expectedBinding) revert WithdrawBindingMismatch(); + if (PROOF_POOL.nullifierWithdrawBinding(nullifiers[1]) != expectedBinding) revert WithdrawBindingMismatch(); + } + + function _requireSignatures( + address creditOwner, + address recipient, + uint256 amount, + bytes32[2] calldata nullifiers, + uint256 nonce, + uint256 deadline, + bytes calldata ownerSignature, + bytes calldata intentSignature + ) internal view returns (bytes32 intentHash, address intentSigner) { + intentHash = computeWithdrawIntentHash(creditOwner, recipient, amount, nullifiers, nonce, deadline); + bytes32 digest = MessageHashUtils.toEthSignedMessageHash(intentHash); + + address ownerSigner = ECDSA.recover(digest, ownerSignature); + if (ownerSigner != creditOwner) revert InvalidOwnerSigner(); + + intentSigner = ECDSA.recover(digest, intentSignature); + if (!intentSigners[intentSigner]) revert UnauthorizedIntentSigner(); + if (intentSigner == creditOwner) revert OwnerCannotCoSign(); + } +} diff --git a/contracts/src/withdraw/MARKWithdrawErrors.sol b/contracts/src/withdraw/MARKWithdrawErrors.sol new file mode 100644 index 0000000..0197079 --- /dev/null +++ b/contracts/src/withdraw/MARKWithdrawErrors.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +/// @notice Custom errors for WithdrawAdapter. +abstract contract MARKWithdrawErrors { + error InvalidCreditOwner(); + error InvalidRecipient(); + error InvalidAmount(); + error InvalidSigner(); + error InvalidIntentDeadline(); + error IntentExpired(); + error IntentExceedsMaxValidity(); + error InsufficientLiquidity(); + error NonceMismatch(); + error NullifierAlreadyClaimed(); + error NullifierInvalid(); + error NullifierDuplicate(); + error NullifierNotConsumed(); + error WithdrawBindingMismatch(); + error InvalidOwnerSigner(); + error UnauthorizedIntentSigner(); + error OwnerCannotCoSign(); + error NativeTransferFailed(); + error MissingOwnerSignature(); + error MissingIntentSignature(); + error InvalidMaxIntentValidity(); + error InvalidProofPool(); + error ProofPoolMustBeContract(); + error InvalidAssetLedger(); + error AssetLedgerMustBeContract(); + error AlreadyPaused(); + error NotPaused(); + error NoStateChange(); +} diff --git a/contracts/test/e2e/pool/MARKPoolE2E.t.sol b/contracts/test/e2e/pool/MARKPoolE2E.t.sol new file mode 100644 index 0000000..a4aada0 --- /dev/null +++ b/contracts/test/e2e/pool/MARKPoolE2E.t.sol @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Test} from "forge-std/Test.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; +import {RYLA} from "../../../src/token/RYLA.sol"; +import {MARKPool} from "../../../src/pool/MARKPool.sol"; +import {MARKWithdrawAdapter} from "../../../src/withdraw/MARKWithdrawAdapter.sol"; +import {RYLACreditLedger} from "../../../src/pool/RYLACreditLedger.sol"; +import {MARKSettlementModule} from "../../../src/settlement/MARKSettlementModule.sol"; +import {IVerifier} from "../../../src/interfaces/IVerifier.sol"; +import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; + +contract AlwaysValidVerifier is IVerifier { + function verifyProof( + uint256[2] calldata, + uint256[2][2] calldata, + uint256[2] calldata, + uint256[13] calldata + ) external pure returns (bool) { return true; } +} + +/// @notice End-to-end test for the full pool withdrawal flow: +/// 1. Operator mints RYLA to user via MARKSettlementModule +/// 2. User calls pool.transactWithWithdrawBinding (ZK proof verified by mock) +/// 3. User calls adapter.withdrawWithSig (burns RYLA, pays ETH to recipient) +contract MARKPoolE2ETest is Test { + RYLA internal token; + MARKPool internal pool; + RYLACreditLedger internal ledger; + MARKWithdrawAdapter internal adapter; + MARKSettlementModule internal settlement; + AccessManager internal accessManager; + AlwaysValidVerifier internal verifier; + + address internal admin = makeAddr("admin"); + address internal settlementOperator = makeAddr("settlementOperator"); + address internal recipient = makeAddr("recipient"); + + uint256 internal ownerPk = 0xA11CE; + uint256 internal intentSignerPk = 0xB0B; + address internal creditOwner; + address internal intentSigner; + + uint64 internal constant POOL_ADMIN_ROLE = 1; + uint256 internal constant MINT_AMOUNT = 1 ether; + + // Unique nullifiers and commitments for the pool transact call + bytes32 internal constant N0 = bytes32(uint256(0xDEAD1)); + bytes32 internal constant N1 = bytes32(uint256(0xDEAD2)); + bytes32 internal constant C0 = bytes32(uint256(0xBEEF1)); + bytes32 internal constant C1 = bytes32(uint256(0xBEEF2)); + + uint256[2] internal A; + uint256[2][2] internal B; + uint256[2] internal C_PROOF; + + function setUp() public { + creditOwner = vm.addr(ownerPk); + intentSigner = vm.addr(intentSignerPk); + + // Deploy token + vm.prank(admin); + token = new RYLA(admin); + + // Deploy settlement module (to mint RYLA to creditOwner) + vm.prank(admin); + settlement = new MARKSettlementModule(admin, address(token)); + + // Deploy pool stack + verifier = new AlwaysValidVerifier(); + + vm.startPrank(admin); + accessManager = new AccessManager(admin); + address poseidon = deployCode("PoseidonT3.sol:PoseidonT3"); + pool = new MARKPool(address(accessManager), address(verifier), poseidon); + ledger = new RYLACreditLedger(address(token), address(pool)); + adapter = new MARKWithdrawAdapter(address(accessManager), address(ledger), address(pool)); + ledger.setAdapter(address(adapter)); + + // Configure AccessManager + accessManager.grantRole(POOL_ADMIN_ROLE, admin, 0); + + bytes4[] memory poolSelectors = new bytes4[](3); + poolSelectors[0] = pool.setAssetLedger.selector; + poolSelectors[1] = pool.setProofTypeEnabled.selector; + poolSelectors[2] = pool.pauseWithdrawals.selector; + accessManager.setTargetFunctionRole(address(pool), poolSelectors, POOL_ADMIN_ROLE); + + bytes4[] memory adapterSelectors = new bytes4[](2); + adapterSelectors[0] = adapter.setIntentSigner.selector; + adapterSelectors[1] = adapter.setMaxIntentValidity.selector; + accessManager.setTargetFunctionRole(address(adapter), adapterSelectors, POOL_ADMIN_ROLE); + + vm.warp(block.timestamp + 1); + + pool.setAssetLedger(address(ledger)); + adapter.setIntentSigner(intentSigner, true); + + // Wire RYLA roles + settlement.setOperator(settlementOperator, true); + token.setMinter(address(settlement), true); + token.setBurner(address(settlement), true); + token.setMinter(address(ledger), true); + token.setBurner(address(ledger), true); + vm.stopPrank(); + } + + /// @dev Full flow: mint RYLA -> transactWithWithdrawBinding -> withdrawWithSig + function testFullWithdrawalFlow() public { + // Step 1: Mint RYLA to creditOwner via settlement module + vm.prank(settlementOperator); + settlement.settleMint(creditOwner, MINT_AMOUNT, keccak256("e2e-mint"), bytes("")); + assertEq(token.balanceOf(creditOwner), MINT_AMOUNT); + + // Step 2: creditOwner approves ledger to burn their RYLA + vm.prank(creditOwner); + token.approve(address(ledger), MINT_AMOUNT); + + // Step 3: transactWithWithdrawBinding — records withdraw binding for (creditOwner, recipient, MINT_AMOUNT) + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transactWithWithdrawBinding( + root, nullifiers, commitments, 0, address(0), + creditOwner, recipient, MINT_AMOUNT, + A, B, C_PROOF + ); + + assertTrue(pool.isNullifierUsedGlobal(N0)); + assertTrue(pool.isNullifierUsedGlobal(N1)); + assertEq( + pool.nullifierWithdrawBinding(N0), + pool.computeWithdrawBindingHash(creditOwner, recipient, MINT_AMOUNT) + ); + + // Step 4: Fund adapter with ETH to pay recipient + vm.deal(address(adapter), MINT_AMOUNT); + + // Step 5: Build signatures for withdrawWithSig + uint256 nonce = adapter.withdrawNonce(creditOwner); + uint256 deadline = block.timestamp + 1 hours; + + bytes32 intentHash = adapter.computeWithdrawIntentHash( + creditOwner, recipient, MINT_AMOUNT, nullifiers, nonce, deadline + ); + bytes32 digest = MessageHashUtils.toEthSignedMessageHash(intentHash); + + (uint8 v1, bytes32 r1, bytes32 s1) = vm.sign(ownerPk, digest); + (uint8 v2, bytes32 r2, bytes32 s2) = vm.sign(intentSignerPk, digest); + bytes memory ownerSig = abi.encodePacked(r1, s1, v1); + bytes memory intentSig = abi.encodePacked(r2, s2, v2); + + // Step 6: Execute withdrawal — burns RYLA, sends ETH to recipient + uint256 recipientEthBefore = recipient.balance; + + adapter.withdrawWithSig( + creditOwner, recipient, MINT_AMOUNT, + nullifiers, nonce, deadline, + ownerSig, intentSig + ); + + // Verify RYLA burned + assertEq(token.balanceOf(creditOwner), 0); + assertEq(token.totalSupply(), 0); + + // Verify ETH paid to recipient + assertEq(recipient.balance, recipientEthBefore + MINT_AMOUNT); + + // Verify nonce incremented + assertEq(adapter.withdrawNonce(creditOwner), nonce + 1); + } + + /// @dev Replay of the same nullifiers is rejected by the adapter. + function testNullifierReplayRejected() public { + vm.prank(settlementOperator); + settlement.settleMint(creditOwner, MINT_AMOUNT * 2, keccak256("e2e-mint-2"), bytes("")); + + vm.prank(creditOwner); + token.approve(address(ledger), MINT_AMOUNT * 2); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transactWithWithdrawBinding( + root, nullifiers, commitments, 0, address(0), + creditOwner, recipient, MINT_AMOUNT, + A, B, C_PROOF + ); + + vm.deal(address(adapter), MINT_AMOUNT * 2); + + uint256 nonce = adapter.withdrawNonce(creditOwner); + uint256 deadline = block.timestamp + 1 hours; + bytes32 intentHash = adapter.computeWithdrawIntentHash( + creditOwner, recipient, MINT_AMOUNT, nullifiers, nonce, deadline + ); + bytes32 digest = MessageHashUtils.toEthSignedMessageHash(intentHash); + (uint8 v1, bytes32 r1, bytes32 s1) = vm.sign(ownerPk, digest); + (uint8 v2, bytes32 r2, bytes32 s2) = vm.sign(intentSignerPk, digest); + + adapter.withdrawWithSig( + creditOwner, recipient, MINT_AMOUNT, + nullifiers, nonce, deadline, + abi.encodePacked(r1, s1, v1), + abi.encodePacked(r2, s2, v2) + ); + + // Second attempt with same nullifiers must revert with NullifierAlreadyClaimed + uint256 nonce2 = adapter.withdrawNonce(creditOwner); + bytes32 intentHash2 = adapter.computeWithdrawIntentHash( + creditOwner, recipient, MINT_AMOUNT, nullifiers, nonce2, deadline + ); + bytes32 digest2 = MessageHashUtils.toEthSignedMessageHash(intentHash2); + (uint8 v3, bytes32 r3, bytes32 s3) = vm.sign(ownerPk, digest2); + (uint8 v4, bytes32 r4, bytes32 s4) = vm.sign(intentSignerPk, digest2); + + vm.expectRevert(); + adapter.withdrawWithSig( + creditOwner, recipient, MINT_AMOUNT, + nullifiers, nonce2, deadline, + abi.encodePacked(r3, s3, v3), + abi.encodePacked(r4, s4, v4) + ); + } + + /// @dev Withdraw binding mismatch (wrong recipient) is rejected. + function testBindingMismatchRejected() public { + vm.prank(settlementOperator); + settlement.settleMint(creditOwner, MINT_AMOUNT, keccak256("e2e-mint-3"), bytes("")); + + vm.prank(creditOwner); + token.approve(address(ledger), MINT_AMOUNT); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + // Bind to `recipient` + pool.transactWithWithdrawBinding( + root, nullifiers, commitments, 0, address(0), + creditOwner, recipient, MINT_AMOUNT, + A, B, C_PROOF + ); + + vm.deal(address(adapter), MINT_AMOUNT); + + address wrongRecipient = makeAddr("wrong"); + uint256 nonce = adapter.withdrawNonce(creditOwner); + uint256 deadline = block.timestamp + 1 hours; + bytes32 intentHash = adapter.computeWithdrawIntentHash( + creditOwner, wrongRecipient, MINT_AMOUNT, nullifiers, nonce, deadline + ); + bytes32 digest = MessageHashUtils.toEthSignedMessageHash(intentHash); + (uint8 v1, bytes32 r1, bytes32 s1) = vm.sign(ownerPk, digest); + (uint8 v2, bytes32 r2, bytes32 s2) = vm.sign(intentSignerPk, digest); + + vm.expectRevert(); + adapter.withdrawWithSig( + creditOwner, wrongRecipient, MINT_AMOUNT, + nullifiers, nonce, deadline, + abi.encodePacked(r1, s1, v1), + abi.encodePacked(r2, s2, v2) + ); + } +} diff --git a/contracts/test/invariant/pool/MARKPoolInvariants.t.sol b/contracts/test/invariant/pool/MARKPoolInvariants.t.sol new file mode 100644 index 0000000..4f5a5cf --- /dev/null +++ b/contracts/test/invariant/pool/MARKPoolInvariants.t.sol @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {StdInvariant} from "forge-std/StdInvariant.sol"; +import {Test} from "forge-std/Test.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; +import {MARKPool} from "../../../src/pool/MARKPool.sol"; +import {IVerifier} from "../../../src/interfaces/IVerifier.sol"; +import {ICreditLedger} from "../../../src/interfaces/ICreditLedger.sol"; +import {PoolErrors} from "../../../src/pool/errors/PoolErrors.sol"; + +contract AlwaysValidVerifier is IVerifier { + function verifyProof( + uint256[2] calldata, + uint256[2][2] calldata, + uint256[2] calldata, + uint256[13] calldata + ) external pure returns (bool) { return true; } +} + +contract NoOpLedger is ICreditLedger { + function credit(address, uint256) external {} + function debit(address, uint256) external {} + function creditBalanceOf(address) external pure returns (uint256) { return 0; } + function totalCreditsMinted() external pure returns (uint256) { return 0; } + function totalCreditsBurned() external pure returns (uint256) { return 0; } + function totalCreditsOutstanding() external pure returns (uint256) { return 0; } + function maxCredits() external pure returns (uint256) { return type(uint256).max; } +} + +contract MARKPoolHandler is Test { + MARKPool public immutable POOL; + + // Tracks nullifiers spent during this run + bytes32[] internal _spentNullifiers; + // Tracks withdraw bindings recorded: nullifier => binding hash + mapping(bytes32 => bytes32) internal _recordedBindings; + + uint256 internal _nonce; + + constructor(MARKPool pool) { + POOL = pool; + } + + /// @dev Calls transact with unique nullifiers and commitments each time. + function transact(uint8 seed) external { + bytes32 root = POOL.getMerkleRoot(); + bytes32 n0 = keccak256(abi.encodePacked("n0", _nonce)); + bytes32 n1 = keccak256(abi.encodePacked("n1", _nonce)); + bytes32 c0 = keccak256(abi.encodePacked("c0", _nonce)); + bytes32 c1 = keccak256(abi.encodePacked("c1", _nonce)); + _nonce++; + + // Skip if nullifiers already used (shouldn't happen with unique nonce) + if (POOL.isNullifierUsedGlobal(n0) || POOL.isNullifierUsedGlobal(n1)) return; + + uint256[2] memory a; + uint256[2][2] memory b; + uint256[2] memory c; + + bytes32[2] memory nullifiers = [n0, n1]; + bytes32[2] memory commitments = [c0, c1]; + + try POOL.transact(root, nullifiers, commitments, 0, address(0), a, b, c) { + _spentNullifiers.push(n0); + _spentNullifiers.push(n1); + } catch {} + + seed; // suppress unused warning + } + + /// @dev Calls transactWithWithdrawBinding with unique nullifiers. + function transactWithBinding(uint8 seed, uint64 amount) external { + if (amount == 0) return; + bytes32 root = POOL.getMerkleRoot(); + bytes32 n0 = keccak256(abi.encodePacked("bn0", _nonce)); + bytes32 n1 = keccak256(abi.encodePacked("bn1", _nonce)); + bytes32 c0 = keccak256(abi.encodePacked("bc0", _nonce)); + bytes32 c1 = keccak256(abi.encodePacked("bc1", _nonce)); + _nonce++; + + if (POOL.isNullifierUsedGlobal(n0) || POOL.isNullifierUsedGlobal(n1)) return; + + address owner = address(uint160(uint256(keccak256(abi.encodePacked("owner", seed))))); + address recipient = address(uint160(uint256(keccak256(abi.encodePacked("recipient", seed))))); + + uint256[2] memory a; + uint256[2][2] memory b; + uint256[2] memory c; + + bytes32[2] memory nullifiers = [n0, n1]; + bytes32[2] memory commitments = [c0, c1]; + + bytes32 expectedBinding = POOL.computeWithdrawBindingHash(owner, recipient, amount); + + try POOL.transactWithWithdrawBinding( + root, nullifiers, commitments, 0, address(0), owner, recipient, amount, a, b, c + ) { + _spentNullifiers.push(n0); + _spentNullifiers.push(n1); + _recordedBindings[n0] = expectedBinding; + _recordedBindings[n1] = expectedBinding; + } catch {} + } + + function spentNullifiers() external view returns (bytes32[] memory) { + return _spentNullifiers; + } + + function recordedBinding(bytes32 nullifier) external view returns (bytes32) { + return _recordedBindings[nullifier]; + } +} + +contract MARKPoolInvariants is StdInvariant, Test { + MARKPool internal pool; + MARKPoolHandler internal handler; + AccessManager internal accessManager; + + address internal admin = makeAddr("admin"); + + function setUp() public { + AlwaysValidVerifier verifier = new AlwaysValidVerifier(); + NoOpLedger ledger = new NoOpLedger(); + + vm.startPrank(admin); + accessManager = new AccessManager(admin); + address poseidon = deployCode("PoseidonT3.sol:PoseidonT3"); + pool = new MARKPool(address(accessManager), address(verifier), poseidon); + + bytes4[] memory selectors = new bytes4[](2); + selectors[0] = pool.setAssetLedger.selector; + selectors[1] = pool.setProofTypeEnabled.selector; + accessManager.setTargetFunctionRole(address(pool), selectors, 1); + accessManager.grantRole(1, admin, 0); + vm.warp(block.timestamp + 1); + + pool.setAssetLedger(address(ledger)); + vm.stopPrank(); + + handler = new MARKPoolHandler(pool); + targetContract(address(handler)); + } + + /// @dev Once a nullifier is spent, it stays spent. + function invariant_nullifiersAreNeverUnspent() public view { + bytes32[] memory spent = handler.spentNullifiers(); + for (uint256 i = 0; i < spent.length; i++) { + assertTrue(pool.isNullifierUsedGlobal(spent[i]), "nullifier was unspent"); + } + } + + /// @dev Withdraw bindings are immutable once recorded. + function invariant_withdrawBindingsAreImmutable() public view { + bytes32[] memory spent = handler.spentNullifiers(); + for (uint256 i = 0; i < spent.length; i++) { + bytes32 recorded = handler.recordedBinding(spent[i]); + if (recorded == bytes32(0)) continue; + assertEq( + pool.nullifierWithdrawBinding(spent[i]), + recorded, + "withdraw binding changed" + ); + } + } + + /// @dev Root queue tail only grows — roots are never removed from the queue. + function invariant_rootQueueOnlyGrows() public view { + assertGe(pool.rootQueueTail(), pool.rootQueueHead(), "root queue tail behind head"); + } +} diff --git a/contracts/test/unit/MARKPoolDeployScripts.t.sol b/contracts/test/unit/MARKPoolDeployScripts.t.sol new file mode 100644 index 0000000..4c56aab --- /dev/null +++ b/contracts/test/unit/MARKPoolDeployScripts.t.sol @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Test} from "forge-std/Test.sol"; +import {RYLA} from "../../src/token/RYLA.sol"; +import {MARKPool} from "../../src/pool/MARKPool.sol"; +import {MARKWithdrawAdapter} from "../../src/withdraw/MARKWithdrawAdapter.sol"; +import {RYLACreditLedger} from "../../src/pool/RYLACreditLedger.sol"; +import {IVerifier} from "../../src/interfaces/IVerifier.sol"; +import {DeployMARKPool} from "../../script/deploy/pool/DeployMARKPool.s.sol"; + +contract MockVerifier is IVerifier { + function verifyProof( + uint256[2] calldata, + uint256[2][2] calldata, + uint256[2] calldata, + uint256[13] calldata + ) external pure returns (bool) { return true; } +} + +contract MARKPoolDeployScriptsTest is Test { + uint256 internal constant DEPLOYER_PK = 0xA11CE; + + DeployMARKPool internal deployPool; + MockVerifier internal verifier; + + address internal deployer; + address internal intentSigner; + + function setUp() public { + deployPool = new DeployMARKPool(); + verifier = new MockVerifier(); + + deployer = vm.addr(DEPLOYER_PK); + intentSigner = makeAddr("intentSigner"); + + vm.setEnv("PRIVATE_KEY", vm.toString(DEPLOYER_PK)); + vm.setEnv("MARK_POOL_VERIFIER", vm.toString(address(verifier))); + vm.setEnv("MARK_POOL_INTENT_SIGNER", vm.toString(address(0))); + // Deploy local PoseidonT3 (test runner bypasses EIP-170 size check) + address poseidon = deployCode("PoseidonT3.sol:PoseidonT3"); + vm.setEnv("MARK_POOL_POSEIDON", vm.toString(poseidon)); + } + + function testDeployMARKPoolWiresAllContracts() public { + vm.prank(deployer); + RYLA token = new RYLA(deployer); + + vm.setEnv("MARK_RYLA_TOKEN", vm.toString(address(token))); + + DeployMARKPool.Deployed memory d = deployPool.run(); + + // Pool wired to ledger + assertEq(address(d.pool.ASSET_LEDGER()), address(d.ledger)); + + // Ledger wired to pool and adapter + assertEq(d.ledger.POOL(), address(d.pool)); + assertEq(d.ledger.ADAPTER(), address(d.adapter)); + + // Adapter wired to ledger and pool + assertEq(address(d.adapter.ASSET_LEDGER()), address(d.ledger)); + assertEq(address(d.adapter.PROOF_POOL()), address(d.pool)); + + // RYLA roles granted to ledger + assertTrue(token.hasRole(token.MINTER_ROLE(), address(d.ledger))); + assertTrue(token.hasRole(token.BURNER_ROLE(), address(d.ledger))); + } + + function testDeployMARKPoolSetsIntentSignerWhenProvided() public { + vm.prank(deployer); + RYLA token = new RYLA(deployer); + + vm.setEnv("MARK_RYLA_TOKEN", vm.toString(address(token))); + vm.setEnv("MARK_POOL_INTENT_SIGNER", vm.toString(intentSigner)); + + DeployMARKPool.Deployed memory d = deployPool.run(); + + assertTrue(d.adapter.intentSigners(intentSigner)); + } + + function testDeployMARKPoolRevertsWhenMissingTokenAdmin() public { + address nonAdmin = makeAddr("nonAdmin"); + vm.prank(nonAdmin); + RYLA token = new RYLA(nonAdmin); + + vm.setEnv("MARK_RYLA_TOKEN", vm.toString(address(token))); + + vm.expectRevert(DeployMARKPool.MissingTokenAdminForRoleGrants.selector); + deployPool.run(); + } +} diff --git a/contracts/test/unit/pool/MARKPool.t.sol b/contracts/test/unit/pool/MARKPool.t.sol new file mode 100644 index 0000000..ca5fc98 --- /dev/null +++ b/contracts/test/unit/pool/MARKPool.t.sol @@ -0,0 +1,390 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Test} from "forge-std/Test.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; +import {MARKPool} from "../../../src/pool/MARKPool.sol"; +import {PoolErrors} from "../../../src/pool/errors/PoolErrors.sol"; +import {IVerifier} from "../../../src/interfaces/IVerifier.sol"; +import {ICreditLedger} from "../../../src/interfaces/ICreditLedger.sol"; + +contract MockVerifier is IVerifier { + bool private _result; + constructor(bool result) { _result = result; } + function verifyProof( + uint256[2] calldata, + uint256[2][2] calldata, + uint256[2] calldata, + uint256[13] calldata + ) external view returns (bool) { return _result; } +} + +contract MockLedger is ICreditLedger { + mapping(address => uint256) public balances; + uint256 public minted; + uint256 public burned; + + function credit(address to, uint256 amount) external { balances[to] += amount; minted += amount; } + function debit(address from, uint256 amount) external { balances[from] -= amount; burned += amount; } + function creditBalanceOf(address account) external view returns (uint256) { return balances[account]; } + function totalCreditsMinted() external view returns (uint256) { return minted; } + function totalCreditsBurned() external view returns (uint256) { return burned; } + function totalCreditsOutstanding() external view returns (uint256) { return minted - burned; } + function maxCredits() external pure returns (uint256) { return type(uint256).max; } +} + +contract MARKPoolTest is Test { + MARKPool internal pool; + MockVerifier internal mockOk; + MockVerifier internal mockFail; + MockLedger internal ledger; + AccessManager internal accessManager; + + address internal admin = makeAddr("admin"); + + // Valid BN254 field elements for commitments/nullifiers + bytes32 internal constant C0 = bytes32(uint256(1)); + bytes32 internal constant C1 = bytes32(uint256(2)); + bytes32 internal constant N0 = bytes32(uint256(3)); + bytes32 internal constant N1 = bytes32(uint256(4)); + + uint256[2] internal A; + uint256[2][2] internal B; + uint256[2] internal C_PROOF; + + function setUp() public { + mockOk = new MockVerifier(true); + mockFail = new MockVerifier(false); + ledger = new MockLedger(); + + vm.startPrank(admin); + accessManager = new AccessManager(admin); + address poseidon = deployCode("PoseidonT3.sol:PoseidonT3"); + pool = new MARKPool(address(accessManager), address(mockOk), poseidon); + + // Grant admin all restricted selectors via a custom role (role 1) + bytes4[] memory selectors = new bytes4[](14); + selectors[0] = pool.pause.selector; + selectors[1] = pool.unpause.selector; + selectors[2] = pool.pauseWithdrawals.selector; + selectors[3] = pool.unpauseWithdrawals.selector; + selectors[4] = pool.setVerifier.selector; + selectors[5] = pool.setProofTypeEnabled.selector; + selectors[6] = pool.emergencyDisableProofType.selector; + selectors[7] = pool.setMaxRootAge.selector; + selectors[8] = pool.setFeeBurnBps.selector; + selectors[9] = pool.setMinFee.selector; + selectors[10] = pool.setProtocolEpoch.selector; + selectors[11] = pool.setBridgeOutEntrypoint.selector; + selectors[12] = pool.bridgeIn.selector; + selectors[13] = pool.setAssetLedger.selector; + accessManager.setTargetFunctionRole(address(pool), selectors, 1); + accessManager.grantRole(1, admin, 0); + vm.warp(block.timestamp + 1); // ensure role grant is active + pool.setAssetLedger(address(ledger)); + vm.stopPrank(); + } + + // --- transact --- + + function testTransactHappyPath() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + + assertTrue(pool.isNullifierUsedGlobal(N0)); + assertTrue(pool.isNullifierUsedGlobal(N1)); + } + + function testTransactRevertsOnNullifierReplay() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + + // New commitments, same nullifiers + bytes32[2] memory commitments2 = [bytes32(uint256(5)), bytes32(uint256(6))]; + vm.expectRevert(PoolErrors.NullifierUsed.selector); + pool.transact(root, nullifiers, commitments2, 0, address(0), A, B, C_PROOF); + } + + function testTransactRevertsOnUnknownRoot() public { + bytes32 badRoot = bytes32(uint256(999)); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.UnknownRoot.selector); + pool.transact(badRoot, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + function testTransactRevertsOnInvalidProof() public { + // Swap to failing verifier + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setVerifier(pool.PROOF_TYPE_TRANSFER(), address(mockFail)); + pool.unpauseWithdrawals(); + vm.stopPrank(); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.InvalidProof.selector); + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + function testTransactRevertsOnDuplicateNullifiers() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N0]; // duplicate + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.NullifierDuplicate.selector); + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + function testTransactRevertsOnDuplicateCommitments() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C0]; // duplicate + + vm.expectRevert(PoolErrors.CommitmentDuplicate.selector); + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + function testTransactRevertsWhenWithdrawalsPaused() public { + vm.prank(admin); + pool.pauseWithdrawals(); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.WithdrawalsArePaused.selector); + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + // --- root expiry --- + + function testRootExpiresAfterMaxRootAge() public { + // First transact to add a new root + bytes32 initialRoot = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + pool.transact(initialRoot, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + + // Set max root age (tightening from 0 requires pause) + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setMaxRootAge(1 days); + pool.unpauseWithdrawals(); + vm.stopPrank(); + + // Warp past expiry + vm.warp(block.timestamp + 2 days); + + // initialRoot should now be expired (not the latest root) + assertFalse(pool.isRootUsable(initialRoot)); + } + + function testLatestRootAlwaysUsable() public { + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setMaxRootAge(1 days); + pool.unpauseWithdrawals(); + vm.stopPrank(); + + vm.warp(block.timestamp + 2 days); + + // Latest root is always usable regardless of age + assertTrue(pool.isRootUsable(pool.getMerkleRoot())); + } + + // --- fee --- + + function testFeeCreditedToRelayer() public { + address relayer = makeAddr("relayer"); + // feeBurnBps defaults to 0, so all fee goes to relayer — no state change needed + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transact(root, nullifiers, commitments, 100, relayer, A, B, C_PROOF); + + assertEq(ledger.balances(relayer), 100); + } + + function testFeeRevertsWithZeroRelayerWhenFeeNonZero() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.InvalidRelayer.selector); + pool.transact(root, nullifiers, commitments, 100, address(0), A, B, C_PROOF); + } + + function testFeeTooLowReverts() public { + vm.prank(admin); + pool.setMinFee(1); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.FeeTooLow.selector); + pool.transact(root, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + } + + // --- pruneRoots --- + + function testPruneRootsRemovesExpiredRoots() public { + bytes32 initialRoot = pool.getMerkleRoot(); + + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setMaxRootAge(1 days); + pool.unpauseWithdrawals(); + vm.stopPrank(); + + // Add a new root + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + pool.transact(initialRoot, nullifiers, commitments, 0, address(0), A, B, C_PROOF); + + vm.warp(block.timestamp + 2 days); + + uint256 pruned = pool.pruneRoots(10); + assertGt(pruned, 0); + assertFalse(pool.knownRoots(initialRoot)); + } + + // --- bridgeOut access control --- + + function testBridgeOutRevertsWhenEntrypointNotSet() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.BridgeOutDisabled.selector); + pool.bridgeOut(root, nullifiers, commitments, 0, address(0), 902, A, B, C_PROOF); + } + + function testBridgeOutRevertsWhenCallerNotEntrypoint() public { + address entrypoint = makeAddr("entrypoint"); + vm.etch(entrypoint, hex"00"); + + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setBridgeOutEntrypoint(entrypoint); + pool.unpauseWithdrawals(); + vm.stopPrank(); + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.UnauthorizedBridgeOutCaller.selector); + pool.bridgeOut(root, nullifiers, commitments, 0, address(0), 902, A, B, C_PROOF); + } + + // --- bridgeIn access control --- + + function testBridgeInRevertsWhenCallerNotRestricted() public { + bytes32[2] memory commitments = [C0, C1]; + vm.expectRevert(abi.encodeWithSignature("AccessManagedUnauthorized(address)", address(this))); + pool.bridgeIn(901, bytes32(uint256(1)), commitments); + } + + function testBridgeInRevertsOnSameChain() public { + bytes32[2] memory commitments = [C0, C1]; + vm.prank(admin); + vm.expectRevert(PoolErrors.SourceIsDestination.selector); + pool.bridgeIn(block.chainid, bytes32(uint256(1)), commitments); + } + + function testBridgeInRevertsOnMessageReplay() public { + bytes32[2] memory commitments = [C0, C1]; + bytes32 messageId = bytes32(uint256(123)); + + vm.prank(admin); + pool.bridgeIn(901, messageId, commitments); + + vm.prank(admin); + vm.expectRevert(PoolErrors.BridgeMessageAlreadyProcessed.selector); + pool.bridgeIn(901, messageId, commitments); + } + + // --- transactWithWithdrawBinding --- + + function testTransactWithWithdrawBindingRecordsBinding() public { + address owner = makeAddr("owner"); + address recipient = makeAddr("recipient"); + uint256 amount = 1 ether; + + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + pool.transactWithWithdrawBinding(root, nullifiers, commitments, 0, address(0), owner, recipient, amount, A, B, C_PROOF); + + bytes32 expectedBinding = pool.computeWithdrawBindingHash(owner, recipient, amount); + assertEq(pool.nullifierWithdrawBinding(N0), expectedBinding); + assertEq(pool.nullifierWithdrawBinding(N1), expectedBinding); + } + + function testTransactWithWithdrawBindingRevertsOnZeroAmount() public { + bytes32 root = pool.getMerkleRoot(); + bytes32[2] memory nullifiers = [N0, N1]; + bytes32[2] memory commitments = [C0, C1]; + + vm.expectRevert(PoolErrors.InvalidWithdrawAmount.selector); + pool.transactWithWithdrawBinding(root, nullifiers, commitments, 0, address(0), makeAddr("o"), makeAddr("r"), 0, A, B, C_PROOF); + } + + // --- admin config --- + + function testSetVerifierRequiresPauseFirst() public { + // proof type is enabled, withdrawals not paused — setVerifier should revert + MockVerifier newVerifier = new MockVerifier(true); + uint8 proofType = pool.PROOF_TYPE_TRANSFER(); // read before expectRevert + vm.startPrank(admin); + vm.expectRevert(PoolErrors.WithdrawalsNotPaused.selector); + pool.setVerifier(proofType, address(newVerifier)); + vm.stopPrank(); + } + + function testSetProtocolEpochCanOnlyIncrease() public { + vm.startPrank(admin); + pool.pauseWithdrawals(); + pool.setProtocolEpoch(5); + vm.expectRevert(PoolErrors.EpochCanOnlyIncrease.selector); + pool.setProtocolEpoch(3); + vm.stopPrank(); + } + + function testEmergencyDisableProofType() public { + vm.startPrank(admin); + pool.emergencyDisableProofType(pool.PROOF_TYPE_TRANSFER()); + vm.stopPrank(); + assertFalse(pool.proofTypeEnabled(pool.PROOF_TYPE_TRANSFER())); + } + function testConstructorRevertsOnZeroPoseidon() public { + vm.startPrank(admin); + AccessManager am = new AccessManager(admin); + vm.expectRevert(PoolErrors.InvalidPoseidon.selector); + new MARKPool(address(am), address(mockOk), address(0)); + vm.stopPrank(); + } + + function testConstructorRevertsOnEOAPoseidon() public { + vm.startPrank(admin); + AccessManager am = new AccessManager(admin); + vm.expectRevert(PoolErrors.PoseidonMustBeContract.selector); + new MARKPool(address(am), address(mockOk), makeAddr("eoa")); + vm.stopPrank(); + } + +} \ No newline at end of file diff --git a/contracts/test/unit/pool/RYLACreditLedger.t.sol b/contracts/test/unit/pool/RYLACreditLedger.t.sol new file mode 100644 index 0000000..802e7a9 --- /dev/null +++ b/contracts/test/unit/pool/RYLACreditLedger.t.sol @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Test} from "forge-std/Test.sol"; +import {RYLACreditLedger} from "../../../src/pool/RYLACreditLedger.sol"; +import {RYLA} from "../../../src/token/RYLA.sol"; + +contract RYLACreditLedgerTest is Test { + RYLACreditLedger internal ledger; + RYLA internal token; + + address internal admin = makeAddr("admin"); + address internal pool = makeAddr("pool"); + address internal adapter = makeAddr("adapter"); + address internal user = makeAddr("user"); + address internal other = makeAddr("other"); + + function setUp() public { + // Give pool and adapter contract bytecode so code.length checks pass + vm.etch(pool, hex"00"); + vm.etch(adapter, hex"00"); + + vm.startPrank(admin); + token = new RYLA(admin); + ledger = new RYLACreditLedger(address(token), pool); + ledger.setAdapter(adapter); + token.setMinter(address(ledger), true); + token.setBurner(address(ledger), true); + vm.stopPrank(); + } + + function testCreditMintsToRecipient() public { + vm.prank(pool); + ledger.credit(user, 100e18); + assertEq(token.balanceOf(user), 100e18); + } + + function testCreditTracksTotal() public { + vm.prank(pool); + ledger.credit(user, 100e18); + assertEq(ledger.totalCreditsMinted(), 100e18); + assertEq(ledger.totalCreditsOutstanding(), 100e18); + } + + function testDebitBurnsTokens() public { + vm.prank(pool); + ledger.credit(user, 100e18); + + vm.prank(user); + token.approve(address(ledger), 100e18); + + vm.prank(adapter); + ledger.debit(user, 100e18); + + assertEq(token.balanceOf(user), 0); + assertEq(ledger.totalCreditsBurned(), 100e18); + assertEq(ledger.totalCreditsOutstanding(), 0); + } + + function testCreditRevertsForNonPool() public { + vm.prank(other); + vm.expectRevert(RYLACreditLedger.Unauthorized.selector); + ledger.credit(user, 100e18); + } + + function testDebitRevertsForNonAdapter() public { + vm.prank(other); + vm.expectRevert(RYLACreditLedger.Unauthorized.selector); + ledger.debit(user, 100e18); + } + + function testDebitRevertsForPool() public { + vm.prank(pool); + vm.expectRevert(RYLACreditLedger.Unauthorized.selector); + ledger.debit(user, 100e18); + } + + function testSetAdapterRevertsIfAlreadySet() public { + vm.prank(admin); + vm.expectRevert(RYLACreditLedger.AdapterAlreadySet.selector); + ledger.setAdapter(makeAddr("other-adapter")); + } + + function testSetAdapterRevertsOnZeroAddress() public { + vm.prank(admin); + RYLACreditLedger fresh = new RYLACreditLedger(address(token), pool); + vm.prank(admin); + vm.expectRevert(RYLACreditLedger.ZeroAddress.selector); + fresh.setAdapter(address(0)); + } + + function testSetAdapterRevertsForNonOwner() public { + vm.prank(admin); + RYLACreditLedger fresh = new RYLACreditLedger(address(token), pool); + vm.prank(other); + vm.expectRevert(RYLACreditLedger.Unauthorized.selector); + fresh.setAdapter(makeAddr("attacker")); + } + + function testConstructorRevertsOnZeroToken() public { + vm.expectRevert(RYLACreditLedger.ZeroAddress.selector); + new RYLACreditLedger(address(0), pool); + } + + function testConstructorRevertsOnZeroPool() public { + vm.expectRevert(RYLACreditLedger.ZeroAddress.selector); + new RYLACreditLedger(address(token), address(0)); + } + + function testCreditBalanceOf() public { + vm.prank(pool); + ledger.credit(user, 50e18); + assertEq(ledger.creditBalanceOf(user), 50e18); + } + + function testConstructorRevertsOnEOAToken() public { + vm.expectRevert(RYLACreditLedger.InvalidContract.selector); + new RYLACreditLedger(makeAddr("eoa-token"), pool); + } + + function testConstructorRevertsOnEOAPool() public { + vm.expectRevert(RYLACreditLedger.InvalidContract.selector); + new RYLACreditLedger(address(token), makeAddr("eoa-pool")); + } + + function testSetAdapterRevertsOnEOA() public { + vm.prank(admin); + RYLACreditLedger fresh = new RYLACreditLedger(address(token), pool); + vm.prank(admin); + vm.expectRevert(RYLACreditLedger.InvalidContract.selector); + fresh.setAdapter(makeAddr("eoa-adapter")); + } +} diff --git a/contracts/test/unit/withdraw/MARKWithdrawAdapter.t.sol b/contracts/test/unit/withdraw/MARKWithdrawAdapter.t.sol new file mode 100644 index 0000000..340aff3 --- /dev/null +++ b/contracts/test/unit/withdraw/MARKWithdrawAdapter.t.sol @@ -0,0 +1,462 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.25; + +import {Test} from "forge-std/Test.sol"; +import {MARKWithdrawAdapter} from "../../../src/withdraw/MARKWithdrawAdapter.sol"; +import {MARKWithdrawErrors} from "../../../src/withdraw/MARKWithdrawErrors.sol"; +import {RYLACreditLedger} from "../../../src/pool/RYLACreditLedger.sol"; +import {RYLA} from "../../../src/token/RYLA.sol"; +import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol"; + +/// @notice Mock Pool for testing WithdrawAdapter. +/// @dev computeWithdrawBindingHash must match Pool.computeWithdrawBindingHash exactly, +/// including the domain separator, address(this), and block.chainid. +contract MockPool { + bytes32 public constant WITHDRAW_BINDING_DOMAIN = + keccak256("MARKPool.WithdrawBinding.v1"); + + mapping(bytes32 => bytes32) public nullifierWithdrawBinding; + mapping(bytes32 => bool) public nullifierUsed; + + function setWithdrawBinding( + bytes32 nullifier, + address owner, + address recipient, + uint256 amount + ) external { + nullifierWithdrawBinding[nullifier] = + computeWithdrawBindingHash(owner, recipient, amount); + nullifierUsed[nullifier] = true; + } + + function computeWithdrawBindingHash( + address owner, + address recipient, + uint256 amount + ) public view returns (bytes32) { + return keccak256( + abi.encode( + WITHDRAW_BINDING_DOMAIN, + address(this), + block.chainid, + owner, + recipient, + amount + ) + ); + } + + function isNullifierUsedGlobal(bytes32 nullifier) + external + view + returns (bool) + { + return nullifierUsed[nullifier]; + } +} + +/// @notice Unit test for WithdrawAdapter +/// @dev Tests withdrawal execution with signature verification +contract MARKWithdrawAdapterTest is Test { + MockPool public pool; + MARKWithdrawAdapter public adapter; + RYLACreditLedger public ledger; + RYLA public token; + AccessManager public accessManager; + + address public admin = address(0x1); + address public intentSigner = address(0x3); + address public user = address(0x4); + address public recipient = address(0x5); + + uint256 public userPrivateKey = 0xA11CE; + uint256 public intentSignerPrivateKey = 0xB0B; + + function setUp() public { + user = vm.addr(userPrivateKey); + intentSigner = vm.addr(intentSignerPrivateKey); + + accessManager = new AccessManager(admin); + + vm.prank(admin); + token = new RYLA(admin); + + pool = new MockPool(); + ledger = new RYLACreditLedger(address(token), address(pool)); + + adapter = new MARKWithdrawAdapter( + address(accessManager), + address(ledger), + address(pool) + ); + ledger.setAdapter(address(adapter)); + + vm.startPrank(admin); + + bytes4[] memory selectors = new bytes4[](4); + selectors[0] = adapter.setIntentSigner.selector; + selectors[1] = adapter.pause.selector; + selectors[2] = adapter.unpause.selector; + selectors[3] = adapter.setMaxIntentValidity.selector; + + accessManager.setTargetFunctionRole(address(adapter), selectors, 1); + accessManager.grantRole(1, admin, 0); + + vm.warp(block.timestamp + 1 days + 1); + + token.grantRole(token.MINTER_ROLE(), address(ledger)); + token.grantRole(token.BURNER_ROLE(), address(ledger)); + + adapter.setIntentSigner(intentSigner, true); + + vm.deal(address(adapter), 100 ether); + + vm.stopPrank(); + } + + function testComputeWithdrawIntentHash() public view { + bytes32[2] memory nullifiers = [ + keccak256("nullifier1"), + keccak256("nullifier2") + ]; + + bytes32 intentHash = adapter.computeWithdrawIntentHash( + user, + recipient, + 1 ether, + nullifiers, + 0, + block.timestamp + 1 hours + ); + + assertTrue(intentHash != bytes32(0)); + } + + function testComputeWithdrawIntentDigest() public view { + bytes32[2] memory nullifiers = [ + keccak256("nullifier1"), + keccak256("nullifier2") + ]; + + bytes32 digest = adapter.computeWithdrawIntentDigest( + user, + recipient, + 1 ether, + nullifiers, + 0, + block.timestamp + 1 hours + ); + + assertTrue(digest != bytes32(0)); + } + + function testWithdrawWithSigHappyPathIncrementsNonceAndClaimsNullifiers() + public + { + bytes32[2] memory nullifiers = [ + keccak256("n-happy-1"), + keccak256("n-happy-2") + ]; + uint256 amount = 2 ether; + uint256 nonce = adapter.withdrawNonce(user); + uint256 deadline = block.timestamp + 30 minutes; + + _configureBindingAndMint(user, recipient, amount, nullifiers); + (bytes memory ownerSig, bytes memory intentSig) = _signWithdraw( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + userPrivateKey, + intentSignerPrivateKey + ); + + uint256 recipientBefore = recipient.balance; + uint256 userTokenBefore = token.balanceOf(user); + + adapter.withdrawWithSig( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + + assertEq(adapter.withdrawNonce(user), nonce + 1); + assertTrue(adapter.claimedNullifiers(nullifiers[0])); + assertTrue(adapter.claimedNullifiers(nullifiers[1])); + assertEq(recipient.balance, recipientBefore + amount); + assertEq(token.balanceOf(user), userTokenBefore - amount); + } + + function testWithdrawWithSigRevertsForInsufficientLiquidity() public { + MARKWithdrawAdapter emptyAdapter = new MARKWithdrawAdapter( + address(accessManager), + address(ledger), + address(pool) + ); + + bytes32[2] memory nullifiers = [ + keccak256("n-empty-1"), + keccak256("n-empty-2") + ]; + uint256 amount = 1 ether; + uint256 nonce = 0; + uint256 deadline = block.timestamp + 30 minutes; + + _configureBindingAndMint(user, recipient, amount, nullifiers); + + bytes32 intentHash = emptyAdapter.computeWithdrawIntentHash( + user, + recipient, + amount, + nullifiers, + nonce, + deadline + ); + bytes32 digest = keccak256( + abi.encodePacked("\x19Ethereum Signed Message:\n32", intentHash) + ); + + (uint8 ov, bytes32 or_, bytes32 os) = vm.sign(userPrivateKey, digest); + (uint8 iv, bytes32 ir, bytes32 is_) = vm.sign( + intentSignerPrivateKey, + digest + ); + + bytes memory ownerSig = abi.encodePacked(or_, os, ov); + bytes memory intentSig = abi.encodePacked(ir, is_, iv); + + vm.expectRevert(MARKWithdrawErrors.InsufficientLiquidity.selector); + emptyAdapter.withdrawWithSig( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + } + + function testWithdrawWithSigRevertsOnReplayByNonce() public { + bytes32[2] memory nullifiers = [ + keccak256("n-replay-1"), + keccak256("n-replay-2") + ]; + uint256 amount = 1 ether; + uint256 nonce = adapter.withdrawNonce(user); + uint256 deadline = block.timestamp + 30 minutes; + + _configureBindingAndMint(user, recipient, amount, nullifiers); + (bytes memory ownerSig, bytes memory intentSig) = _signWithdraw( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + userPrivateKey, + intentSignerPrivateKey + ); + + adapter.withdrawWithSig( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + + vm.expectRevert(MARKWithdrawErrors.NonceMismatch.selector); + adapter.withdrawWithSig( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + } + + function testWithdrawWithSigRevertsOnBindingMismatch() public { + bytes32[2] memory nullifiers = [ + keccak256("n-bind-1"), + keccak256("n-bind-2") + ]; + uint256 amount = 1 ether; + uint256 nonce = adapter.withdrawNonce(user); + uint256 deadline = block.timestamp + 30 minutes; + + _configureBindingAndMint(user, recipient, amount, nullifiers); + (bytes memory ownerSig, bytes memory intentSig) = _signWithdraw( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + userPrivateKey, + intentSignerPrivateKey + ); + + vm.expectRevert(MARKWithdrawErrors.WithdrawBindingMismatch.selector); + adapter.withdrawWithSig( + user, + makeAddr("other-recipient"), + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + } + + function testWithdrawWithSigRevertsOnUnauthorizedIntentSigner() public { + bytes32[2] memory nullifiers = [ + keccak256("n-auth-1"), + keccak256("n-auth-2") + ]; + uint256 amount = 1 ether; + uint256 nonce = adapter.withdrawNonce(user); + uint256 deadline = block.timestamp + 30 minutes; + + _configureBindingAndMint(user, recipient, amount, nullifiers); + (bytes memory ownerSig, bytes memory intentSig) = _signWithdraw( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + userPrivateKey, + 0xDEAD + ); + + vm.expectRevert(MARKWithdrawErrors.UnauthorizedIntentSigner.selector); + adapter.withdrawWithSig( + user, + recipient, + amount, + nullifiers, + nonce, + deadline, + ownerSig, + intentSig + ); + } + + function testAdapterReceivesNativeTokens() public { + uint256 balanceBefore = address(adapter).balance; + + vm.deal(address(this), 1 ether); + (bool ok, ) = address(adapter).call{value: 1 ether}(""); + + assertTrue(ok); + assertEq(address(adapter).balance, balanceBefore + 1 ether); + } + + function testSetMaxIntentValidity() public { + vm.prank(admin); + adapter.setMaxIntentValidity(2 hours); + + assertEq(adapter.maxIntentValidity(), 2 hours); + } + + function testSetIntentSigner() public { + address newSigner = address(0x999); + + vm.prank(admin); + adapter.setIntentSigner(newSigner, true); + + assertTrue(adapter.intentSigners(newSigner)); + + vm.prank(admin); + adapter.setIntentSigner(newSigner, false); + + assertFalse(adapter.intentSigners(newSigner)); + } + + function testAdapterPause() public { + vm.prank(admin); + adapter.pause(); + + assertTrue(adapter.paused()); + + vm.prank(admin); + adapter.unpause(); + + assertFalse(adapter.paused()); + } + + function _configureBindingAndMint( + address owner, + address withdrawRecipient, + uint256 amount, + bytes32[2] memory nullifiers + ) internal { + pool.setWithdrawBinding(nullifiers[0], owner, withdrawRecipient, amount); + pool.setWithdrawBinding(nullifiers[1], owner, withdrawRecipient, amount); + + vm.prank(address(pool)); + ledger.credit(owner, amount); + + vm.prank(owner); + token.approve(address(ledger), type(uint256).max); + } + + function _signWithdraw( + address owner, + address withdrawRecipient, + uint256 amount, + bytes32[2] memory nullifiers, + uint256 nonce, + uint256 deadline, + uint256 ownerPk, + uint256 intentPk + ) internal view returns (bytes memory ownerSig, bytes memory intentSig) { + bytes32 intentHash = adapter.computeWithdrawIntentHash( + owner, + withdrawRecipient, + amount, + nullifiers, + nonce, + deadline + ); + bytes32 digest = keccak256( + abi.encodePacked("\x19Ethereum Signed Message:\n32", intentHash) + ); + + (uint8 ov, bytes32 or_, bytes32 os) = vm.sign(ownerPk, digest); + (uint8 iv, bytes32 ir, bytes32 is_) = vm.sign(intentPk, digest); + + ownerSig = abi.encodePacked(or_, os, ov); + intentSig = abi.encodePacked(ir, is_, iv); + } + function testWithdrawWithSigRevertsForZeroRecipient() public { + vm.expectRevert(MARKWithdrawErrors.InvalidRecipient.selector); + adapter.withdrawWithSig( + user, + address(0), + 1 ether, + [keccak256("n1"), keccak256("n2")], + 0, + block.timestamp + 1, + bytes(""), + bytes("") + ); + } + +} \ No newline at end of file diff --git a/mprocs.yaml b/mprocs.yaml index 86b023c..662eed1 100644 --- a/mprocs.yaml +++ b/mprocs.yaml @@ -11,6 +11,3 @@ procs: frontend: cwd: . shell: pnpm dev:frontend - deploy-contracts: - cwd: . - shell: pnpm wait-port http://:8420/ready && pnpm deploy:supersim && pnpm deploy:counter-incrementer:supersim diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index caea721..3caff4e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -852,6 +852,7 @@ packages: '@safe-global/safe-gateway-typescript-sdk@3.23.1': resolution: {integrity: sha512-6ORQfwtEJYpalCeVO21L4XXGSdbEMfyp2hEv6cP82afKXSwvse6d3sdelgaPWUxHIsFRkWvHDdzh8IyyKHZKxw==} engines: {node: '>=16'} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. '@scure/base@1.1.9': resolution: {integrity: sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg==}