diff --git a/.github/workflows/mirror_barretenberg_repo.yml b/.github/workflows/mirror_barretenberg_repo.yml deleted file mode 100644 index d4ab13d76e1..00000000000 --- a/.github/workflows/mirror_barretenberg_repo.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Mirror to barretenberg repo - -on: - push: - branches: - - master - paths: - - "barretenberg/**" - - "!barretenberg/.gitrepo" - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} - - - name: Push to branch - run: | - # we push using git subrepo (https://github.com/ingydotnet/git-subrepo) - # with some logic to recover from squashed parent commits - SUBREPO_PATH=barretenberg - # identify ourselves, needed to commit - git config --global user.name AztecBot - git config --global user.email tech@aztecprotocol.com - # push to subrepo, commit to master. The commit is needed - # to continue to replay. If we still hit issues such as this - # action failing due to upstream changes, a manual resolution - # PR with ./scripts/git_subrepo.sh pull will be needed. - ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=master - git push # update .gitrepo on master diff --git a/.github/workflows/mirror_build_system_repo.yml b/.github/workflows/mirror_build_system_repo.yml deleted file mode 100644 index 9e85d3600f0..00000000000 --- a/.github/workflows/mirror_build_system_repo.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Mirror to build-system repo - -on: - push: - branches: - - master - paths: - - "build-system/**" - - "!build-system/.gitrepo" - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} - - - name: Push to branch - run: | - # we push using git subrepo (https://github.com/ingydotnet/git-subrepo) - # with some logic to recover from squashed parent commits - SUBREPO_PATH=build-system - # identify ourselves, needed to commit - git config --global user.name AztecBot - git config --global user.email tech@aztecprotocol.com - # push to subrepo, commit to master. The commit is needed - # to continue to replay. If we still hit issues such as this - # action failing due to upstream changes, a manual resolution - # PR with ./scripts/git_subrepo.sh pull will be needed. - ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=master - git push # update .gitrepo on master diff --git a/.github/workflows/mirror_docs_repo.yml b/.github/workflows/mirror_docs_repo.yml deleted file mode 100644 index 7965b5c867d..00000000000 --- a/.github/workflows/mirror_docs_repo.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Mirror to docs repo - -on: - push: - branches: - - master - paths: - - 'docs/**' - - '!docs/.gitrepo' - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} - - - name: Push to branch - run: | - # we push using git subrepo (https://github.com/ingydotnet/git-subrepo) - # with some logic to recover from squashed parent commits - SUBREPO_PATH=docs - # identify ourselves, needed to commit - git config --global user.name AztecBot - git config --global user.email tech@aztecprotocol.com - # push to subrepo, commit to master. The commit is needed - # to continue to replay. If we still hit issues such as this - # action failing due to upstream changes, a manual resolution - # PR with ./scripts/git_subrepo.sh pull will be needed. - ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=main - git push # update .gitrepo on master diff --git a/.github/workflows/mirror_repos.yml b/.github/workflows/mirror_repos.yml new file mode 100644 index 00000000000..f93244bbce2 --- /dev/null +++ b/.github/workflows/mirror_repos.yml @@ -0,0 +1,100 @@ +# We push using git subrepo (https://github.com/ingydotnet/git-subrepo) +# with some logic to recover from squashed parent commits +# We first identify ourselves, needed to commit. +# Then push to subrepo, commit to master. The commit is needed +# to continue to replay. If we still hit issues such as this +# action failing due to upstream changes, a manual resolution +# PR with ./scripts/git_subrepo.sh pull will be needed. +name: Mirror Repositories + +concurrency: + group: mirror-repositories +on: + schedule: + # Run the workflow every night at 2:00 AM UTC. + - cron: '0 2 * * *' + +jobs: + mirror-to-docs-repo: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} + - name: Push to docs repo + run: | + SUBREPO_PATH=docs + git config --global user.name AztecBot + git config --global user.email tech@aztecprotocol.com + + if ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=main; then + git fetch # in case a commit came after this + git rebase origin/master + git commit --amend -m "$(git log -1 --pretty=%B) [skip ci]" + git push + fi + + mirror-to-build-system-repo: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} + - name: Push to build-system repo + run: | + SUBREPO_PATH=build-system + git config --global user.name AztecBot + git config --global user.email tech@aztecprotocol.com + + if ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=main; then + git fetch # in case a commit came after this + git rebase origin/master + git commit --amend -m "$(git log -1 --pretty=%B) [skip ci]" + git push + fi + + mirror-to-barretenberg-repo: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} + - name: Push to barretenberg repo + run: | + SUBREPO_PATH=barretenberg + git config --global user.name AztecBot + git config --global user.email tech@aztecprotocol.com + + if ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=main; then + git fetch # in case a commit came after this + git rebase origin/master + git commit --amend -m "$(git log -1 --pretty=%B) [skip ci]" + git push + fi + + mirror-to-aztec-nr-repo: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.AZTEC_BOT_GITHUB_TOKEN }} + - name: Push to aztec-nr repo + run: | + SUBREPO_PATH=yarn-project/aztec-nr + git config --global user.name AztecBot + git config --global user.email tech@aztecprotocol.com + + if ./scripts/git_subrepo.sh push $SUBREPO_PATH --branch=main; then + git fetch # in case a commit came after this + git rebase origin/master + git commit --amend -m "$(git log -1 --pretty=%B) [skip ci]" + git push + fi \ No newline at end of file diff --git a/barretenberg/.gitrepo b/barretenberg/.gitrepo index c7afea8c09a..875ba73837d 100644 --- a/barretenberg/.gitrepo +++ b/barretenberg/.gitrepo @@ -5,8 +5,8 @@ ; [subrepo] remote = https://github.com/AztecProtocol/barretenberg - branch = master - commit = 7edb1644d0ae472a70fc3554b7d2cfc6c5496168 - parent = 404ec34d38e1a9c3fbe7a3cdb6e88c28f62f72e4 + branch = main + commit = ae9f99c3caf0213882d843577374b03871cc7092 + parent = c8a5cfb375b498475503c12cc83fcdba39f2ec5f method = merge cmdver = 0.4.6 diff --git a/bootstrap.sh b/bootstrap.sh index 88bca947176..12da08e2b23 100755 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -1,29 +1,19 @@ #!/bin/bash +# Usage: +# Bootstraps the repo. End to end tests should be runnable after a bootstrap: +# ./bootstrap.sh +# Run a second time to perform a "light bootstrap", rebuilds code that's changed: +# ./bootstrap.sh +# Force a clean of the repo before performing a full bootstrap, erases untracked files, be careful! +# ./bootstrap.sh clean set -eu export CMD=${1:-} cd "$(dirname "$0")" -# Lightweight bootstrap. Run `./bootstrap.sh clean` to bypass. -if [ -f .bootstrapped ]; then - echo -e '\033[1mRebuild L1 contracts...\033[0m' - (cd l1-contracts && forge build) - - echo -e '\n\033[1mUpdate npm deps...\033[0m' - (cd yarn-project && yarn install) - - echo -e '\n\033[1mRebuild Noir contracts...\033[0m' - (cd yarn-project/noir-contracts && yarn noir:build:all 2> /dev/null) - - echo -e '\n\033[1mRebuild barretenberg wasm...\033[0m' - (cd barretenberg/cpp && cmake --build --preset wasm && cmake --build --preset wasm-threads) - - echo -e '\n\033[1mRebuild circuits wasm...\033[0m' - (cd circuits/cpp && cmake --build --preset wasm -j --target aztec3-circuits.wasm) - - exit 0 -fi +# Bump this number to force a full bootstrap. +VERSION=1 # Remove all untracked files and directories. if [ -n "$CMD" ]; then @@ -34,21 +24,39 @@ if [ -n "$CMD" ]; then if [ "$user_input" != "y" ] && [ "$user_input" != "Y" ]; then exit 1 fi - rm .bootstrapped + rm -f .bootstrapped rm -rf .git/hooks/* rm -rf .git/modules/* git clean -fd for SUBMODULE in $(git config --file .gitmodules --get-regexp path | awk '{print $2}'); do rm -rf $SUBMODULE done - git submodule update --init --recursive - exit 0 else echo "Unknown command: $CLEAN" exit 1 fi fi +# Lightweight bootstrap. Run `./bootstrap.sh clean` to bypass. +if [[ -f .bootstrapped && $(cat .bootstrapped) -eq "$VERSION" ]]; then + echo -e '\033[1mRebuild L1 contracts...\033[0m' + (cd l1-contracts && .foundry/bin/forge build) + + echo -e '\n\033[1mUpdate npm deps...\033[0m' + (cd yarn-project && yarn install) + + echo -e '\n\033[1mRebuild Noir contracts...\033[0m' + (cd yarn-project/noir-contracts && yarn noir:build:all 2> /dev/null) + + echo -e '\n\033[1mRebuild barretenberg wasm...\033[0m' + (cd barretenberg/cpp && cmake --build --preset default && cmake --build --preset wasm && cmake --build --preset wasm-threads) + + echo -e '\n\033[1mRebuild circuits wasm...\033[0m' + (cd circuits/cpp && cmake --build --preset wasm -j --target aztec3-circuits.wasm) + + exit 0 +fi + git submodule update --init --recursive if [ ! -f ~/.nvm/nvm.sh ]; then @@ -66,4 +74,4 @@ barretenberg/cpp/bootstrap.sh circuits/cpp/bootstrap.sh yarn-project/bootstrap.sh -touch .bootstrapped \ No newline at end of file +echo $VERSION > .bootstrapped \ No newline at end of file diff --git a/build-system/scripts/query_manifest b/build-system/scripts/query_manifest index e64086badc0..85ccbf1e96d 100755 --- a/build-system/scripts/query_manifest +++ b/build-system/scripts/query_manifest @@ -11,26 +11,59 @@ if [ $(jq "has(\"$REPO\")" $MANIFEST) == "false" ]; then exit 1 fi -function addRebuildPatterns { - local TYPE=$(jq -r ".\"$1\".rebuildPatterns | type" $MANIFEST) - if [ "$TYPE" == "string" ]; then - local FILE=$(jq -r ".\"$1\".rebuildPatterns" $MANIFEST) - local BUILD_DIR=$($0 buildDir $1) - PATTERNS=(${PATTERNS[@]} $(cat $BUILD_DIR/$FILE)) - elif [ "$TYPE" == "array" ]; then - PATTERNS=(${PATTERNS[@]} $(jq -r ".\"$1\".rebuildPatterns | .[]" $MANIFEST)) - else - >&2 echo "Missing rebuildPatterns property. Either filename as string, or patterns as array." +function get_deps { + local TYPE=$(jq -r ".\"$1\".dependencies | type" $MANIFEST) + if [ "$TYPE" == "string" ]; then + # Execute string as command relative to buildDir to retrieve dependencies. + local BUILD_DIR=$($0 buildDir $1) + local CMD=$BUILD_DIR/$(jq -r ".\"$1\".dependencies") + if [ ! -f "$CMD" ]; then + >&2 echo "Dependency script not found: $CMD" exit 1 fi + local PROJECT_DIR=$($0 projectDir $1) + DEPS=($($CMD $PROJECT_DIR)) + elif [ "$TYPE" == "null" ]; then + # Execute default script relative to buildDir to retrieve dependencies. + local BUILD_DIR=$($0 buildDir $1) + local CMD=$BUILD_DIR/scripts/get_dependencies.sh + if [ ! -f "$CMD" ]; then + DEPS=() + return + fi + local PROJECT_DIR=$($0 projectDir $1) + DEPS=($($CMD $PROJECT_DIR)) + elif [ "$TYPE" == "array" ]; then + DEPS=($(jq -r ".\"$1\".dependencies // [] | .[]" $MANIFEST)) + else + >&2 echo "dependencies must be a array, string or null." + exit 1 + fi +} + +function add_rebuild_patterns { + local TYPE=$(jq -r ".\"$1\".rebuildPatterns | type" $MANIFEST) + if [ "$TYPE" == "string" ]; then + local FILE=$(jq -r ".\"$1\".rebuildPatterns" $MANIFEST) + local PROJECT_DIR=$($0 projectDir $1) + PATTERNS=(${PATTERNS[@]} $(cat $PROJECT_DIR/$FILE)) + elif [ "$TYPE" == "array" ]; then + PATTERNS=(${PATTERNS[@]} $(jq -r ".\"$1\".rebuildPatterns | .[]" $MANIFEST)) + elif [ "$TYPE" == "null" ]; then + local PROJECT_DIR=$($0 relativeProjectDir $1) + PATTERNS=(${PATTERNS[@]} "^$PROJECT_DIR/") + else + >&2 echo "rebuildPatterns must be array, string, or null." + exit 1 + fi } case "$CMD" in dockerfile) - # In the manifest, the path is relative to buildDir. Return absolute path. - BUILD_DIR=$($0 buildDir $REPO) + # In the manifest, the path is relative to projectDir. Return absolute path. + PROJECT_DIR=$($0 projectDir $REPO) DOCKERFILE=$(jq -r ".\"$REPO\".dockerfile // \"Dockerfile\"" $MANIFEST) - echo $BUILD_DIR/$DOCKERFILE + echo $PROJECT_DIR/$DOCKERFILE ;; buildDir) # In the manifest, the path is relative to the repo root. Return absolute path. @@ -43,31 +76,44 @@ case "$CMD" in echo $ROOT_PATH/$PROJECT_DIR ;; relativeProjectDir) + # Return the relative path as it is in the manifest. jq -r ".\"$REPO\".projectDir // .\"$REPO\".buildDir" $MANIFEST ;; dependencies) + # Get dependencies for a given repo. + # If no entry in the manifest file, attempt to call /scripts/get_dependencies.sh if exists, else empty. + # If a string, attempt to call / if exists, else error. + # If an array, the array lists the dependencies. + # Recursively descend "unvisited" dependencies to collect all dependencies. declare -A ALL_DEPS add_deps() { if [[ -v ALL_DEPS[$1] ]]; then return fi ALL_DEPS["$1"]=1 - DEPS=($(jq -r ".\"$1\".dependencies // [] | .[]" $MANIFEST)) + get_deps $1 for DEP in "${DEPS[@]}"; do add_deps $DEP done } add_deps $REPO + # Remove ourself as a dependency. + unset ALL_DEPS["$REPO"] for KEY in "${!ALL_DEPS[@]}"; do echo $KEY done | sort ;; rebuildPatterns) + # Get rebuild patterns for a given repo (the file patterns that if changed result in rebuilds). + # First add rebuild patterns for requested repo, then add rebuild patterns for each dependency. + # If no rebuild patterns are given, the result is ["^/"]. + # If a projects rebuildPattern is a string, the rebuild patterns are in /. + # If an array, the array lists the rebuild patterns. DEPS=($($0 dependencies $REPO)) PATTERNS=() - addRebuildPatterns $REPO + add_rebuild_patterns $REPO for DEP in "${DEPS[@]}"; do - addRebuildPatterns $DEP + add_rebuild_patterns $DEP done printf "%s\n" "${PATTERNS[@]}" | sort | uniq ;; diff --git a/build_manifest.json b/build_manifest.json index 349f196fa9e..065dafddee4 100644 --- a/build_manifest.json +++ b/build_manifest.json @@ -2,48 +2,40 @@ "barretenberg-x86_64-linux-clang": { "buildDir": "barretenberg/cpp", "dockerfile": "dockerfiles/Dockerfile.x86_64-linux-clang", - "rebuildPatterns": ".rebuild_patterns", - "dependencies": [] + "rebuildPatterns": ".rebuild_patterns" }, "barretenberg-x86_64-linux-clang-assert": { "buildDir": "barretenberg/cpp", "dockerfile": "dockerfiles/Dockerfile.x86_64-linux-clang-assert", - "rebuildPatterns": ".rebuild_patterns", - "dependencies": [] + "rebuildPatterns": ".rebuild_patterns" }, "barretenberg-x86_64-linux-clang-fuzzing": { "buildDir": "barretenberg/cpp", "dockerfile": "dockerfiles/Dockerfile.x86_64-linux-clang-fuzzing", - "rebuildPatterns": ".rebuild_patterns", - "dependencies": [] + "rebuildPatterns": ".rebuild_patterns" }, "barretenberg-x86_64-linux-gcc": { "buildDir": "barretenberg/cpp", "dockerfile": "dockerfiles/Dockerfile.x86_64-linux-gcc", - "rebuildPatterns": ".rebuild_patterns", - "dependencies": [] + "rebuildPatterns": ".rebuild_patterns" }, "barretenberg-wasm-linux-clang": { "buildDir": "barretenberg/cpp", "dockerfile": "dockerfiles/Dockerfile.wasm-linux-clang", - "rebuildPatterns": ".rebuild_patterns", - "dependencies": [] + "rebuildPatterns": ".rebuild_patterns" }, "bb.js": { "buildDir": "barretenberg/ts", - "rebuildPatterns": ["^barretenberg/ts/"], "dependencies": ["barretenberg-wasm-linux-clang"] }, "barretenberg-acir-tests-bb": { "buildDir": "barretenberg/acir_tests", "dockerfile": "Dockerfile.bb", - "rebuildPatterns": ["^barretenberg/acir_tests/"], "dependencies": ["barretenberg-x86_64-linux-clang-assert"] }, "barretenberg-acir-tests-bb.js": { "buildDir": "barretenberg/acir_tests", "dockerfile": "Dockerfile.bb.js", - "rebuildPatterns": ["^barretenberg/acir_tests/"], "dependencies": ["bb.js"] }, "circuits-wasm-linux-clang": { @@ -79,19 +71,14 @@ "docs": { "buildDir": ".", "dockerfile": "docs/Dockerfile", - "rebuildPatterns": ["^docs/", "^.*.cpp$", "^.*.ts$"], - "dependencies": [] + "rebuildPatterns": ["^docs/", "^.*.cpp$", "^.*.ts$"] }, "l1-contracts": { - "buildDir": "l1-contracts", - "dockerfile": "Dockerfile", - "rebuildPatterns": ["^l1-contracts/"], - "dependencies": [] + "buildDir": "l1-contracts" }, "l1-artifacts": { "buildDir": "yarn-project", "projectDir": "yarn-project/l1-artifacts", - "dockerfile": "l1-artifacts/Dockerfile", "rebuildPatterns": ["^l1-contracts/", "^yarn-project/l1-artifacts/"], "dependencies": [] }, @@ -102,7 +89,7 @@ "^l1-contracts/", "^yarn-project/l1-artifacts/", "^yarn-project/noir-contracts/", - "^yarn-project/noir-libs/", + "^yarn-project/aztec-nr/", "^yarn-project/noir-compiler/", "^yarn-project/yarn-project-base/", "^yarn-project/yarn.lock" @@ -111,78 +98,23 @@ }, "acir-simulator": { "buildDir": "yarn-project", - "projectDir": "yarn-project/acir-simulator", - "dockerfile": "acir-simulator/Dockerfile", - "rebuildPatterns": ["^yarn-project/acir-simulator/"], - "dependencies": [ - "yarn-project-base", - "circuits.js", - "foundation", - "types", - "merkle-tree", - "noir-contracts" - ] + "projectDir": "yarn-project/acir-simulator" }, "archiver": { "buildDir": "yarn-project", - "projectDir": "yarn-project/archiver", - "dockerfile": "archiver/Dockerfile", - "rebuildPatterns": ["^yarn-project/archiver/"], - "dependencies": [ - "yarn-project-base", - "circuits.js", - "ethereum", - "foundation", - "l1-artifacts", - "types" - ] + "projectDir": "yarn-project/archiver" }, "cli": { "buildDir": "yarn-project", - "projectDir": "yarn-project/cli", - "dockerfile": "cli/Dockerfile", - "rebuildPatterns": ["^yarn-project/cli/"], - "dependencies": [ - "yarn-project-base", - "aztec.js", - "ethereum", - "foundation", - "noir-compiler", - "noir-contracts", - "types" - ] + "projectDir": "yarn-project/cli" }, "aztec-rpc": { "buildDir": "yarn-project", - "projectDir": "yarn-project/aztec-rpc", - "dockerfile": "aztec-rpc/Dockerfile", - "rebuildPatterns": ["^yarn-project/aztec-rpc/"], - "dependencies": [ - "yarn-project-base", - "acir-simulator", - "circuits.js", - "foundation", - "key-store", - "types" - ] + "projectDir": "yarn-project/aztec-rpc" }, "aztec-sandbox": { "buildDir": "yarn-project", - "projectDir": "yarn-project/aztec-sandbox", - "dockerfile": "aztec-sandbox/Dockerfile", - "rebuildPatterns": ["^yarn-project/aztec-sandbox/"], - "dependencies": [ - "yarn-project-base", - "aztec-node", - "aztec-rpc", - "aztec.js", - "circuits.js", - "ethereum", - "foundation", - "l1-artifacts", - "noir-contracts", - "types" - ] + "projectDir": "yarn-project/aztec-sandbox" }, "aztec-sandbox-arm": { "buildDir": "yarn-project", @@ -203,221 +135,93 @@ }, "aztec.js": { "buildDir": "yarn-project", - "projectDir": "yarn-project/aztec.js", - "dockerfile": "aztec.js/Dockerfile", - "rebuildPatterns": ["^yarn-project/aztec.js/"], - "dependencies": ["yarn-project-base", "circuits.js", "foundation", "types"] + "projectDir": "yarn-project/aztec.js" }, "canary-build": { "buildDir": "yarn-project", "projectDir": "yarn-project/canary", - "dockerfile": "canary/Dockerfile.build", - "rebuildPatterns": ["^yarn-project/canary/"], - "dependencies": [ - "yarn-project-base", - "aztec.js", - "l1-artifacts", - "noir-contracts", - "aztec-sandbox" - ] + "dockerfile": "Dockerfile.build" }, "canary": { "buildDir": "yarn-project", - "projectDir": "yarn-project/canary", - "dockerfile": "canary/Dockerfile", - "rebuildPatterns": ["^yarn-project/canary/"], - "dependencies": [ - "yarn-project-base", - "aztec.js", - "foundation", - "l1-artifacts", - "noir-contracts" - ] + "projectDir": "yarn-project/canary" }, "circuits.js": { "buildDir": "yarn-project", - "projectDir": "yarn-project/circuits.js", - "dockerfile": "circuits.js/Dockerfile", - "rebuildPatterns": ["^yarn-project/circuits.js/"], - "dependencies": ["yarn-project-base", "foundation"] + "projectDir": "yarn-project/circuits.js" }, "end-to-end": { "buildDir": "yarn-project", - "projectDir": "yarn-project/end-to-end", - "dockerfile": "end-to-end/Dockerfile", - "rebuildPatterns": ["^yarn-project/end-to-end/"], - "dependencies": [ - "yarn-project-base", - "archiver", - "aztec-node", - "aztec-rpc", - "aztec-sandbox", - "aztec.js", - "circuits.js", - "cli", - "ethereum", - "foundation", - "l1-artifacts", - "noir-contracts", - "p2p", - "sequencer-client", - "types", - "world-state" - ] + "projectDir": "yarn-project/end-to-end" }, "ethereum": { "buildDir": "yarn-project", - "projectDir": "yarn-project/ethereum", - "dockerfile": "ethereum/Dockerfile", - "rebuildPatterns": ["^yarn-project/ethereum/"], - "dependencies": ["yarn-project-base", "foundation", "l1-artifacts"] + "projectDir": "yarn-project/ethereum" }, "foundation": { "buildDir": "yarn-project", - "projectDir": "yarn-project/foundation", - "dockerfile": "foundation/Dockerfile", - "rebuildPatterns": ["^yarn-project/foundation/"], - "dependencies": ["yarn-project-base"] + "projectDir": "yarn-project/foundation" }, "key-store": { "buildDir": "yarn-project", - "projectDir": "yarn-project/key-store", - "dockerfile": "key-store/Dockerfile", - "rebuildPatterns": ["^yarn-project/key-store/"], - "dependencies": ["yarn-project-base", "circuits.js", "foundation", "types"] + "projectDir": "yarn-project/key-store" }, "merkle-tree": { "buildDir": "yarn-project", - "projectDir": "yarn-project/merkle-tree", - "dockerfile": "merkle-tree/Dockerfile", - "rebuildPatterns": ["^yarn-project/merkle-tree/"], - "dependencies": ["yarn-project-base", "circuits.js", "foundation", "types"] + "projectDir": "yarn-project/merkle-tree" }, "noir-contracts-build": { "buildDir": "yarn-project", "projectDir": "yarn-project/noir-contracts", - "dockerfile": "noir-contracts/Dockerfile.build", + "dockerfile": "Dockerfile.build", "rebuildPatterns": [ "^yarn-project/noir-contracts/", - "^yarn-project/noir-libs/" - ], - "dependencies": [ - "yarn-project-base", - "aztec.js", - "foundation", - "noir-compiler" + "^yarn-project/aztec-nr/" ] }, "noir-contracts": { "buildDir": "yarn-project", "projectDir": "yarn-project/noir-contracts", - "dockerfile": "noir-contracts/Dockerfile", "rebuildPatterns": [ "^yarn-project/noir-contracts/", - "^yarn-project/noir-libs/" - ], - "dependencies": [ - "yarn-project-base", - "aztec.js", - "foundation", - "noir-compiler" + "^yarn-project/aztec-nr/" ] }, "noir-compiler": { "buildDir": "yarn-project", - "projectDir": "yarn-project/noir-compiler", - "dockerfile": "noir-compiler/Dockerfile", - "rebuildPatterns": ["^yarn-project/noir-compiler/"], - "dependencies": ["yarn-project-base", "foundation"] + "projectDir": "yarn-project/noir-compiler" }, "p2p": { "buildDir": "yarn-project", - "projectDir": "yarn-project/p2p", - "dockerfile": "p2p/Dockerfile", - "rebuildPatterns": ["^yarn-project/p2p/"], - "dependencies": ["yarn-project-base", "circuits.js", "foundation", "types"] + "projectDir": "yarn-project/p2p" }, "p2p-bootstrap": { "buildDir": "yarn-project", "projectDir": "yarn-project/p2p-bootstrap", - "dockerfile": "p2p/Dockerfile", - "rebuildPatterns": ["^yarn-project/p2p-bootstrap/"], - "dependencies": ["yarn-project-base", "foundation", "p2p"] + "dockerfile": "../p2p/Dockerfile" }, "prover-client": { "buildDir": "yarn-project", - "projectDir": "yarn-project/prover-client", - "dockerfile": "prover-client/Dockerfile", - "rebuildPatterns": ["^yarn-project/prover-client/"], - "dependencies": ["yarn-project-base", "foundation"] + "projectDir": "yarn-project/prover-client" }, "rollup-provider": { "buildDir": "yarn-project", - "projectDir": "yarn-project/rollup-provider", - "dockerfile": "rollup-provider/Dockerfile", - "rebuildPatterns": ["^yarn-project/rollup-provider/"], - "dependencies": [ - "yarn-project-base", - "aztec-node", - "circuits.js", - "foundation", - "types" - ] + "projectDir": "yarn-project/rollup-provider" }, "aztec-node": { "buildDir": "yarn-project", - "projectDir": "yarn-project/aztec-node", - "dockerfile": "aztec-node/Dockerfile", - "rebuildPatterns": ["^yarn-project/aztec-node/"], - "dependencies": [ - "yarn-project-base", - "archiver", - "circuits.js", - "foundation", - "l1-artifacts", - "merkle-tree", - "p2p", - "sequencer-client", - "types", - "world-state" - ] + "projectDir": "yarn-project/aztec-node" }, "sequencer-client": { "buildDir": "yarn-project", - "projectDir": "yarn-project/sequencer-client", - "dockerfile": "sequencer-client/Dockerfile", - "rebuildPatterns": ["^yarn-project/sequencer-client/"], - "dependencies": [ - "yarn-project-base", - "acir-simulator", - "circuits.js", - "ethereum", - "foundation", - "l1-artifacts", - "merkle-tree", - "p2p", - "types", - "world-state" - ] + "projectDir": "yarn-project/sequencer-client" }, "types": { "buildDir": "yarn-project", - "projectDir": "yarn-project/types", - "dockerfile": "types/Dockerfile", - "rebuildPatterns": ["^yarn-project/types/"], - "dependencies": ["yarn-project-base", "circuits.js", "foundation"] + "projectDir": "yarn-project/types" }, "world-state": { "buildDir": "yarn-project", - "projectDir": "yarn-project/world-state", - "dockerfile": "world-state/Dockerfile", - "rebuildPatterns": ["^yarn-project/world-state/"], - "dependencies": [ - "yarn-project-base", - "circuits.js", - "foundation", - "merkle-tree", - "types" - ] + "projectDir": "yarn-project/world-state" } } diff --git a/docs/.gitrepo b/docs/.gitrepo index e3df984cbe5..31bff7a92d6 100644 --- a/docs/.gitrepo +++ b/docs/.gitrepo @@ -6,7 +6,7 @@ [subrepo] remote = https://github.com/AztecProtocol/docs branch = main - commit = 6905fb906199ab1a69c4c263029f9a0b8708ee4d - parent = 0c3a6271a1d90fa95a0163606e49f432573e66da + commit = a6b558800fa7712fec7045a2d3a238824cf17084 + parent = c8a5cfb375b498475503c12cc83fcdba39f2ec5f method = merge cmdver = 0.4.6 diff --git a/docs/docs/about_aztec/roadmap/features_initial_ldt.md b/docs/docs/about_aztec/roadmap/features_initial_ldt.md index f85c0bc28bf..50cf79233f1 100644 --- a/docs/docs/about_aztec/roadmap/features_initial_ldt.md +++ b/docs/docs/about_aztec/roadmap/features_initial_ldt.md @@ -8,7 +8,7 @@ Devs should be able to quickly spin up local, emulated instances of an Ethereum Here's a summary of the features we intend to support with the first release of the Aztec Sandbox. -## Noir Contracts +## Aztec.nr Contracts - Noir `contract` scopes. - Declare a `contract`, containing a collection of state variables and functions. @@ -21,7 +21,7 @@ Here's a summary of the features we intend to support with the first release of - public functions - May read and modify public state. - `constructor` functions, for initialising contract state. -- `import` other Noir contracts, so their functions may be called. +- `import` other Aztec.nr contracts, so their functions may be called. - Nested function calls, for contract composability - private functions can call private functions of other contracts, and receive return values. - private functions can call public functions any contract. @@ -29,14 +29,14 @@ Here's a summary of the features we intend to support with the first release of - public functions can call public functions of other contracts, and receive return values. - private functions can be called recursively. - public functions can be called recursively. -- Send messages from Noir contracts to Ethereum L1, for consumption by L1 smart contracts. +- Send messages from Aztec.nr contracts to Ethereum L1, for consumption by L1 smart contracts. - Useful, for example, if writing an app to withdraw funds from L2 to L1. - Consume messages which have been sent by: - L1 functions. - Useful, for example, if writing an app to deposit funds from L1 to L2. - public L2 functions. -- Emit `event` data from a Noir Contract. - - Allows applications to subscribe to events which have been emitted by a Noir contract's functions, for example. +- Emit `event` data from a Aztec.nr Contract. + - Allows applications to subscribe to events which have been emitted by a Aztec.nr contract's functions, for example. - Write `unconstrained` functions. - These allow developers to write `pure` and `view` functions, which can perform calculations and retrieve state. E.g. for fetching contract-specific information, which may then be consumed by a dapp, without having to generate a zero-knowledge proof or interact with the 'network'. @@ -46,13 +46,13 @@ A typescript wrapper for making RPC calls to an Aztec LDT node. - Similar in purpose to `web3.js`/`ethers.js`/`viem`, but for interacting with Aztec Network nodes. The RPC interface for an Aztec node is necessarily different from that of an Ethereum node, because it deals with encrypted transactions and state variables. - A library for public/private key management. -- Construct `Contract` instances from a Noir contract's JSON ABI. +- Construct `Contract` instances from a Aztec.nr contract's JSON ABI. - Deploy new contracts to the Aztec LDT. - Construct tx requests, passing arguments to a function of a contract. - Sign tx requests. - Send txs to the LDT node, for simulating. - Send txs to the LDT node, to be sent to the LDT network. -- Call `unconstrained` functions of a Noir contract, to perform `pure` calculations or retrieve state. +- Call `unconstrained` functions of a Aztec.nr contract, to perform `pure` calculations or retrieve state. ## Aztec Local Developer Testnet Node diff --git a/docs/docs/concepts/advanced/circuits/kernels/private_kernel.md b/docs/docs/concepts/advanced/circuits/kernels/private_kernel.md index d079a3deaa8..405a6163061 100644 --- a/docs/docs/concepts/advanced/circuits/kernels/private_kernel.md +++ b/docs/docs/concepts/advanced/circuits/kernels/private_kernel.md @@ -6,7 +6,7 @@ This circuit is executed by the user, on their own device. This is to ensure pri - Verifies a user's signature. - Hides the user's address. -- Verifies an app's proof - i.e. a proof which has been output after the execution of some function in a Noir Contract. +- Verifies an app's proof - i.e. a proof which has been output after the execution of some function in an Aztec.nr Contract. - Performs private state reads and writes. - Exposes (forwards) the following data to the next recursive circuit: - new note hashes; @@ -21,5 +21,5 @@ This circuit is executed by the user, on their own device. This is to ensure pri - Verifies a previous 'Private Kernel Proof', recursively, when verifying transactions which are composed of many private function calls. - Optionally can [deploy](../../contract_creation) a new private contract. -> Note: **This is the only core protocol circuit which actually needs to be "zk" (zero knowledge)!!!** That's because this is the only core protocol circuit which handles private data, and hence the only circuit for which proofs must not leak any information about witnesses! (The private data being handled includes: details of the Noir Contract function which has been executed; the address of the user who executed the function; the intelligible inputs and outputs of that function). +> Note: **This is the only core protocol circuit which actually needs to be "zk" (zero knowledge)!!!** That's because this is the only core protocol circuit which handles private data, and hence the only circuit for which proofs must not leak any information about witnesses! (The private data being handled includes: details of the Aztec.nr Contract function which has been executed; the address of the user who executed the function; the intelligible inputs and outputs of that function). > This is a really interesting point. Most so-called "zk-Rollups" do not make use of this "zero knowledge" property. Their snarks are "snarks"; with no need for zero-knowledge, because they don't seek privacy; they only seek the 'succinct' computation-compression properties of snarks. Aztec's "zk-Rollup" actually makes use of "zero knowledge" snarks. That's why we sometimes call it a "zk-zk-Rollup", or "_actual_ zk-Rollup". diff --git a/docs/docs/concepts/advanced/circuits/main.md b/docs/docs/concepts/advanced/circuits/main.md index b959287941a..3f21cb79053 100644 --- a/docs/docs/concepts/advanced/circuits/main.md +++ b/docs/docs/concepts/advanced/circuits/main.md @@ -7,7 +7,7 @@ title: Circuits In Aztec, circuits come from two sources: 1. Core protocol circuits -2. User-written circuits (written as Noir Contracts and deployed to the network) +2. User-written circuits (written as Aztec.nr Contracts and deployed to the network) This page focusses on the core protocol circuits. These circuits check that the rules of the protocol are being adhered to. diff --git a/docs/docs/concepts/advanced/data_structures/trees.md b/docs/docs/concepts/advanced/data_structures/trees.md index 75cbcdddf45..903b80a3de1 100644 --- a/docs/docs/concepts/advanced/data_structures/trees.md +++ b/docs/docs/concepts/advanced/data_structures/trees.md @@ -25,11 +25,11 @@ So, if an app needs to edit a private state variable (which will be represented ### Example Note -An example blob of data might be defined in a Noir Contract as: +An example blob of data might be defined in an Aztec.nr Contract as: ```rust struct MyNote { - storage_slot: Field, // determined by the Noir Contract + storage_slot: Field, // determined by the Aztec.nr Contract value: Field, owner_public_key: Point, // The owner of this private state // (and the person who may edit it). @@ -37,7 +37,7 @@ struct MyNote { } ``` -The note might be committed-to, within a function of the Noir Contract as: +The note might be committed-to, within a function of the Aztec.nr Contract as: ```rust note_hash: Field = pedersen::compress( diff --git a/docs/docs/concepts/foundation/accounts/keys.md b/docs/docs/concepts/foundation/accounts/keys.md index 0e4755c3798..2fb19d87860 100644 --- a/docs/docs/concepts/foundation/accounts/keys.md +++ b/docs/docs/concepts/foundation/accounts/keys.md @@ -69,9 +69,9 @@ The privacy master key is used to derive encryption keys. Encryption keys, as th In a future version, encryption keys will be differentiated between incoming and outgoing. When sending a note to another user, the sender will use the recipient's incoming encryption key for encrypting the data for them, and will optionally use their own outgoing encryption key for encrypting any data about the destination of that note. This is useful for reconstructing transaction history from on-chain data. For example, during a token transfer, the token contract may dictate that the sender encrypts the note with value with the recipient's incoming key, but also records the transfer with its own outgoing key for bookkeeping purposes. -An application in Noir can access the encryption public key for a given address using the oracle call `get_public_key`, which you can then use for calls such as `emit_encrypted_log`: +An application in Aztec.nr can access the encryption public key for a given address using the oracle call `get_public_key`, which you can then use for calls such as `emit_encrypted_log`: -#include_code encrypted /yarn-project/noir-libs/value-note/src/utils.nr rust +#include_code encrypted /yarn-project/aztec-nr/value-note/src/utils.nr rust :::info In order to be able to provide the public encryption key for a given address, that public key needs to have been registered in advance. At the moment, there is no broadcasting mechanism for public keys, which means that you will need to manually register all addresses you intend to send encrypted notes to. You can do this via the `registerRecipient` method of the Aztec RPC server, callable either via aztec.js or the CLI. Note that any accounts you own that have been added to the RPC server are automatically registered. @@ -81,9 +81,9 @@ In order to be able to provide the public encryption key for a given address, th In addition to deriving encryption keys, the privacy master key is used for deriving nullifier secrets. Whenever a private note is consumed, a nullifier deterministically derived from it is emitted. This mechanisms prevents double-spends, since nullifiers are checked by the protocol to be unique. Now, in order to preserve privacy, a third party should not be able to link a note commitment to its nullifier - this link is enforced by the note implementation. Therefore, calculating the nullifier for a note requires a secret from its owner. -An application in Noir can request a nullifier from the current user for computing the nullifier of a note via the `get_secret_key` oracle call: +An application in Aztec.nr can request a nullifier from the current user for computing the nullifier of a note via the `get_secret_key` oracle call: -#include_code nullifier /yarn-project/noir-libs/value-note/src/value_note.nr rust +#include_code nullifier /yarn-project/aztec-nr/value-note/src/value_note.nr rust ### Scoped keys diff --git a/docs/docs/concepts/foundation/state_model.md b/docs/docs/concepts/foundation/state_model.md index e29d1350849..87db190203c 100644 --- a/docs/docs/concepts/foundation/state_model.md +++ b/docs/docs/concepts/foundation/state_model.md @@ -10,7 +10,7 @@ import Disclaimer from '../../misc/common/\_disclaimer.mdx'; ## Private State -Private state must be treated differently from public state and this must be expressed in the semantics of the Noir language. +Private state must be treated differently from public state and this must be expressed in the semantics of Aztec.nr. Private state is encrypted and therefore is "owned" by a user or a set of users (via shared secrets) that are able to decrypt the state. @@ -22,12 +22,12 @@ Modification of state variables can be emulated by nullifying the a state record ### Abstracting UTXO's from App's / Users -The goal of Noir's contract syntax is abstract the UTXO model away from an app user / developer, contract developers are the only actor who should have to think about UTXO's. +The goal of the Aztec.nr smart contract library is to abstract the UTXO model away from an app user / developer, contract developers are the only actor who should have to think about UTXO's. This is achieved with two main features: 1. Users sign over transactions, not over specific UTXO's -2. Noir contracts support developer defined `unconstrained` getter functions to help dApp's make sense of UTXO's. e.g `getBalance()`. These functions can be called outside of a transaction context to read private state. +2. Aztec.nr contracts support developer defined `unconstrained` getter functions to help dApp's make sense of UTXO's. e.g `getBalance()`. These functions can be called outside of a transaction context to read private state. ### The lifecycle of a note diff --git a/docs/docs/dev_docs/contracts/common_errors.md b/docs/docs/dev_docs/contracts/common_errors.md index 75762ef9cd6..ce96e27ed09 100644 --- a/docs/docs/dev_docs/contracts/common_errors.md +++ b/docs/docs/dev_docs/contracts/common_errors.md @@ -2,7 +2,7 @@ List common errors. -There are two kinds of errors: errors in a noir contract, and errors spat out by an Aztec Sandbox node! +There are two kinds of errors: errors in an Aztec.nr contract, and errors spat out by an Aztec Sandbox node! Maybe even auto-generate error docs, based on error codes in our codebase. diff --git a/docs/docs/dev_docs/contracts/compiling.md b/docs/docs/dev_docs/contracts/compiling.md index 109aa96732b..845ffdf645e 100644 --- a/docs/docs/dev_docs/contracts/compiling.md +++ b/docs/docs/dev_docs/contracts/compiling.md @@ -1,10 +1,10 @@ # Compiling contracts -Once you have written a [contract](../contracts/main.md) in Noir, you will need to compile it into an [artifact](./abi.md) in order to use it. +Once you have written a [contract](../contracts/main.md) in Aztec.nr, you will need to compile it into an [artifact](./abi.md) in order to use it. In this guide we will cover how to do so, both using the CLI and programmatically. -We'll also cover how to generate a helper [TypeScript interface](#typescript-interfaces) and a [Noir interface](#noir-interfaces) for easily interacting with your contract from your typescript app and from other noir contracts, respectively. +We'll also cover how to generate a helper [TypeScript interface](#typescript-interfaces) and an [Aztec.nr interface](#noir-interfaces) for easily interacting with your contract from your typescript app and from other Aztec.nr contracts, respectively. ## Prerequisites @@ -76,13 +76,13 @@ export class PrivateTokenContract extends ContractBase { Read more about interacting with contracts using `aztec.js` [here](../dapps/main.md). -### Noir interfaces +### Aztec.nr interfaces -A Noir contract can [call a function](./functions.md) in another contract via `context.call_private_function` or `context.call_public_function`. However, this requires manually assembling the function selector and manually serialising the arguments, which is not type-safe. +An Aztec.nr contract can [call a function](./functions.md) in another contract via `context.call_private_function` or `context.call_public_function`. However, this requires manually assembling the function selector and manually serialising the arguments, which is not type-safe. To make this easier, the compiler can generate contract interface structs that expose a convenience method for each function listed in a given contract ABI. These structs are intended to be used from another contract project that calls into the current one. For each contract, two interface structs are generated: one to be used from private functions with a `PrivateContext`, and one to be used from open functions with a `PublicContext`. -To generate them, include a `--interface` option in the compile command with a path to the target folder for the generated Noir interface files: +To generate them, include a `--interface` option in the compile command with a path to the target folder for the generated Aztec.nr interface files: ``` aztec-cli compile --interface ./path/to/another_aztec_contract_project/src ./path/to/my_aztec_contract_project @@ -128,7 +128,7 @@ impl PrivateTokenPrivateContextInterface { } ``` -Read more about how to use the Noir interfaces [here](./functions.md#contract-interface). +Read more about how to use the Aztec.nr interfaces [here](./functions.md#contract-interface). :::info At the moment, the compiler generates these interfaces from already compiled ABIs, and not from source code. This means that you should not import a generated interface from within the same project as its source contract, or you risk circular references. @@ -143,9 +143,9 @@ npm install @aztec/noir-compiler ` The compiler exposes the following functions: -- `compileUsingNargo`: Compiles a Noir project in the target folder using the `nargo` binary available on the shell `PATH` and returns the generated ABIs. +- `compileUsingNargo`: Compiles an Aztec.nr project in the target folder using the `nargo` binary available on the shell `PATH` and returns the generated ABIs. - `generateTypescriptContractInterface`: Generates a typescript class for the given contract ABI. -- `generateNoirContractInterface`: Generates a Noir interface struct for the given contract ABI. +- `generateNoirContractInterface`: Generates a Aztec.nr interface struct for the given contract ABI. ## Next steps diff --git a/docs/docs/dev_docs/contracts/contract.md b/docs/docs/dev_docs/contracts/contract.md index 9e94abb09ff..211491237ee 100644 --- a/docs/docs/dev_docs/contracts/contract.md +++ b/docs/docs/dev_docs/contracts/contract.md @@ -18,7 +18,7 @@ contract MyContract { ``` -> A note for vanilla Noir devs: There is no [`main()`](https://noir-lang.org/getting_started/breakdown/#mainnr) function within a Noir Contract scope. This is because more than one function of a contract may be called and proven as external (as opposed to inlined by the compiler). +> A note for vanilla Noir devs: There is no [`main()`](https://noir-lang.org/getting_started/breakdown/#mainnr) function within a Noir `contract` scope. This is because more than one function of a contract may be called and proven as external (as opposed to inlined by the compiler). ## Structure of a contract diff --git a/docs/docs/dev_docs/contracts/events.md b/docs/docs/dev_docs/contracts/events.md index 1f12b91c8e5..88eaf3b2396 100644 --- a/docs/docs/dev_docs/contracts/events.md +++ b/docs/docs/dev_docs/contracts/events.md @@ -44,11 +44,11 @@ await aztecRpc.registerRecipient(completeAddress); To emit encrypted logs first import the `emit_encrypted_log` utility function inside your contract: -#include_code encrypted_import /yarn-project/noir-libs/value-note/src/utils.nr rust +#include_code encrypted_import /yarn-project/aztec-nr/value-note/src/utils.nr rust Then you can call the function: -#include_code encrypted /yarn-project/noir-libs/value-note/src/utils.nr rust +#include_code encrypted /yarn-project/aztec-nr/value-note/src/utils.nr rust ### Unencrypted Events diff --git a/docs/docs/dev_docs/contracts/layout.md b/docs/docs/dev_docs/contracts/layout.md index 2c657d37fc7..a6db7b63a6d 100644 --- a/docs/docs/dev_docs/contracts/layout.md +++ b/docs/docs/dev_docs/contracts/layout.md @@ -2,7 +2,7 @@ ## Directory structure -Here's a common layout for a basic Noir Contract project: +Here's a common layout for a basic Aztec.nr Contract project: ```title="layout of an aztec contract project" ─── my_aztec_contract_project diff --git a/docs/docs/dev_docs/contracts/main.md b/docs/docs/dev_docs/contracts/main.md index 571a4fe3156..b5e5ecc1787 100644 --- a/docs/docs/dev_docs/contracts/main.md +++ b/docs/docs/dev_docs/contracts/main.md @@ -2,7 +2,7 @@ ## What is Aztec.nr? -**Aztec.nr** is a library for writing Aztec smart contracts. +**Aztec.nr** is a framework for writing Aztec smart contracts. ## Nomenclature @@ -12,17 +12,17 @@ A **smart contract** is just a collection of persistent state variables, and a c An **Aztec smart contract** is a smart contract with **private** state variables and **private** functions. -**Aztec.nr** is a library for writing Aztec smart contracts, written in Noir. +**Aztec.nr** is a framework for writing Aztec smart contracts, written in Noir. # Getting started ## Install Noir -To write a Noir Contract, you need to write Noir, and to write Noir, you need to [install Nargo](https://noir-lang.org/getting_started/nargo_installation). +To write an Aztec.nr contract, you need to write Noir, and to write Noir, you need to [install Nargo](https://noir-lang.org/getting_started/nargo_installation). ## Install Noir tooling -There are a number of tools to make writing Noir Contracts more pleasant. See [here](https://github.com/noir-lang/awesome-noir#get-coding). +There are a number of tools to make writing Aztec.nr contracts more pleasant. See [here](https://github.com/noir-lang/awesome-noir#get-coding). ## Quick start @@ -30,7 +30,8 @@ There are a number of tools to make writing Noir Contracts more pleasant. See [h Starter kit ::: -## Example Noir Contract + +## Example Aztec.nr Contract In keeping with the origins of blockchain, here's an example of a simple private token contract. Everyone's balances are private. diff --git a/docs/docs/dev_docs/contracts/portals/main.md b/docs/docs/dev_docs/contracts/portals/main.md index b1ead86a80e..67074e53aab 100644 --- a/docs/docs/dev_docs/contracts/portals/main.md +++ b/docs/docs/dev_docs/contracts/portals/main.md @@ -37,7 +37,7 @@ As time passes, a sequencer will see your tx, the juicy fee provided and include To consume the message, we can use the `consume_l1_to_l2_message` function within the `context` struct. The `msg_key` is the hash of the message produced from the `sendL2Message` call, the `content` is the content of the message, and the `secret` is the pre-image hashed to compute the `secretHash`. -#include_code context_consume_l1_to_l2_message /yarn-project/noir-libs/aztec-noir/src/context.nr rust +#include_code context_consume_l1_to_l2_message /yarn-project/aztec-nr/aztec/src/context.nr rust Computing the `content` might be a little clunky in its current form, as we are still adding a number of bytes utilities. A good example exists within the [Non-native token example](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/hash.nr). @@ -63,7 +63,7 @@ The portal must ensure that the sender is as expected. One way to do this, is to To send a message to L1 from your Aztec contract, you must use the `message_portal` function on the `context`. When messaging to L1, only the `content` is required (as field). -#include_code context_message_portal /yarn-project/noir-libs/aztec-noir/src/context.nr rust +#include_code context_message_portal /yarn-project/aztec-nr/aztec/src/context.nr rust When sending a message from L2 to L1 we don't need to pass recipient, deadline, secret nor fees. Recipient is populated with the attached portal and the remaining values are not needed as the message is inserted into the outbox at the same time as it was included in a block (for the inbox it could be inserted and then only included in rollup block later). diff --git a/docs/docs/dev_docs/contracts/state_variables.md b/docs/docs/dev_docs/contracts/state_variables.md index d11e7fb8b2d..db6ac3f6289 100644 --- a/docs/docs/dev_docs/contracts/state_variables.md +++ b/docs/docs/dev_docs/contracts/state_variables.md @@ -28,7 +28,7 @@ The BoolSerialisationMethods is part of the Aztec stdlib: It contains methods that instruct its PublicState wrapper how to serialise and deserialise a boolean to and from a Field, which is the data type being saved in the public state tree. -The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-libs/aztec-noir/src/types/type_serialisation) for the complete list. +The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/types/type_serialisation) for the complete list. ### Custom types @@ -36,7 +36,7 @@ It's possible to create a public state for any types. Simply define methods that The methods should be implemented in a struct that conforms to the following interface: -#include_code TypeSerialisationInterface /yarn-project/noir-libs/aztec-noir/src/types/type_serialisation.nr rust +#include_code TypeSerialisationInterface /yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr rust For example, to create a public state for the following type: @@ -118,7 +118,7 @@ Notes are the fundamental elements in the private world. A note should conform to the following interface: -#include_code NoteInterface /yarn-project/noir-libs/aztec-noir/src/note/note_interface.nr rust +#include_code NoteInterface /yarn-project/aztec-nr/aztec/src/note/note_interface.nr rust The interplay between a private state variable and its notes can be confusing. Here's a summary to aid intuition: @@ -243,7 +243,7 @@ Because of this limit, we should always consider using the second argument `Note `NoteGetterOptions` encapsulates a set of configurable options for filtering and retrieving a selection of notes from a database: -#include_code NoteGetterOptions /yarn-project/noir-libs/aztec-noir/src/note/note_getter_options.nr rust +#include_code NoteGetterOptions /yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr rust Developers can design instances of `NoteGetterOptions`, to determine how notes should be filtered and returned to the functions of their smart contracts. diff --git a/docs/docs/dev_docs/contracts/syntax.md b/docs/docs/dev_docs/contracts/syntax.md index a5d5008e78d..584bdeab7ae 100644 --- a/docs/docs/dev_docs/contracts/syntax.md +++ b/docs/docs/dev_docs/contracts/syntax.md @@ -2,7 +2,7 @@ [Noir](https://noir-lang.org/) is a language which is agnostic to proof systems and use cases. Rather than baking Aztec-specific keywords and smart contract types directly into Noir (which would break this agnosticism), we have developed a library -- written in Noir -- whose types and methods provide rich smart contract semantics. -On top of [Noir's stdlib](https://noir-lang.org/standard_library/array_methods), we provide [Aztec.nr](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-libs) for writing contracts on Aztec. +On top of [Noir's stdlib](https://noir-lang.org/standard_library/array_methods), we provide [Aztec.nr](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec-nr) for writing contracts on Aztec. Aztec.nr contains abstractions which remove the need to understand the low-level Aztec protocol. Notably, it provides: diff --git a/docs/docs/dev_docs/contracts/types.md b/docs/docs/dev_docs/contracts/types.md index de66faed98b..a7e81ff0027 100644 --- a/docs/docs/dev_docs/contracts/types.md +++ b/docs/docs/dev_docs/contracts/types.md @@ -1,2 +1,2 @@ See Noir docs for Noir types. -See [state_variables](./state_variables.md) for Noir Contract state variable types. \ No newline at end of file +See [state_variables](./state_variables.md) for Aztec.nr state variable types. \ No newline at end of file diff --git a/docs/docs/dev_docs/contracts/workflow.md b/docs/docs/dev_docs/contracts/workflow.md index f208a34e33b..9ebe0ac2431 100644 --- a/docs/docs/dev_docs/contracts/workflow.md +++ b/docs/docs/dev_docs/contracts/workflow.md @@ -1,4 +1,4 @@ -# Noir contract workflow +# Aztec.nr smart contract workflow ## Write diff --git a/docs/docs/dev_docs/dapps/main.md b/docs/docs/dev_docs/dapps/main.md index cf4484cd4eb..d267ad9a162 100644 --- a/docs/docs/dev_docs/dapps/main.md +++ b/docs/docs/dev_docs/dapps/main.md @@ -21,7 +21,7 @@ Explain how to write a dapp using [`aztec.js`](https://github.com/AztecProtocol/ - Use the e2e tests as inspiration. - Instantiate a contract - Deploy a contract - - How to generate a nice typescript interface for a Noir Contract's functions (we have a little `.ts` program in `noir-contracts` to generate a types file at the moment... how would a user do this?) + - How to generate a nice typescript interface for an Aztec.nr contract's functions (we have a little `.ts` program in `noir-contracts` to generate a types file at the moment... how would a user do this?) - Call 'view' functions - Simulate functions (simulate the result, without sending to the 'network') - Execute functions (send them to the 'network') diff --git a/docs/docs/dev_docs/dapps/testing.md b/docs/docs/dev_docs/dapps/testing.md index c8395ae51a6..ec59f1d7516 100644 --- a/docs/docs/dev_docs/dapps/testing.md +++ b/docs/docs/dev_docs/dapps/testing.md @@ -133,7 +133,7 @@ To query storage directly, you'll need to know the slot you want to access. This Private state in the Aztec Network is represented via sets of [private notes](../../concepts/foundation/state_model.md#private-state). In our token contract example, the balance of a user is represented as a set of unspent value notes, each with their own corresponding numeric value. -#include_code value-note-def yarn-project/noir-libs/value-note/src/value_note.nr rust +#include_code value-note-def yarn-project/aztec-nr/value-note/src/value_note.nr rust We can query the RPC server for all notes encrypted for a given user in a contract slot. For this example, we'll get all notes encrypted for the `owner` user that are stored on the token contract address and on the slot we calculated earlier. To calculate the actual balance, we extract the `value` of each note, which is the first element, and sum them up. diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md b/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md index 9bbbbdc3669..d78a68969fd 100644 --- a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md +++ b/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md @@ -19,8 +19,8 @@ Then, open the `contracts/private_token/Nargo.toml` configuration file, and add ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/noir-libs/noir-aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/noir-libs/value-note" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/aztec-nr/noir-aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/aztec-nr/value-note" } ``` Last, copy-paste the code from the `PrivateToken` contract into `contracts/private_token/main.nr`: diff --git a/docs/docs/dev_docs/getting_started/noir_contracts.md b/docs/docs/dev_docs/getting_started/noir_contracts.md index e6b9e3a96f8..65e27c14643 100644 --- a/docs/docs/dev_docs/getting_started/noir_contracts.md +++ b/docs/docs/dev_docs/getting_started/noir_contracts.md @@ -61,7 +61,7 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/noir-libs/aztec-noir" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="master", directory="yarn-project/aztec-nr/aztec" } ``` You are now ready to write your own contracts! diff --git a/docs/docs/dev_docs/getting_started/sandbox.md b/docs/docs/dev_docs/getting_started/sandbox.md index 8f2dc173a20..fc31b6708da 100644 --- a/docs/docs/dev_docs/getting_started/sandbox.md +++ b/docs/docs/dev_docs/getting_started/sandbox.md @@ -6,7 +6,7 @@ import Image from "@theme/IdealImage"; ## Introduction -The Aztec Sandbox aims to provide a local development system against which you can build and test Noir contracts in a fast, safe, and free environment. +The Aztec Sandbox aims to provide a local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. Here we will walkthrough the process of retrieving the Sandbox, installing the client libraries and using it to deploy and use a fully private token contract on the Aztec network. diff --git a/docs/docs/dev_docs/sandbox/common_errors.md b/docs/docs/dev_docs/sandbox/common_errors.md index 5552601ff65..c13345e00dd 100644 --- a/docs/docs/dev_docs/sandbox/common_errors.md +++ b/docs/docs/dev_docs/sandbox/common_errors.md @@ -26,7 +26,7 @@ For static calls, new commitments aren't allowed For static calls, new nullifiers aren't allowed #### 2009 - PRIVATE_KERNEL__NON_PRIVATE_FUNCTION_EXECUTED_WITH_PRIVATE_KERNEL -You cannot execute a public noir function in the private kernel +You cannot execute a public Aztec.nr function in the private kernel #### 2011 - PRIVATE_KERNEL__UNSUPPORTED_OP You are trying to do something that is currently unsupported in the private kernel. If this is a blocker feel free to open up an issue on our monorepo [aztec3-packages](https://github.com/AztecProtocol/aztec3-packages/tree/master) or reach out to us on discord @@ -34,7 +34,7 @@ You are trying to do something that is currently unsupported in the private kern Note that certain operations are unsupported on certain versions of the private kernel. Eg static calls are allowed for all but the initial iteration of the private kernel (which initialises the kernel for subsequent function calls). #### 2012 - PRIVATE_KERNEL__CONTRACT_ADDRESS_MISMATCH -For the initial iteration of the private kernel, only the expected noir contract should be the entrypoint. Static and delegate calls are not allowed in the initial iteration. +For the initial iteration of the private kernel, only the expected Aztec.nr contract should be the entrypoint. Static and delegate calls are not allowed in the initial iteration. #### 2013 - PRIVATE_KERNEL__NON_PRIVATE_KERNEL_VERIFIED_WITH_PRIVATE_KERNEL The previous kernel iteration within the private kernel must also be private @@ -46,7 +46,7 @@ A constructor must be executed as the first tx in the recursion i.e. a construct Confirms that the TxRequest (user's intent) matches the private call being executed. This error may happen when: * origin address of tx_request doesn't match call_stack_item's contract_address * tx_request.function_data doesn't match call_stack_item.function_data -* noir function args passed to tx_request doesn't match args in the call_stack_item +* Aztec.nr function args passed to tx_request doesn't match args in the call_stack_item #### 2018 - PRIVATE_KERNEL__READ_REQUEST_PRIVATE_DATA_ROOT_MISMATCH Given a read request and provided witness, we check that the merkle root obtained from the witness' sibling path and it's leaf is similar to the historic state root we want to read against. This is a sanity check to ensure we are reading from the right state. @@ -65,7 +65,7 @@ But for non transient reads, we do a merkle membership check. Redas are done at You are trying to do something that is currently unsupported in the public kernel. If this is a blocker feel free to open up an issue on our monorepo [aztec3-packages](https://github.com/AztecProtocol/aztec3-packages/tree/master) or reach out to us on discord #### 3002 - PUBLIC_KERNEL__PRIVATE_FUNCTION_NOT_ALLOWED -Calling a private noir function in a public kernel is not allowed. +Calling a private Aztec.nr function in a public kernel is not allowed. #### 3005 - PUBLIC_KERNEL__NON_EMPTY_PRIVATE_CALL_STACK Public functions are executed after all the private functions are (see [private-public execution](../../concepts/foundation/communication/public_private_calls.md)). As such, private call stack must be empty when executing in the public kernel. @@ -109,7 +109,7 @@ The L1 chain ID you used in your proof generation (for your private transaction) #### 4008 - BASE__INVALID_VERSION Same as [section 4007](#4007---base__invalid_chain_id) except the `version` refers to the version of the Aztec L2 instance. -Some scary bugs like `4003 - BASE__INVALID_NULLIFIER_SUBTREE` and `4004 - BASE__INVALID_NULLIFIER_RANGE` which are to do malformed nullifier trees (see [Indexed Merkle Trees](../../concepts/advanced/data_structures/indexed_merkle_tree.md)) etc may seem unrelated at a glance, but at a closer look may be because of some bug in an application's Noir code. Same is true for certain instances of `7008 - MEMBERSHIP_CHECK_FAILED`. +Some scary bugs like `4003 - BASE__INVALID_NULLIFIER_SUBTREE` and `4004 - BASE__INVALID_NULLIFIER_RANGE` which are to do malformed nullifier trees (see [Indexed Merkle Trees](../../concepts/advanced/data_structures/indexed_merkle_tree.md)) etc may seem unrelated at a glance, but at a closer look may be because of some bug in an application's Aztec.nr code. Same is true for certain instances of `7008 - MEMBERSHIP_CHECK_FAILED`. ### Generic circuit errors @@ -119,7 +119,7 @@ Circuits work by having a fixed size array. As such, we have limits on how many * too many new commitments in one tx * too many new nullifiers in one tx - - Note: Nullifiers may be created even outside the context of your noir code. Eg, when creating a contract, we add a nullifier for its address to prevent same address from ever occurring. Similarly, we add a nullifier for your transaction hash too. + - Note: Nullifiers may be created even outside the context of your Aztec.nr code. Eg, when creating a contract, we add a nullifier for its address to prevent same address from ever occurring. Similarly, we add a nullifier for your transaction hash too. * too many private function calls in one tx (i.e. call stack size exceeded) * too many public function calls in one tx (i.e. call stack size exceeded) * too many new L2 to L1 messages in one tx @@ -159,7 +159,7 @@ Users may create a proof against a historic state in Aztec. The rollup circuits * "Public call stack size exceeded" - In Aztec, the sequencer executes all enqueued public functions in a transaction (to prevent race conditions - see [private-public execution](../../concepts/foundation/communication/public_private_calls.md)). This error says there are too many public functions requested. -* "Array size exceeds target length" - happens if you add more items than allowed by the constants set due to our circuit limitations (eg sending too many L2 to L1 messages or creating a function that exceeds the call stack length or return more values than what Noir functions allows) +* "Array size exceeds target length" - happens if you add more items than allowed by the constants set due to our circuit limitations (eg sending too many L2 to L1 messages or creating a function that exceeds the call stack length or returns more values than what Aztec.nr functions allow) * "Failed to publish block" - Happens when sequencer tries to submit its L2 block + proof to the rollup contract. Use the CLI to find any solidity error and then refer the [Contract errors section](#l1-aztec-contract-errors). diff --git a/docs/docs/dev_docs/sandbox/components.md b/docs/docs/dev_docs/sandbox/components.md index 588aeaa016f..cb07a4b6139 100644 --- a/docs/docs/dev_docs/sandbox/components.md +++ b/docs/docs/dev_docs/sandbox/components.md @@ -2,7 +2,11 @@ title: Components --- - + + +:::TODO Outdated +This page needs to be updated. +::: import Disclaimer from '../../misc/common/\_disclaimer.mdx'; @@ -84,10 +88,10 @@ Responsibilities: These tasks are lower priority than providing a handcrafted ABI. -- The ability for a dev to enclose a collection of Noir functions in a 'contract scope'. -- The ability to create a Noir contract abi from the above. +- The ability for a dev to enclose a collection of Aztec.nr functions in a 'contract scope'. +- The ability to create an Aztec.nr contract abi from the above. -Design a Noir Contract ABI, similar to a Solidity ABI which is output by Solc (see [here](https://docs.soliditylang.org/en/v0.8.13/abi-spec.html#json)). It might include for each function: +Design an Aztec.nr Contract ABI, similar to a Solidity ABI which is output by Solc (see [here](https://docs.soliditylang.org/en/v0.8.13/abi-spec.html#json)). It might include for each function: - ACIR opcodes (akin to Solidity bytecode). - Function name and parameter names & types. @@ -109,7 +113,7 @@ aztec.js should always be stateless. It offers the ability to interact with stat The analogous AC component would be the AztecSdk (wraps the CoreSdk which is more analogous to the private client). - Allows a user to create an Aztec keypair. Call `create_account` on Wallet. -- Create a `Contract` instance (similar to web3.js), given a path to a Noir Contract ABI. +- Create a `Contract` instance (similar to web3.js), given a path to an Aztec.nr Contract ABI. - Construct `tx_request` by calling e.g. `contract.get_deployment_request(constructor_args)`. - Call wallet `sign_tx_request(tx_request)` to get signature. - Call `simulate_tx(signed_tx_request)` on the Private Client. In future this would help compute gas, for now we won't actually return gas (it's hard). Returns success or failure, so client knows if it should proceed, and computed kernel circuit public outputs. diff --git a/docs/docs/dev_docs/sandbox/main.md b/docs/docs/dev_docs/sandbox/main.md index 9ddf0ce78ac..2f33ffa684a 100644 --- a/docs/docs/dev_docs/sandbox/main.md +++ b/docs/docs/dev_docs/sandbox/main.md @@ -2,7 +2,7 @@ ## What is the Aztec Sandbox? -The Aztec Sandbox is local development system against which you can build and test Noir contracts in a fast, safe, and free environment. +The Aztec Sandbox is local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. To learn more and to download to for yourself you can visit the [website](https://sandbox.aztec.network). diff --git a/docs/docs/dev_docs/testing/cheat_codes.md b/docs/docs/dev_docs/testing/cheat_codes.md index 4a09ac7f811..458b5f406db 100644 --- a/docs/docs/dev_docs/testing/cheat_codes.md +++ b/docs/docs/dev_docs/testing/cheat_codes.md @@ -382,7 +382,7 @@ Otherwise, it will throw an error. const timestamp = await cc.eth.timestamp(); const newTimestamp = timestamp + 100_000_000; await cc.aztec.warp(newTimestamp); -// any noir contract calls that make use of current timestamp +// any Aztec.nr contract calls that make use of current timestamp // and is executed in the next rollup block will now read `newTimestamp` ``` @@ -395,7 +395,7 @@ public computeSlotInMap(baseSlot: Fr | bigint, key: Fr | bigint): Fr #### Description Compute storage slot for a map key. -The baseSlot is specified in the noir contract. +The baseSlot is specified in the Aztec.nr contract. #### Example ```rust diff --git a/docs/docs/dev_docs/testing/main.md b/docs/docs/dev_docs/testing/main.md index ca7cd33a835..a6adae5114b 100644 --- a/docs/docs/dev_docs/testing/main.md +++ b/docs/docs/dev_docs/testing/main.md @@ -2,8 +2,8 @@ Please use the [TUTORIAL-TEMPLATE](../../TUTORIAL_TEMPLATE.md) for standalone guides / tutorials. -## Testing in Noir +## Testing in Aztec.nr Individual functions can be tested much like [how 'regular Noir' functions can be tested](https://noir-lang.org/nargo/testing). -But a Noir Contract typically tracks state variables, so you'll likely need to write more complex tests in TypeScript, using Aztec.js \ No newline at end of file +But an Aztec.nr contract typically tracks state variables, so you'll likely need to write more complex tests in TypeScript, using Aztec.js \ No newline at end of file diff --git a/docs/docs/dev_docs/wallets/architecture.md b/docs/docs/dev_docs/wallets/architecture.md index 27818b48b9f..2d81c594655 100644 --- a/docs/docs/dev_docs/wallets/architecture.md +++ b/docs/docs/dev_docs/wallets/architecture.md @@ -8,7 +8,7 @@ Architecture-wise, a wallet is an instance of an **Aztec RPC Server** which mana Additionally, a wallet must be able to handle one or more [account contract implementations](../../concepts/foundation/accounts/main.md#account-contracts-and-wallets). When a user creates a new account, the account is represented on-chain by an account contract. The wallet is responsible for deploying and interacting with this contract. A wallet may support multiple flavours of accounts, such as an account that uses ECDSA signatures, or one that relies on WebAuthn, or one that requires multi-factor authentication. For a user, the choice of what account implementation to use is then determined by the wallet they interact with. -In code, this translates to a wallet implementing an **Entrypoint** interface that defines [how to create an _execution request_ out of an array of _function calls_](./main.md#transaction-lifecycle) for the specific implementation of an account contract. Think of the entrypoint interface as the Javascript counterpart of an account contract, or the piece of code that knows how to format and authenticate a transaction based on the rules defined in Noir by the user's account. +In code, this translates to a wallet implementing an **Entrypoint** interface that defines [how to create an _execution request_ out of an array of _function calls_](./main.md#transaction-lifecycle) for the specific implementation of an account contract. Think of the entrypoint interface as the Javascript counterpart of an account contract, or the piece of code that knows how to format and authenticate a transaction based on the rules defined in Aztec.nr by the user's account. ## Entrypoint interface diff --git a/docs/docs/dev_docs/wallets/writing_an_account_contract.md b/docs/docs/dev_docs/wallets/writing_an_account_contract.md index b6ddc219c5d..4e42ae43efa 100644 --- a/docs/docs/dev_docs/wallets/writing_an_account_contract.md +++ b/docs/docs/dev_docs/wallets/writing_an_account_contract.md @@ -14,7 +14,7 @@ For the sake of simplicity, we will hardcode the signing public key into the con ## The account contract -Let's start with the account contract itself in Noir. Create [a new Noir contract project](../contracts/main.md) that will contain a file with the code for the account contract, with a hardcoded public key: +Let's start with the account contract itself in Aztec.nr. Create [a new Aztec.nr contract project](../contracts/main.md) that will contain a file with the code for the account contract, with a hardcoded public key: #include_code contract yarn-project/noir-contracts/src/contracts/schnorr_hardcoded_account_contract/src/main.nr rust @@ -32,7 +32,7 @@ Public Key: 0x0ede151adaef1cfcc1b3e152ea39f00c5cda3f3857cef00decb049d283672dc71 The important part of this contract is the `entrypoint` function, which will be the first function executed in any transaction originated from this account. This function has two main responsibilities: 1) authenticating the transaction and 2) executing calls. It receives a `payload` with the list of function calls to execute, as well as a signature over that payload. -#include_code entrypoint-struct yarn-project/noir-libs/aztec-noir/src/entrypoint.nr rust +#include_code entrypoint-struct yarn-project/aztec-nr/aztec/src/entrypoint.nr rust :::info Using the `EntrypointPayload` struct is not mandatory. You can package the instructions to be carried out by your account contract however you want. However, the entrypoint payload already provides a set of helper functions, both in Noir and Typescript, that can save you a lot of time when writing a new account contract. @@ -48,13 +48,13 @@ We authenticate the transaction. To do this, we serialise and Pedersen-hash the Last, we execute the calls in the payload struct. The `execute_calls` helper function runs through the private and public calls included in the entrypoint payload and executes them: -#include_code entrypoint-execute-calls yarn-project/noir-libs/aztec-noir/src/entrypoint.nr rust +#include_code entrypoint-execute-calls yarn-project/aztec-nr/aztec/src/entrypoint.nr rust Note the usage of the `_with_packed_args` variant of [`call_public_function` and `call_private_function`](../contracts/functions.md#calling-functions). Due to Noir limitations, we cannot include more than a small number of arguments in a function call. However, we can bypass this restriction by using a hash of the arguments in a function call, which gets automatically expanded to the full set of arguments when the nested call is executed. We call this _argument packing_. ## The typescript side of things -Now that we have a valid Noir account contract, we need to write the typescript glue code that will take care of formatting and authenticating transactions so they can be processed by our contract, as well as deploying the contract during account setup. This takes the form of implementing the `AccountContract` interface: +Now that we have a valid Aztec.nr account contract, we need to write the typescript glue code that will take care of formatting and authenticating transactions so they can be processed by our contract, as well as deploying the contract during account setup. This takes the form of implementing the `AccountContract` interface: #include_code account-contract-interface yarn-project/aztec.js/src/account/contract/index.ts typescript diff --git a/l1-contracts/GUIDE_LINES.md b/l1-contracts/GUIDE_LINES.md index 255f85c52a5..650c09befbf 100644 --- a/l1-contracts/GUIDE_LINES.md +++ b/l1-contracts/GUIDE_LINES.md @@ -5,7 +5,7 @@ In the following, there will be guidelines for the process of writing readable, - when optimizing - when reviewing. -In general the language of choice will be Solidity for our L1 contracts, so most of the specific style rules will be having that in mind, but the process for writing it can be adapted slightly for vyper, and will have an extension when Noir contracts are more mature. +In general the language of choice will be Solidity for our L1 contracts, so most of the specific style rules will be having that in mind, but the process for writing it can be adapted slightly for vyper, and will have an extension when Aztec.nr contracts are more mature. ![](https://media.tenor.com/ry_sCXk6wH0AAAAC/pirates-caribbean-code.gif) diff --git a/l1-contracts/src/core/libraries/Decoder.sol b/l1-contracts/src/core/libraries/Decoder.sol index 2de68f9d980..b5f604437fc 100644 --- a/l1-contracts/src/core/libraries/Decoder.sol +++ b/l1-contracts/src/core/libraries/Decoder.sol @@ -401,7 +401,7 @@ library Decoder { // Iterate until all the logs were processed while (remainingLogsLength > 0) { - // The length of the logs emitted by Noir from the function call corresponding to this kernel iteration + // The length of the logs emitted by Aztec.nr from the function call corresponding to this kernel iteration uint256 privateCircuitPublicInputLogsLength = read4(_l2Block, offset); offset += 0x4; diff --git a/yarn-project/acir-simulator/package.json b/yarn-project/acir-simulator/package.json index ef6fd4d3bfc..d11b6d6fafa 100644 --- a/yarn-project/acir-simulator/package.json +++ b/yarn-project/acir-simulator/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/acir-simulator/src/acvm/acvm.ts b/yarn-project/acir-simulator/src/acvm/acvm.ts index e806f22618c..2a9db8fb761 100644 --- a/yarn-project/acir-simulator/src/acvm/acvm.ts +++ b/yarn-project/acir-simulator/src/acvm/acvm.ts @@ -38,6 +38,7 @@ type ORACLE_NAMES = | 'getSecretKey' | 'getNote' | 'getNotes' + | 'checkNoteHashExists' | 'getRandomField' | 'notifyCreatedNote' | 'notifyNullifiedNote' @@ -46,7 +47,6 @@ type ORACLE_NAMES = | 'enqueuePublicFunctionCall' | 'storageRead' | 'storageWrite' - | 'getCommitment' | 'getL1ToL2Message' | 'getPortalContractAddress' | 'emitEncryptedLog' diff --git a/yarn-project/acir-simulator/src/acvm/serialize.ts b/yarn-project/acir-simulator/src/acvm/serialize.ts index 9b8e2640315..00ca0d9de48 100644 --- a/yarn-project/acir-simulator/src/acvm/serialize.ts +++ b/yarn-project/acir-simulator/src/acvm/serialize.ts @@ -9,7 +9,7 @@ import { } from '@aztec/circuits.js'; import { Fr } from '@aztec/foundation/fields'; -import { CommitmentDataOracleInputs, MessageLoadOracleInputs } from '../client/db_oracle.js'; +import { MessageLoadOracleInputs } from '../client/db_oracle.js'; import { ACVMField, toACVMField } from './acvm.js'; // Utilities to write TS classes to ACVM Field arrays @@ -127,11 +127,11 @@ export function toAcvmCallPrivateStackItem(item: PrivateCallStackItem): ACVMFiel /** * Converts a public call stack item with the request for executing a public function to - * a set of ACVM fields accepted by the enqueue_public_function_call_oracle Noir function. + * a set of ACVM fields accepted by the enqueue_public_function_call_oracle Aztec.nr function. * Note that only the fields related to the request are serialized: those related to the result * are empty since this is just an execution request, so we don't send them to the circuit. * @param item - The public call stack item to serialize to be passed onto Noir. - * @returns The fields expected by the enqueue_public_function_call_oracle Noir function. + * @returns The fields expected by the enqueue_public_function_call_oracle Aztec.nr function. */ export async function toAcvmEnqueuePublicFunctionResult(item: PublicCallRequest): Promise { return [ @@ -160,23 +160,6 @@ export function toAcvmL1ToL2MessageLoadOracleInputs( ]; } -/** - * Converts the result of loading commitments to ACVM fields. - * @param commitmentLoadOracleInputs - The result of loading messages to convert. - * @param l1ToL2MessagesTreeRoot - The L1 to L2 messages tree root - * @returns The Message Oracle Fields. - */ -export function toAcvmCommitmentLoadOracleInputs( - messageLoadOracleInputs: CommitmentDataOracleInputs, - l1ToL2MessagesTreeRoot: Fr, -): ACVMField[] { - return [ - toACVMField(messageLoadOracleInputs.commitment), - toACVMField(messageLoadOracleInputs.index), - toACVMField(l1ToL2MessagesTreeRoot), - ]; -} - /** * Inserts a list of ACVM fields to a witness. * @param witnessStartIndex - The index where to start inserting the fields. diff --git a/yarn-project/acir-simulator/src/client/client_execution_context.ts b/yarn-project/acir-simulator/src/client/client_execution_context.ts index 61d1d09c779..5dc9ff7d549 100644 --- a/yarn-project/acir-simulator/src/client/client_execution_context.ts +++ b/yarn-project/acir-simulator/src/client/client_execution_context.ts @@ -6,9 +6,10 @@ import { createDebugLogger } from '@aztec/foundation/log'; import { ACVMField, + ONE_ACVM_FIELD, + ZERO_ACVM_FIELD, fromACVMField, toACVMField, - toAcvmCommitmentLoadOracleInputs, toAcvmL1ToL2MessageLoadOracleInputs, } from '../acvm/index.js'; import { PackedArgsCache } from '../common/packed_args_cache.js'; @@ -156,7 +157,7 @@ export class ClientTxExecutionContext { // Nullified pending notes are already removed from the list. const pendingNotes = this.noteCache.getNotes(contractAddress, storageSlotField); - const pendingNullifiers = this.noteCache.getNullifiers(contractAddress, storageSlotField); + const pendingNullifiers = this.noteCache.getNullifiers(contractAddress); const dbNotes = await this.db.getNotes(contractAddress, storageSlotField); const dbNotesFiltered = dbNotes.filter(n => !pendingNullifiers.has((n.siloedNullifier as Fr).value)); @@ -185,7 +186,7 @@ export class ClientTxExecutionContext { }); // TODO: notice, that if we don't have a note in our DB, we don't know how big the preimage needs to be, and so we don't actually know how many dummy notes to return, or big to make those dummy notes, or where to position `is_some` booleans to inform the noir program that _all_ the notes should be dummies. - // By a happy coincidence, a `0` field is interpreted as `is_none`, and since in this case (of an empty db) we'll return all zeros (paddedZeros), the noir program will treat the returned data as all dummies, but this is luck. Perhaps a preimage size should be conveyed by the get_notes noir oracle? + // By a happy coincidence, a `0` field is interpreted as `is_none`, and since in this case (of an empty db) we'll return all zeros (paddedZeros), the noir program will treat the returned data as all dummies, but this is luck. Perhaps a preimage size should be conveyed by the get_notes Aztec.nr oracle? const preimageLength = notes?.[0]?.preimage.length ?? 0; if ( !notes.every(({ preimage }) => { @@ -253,23 +254,12 @@ export class ClientTxExecutionContext { * Adding a siloed nullifier into the current set of all pending nullifiers created * within the current transaction/execution. * @param contractAddress - The contract address. - * @param storageSlot - The storage slot. * @param innerNullifier - The pending nullifier to add in the list (not yet siloed by contract address). * @param innerNoteHash - The inner note hash of the new note. * @param contractAddress - The contract address */ - public async handleNullifiedNote( - contractAddress: AztecAddress, - storageSlot: ACVMField, - innerNullifier: ACVMField, - innerNoteHash: ACVMField, - ) { - await this.noteCache.nullifyNote( - contractAddress, - fromACVMField(storageSlot), - fromACVMField(innerNullifier), - fromACVMField(innerNoteHash), - ); + public async handleNullifiedNote(contractAddress: AztecAddress, innerNullifier: ACVMField, innerNoteHash: ACVMField) { + await this.noteCache.nullifyNote(contractAddress, fromACVMField(innerNullifier), fromACVMField(innerNoteHash)); } /** @@ -285,20 +275,39 @@ export class ClientTxExecutionContext { /** * Fetches a path to prove existence of a commitment in the db, given its contract side commitment (before silo). * @param contractAddress - The contract address. - * @param commitment - The commitment. - * @returns The commitment data. + * @param nonce - The nonce of the note. + * @param innerNoteHash - The inner note hash of the note. + * @returns 1 if (persistent or transient) note hash exists, 0 otherwise. Value is in ACVMField form. */ - public async getCommitment(contractAddress: AztecAddress, commitment: ACVMField) { - const innerNoteHash = fromACVMField(commitment); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): only works - // for noteHashes/commitments created by public functions! Once public kernel or - // base rollup circuit injects nonces, this can be used with commitments created by - // private functions as well. - const commitmentInputs = await this.db.getCommitmentOracle(contractAddress, innerNoteHash); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1029): support pending commitments here + public async checkNoteHashExists( + contractAddress: AztecAddress, + nonce: ACVMField, + innerNoteHash: ACVMField, + ): Promise { + const nonceField = fromACVMField(nonce); + const innerNoteHashField = fromACVMField(innerNoteHash); + if (nonceField.isZero()) { + // If nonce is 0, we are looking for a new note created in this transaction. + const exists = this.noteCache.checkNoteExists(contractAddress, innerNoteHashField); + if (exists) { + return ONE_ACVM_FIELD; + } + // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386) + // Currently it can also be a note created from public if nonce is 0. + // If we can't find a matching new note, keep looking for the match from the notes created in previous transactions. + } + + // If nonce is zero, SHOULD only be able to reach this point if note was publicly created const wasm = await CircuitsWasm.get(); - const siloedNoteHash = siloCommitment(wasm, contractAddress, innerNoteHash); - this.gotNotes.set(siloedNoteHash.value, commitmentInputs.index); - return toAcvmCommitmentLoadOracleInputs(commitmentInputs, this.historicBlockData.privateDataTreeRoot); + let noteHashToLookUp = siloCommitment(wasm, contractAddress, innerNoteHashField); + if (!nonceField.isZero()) { + noteHashToLookUp = computeUniqueCommitment(wasm, nonceField, noteHashToLookUp); + } + + const index = await this.db.getCommitmentIndex(noteHashToLookUp); + if (index !== undefined) { + this.gotNotes.set(noteHashToLookUp.value, index); + } + return index !== undefined ? ONE_ACVM_FIELD : ZERO_ACVM_FIELD; } } diff --git a/yarn-project/acir-simulator/src/client/db_oracle.ts b/yarn-project/acir-simulator/src/client/db_oracle.ts index df56338f9fa..cb3c77b113c 100644 --- a/yarn-project/acir-simulator/src/client/db_oracle.ts +++ b/yarn-project/acir-simulator/src/client/db_oracle.ts @@ -27,7 +27,7 @@ export interface NoteData { } /** - * The format that noir uses to get L1 to L2 Messages. + * The format that Aztec.nr uses to get L1 to L2 Messages. */ export interface MessageLoadOracleInputs { /** @@ -45,22 +45,6 @@ export interface MessageLoadOracleInputs { index: bigint; } -/** - * The format noir uses to get commitments. - */ -export interface CommitmentDataOracleInputs { - /** The siloed commitment. */ - commitment: Fr; - /** - * The path in the merkle tree to the commitment. - */ - siblingPath: Fr[]; - /** - * The index of the message commitment in the merkle tree. - */ - index: bigint; -} - /** * A function ABI with optional debug metadata */ diff --git a/yarn-project/acir-simulator/src/client/debug.ts b/yarn-project/acir-simulator/src/client/debug.ts index 21efa0e576c..a6e7d97d075 100644 --- a/yarn-project/acir-simulator/src/client/debug.ts +++ b/yarn-project/acir-simulator/src/client/debug.ts @@ -24,7 +24,7 @@ export function acvmFieldMessageToString(msg: ACVMField[]): string { } /** - * Format a debug string for Noir filling in `'{0}'` entries with their + * Format a debug string for Aztec.nr filling in `'{0}'` entries with their * corresponding values from the args array. * * @param formatStr - str of form `'this is a string with some entries like {0} and {1}'` diff --git a/yarn-project/acir-simulator/src/client/execution_note_cache.ts b/yarn-project/acir-simulator/src/client/execution_note_cache.ts index 18de0658095..45e883dda6f 100644 --- a/yarn-project/acir-simulator/src/client/execution_note_cache.ts +++ b/yarn-project/acir-simulator/src/client/execution_note_cache.ts @@ -5,41 +5,32 @@ import { Fr } from '@aztec/foundation/fields'; import { NoteData } from './db_oracle.js'; -/** - * Generate a key with the given contract address and storage slot. - * @param contractAddress - Contract address. - * @param storageSlot - Storage slot. - */ -const generateKeyForContractStorageSlot = (contractAddress: AztecAddress, storageSlot: Fr) => - `${contractAddress.toShortString}${storageSlot}`; - /** * Data that's accessible by all the function calls in an execution. */ export class ExecutionNoteCache { /** - * Notes created during execution. - * The key of the mapping is a value representing a contract address and storage slot combination. + * New notes created in this transaction. + * This mapping maps from a contract address to the notes in the contract. */ - private newNotes: Map = new Map(); + private newNotes: Map = new Map(); /** * The list of nullifiers created in this transaction. - * The key of the mapping is a value representing a contract address and storage slot combination. + * This mapping maps from a contract address to the nullifiers emitted from the contract. * The note which is nullified might be new or not (i.e., was generated in a previous transaction). * Note that their value (bigint representation) is used because Frs cannot be looked up in Sets. */ - private nullifiers: Map> = new Map(); + private nullifiers: Map> = new Map(); /** * Add a new note to cache. * @param note - New note created during execution. */ public addNewNote(note: NoteData) { - const key = generateKeyForContractStorageSlot(note.contractAddress, note.storageSlot); - const notes = this.newNotes.get(key) ?? []; + const notes = this.newNotes.get(note.contractAddress.toBigInt()) ?? []; notes.push(note); - this.newNotes.set(key, notes); + this.newNotes.set(note.contractAddress.toBigInt(), notes); } /** @@ -50,32 +41,22 @@ export class ExecutionNoteCache { * @param innerNoteHash - Inner note hash of the note. If this value equals EMPTY_NULLIFIED_COMMITMENT, it means the * note being nullified is from a previous transaction (and thus not a new note). */ - public async nullifyNote(contractAddress: AztecAddress, storageSlot: Fr, innerNullifier: Fr, innerNoteHash: Fr) { + public async nullifyNote(contractAddress: AztecAddress, innerNullifier: Fr, innerNoteHash: Fr) { const wasm = await CircuitsWasm.get(); const siloedNullifier = siloNullifier(wasm, contractAddress, innerNullifier); - const nullifiers = this.getNullifiers(contractAddress, storageSlot); - if (nullifiers.has(siloedNullifier.value)) { - throw new Error('Attemp to nullify the same note twice.'); - } - + const nullifiers = this.getNullifiers(contractAddress); nullifiers.add(siloedNullifier.value); - const key = generateKeyForContractStorageSlot(contractAddress, storageSlot); - this.nullifiers.set(key, nullifiers); + this.nullifiers.set(contractAddress.toBigInt(), nullifiers); // Find and remove the matching new note if the emitted innerNoteHash is not empty. if (!innerNoteHash.equals(new Fr(EMPTY_NULLIFIED_COMMITMENT))) { - const notes = this.newNotes.get(key) ?? []; - /** - * The identifier used to determine matching is the inner note hash value. - * However, we adopt a defensive approach and ensure that the contract address - * and storage slot do match. - */ + const notes = this.newNotes.get(contractAddress.toBigInt()) ?? []; const noteIndexToRemove = notes.findIndex(n => n.innerNoteHash.equals(innerNoteHash)); if (noteIndexToRemove === -1) { throw new Error('Attemp to remove a pending note that does not exist.'); } notes.splice(noteIndexToRemove, 1); - this.newNotes.set(key, notes); + this.newNotes.set(contractAddress.toBigInt(), notes); } } @@ -86,17 +67,26 @@ export class ExecutionNoteCache { * @param storageSlot - Storage slot of the notes. **/ public getNotes(contractAddress: AztecAddress, storageSlot: Fr) { - const key = generateKeyForContractStorageSlot(contractAddress, storageSlot); - return this.newNotes.get(key) ?? []; + const notes = this.newNotes.get(contractAddress.toBigInt()) ?? []; + return notes.filter(n => n.storageSlot.equals(storageSlot)); } /** - * Return all nullifiers of a storage slot. - * @param contractAddress - Contract address of the notes. - * @param storageSlot - Storage slot of the notes. + * Check if a note exists in the newNotes array. + * @param contractAddress - Contract address of the note. + * @param storageSlot - Storage slot of the note. + * @param innerNoteHash - Inner note hash of the note. + **/ + public checkNoteExists(contractAddress: AztecAddress, innerNoteHash: Fr) { + const notes = this.newNotes.get(contractAddress.toBigInt()) ?? []; + return notes.some(n => n.innerNoteHash.equals(innerNoteHash)); + } + + /** + * Return all nullifiers emitted from a contract. + * @param contractAddress - Address of the contract. */ - public getNullifiers(contractAddress: AztecAddress, storageSlot: Fr): Set { - const key = generateKeyForContractStorageSlot(contractAddress, storageSlot); - return this.nullifiers.get(key) || new Set(); + public getNullifiers(contractAddress: AztecAddress): Set { + return this.nullifiers.get(contractAddress.toBigInt()) ?? new Set(); } } diff --git a/yarn-project/acir-simulator/src/client/private_execution.test.ts b/yarn-project/acir-simulator/src/client/private_execution.test.ts index e7d769cd235..3ba37e9f200 100644 --- a/yarn-project/acir-simulator/src/client/private_execution.test.ts +++ b/yarn-project/acir-simulator/src/client/private_execution.test.ts @@ -223,7 +223,7 @@ describe('Private Execution test suite', () => { const storageSlot = Fr.random(); const note = buildNote(60n, owner, storageSlot); - // Should be the same as how we compute the values for the ValueNote in the noir library. + // Should be the same as how we compute the values for the ValueNote in the Aztec.nr library. const valueNoteHash = pedersenPlookupCommitInputs( circuitsWasm, note.preimage.map(f => f.toBuffer()), @@ -365,7 +365,7 @@ describe('Private Execution test suite', () => { expect(changeNote.preimage[0]).toEqual(new Fr(balance - amountToTransfer)); }); - it('Should be able to claim a note by providing the correct secret', async () => { + it('Should be able to claim a note by providing the correct secret and nonce', async () => { const amount = 100n; const secret = Fr.random(); const abi = getFunctionAbi(PrivateTokenAirdropContractAbi, 'claim'); @@ -374,22 +374,11 @@ describe('Private Execution test suite', () => { const nonce = new Fr(1n); const customNoteHash = hash([toBufferBE(amount, 32), secret.toBuffer()]); const innerNoteHash = Fr.fromBuffer(hash([storageSlot.toBuffer(), customNoteHash])); - - oracle.getNotes.mockResolvedValue([ - { - contractAddress, - storageSlot, - nonce, - preimage: [new Fr(amount), secret], - innerNoteHash, - siloedNullifier: new Fr(0), - index: 1n, - }, - ]); + oracle.getCommitmentIndex.mockResolvedValue(2n); const result = await runSimulator({ abi, - args: [amount, secret, recipient], + args: [amount, secret, recipient, nonce], }); // Check a nullifier has been inserted. @@ -462,7 +451,7 @@ describe('Private Execution test suite', () => { const storageSlot = Fr.random(); const note = buildNote(60n, owner, storageSlot); - // Should be the same as how we compute the values for the ValueNote in the noir library. + // Should be the same as how we compute the values for the ValueNote in the Aztec.nr library. const valueNoteHash = pedersenPlookupCommitInputs( circuitsWasm, note.preimage.map(f => f.toBuffer()), @@ -638,7 +627,7 @@ describe('Private Execution test suite', () => { expect(result.nestedExecutions).toHaveLength(1); expect(result.nestedExecutions[0].callStackItem.publicInputs.returnValues[0]).toEqual(new Fr(privateIncrement)); - // check that Noir calculated the call stack item hash like cpp does + // check that Aztec.nr calculated the call stack item hash like cpp does const wasm = await CircuitsWasm.get(); const expectedCallStackItemHash = computeCallStackItemHash(wasm, result.nestedExecutions[0].callStackItem); expect(result.callStackItem.publicInputs.privateCallStack[0]).toEqual(expectedCallStackItemHash); @@ -751,20 +740,7 @@ describe('Private Execution test suite', () => { const storageSlot = new Fr(2); const innerNoteHash = hash([storageSlot.toBuffer(), noteHash.toBuffer()]); const siloedNoteHash = siloCommitment(wasm, contractAddress, Fr.fromBuffer(innerNoteHash)); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): should insert - // uniqueSiloedNoteHash in tree and that should be what is expected in Noir - //const uniqueSiloedNoteHash = computeUniqueCommitment(wasm, nonce, Fr.fromBuffer(innerNoteHash)); - - const tree = await insertLeaves([siloedNoteHash]); - - oracle.getCommitmentOracle.mockImplementation(async () => { - // Check the calculated commitment is correct - return Promise.resolve({ - commitment: siloedNoteHash, - siblingPath: (await tree.getSiblingPath(0n, false)).toFieldArray(), - index: 0n, - }); - }); + oracle.getCommitmentIndex.mockResolvedValue(0n); const result = await runSimulator({ abi, diff --git a/yarn-project/acir-simulator/src/client/private_execution.ts b/yarn-project/acir-simulator/src/client/private_execution.ts index 2e058c86852..1ee35591083 100644 --- a/yarn-project/acir-simulator/src/client/private_execution.ts +++ b/yarn-project/acir-simulator/src/client/private_execution.ts @@ -99,10 +99,12 @@ export class PrivateFunctionExecution { this.context.handleNewNote(this.contractAddress, storageSlot, preimage, innerNoteHash); return Promise.resolve(ZERO_ACVM_FIELD); }, - notifyNullifiedNote: async ([slot], [innerNullifier], [innerNoteHash]) => { - await this.context.handleNullifiedNote(this.contractAddress, slot, innerNullifier, innerNoteHash); + notifyNullifiedNote: async ([innerNullifier], [innerNoteHash]) => { + await this.context.handleNullifiedNote(this.contractAddress, innerNullifier, innerNoteHash); return Promise.resolve(ZERO_ACVM_FIELD); }, + checkNoteHashExists: ([nonce], [innerNoteHash]) => + this.context.checkNoteHashExists(this.contractAddress, nonce, innerNoteHash), callPrivateFunction: async ([acvmContractAddress], [acvmFunctionSelector], [acvmArgsHash]) => { const contractAddress = fromACVMField(acvmContractAddress); const functionSelector = fromACVMField(acvmFunctionSelector); @@ -125,7 +127,6 @@ export class PrivateFunctionExecution { getL1ToL2Message: ([msgKey]) => { return this.context.getL1ToL2Message(fromACVMField(msgKey)); }, - getCommitment: ([commitment]) => this.context.getCommitment(this.contractAddress, commitment), debugLog: (...args) => { this.log(oracleDebugCallToFormattedStr(args)); return Promise.resolve(ZERO_ACVM_FIELD); diff --git a/yarn-project/acir-simulator/src/client/unconstrained_execution.ts b/yarn-project/acir-simulator/src/client/unconstrained_execution.ts index f11c95d4c70..4a1d8fc89c3 100644 --- a/yarn-project/acir-simulator/src/client/unconstrained_execution.ts +++ b/yarn-project/acir-simulator/src/client/unconstrained_execution.ts @@ -72,13 +72,14 @@ export class UnconstrainedFunctionExecution { +offset, +returnSize, ), + checkNoteHashExists: ([nonce], [innerNoteHash]) => + this.context.checkNoteHashExists(this.contractAddress, nonce, innerNoteHash), getRandomField: () => Promise.resolve(toACVMField(Fr.random())), debugLog: (...params) => { this.log(oracleDebugCallToFormattedStr(params)); return Promise.resolve(ZERO_ACVM_FIELD); }, getL1ToL2Message: ([msgKey]) => this.context.getL1ToL2Message(fromACVMField(msgKey)), - getCommitment: ([commitment]) => this.context.getCommitment(this.contractAddress, commitment), storageRead: async ([slot], [numberOfElements]) => { if (!aztecNode) { const errMsg = `Aztec node is undefined, cannot read storage`; diff --git a/yarn-project/acir-simulator/src/public/db.ts b/yarn-project/acir-simulator/src/public/db.ts index bc79cb17b76..245c3f103c7 100644 --- a/yarn-project/acir-simulator/src/public/db.ts +++ b/yarn-project/acir-simulator/src/public/db.ts @@ -2,7 +2,7 @@ import { EthAddress, FunctionSelector } from '@aztec/circuits.js'; import { AztecAddress } from '@aztec/foundation/aztec-address'; import { Fr } from '@aztec/foundation/fields'; -import { CommitmentDataOracleInputs, MessageLoadOracleInputs } from '../index.js'; +import { MessageLoadOracleInputs } from '../index.js'; /** * Database interface for providing access to public state. @@ -65,10 +65,9 @@ export interface CommitmentsDB { getL1ToL2Message(msgKey: Fr): Promise; /** - * Gets a message index and sibling path to some commitment in the private data tree. - * @param address - The contract address owning storage. - * @param commitment - The preimage of the siloed data. - * @returns - The Commitment data oracle object + * Gets the index of a commitment in the private data tree. + * @param commitment - The commitment. + * @returns - The index of the commitment. Undefined if it does not exist in the tree. */ - getCommitmentOracle(address: AztecAddress, commitment: Fr): Promise; + getCommitmentIndex(commitment: Fr): Promise; } diff --git a/yarn-project/acir-simulator/src/public/executor.ts b/yarn-project/acir-simulator/src/public/executor.ts index 4d8fe6da158..ca1451771dd 100644 --- a/yarn-project/acir-simulator/src/public/executor.ts +++ b/yarn-project/acir-simulator/src/public/executor.ts @@ -1,6 +1,7 @@ import { AztecAddress, CallContext, + CircuitsWasm, EthAddress, Fr, FunctionData, @@ -9,11 +10,13 @@ import { HistoricBlockData, RETURN_VALUES_LENGTH, } from '@aztec/circuits.js'; +import { siloCommitment } from '@aztec/circuits.js/abis'; import { padArrayEnd } from '@aztec/foundation/collection'; import { createDebugLogger } from '@aztec/foundation/log'; import { FunctionL2Logs } from '@aztec/types'; import { + ONE_ACVM_FIELD, ZERO_ACVM_FIELD, acvm, convertACVMFieldToBuffer, @@ -23,7 +26,6 @@ import { fromACVMField, toACVMField, toACVMWitness, - toAcvmCommitmentLoadOracleInputs, toAcvmL1ToL2MessageLoadOracleInputs, } from '../acvm/index.js'; import { oracleDebugCallToFormattedStr } from '../client/debug.js'; @@ -91,12 +93,14 @@ export class PublicExecutor { const messageInputs = await this.commitmentsDb.getL1ToL2Message(fromACVMField(msgKey)); return toAcvmL1ToL2MessageLoadOracleInputs(messageInputs, this.blockData.l1ToL2MessagesTreeRoot); }, // l1 to l2 messages in public contexts TODO: https://github.com/AztecProtocol/aztec-packages/issues/616 - getCommitment: async ([commitment]) => { - const commitmentInputs = await this.commitmentsDb.getCommitmentOracle( - execution.contractAddress, - fromACVMField(commitment), - ); - return toAcvmCommitmentLoadOracleInputs(commitmentInputs, this.blockData.privateDataTreeRoot); + checkNoteHashExists: async ([_nonce], [innerNoteHash]) => { + // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386) + // Once public kernel or base rollup circuit injects nonces, this can be updated to use uniqueSiloedCommitment. + const wasm = await CircuitsWasm.get(); + const siloedNoteHash = siloCommitment(wasm, execution.contractAddress, fromACVMField(innerNoteHash)); + const index = await this.commitmentsDb.getCommitmentIndex(siloedNoteHash); + // return 0 or 1 for whether note hash exists + return index === undefined ? ZERO_ACVM_FIELD : ONE_ACVM_FIELD; }, storageRead: async ([slot], [numberOfElements]) => { const startStorageSlot = fromACVMField(slot); diff --git a/yarn-project/acir-simulator/src/utils.ts b/yarn-project/acir-simulator/src/utils.ts index fa30e578657..a15b8f74b0f 100644 --- a/yarn-project/acir-simulator/src/utils.ts +++ b/yarn-project/acir-simulator/src/utils.ts @@ -3,7 +3,7 @@ import { Grumpkin, pedersenPlookupCommitInputs } from '@aztec/circuits.js/barret import { Fr } from '@aztec/foundation/fields'; /** - * A point in the format that noir uses. + * A point in the format that Aztec.nr uses. */ export type NoirPoint = { /** The x coordinate. */ diff --git a/yarn-project/archiver/package.json b/yarn-project/archiver/package.json index 4dbc4a5465e..48867bed693 100644 --- a/yarn-project/archiver/package.json +++ b/yarn-project/archiver/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/aztec-node/package.json b/yarn-project/aztec-node/package.json index ec5beb82863..8e785e5b058 100644 --- a/yarn-project/aztec-node/package.json +++ b/yarn-project/aztec-node/package.json @@ -12,8 +12,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/aztec-nr/.gitrepo b/yarn-project/aztec-nr/.gitrepo new file mode 100644 index 00000000000..9b54eedeb04 --- /dev/null +++ b/yarn-project/aztec-nr/.gitrepo @@ -0,0 +1,12 @@ +; DO NOT EDIT (unless you know what you are doing) +; +; This subdirectory is a git "subrepo", and this file is maintained by the +; git-subrepo command. See https://github.com/ingydotnet/git-subrepo#readme +; +[subrepo] + remote = git@github.com:AztecProtocol/aztec-nr.git + branch = master + commit = f662901567fa19e205062d84180763f06cddd641 + method = merge + cmdver = 0.4.6 + parent = 8df8fa7351ca79c022e2eb7dddfd7cf0145876df diff --git a/yarn-project/aztec-nr/LICENCE b/yarn-project/aztec-nr/LICENCE new file mode 100644 index 00000000000..7a4a3ea2424 --- /dev/null +++ b/yarn-project/aztec-nr/LICENCE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/yarn-project/aztec-nr/README.md b/yarn-project/aztec-nr/README.md new file mode 100644 index 00000000000..c137de45e0c --- /dev/null +++ b/yarn-project/aztec-nr/README.md @@ -0,0 +1,66 @@ +
+ + +

Aztec.nr

+ +

+ Aztec Smart Contract Development Framework +

+ +

+ Build Status + Aztec Website + Discord Chat + License +

+
+ + +# Aztec.nr + +`Aztec-nr` is a [Noir](https://noir-lang.org) framework for contract development on [Aztec](aztec.network). + +### Directory Structure +``` +. +├── aztec // The core of the aztec framework +├── easy-private-state // A library for easily creating private state +├── safe-math // A library for safe arithmetic +└── value-note // A library for storing arbitrary values +``` + +## Installing Aztec-nr libraries + +```toml +[package] +name = "your_contract" +authors = ["you! ;) "] +compiler_version = "" +type = "contract" + +[dependencies] +# To install the aztec framework (required to create aztec contracts). +aztec = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "aztec" } + +# Optional libraries +easy_private_state = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "easy-private-state" } +safe_math = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "safe-math" } +value_note = { git = "https://github.com/AztecProtocol/aztec-nr", tag = "master" , directory = "value-note" } +``` + + +## Prerequisites +To use `Aztec.nr` you must have [Noir](https://noir-lang.org/) installed. Noir is a general purpose programming language for creating zero-knowledge-proofs. `Aztec.nr` supercharges the Noir language with Aztec Smart Contract capabilities. + +### Quick Installation +The fastest way to install is with [noirup](https://noir-lang.org/getting_started/nargo_installation#option-1-noirup). + +To use `Aztec-nr` the `aztec` version of `Noir` is required (Note; this version is temporarily required if you would like to use `#[aztec()]` macros). + +Once noirup is installed, you can run the following: +```bash +noirup -v aztec +``` + +For more installation options, please view [Noir's getting started.](https://noir-lang.org/getting_started/nargo_installation) + diff --git a/yarn-project/aztec-nr/assets/Aztec_banner.png b/yarn-project/aztec-nr/assets/Aztec_banner.png new file mode 100644 index 00000000000..503202966b9 Binary files /dev/null and b/yarn-project/aztec-nr/assets/Aztec_banner.png differ diff --git a/yarn-project/noir-libs/aztec-noir/Nargo.toml b/yarn-project/aztec-nr/aztec/Nargo.toml similarity index 100% rename from yarn-project/noir-libs/aztec-noir/Nargo.toml rename to yarn-project/aztec-nr/aztec/Nargo.toml diff --git a/yarn-project/noir-libs/aztec-noir/src/abi.nr b/yarn-project/aztec-nr/aztec/src/abi.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/abi.nr rename to yarn-project/aztec-nr/aztec/src/abi.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/auth.nr b/yarn-project/aztec-nr/aztec/src/auth.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/auth.nr rename to yarn-project/aztec-nr/aztec/src/auth.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/constants_gen.nr b/yarn-project/aztec-nr/aztec/src/constants_gen.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/constants_gen.nr rename to yarn-project/aztec-nr/aztec/src/constants_gen.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/context.nr b/yarn-project/aztec-nr/aztec/src/context.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/context.nr rename to yarn-project/aztec-nr/aztec/src/context.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/entrypoint.nr b/yarn-project/aztec-nr/aztec/src/entrypoint.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/entrypoint.nr rename to yarn-project/aztec-nr/aztec/src/entrypoint.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/lib.nr b/yarn-project/aztec-nr/aztec/src/lib.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/lib.nr rename to yarn-project/aztec-nr/aztec/src/lib.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/log.nr b/yarn-project/aztec-nr/aztec/src/log.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/log.nr rename to yarn-project/aztec-nr/aztec/src/log.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/messaging.nr b/yarn-project/aztec-nr/aztec/src/messaging.nr similarity index 97% rename from yarn-project/noir-libs/aztec-noir/src/messaging.nr rename to yarn-project/aztec-nr/aztec/src/messaging.nr index c9ee3be0a3e..8f41c29c943 100644 --- a/yarn-project/noir-libs/aztec-noir/src/messaging.nr +++ b/yarn-project/aztec-nr/aztec/src/messaging.nr @@ -1,4 +1,3 @@ -mod get_commitment_getter_data; mod l1_to_l2_message; mod l1_to_l2_message_getter_data; diff --git a/yarn-project/noir-libs/aztec-noir/src/messaging/l1_to_l2_message.nr b/yarn-project/aztec-nr/aztec/src/messaging/l1_to_l2_message.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/messaging/l1_to_l2_message.nr rename to yarn-project/aztec-nr/aztec/src/messaging/l1_to_l2_message.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/messaging/l1_to_l2_message_getter_data.nr b/yarn-project/aztec-nr/aztec/src/messaging/l1_to_l2_message_getter_data.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/messaging/l1_to_l2_message_getter_data.nr rename to yarn-project/aztec-nr/aztec/src/messaging/l1_to_l2_message_getter_data.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note.nr b/yarn-project/aztec-nr/aztec/src/note.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note.nr rename to yarn-project/aztec-nr/aztec/src/note.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/lifecycle.nr b/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr similarity index 96% rename from yarn-project/noir-libs/aztec-noir/src/note/lifecycle.nr rename to yarn-project/aztec-nr/aztec/src/note/lifecycle.nr index b6e530ed94f..43ccdfad556 100644 --- a/yarn-project/noir-libs/aztec-noir/src/note/lifecycle.nr +++ b/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr @@ -50,7 +50,6 @@ fn create_note_hash_from_public( fn destroy_note( context: &mut PrivateContext, - storage_slot: Field, note: Note, note_interface: NoteInterface, ) { @@ -72,7 +71,7 @@ fn destroy_note( // TODO(1718): Can we reuse the note commitment computed in `compute_nullifier`? nullified_commitment = compute_inner_note_hash(note_interface, note); } - assert(notify_nullified_note(storage_slot, nullifier, nullified_commitment) == 0); + assert(notify_nullified_note(nullifier, nullified_commitment) == 0); context.push_new_nullifier(nullifier, nullified_commitment) } \ No newline at end of file diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_getter.nr b/yarn-project/aztec-nr/aztec/src/note/note_getter.nr similarity index 70% rename from yarn-project/noir-libs/aztec-noir/src/note/note_getter.nr rename to yarn-project/aztec-nr/aztec/src/note/note_getter.nr index ee407657547..808f9389b3a 100644 --- a/yarn-project/noir-libs/aztec-noir/src/note/note_getter.nr +++ b/yarn-project/aztec-nr/aztec/src/note/note_getter.nr @@ -13,11 +13,9 @@ use crate::note::{ note_header::NoteHeader, note_viewer_options::NoteViewerOptions, utils::compute_note_hash_for_read_or_nullify, - utils::compute_unique_siloed_note_hash, utils::compute_inner_note_hash, utils::compute_siloed_note_hash, }; -use crate::messaging::get_commitment_getter_data::make_commitment_getter_data; use crate::oracle; use crate::types::vec::BoundedVec; @@ -34,69 +32,29 @@ fn check_note_header( assert(header.storage_slot == storage_slot); } -fn ensure_note_exists( - context: &mut PrivateContext, - storage_slot: Field, - note_interface: NoteInterface, - note: &mut Note, -) { - let saved_note = get_note_internal(storage_slot, note_interface); - - // Only copy over the header to the original note to make sure the preimage is the same. - let get_header = note_interface.get_header; - let set_header = note_interface.set_header; - let note_header = get_header(saved_note); - set_header(note, note_header); - - check_note_header(*context, storage_slot, note_interface, *note); - - let note_hash_for_read_request = compute_note_hash_for_read_or_nullify(note_interface, *note); - context.push_read_request(note_hash_for_read_request); -} - // Ensure a note's hash exists in the tree without retrieving the entire // notes via the oracle. -// Modifies the note by populating it with header info. fn ensure_note_hash_exists( context: &mut PrivateContext, - storage_slot: Field, note_interface: NoteInterface, - note: &mut Note, + note: Note, + from_public: bool, ) { - // Initialize header of note. Must be done before computing note hashes as it initializes the: - // - storage slot (used in inner note hash) - // - the contract address (used in siloed note hash) - // - and the nonce (used in the unique siloed note hash) - let set_header = note_interface.set_header; - let note_header = NoteHeader { - contract_address: (*context).this_address(), - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): should be - // real nonce (once public kernel applies nonces). - nonce: 0, - storage_slot - }; - set_header(note, note_header); - - // Get a note from oracle and early out if it doesn't exist. - let inner_note_hash = compute_inner_note_hash(note_interface, *note); - - let raw_oracle_ret = oracle::get_commitment::get_commitment(inner_note_hash); - let deserialized_oracle_ret = make_commitment_getter_data(raw_oracle_ret, 0); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): should be - // unique_siloed_note_hash once public kernel applies nonces - let saved_siloed_note_hash = deserialized_oracle_ret.message; - - assert(saved_siloed_note_hash != 0); // TODO(dbanks12): necessary? - - check_note_header(*context, storage_slot, note_interface, *note); - - // Ensure that the note hash retrieved from oracle matches the one computed from note. - let computed_siloed_note_hash = compute_siloed_note_hash(note_interface, *note); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): should be - // compute_note_hash_for_read_or_nullify once public kernel applies nonces - assert(computed_siloed_note_hash == saved_siloed_note_hash); + let get_header = note_interface.get_header; + let header = get_header(note); - context.push_read_request(computed_siloed_note_hash); + // Check the note hash via oracle and early out if it doesn't exist. + let inner_note_hash = compute_inner_note_hash(note_interface, note); + let exists = oracle::notes::check_note_hash_exists(header.nonce, inner_note_hash); + assert(exists, "Note hash does not exist."); + + let mut note_hash_for_read_request = compute_note_hash_for_read_or_nullify(note_interface, note); + if from_public { + // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386) + // Should remove this once public kernel applies nonces. + note_hash_for_read_request = compute_siloed_note_hash(note_interface, note); + } + context.push_read_request(note_hash_for_read_request); } fn get_note( diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_getter_options.nr b/yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/note_getter_options.nr rename to yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_hash.nr b/yarn-project/aztec-nr/aztec/src/note/note_hash.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/note_hash.nr rename to yarn-project/aztec-nr/aztec/src/note/note_hash.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_header.nr b/yarn-project/aztec-nr/aztec/src/note/note_header.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/note_header.nr rename to yarn-project/aztec-nr/aztec/src/note/note_header.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_interface.nr b/yarn-project/aztec-nr/aztec/src/note/note_interface.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/note_interface.nr rename to yarn-project/aztec-nr/aztec/src/note/note_interface.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/note_viewer_options.nr b/yarn-project/aztec-nr/aztec/src/note/note_viewer_options.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/note_viewer_options.nr rename to yarn-project/aztec-nr/aztec/src/note/note_viewer_options.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/note/utils.nr b/yarn-project/aztec-nr/aztec/src/note/utils.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/note/utils.nr rename to yarn-project/aztec-nr/aztec/src/note/utils.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle.nr b/yarn-project/aztec-nr/aztec/src/oracle.nr similarity index 94% rename from yarn-project/noir-libs/aztec-noir/src/oracle.nr rename to yarn-project/aztec-nr/aztec/src/oracle.nr index 056617ed42f..da760abf487 100644 --- a/yarn-project/noir-libs/aztec-noir/src/oracle.nr +++ b/yarn-project/aztec-nr/aztec/src/oracle.nr @@ -6,7 +6,6 @@ mod arguments; mod call_private_function; mod context; mod debug_log; -mod get_commitment; mod get_l1_to_l2_message; mod get_public_key; mod get_secret_key; diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/arguments.nr b/yarn-project/aztec-nr/aztec/src/oracle/arguments.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/arguments.nr rename to yarn-project/aztec-nr/aztec/src/oracle/arguments.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/call_private_function.nr b/yarn-project/aztec-nr/aztec/src/oracle/call_private_function.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/call_private_function.nr rename to yarn-project/aztec-nr/aztec/src/oracle/call_private_function.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/compute_selector.nr b/yarn-project/aztec-nr/aztec/src/oracle/compute_selector.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/compute_selector.nr rename to yarn-project/aztec-nr/aztec/src/oracle/compute_selector.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/context.nr b/yarn-project/aztec-nr/aztec/src/oracle/context.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/context.nr rename to yarn-project/aztec-nr/aztec/src/oracle/context.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/create_commitment.nr b/yarn-project/aztec-nr/aztec/src/oracle/create_commitment.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/create_commitment.nr rename to yarn-project/aztec-nr/aztec/src/oracle/create_commitment.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/debug_log.nr b/yarn-project/aztec-nr/aztec/src/oracle/debug_log.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/debug_log.nr rename to yarn-project/aztec-nr/aztec/src/oracle/debug_log.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/enqueue_public_function_call.nr b/yarn-project/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/enqueue_public_function_call.nr rename to yarn-project/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/get_l1_to_l2_message.nr b/yarn-project/aztec-nr/aztec/src/oracle/get_l1_to_l2_message.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/get_l1_to_l2_message.nr rename to yarn-project/aztec-nr/aztec/src/oracle/get_l1_to_l2_message.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/get_public_key.nr b/yarn-project/aztec-nr/aztec/src/oracle/get_public_key.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/get_public_key.nr rename to yarn-project/aztec-nr/aztec/src/oracle/get_public_key.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/get_secret_key.nr b/yarn-project/aztec-nr/aztec/src/oracle/get_secret_key.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/get_secret_key.nr rename to yarn-project/aztec-nr/aztec/src/oracle/get_secret_key.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/logs.nr b/yarn-project/aztec-nr/aztec/src/oracle/logs.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/logs.nr rename to yarn-project/aztec-nr/aztec/src/oracle/logs.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/notes.nr b/yarn-project/aztec-nr/aztec/src/oracle/notes.nr similarity index 90% rename from yarn-project/noir-libs/aztec-noir/src/oracle/notes.nr rename to yarn-project/aztec-nr/aztec/src/oracle/notes.nr index 52d4a445389..356cf5de4aa 100644 --- a/yarn-project/noir-libs/aztec-noir/src/oracle/notes.nr +++ b/yarn-project/aztec-nr/aztec/src/oracle/notes.nr @@ -22,17 +22,28 @@ unconstrained fn notify_created_note( #[oracle(notifyNullifiedNote)] fn notify_nullified_note_oracle( - _storage_slot: Field, _nullifier: Field, _inner_note_hash: Field, ) -> Field {} unconstrained fn notify_nullified_note( - storage_slot: Field, nullifier: Field, inner_note_hash: Field, ) -> Field { - notify_nullified_note_oracle(storage_slot, nullifier, inner_note_hash) + notify_nullified_note_oracle(nullifier, inner_note_hash) +} + +#[oracle(checkNoteHashExists)] +fn check_note_hash_exists_oracle( + _nonce: Field, + _inner_note_hash: Field, +) -> Field {} + +unconstrained fn check_note_hash_exists( + nonce: Field, + inner_note_hash: Field, +) -> bool { + check_note_hash_exists_oracle(nonce, inner_note_hash) == 1 } #[oracle(getNotes)] diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/public_call.nr b/yarn-project/aztec-nr/aztec/src/oracle/public_call.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/public_call.nr rename to yarn-project/aztec-nr/aztec/src/oracle/public_call.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/rand.nr b/yarn-project/aztec-nr/aztec/src/oracle/rand.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/rand.nr rename to yarn-project/aztec-nr/aztec/src/oracle/rand.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/storage.nr b/yarn-project/aztec-nr/aztec/src/oracle/storage.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/oracle/storage.nr rename to yarn-project/aztec-nr/aztec/src/oracle/storage.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/private_call_stack_item.nr b/yarn-project/aztec-nr/aztec/src/private_call_stack_item.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/private_call_stack_item.nr rename to yarn-project/aztec-nr/aztec/src/private_call_stack_item.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/public_call_stack_item.nr b/yarn-project/aztec-nr/aztec/src/public_call_stack_item.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/public_call_stack_item.nr rename to yarn-project/aztec-nr/aztec/src/public_call_stack_item.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars.nr b/yarn-project/aztec-nr/aztec/src/state_vars.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/state_vars.nr rename to yarn-project/aztec-nr/aztec/src/state_vars.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars/immutable_singleton.nr b/yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/state_vars/immutable_singleton.nr rename to yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars/map.nr b/yarn-project/aztec-nr/aztec/src/state_vars/map.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/state_vars/map.nr rename to yarn-project/aztec-nr/aztec/src/state_vars/map.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars/public_state.nr b/yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/state_vars/public_state.nr rename to yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars/set.nr b/yarn-project/aztec-nr/aztec/src/state_vars/set.nr similarity index 64% rename from yarn-project/noir-libs/aztec-noir/src/state_vars/set.nr rename to yarn-project/aztec-nr/aztec/src/state_vars/set.nr index c14eebb770d..698af2ef11c 100644 --- a/yarn-project/noir-libs/aztec-noir/src/state_vars/set.nr +++ b/yarn-project/aztec-nr/aztec/src/state_vars/set.nr @@ -4,8 +4,9 @@ use crate::constants_gen::{MAX_NOTES_PER_PAGE, MAX_READ_REQUESTS_PER_CALL}; use crate::context::{PrivateContext, PublicContext, Context}; use crate::note::{ lifecycle::{create_note, create_note_hash_from_public, destroy_note}, - note_getter::{ensure_note_exists, ensure_note_hash_exists, get_notes, view_notes}, + note_getter::{ensure_note_hash_exists, get_notes, view_notes}, note_getter_options::NoteGetterOptions, + note_header::NoteHeader, note_interface::NoteInterface, note_viewer_options::NoteViewerOptions, utils::compute_note_hash_for_read_or_nullify, @@ -49,64 +50,79 @@ impl Set { ); } - fn assert_contains_and_remove(self, note: Note) { - let mut note_with_header = note; - // TODO(1386): replace with `ensure_note_hash_exists` - // once `get_commitment` works for privately created note hashes - ensure_note_exists( - self.context.private.unwrap(), - self.storage_slot, + fn assert_contains_and_remove(self, note: &mut Note, nonce: Field) { + // Initialize header of note. Must be done before computing note hashes as it initializes the: + // - storage slot (used in inner note hash) + // - the contract address (used in siloed note hash) + // - and the nonce (used in the unique siloed note hash) + let context = self.context.private.unwrap(); + let set_header = self.note_interface.set_header; + let note_header = NoteHeader{ + contract_address: context.this_address(), + storage_slot: self.storage_slot, + nonce + }; + set_header(note, note_header); + + ensure_note_hash_exists( + context, self.note_interface, - &mut note_with_header, + *note, + false, ); + destroy_note( - self.context.private.unwrap(), - self.storage_slot, - note_with_header, + context, + *note, self.note_interface, ); } // NOTE: this function should ONLY be used for PUBLICLY-CREATED note hashes! - // WARNING: function will be deprecated/removed eventually once `assert_contains_and_remove` - // works for publicly-created note hashes as well. - fn assert_contains_and_remove_publicly_created(self, note: Note) { - let mut note_with_header = note; - // Modifies note with the header which is necessary for the next step (remove). + // WARNING: function will be deprecated/removed eventually once public kernel applies nonces. + fn assert_contains_and_remove_publicly_created(self, note: &mut Note) { + // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386) + // Should be real nonce (once public kernel applies nonces). + let nonce = 0; + let context = self.context.private.unwrap(); + let set_header = self.note_interface.set_header; + let mut note_header = NoteHeader{ + contract_address: context.this_address(), + storage_slot: self.storage_slot, + nonce + }; + set_header(note, note_header); + ensure_note_hash_exists( - self.context.private.unwrap(), - self.storage_slot, + context, self.note_interface, - &mut note_with_header, + *note, + true, ); - let get_header = self.note_interface.get_header; - let set_header = self.note_interface.set_header; - let mut header = get_header(note); // Set the nonce to nonzero so that the nullifier is treated as persistable // (non-transient) and so the private kernel does not attempt to match it to // a pending noteHash/commitment and squash them. // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): remove // this hack once public kernel injects nonces. - header.nonce = 1; - set_header(&mut note_with_header, header); + note_header.nonce = 1; + set_header(note, note_header); + destroy_note( - self.context.private.unwrap(), - self.storage_slot, - note_with_header, + context, + *note, self.note_interface, ); } fn remove(self, note: Note) { + let context = self.context.private.unwrap(); let note_hash = compute_note_hash_for_read_or_nullify(self.note_interface, note); - let read_requests = self.context.private.unwrap_unchecked().read_requests; - let has_been_read = read_requests.any(|r| r == note_hash); + let has_been_read = context.read_requests.any(|r| r == note_hash); assert(has_been_read, "Can only remove a note that has been read from the set."); destroy_note( - self.context.private.unwrap(), - self.storage_slot, + context, note, self.note_interface, ); diff --git a/yarn-project/noir-libs/aztec-noir/src/state_vars/singleton.nr b/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr similarity index 94% rename from yarn-project/noir-libs/aztec-noir/src/state_vars/singleton.nr rename to yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr index e1033604995..6b7afcba2ce 100644 --- a/yarn-project/noir-libs/aztec-noir/src/state_vars/singleton.nr +++ b/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr @@ -56,7 +56,7 @@ impl Singleton { let prev_note = get_note(context, self.storage_slot, self.note_interface); // Nullify previous note. - destroy_note(context, self.storage_slot, prev_note, self.note_interface); + destroy_note(context, prev_note, self.note_interface); // Add replacement note. create_note(context, self.storage_slot, new_note, self.note_interface); @@ -67,7 +67,7 @@ impl Singleton { let mut note = get_note(context, self.storage_slot, self.note_interface); // Nullify current note to make sure it's reading the latest note. - destroy_note(context, self.storage_slot, note, self.note_interface); + destroy_note(context, note, self.note_interface); // Add the same note again. // Because a nonce is added to every note in the kernel, its nullifier will be different. diff --git a/yarn-project/noir-libs/aztec-noir/src/types.nr b/yarn-project/aztec-nr/aztec/src/types.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types.nr rename to yarn-project/aztec-nr/aztec/src/types.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/grumpkin_scalar.nr b/yarn-project/aztec-nr/aztec/src/types/grumpkin_scalar.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/grumpkin_scalar.nr rename to yarn-project/aztec-nr/aztec/src/types/grumpkin_scalar.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/point.nr b/yarn-project/aztec-nr/aztec/src/types/point.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/point.nr rename to yarn-project/aztec-nr/aztec/src/types/point.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/type_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/type_serialisation.nr rename to yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/bool_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/bool_serialisation.nr rename to yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/field_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/field_serialisation.nr rename to yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/u32_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/type_serialisation/u32_serialisation.nr rename to yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/types/vec.nr b/yarn-project/aztec-nr/aztec/src/types/vec.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/types/vec.nr rename to yarn-project/aztec-nr/aztec/src/types/vec.nr diff --git a/yarn-project/noir-libs/aztec-noir/src/utils.nr b/yarn-project/aztec-nr/aztec/src/utils.nr similarity index 100% rename from yarn-project/noir-libs/aztec-noir/src/utils.nr rename to yarn-project/aztec-nr/aztec/src/utils.nr diff --git a/yarn-project/noir-libs/easy-private-state/Nargo.toml b/yarn-project/aztec-nr/easy-private-state/Nargo.toml similarity index 81% rename from yarn-project/noir-libs/easy-private-state/Nargo.toml rename to yarn-project/aztec-nr/easy-private-state/Nargo.toml index eef8798d8c8..c6364218f27 100644 --- a/yarn-project/noir-libs/easy-private-state/Nargo.toml +++ b/yarn-project/aztec-nr/easy-private-state/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.7.1" type = "lib" [dependencies] -aztec = { path = "../aztec-noir" } +aztec = { path = "../aztec" } value_note = { path = "../value-note" } \ No newline at end of file diff --git a/yarn-project/noir-libs/easy-private-state/src/easy_private_state.nr b/yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr similarity index 100% rename from yarn-project/noir-libs/easy-private-state/src/easy_private_state.nr rename to yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr diff --git a/yarn-project/noir-libs/easy-private-state/src/lib.nr b/yarn-project/aztec-nr/easy-private-state/src/lib.nr similarity index 100% rename from yarn-project/noir-libs/easy-private-state/src/lib.nr rename to yarn-project/aztec-nr/easy-private-state/src/lib.nr diff --git a/yarn-project/noir-libs/safe-math/Nargo.toml b/yarn-project/aztec-nr/safe-math/Nargo.toml similarity index 100% rename from yarn-project/noir-libs/safe-math/Nargo.toml rename to yarn-project/aztec-nr/safe-math/Nargo.toml diff --git a/yarn-project/noir-libs/safe-math/src/lib.nr b/yarn-project/aztec-nr/safe-math/src/lib.nr similarity index 100% rename from yarn-project/noir-libs/safe-math/src/lib.nr rename to yarn-project/aztec-nr/safe-math/src/lib.nr diff --git a/yarn-project/noir-libs/safe-math/src/safe_u120.nr b/yarn-project/aztec-nr/safe-math/src/safe_u120.nr similarity index 99% rename from yarn-project/noir-libs/safe-math/src/safe_u120.nr rename to yarn-project/aztec-nr/safe-math/src/safe_u120.nr index ccb6ab906a8..5feeb3cca23 100644 --- a/yarn-project/noir-libs/safe-math/src/safe_u120.nr +++ b/yarn-project/aztec-nr/safe-math/src/safe_u120.nr @@ -259,11 +259,10 @@ fn test_mul_div_up_ghost_overflow() { // It should not be possible for us to overflow `mul_div_up` through the adder, since that require the divisor to be 1 // since we otherwise would not be at the max value. If divisor is 1, adder is 0. - #[test(should_fail)] fn test_mul_div_up_zero_divisor() { let a = SafeU120::new(6); let b = SafeU120::new(3); let c = SafeU120::new(0); let _d = SafeU120::mul_div_up(a, b, c); -} \ No newline at end of file +} diff --git a/yarn-project/noir-libs/value-note/Nargo.toml b/yarn-project/aztec-nr/value-note/Nargo.toml similarity index 76% rename from yarn-project/noir-libs/value-note/Nargo.toml rename to yarn-project/aztec-nr/value-note/Nargo.toml index 7f527d67f21..d0e7bb52461 100644 --- a/yarn-project/noir-libs/value-note/Nargo.toml +++ b/yarn-project/aztec-nr/value-note/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.7.1" type = "lib" [dependencies] -aztec = { path = "../aztec-noir" } \ No newline at end of file +aztec = { path = "../aztec" } \ No newline at end of file diff --git a/yarn-project/noir-libs/value-note/src/balance_utils.nr b/yarn-project/aztec-nr/value-note/src/balance_utils.nr similarity index 100% rename from yarn-project/noir-libs/value-note/src/balance_utils.nr rename to yarn-project/aztec-nr/value-note/src/balance_utils.nr diff --git a/yarn-project/noir-libs/value-note/src/filter.nr b/yarn-project/aztec-nr/value-note/src/filter.nr similarity index 100% rename from yarn-project/noir-libs/value-note/src/filter.nr rename to yarn-project/aztec-nr/value-note/src/filter.nr diff --git a/yarn-project/noir-libs/value-note/src/lib.nr b/yarn-project/aztec-nr/value-note/src/lib.nr similarity index 100% rename from yarn-project/noir-libs/value-note/src/lib.nr rename to yarn-project/aztec-nr/value-note/src/lib.nr diff --git a/yarn-project/noir-libs/value-note/src/utils.nr b/yarn-project/aztec-nr/value-note/src/utils.nr similarity index 100% rename from yarn-project/noir-libs/value-note/src/utils.nr rename to yarn-project/aztec-nr/value-note/src/utils.nr diff --git a/yarn-project/noir-libs/value-note/src/value_note.nr b/yarn-project/aztec-nr/value-note/src/value_note.nr similarity index 100% rename from yarn-project/noir-libs/value-note/src/value_note.nr rename to yarn-project/aztec-nr/value-note/src/value_note.nr diff --git a/yarn-project/aztec-rpc/package.json b/yarn-project/aztec-rpc/package.json index 7ac8adacfc0..78f906e82b5 100644 --- a/yarn-project/aztec-rpc/package.json +++ b/yarn-project/aztec-rpc/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/aztec-rpc/src/contract_data_oracle/index.ts b/yarn-project/aztec-rpc/src/contract_data_oracle/index.ts index f398edfe86b..0984e3dcc70 100644 --- a/yarn-project/aztec-rpc/src/contract_data_oracle/index.ts +++ b/yarn-project/aztec-rpc/src/contract_data_oracle/index.ts @@ -5,7 +5,7 @@ import { ContractCommitmentProvider, ContractDatabase } from '@aztec/types'; import { ContractTree } from '../contract_tree/index.js'; /** - * ContractDataOracle serves as a data manager and retriever for noir contracts. + * ContractDataOracle serves as a data manager and retriever for Aztec.nr contracts. * It provides methods to obtain contract addresses, function ABI, bytecode, and membership witnesses * from a given contract address and function selector. The class maintains a cache of ContractTree instances * to efficiently serve the requested data. It interacts with the ContractDatabase and AztecNode to fetch diff --git a/yarn-project/aztec-rpc/src/simulator_oracle/index.ts b/yarn-project/aztec-rpc/src/simulator_oracle/index.ts index 52737d91a42..68309243747 100644 --- a/yarn-project/aztec-rpc/src/simulator_oracle/index.ts +++ b/yarn-project/aztec-rpc/src/simulator_oracle/index.ts @@ -1,12 +1,6 @@ -import { - CommitmentDataOracleInputs, - DBOracle, - FunctionAbiWithDebugMetadata, - MessageLoadOracleInputs, -} from '@aztec/acir-simulator'; +import { DBOracle, FunctionAbiWithDebugMetadata, MessageLoadOracleInputs } from '@aztec/acir-simulator'; import { AztecAddress, - CircuitsWasm, CompleteAddress, EthAddress, Fr, @@ -15,7 +9,6 @@ import { HistoricBlockData, PublicKey, } from '@aztec/circuits.js'; -import { siloCommitment } from '@aztec/circuits.js/abis'; import { DataCommitmentProvider, KeyStore, L1ToL2MessageProvider } from '@aztec/types'; import { ContractDataOracle } from '../contract_data_oracle/index.js'; @@ -105,23 +98,12 @@ export class SimulatorOracle implements DBOracle { } /** - * Retrieves the noir oracle data required to prove existence of a given commitment. - * @param contractAddress - The contract Address. - * @param innerCommitment - The key of the message being fetched. - * @returns - A promise that resolves to the commitment data, a sibling path and the - * index of the message in the private data tree. + * Gets the index of a commitment in the private data tree. + * @param commitment - The commitment. + * @returns - The index of the commitment. Undefined if it does not exist in the tree. */ - async getCommitmentOracle(contractAddress: AztecAddress, innerCommitment: Fr): Promise { - const siloedCommitment = siloCommitment(await CircuitsWasm.get(), contractAddress, innerCommitment); - const index = await this.dataTreeProvider.findCommitmentIndex(siloedCommitment.toBuffer()); - if (!index) throw new Error(`Commitment not found ${siloedCommitment.toString()}`); - - const siblingPath = await this.dataTreeProvider.getDataTreePath(index); - return await Promise.resolve({ - commitment: siloedCommitment, - siblingPath: siblingPath.toFieldArray(), - index, - }); + async getCommitmentIndex(commitment: Fr) { + return await this.dataTreeProvider.findCommitmentIndex(commitment.toBuffer()); } /** diff --git a/yarn-project/aztec-sandbox/package.json b/yarn-project/aztec-sandbox/package.json index 041da41d296..d176756f835 100644 --- a/yarn-project/aztec-sandbox/package.json +++ b/yarn-project/aztec-sandbox/package.json @@ -14,13 +14,11 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", "build": "yarn clean && tsc -b", "start": "node --no-warnings ./dest/bin", "clean": "rm -rf ./dest .tsbuildinfo", "formatting": "run -T prettier --check ./src && run -T eslint ./src", "formatting:fix": "run -T prettier -w ./src", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build:dev": "tsc -b --watch", "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules $(yarn bin jest) --passWithNoTests", "run:example:token": "DEBUG='aztec:*' node ./dest/examples/private_token_contract.js", diff --git a/yarn-project/aztec-sandbox/src/examples/uniswap_trade_on_l1_from_l2.ts b/yarn-project/aztec-sandbox/src/examples/uniswap_trade_on_l1_from_l2.ts index 72fd032da4a..9feaa2d9b89 100644 --- a/yarn-project/aztec-sandbox/src/examples/uniswap_trade_on_l1_from_l2.ts +++ b/yarn-project/aztec-sandbox/src/examples/uniswap_trade_on_l1_from_l2.ts @@ -217,7 +217,7 @@ async function main() { // 3. Claim WETH on L2 logger('Minting weth on L2'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const consumptionTx = wethL2Contract.methods .mint(wethAmountToBridge, owner.address, messageKey, secret, ethAccount.toField()) .send(); @@ -298,7 +298,7 @@ async function main() { // 6. claim dai on L2 logger('Consuming messages to mint dai on L2'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const daiMintTx = daiL2Contract.methods .mint(daiAmountToBridge, owner.address, depositDaiMessageKey, secret, ethAccount.toField()) .send(); diff --git a/yarn-project/aztec.js/package.json b/yarn-project/aztec.js/package.json index 0a67c34d5b3..44e2441449b 100644 --- a/yarn-project/aztec.js/package.json +++ b/yarn-project/aztec.js/package.json @@ -16,8 +16,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b && webpack", "build:web": "webpack", "build:dev": "tsc -b --watch", diff --git a/yarn-project/aztec.js/src/account/entrypoint/entrypoint_payload.ts b/yarn-project/aztec.js/src/account/entrypoint/entrypoint_payload.ts index 56bc26c9207..6d41291437b 100644 --- a/yarn-project/aztec.js/src/account/entrypoint/entrypoint_payload.ts +++ b/yarn-project/aztec.js/src/account/entrypoint/entrypoint_payload.ts @@ -5,7 +5,7 @@ import { FunctionCall, PackedArguments, emptyFunctionCall } from '@aztec/types'; import partition from 'lodash.partition'; -// These must match the values defined in yarn-project/noir-libs/aztec-noir/src/entrypoint.nr +// These must match the values defined in yarn-project/aztec-nr/aztec/src/entrypoint.nr export const ACCOUNT_MAX_PRIVATE_CALLS = 2; export const ACCOUNT_MAX_PUBLIC_CALLS = 2; diff --git a/yarn-project/aztec.js/src/contract_deployer/contract_deployer.ts b/yarn-project/aztec.js/src/contract_deployer/contract_deployer.ts index fb9a9b14ea7..c01f4490025 100644 --- a/yarn-project/aztec.js/src/contract_deployer/contract_deployer.ts +++ b/yarn-project/aztec.js/src/contract_deployer/contract_deployer.ts @@ -6,7 +6,7 @@ import { DeployMethod } from './deploy_method.js'; /** * A class for deploying contract. - * @remarks Keeping this around even though we have noir contract types because it can be useful for non-TS users. + * @remarks Keeping this around even though we have Aztec.nr contract types because it can be useful for non-TS users. */ export class ContractDeployer { constructor(private abi: ContractAbi, private arc: AztecRPC, private publicKey?: PublicKey) {} diff --git a/yarn-project/aztec.js/src/utils/cheat_codes.ts b/yarn-project/aztec.js/src/utils/cheat_codes.ts index 1dc12106108..fc3fe96c080 100644 --- a/yarn-project/aztec.js/src/utils/cheat_codes.ts +++ b/yarn-project/aztec.js/src/utils/cheat_codes.ts @@ -151,7 +151,7 @@ export class EthCheatCodes { /** * Computes the slot value for a given map and key. - * @param baseSlot - The base slot of the map (specified in noir contract) + * @param baseSlot - The base slot of the map (specified in Aztec.nr contract) * @param key - The key to lookup in the map * @returns The storage slot of the value in the map */ @@ -228,13 +228,13 @@ export class AztecCheatCodes { /** * Computes the slot value for a given map and key. - * @param baseSlot - The base slot of the map (specified in noir contract) + * @param baseSlot - The base slot of the map (specified in Aztec.nr contract) * @param key - The key to lookup in the map * @returns The storage slot of the value in the map */ public computeSlotInMap(baseSlot: Fr | bigint, key: Fr | bigint | AztecAddress): Fr { // Based on `at` function in - // aztec3-packages/yarn-project/noir-libs/aztec-noir/src/state_vars/map.nr + // aztec3-packages/yarn-project/aztec-nr/aztec/src/state_vars/map.nr return Fr.fromBuffer( pedersenPlookupCommitInputs( this.wasm, diff --git a/yarn-project/bootstrap.sh b/yarn-project/bootstrap.sh index f3ad539416e..78be8c3e692 100755 --- a/yarn-project/bootstrap.sh +++ b/yarn-project/bootstrap.sh @@ -16,7 +16,7 @@ set -eu yarn install --immutable -# Build the necessary dependencies for noir contracts typegen. +# Build the necessary dependencies for Aztec.nr contracts typegen. for DIR in foundation noir-compiler circuits.js; do echo "Building $DIR..." cd $DIR @@ -24,7 +24,7 @@ for DIR in foundation noir-compiler circuits.js; do cd .. done -# Run remake bindings before building noir contracts or l1 contracts as they depend on files created by it. +# Run remake bindings before building Aztec.nr contracts or l1 contracts as they depend on files created by it. yarn --cwd circuits.js remake-bindings yarn --cwd circuits.js remake-constants diff --git a/yarn-project/canary/src/uniswap_trade_on_l1_from_l2.test.ts b/yarn-project/canary/src/uniswap_trade_on_l1_from_l2.test.ts index f79632c5f83..7a142332a03 100644 --- a/yarn-project/canary/src/uniswap_trade_on_l1_from_l2.test.ts +++ b/yarn-project/canary/src/uniswap_trade_on_l1_from_l2.test.ts @@ -243,7 +243,7 @@ describe('uniswap_trade_on_l1_from_l2', () => { // 3. Claim WETH on L2 logger('Minting weth on L2'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const consumptionTx = wethL2Contract.methods .mint(wethAmountToBridge, owner, messageKey, secret, ethAccount.toField()) .send(); @@ -324,7 +324,7 @@ describe('uniswap_trade_on_l1_from_l2', () => { // 6. claim dai on L2 logger('Consuming messages to mint dai on L2'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const daiMintTx = daiL2Contract.methods .mint(daiAmountToBridge, owner, depositDaiMessageKey, secret, ethAccount.toField()) .send(); diff --git a/yarn-project/circuits.js/package.json b/yarn-project/circuits.js/package.json index b2fbac5e846..58628aaf169 100644 --- a/yarn-project/circuits.js/package.json +++ b/yarn-project/circuits.js/package.json @@ -18,8 +18,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/circuits.js/src/cbind/constants.in.ts b/yarn-project/circuits.js/src/cbind/constants.in.ts index 68bf902704b..300e676a207 100644 --- a/yarn-project/circuits.js/src/cbind/constants.in.ts +++ b/yarn-project/circuits.js/src/cbind/constants.in.ts @@ -39,7 +39,7 @@ async function main(): Promise { processEnumNoir(privateStateNoteGeneratorIndexEnum, 'PRIVATE_STATE_NOTE_GENERATOR_INDEX__') + processEnumNoir(privateStateTypeEnum, 'PRIVATE_STATE_TYPE__'); - const noirTargetPath = join(__dirname, '../../../noir-libs/aztec-noir/src/constants_gen.nr'); + const noirTargetPath = join(__dirname, '../../../aztec-nr/aztec/src/constants_gen.nr'); fs.writeFileSync(noirTargetPath, resultNoir); // Solidity diff --git a/yarn-project/circuits.js/src/structs/verification_key.test.ts b/yarn-project/circuits.js/src/structs/verification_key.test.ts index 40256ed8613..7dd17b375dc 100644 --- a/yarn-project/circuits.js/src/structs/verification_key.test.ts +++ b/yarn-project/circuits.js/src/structs/verification_key.test.ts @@ -1,7 +1,7 @@ import { VerificationKey } from './verification_key.js'; describe('structs/verification_key', () => { - // The VK below was grabbed from the noir contract artifact child_contract.json + // The VK below was grabbed from the Aztec.nr contract artifact child_contract.json it(`can deserialize vk built by noir`, () => { const serialized = `0000000200000800000000740000000f00000003515f3109623eb3c25aa5b16a1a79fd558bac7a7ce62c4560a8c537c77ce80dd339128d1d37b6582ee9e6df9567efb64313471dfa18f520f9ce53161b50dbf7731bc5f900000003515f322bc4cce83a486a92c92fd59bd84e0f92595baa639fc2ed86b00ffa0dfded2a092a669a3bdb7a273a015eda494457cc7ed5236f26cee330c290d45a33b9daa94800000003515f332729426c008c085a81bd34d8ef12dd31e80130339ef99d50013a89e4558eee6d0fa4ffe2ee7b7b62eb92608b2251ac31396a718f9b34978888789042b790a30100000003515f342be6b6824a913eb7a57b03cb1ee7bfb4de02f2f65fe8a4e97baa7766ddb353a82a8a25c49dc63778cd9fe96173f12a2bc77f3682f4c4448f98f1df82c75234a100000003515f351f85760d6ab567465aadc2f180af9eae3800e6958fec96aef53fd8a7b195d7c000c6267a0dd5cfc22b3fe804f53e266069c0e36f51885baec1e7e67650c62e170000000c515f41524954484d455449430d9d0f8ece2aa12012fa21e6e5c859e97bd5704e5c122064a66051294bc5e04213f61f54a0ebdf6fee4d4a6ecf693478191de0c2899bcd8e86a636c8d3eff43400000003515f43224a99d02c86336737c8dd5b746c40d2be6aead8393889a76a18d664029096e90f7fe81adcc92a74350eada9622ac453f49ebac24a066a1f83b394df54dfa0130000000c515f46495845445f42415345060e8a013ed289c2f9fd7473b04f6594b138ddb4b4cf6b901622a14088f04b8d2c83ff74fce56e3d5573b99c7b26d85d5046ce0c6559506acb7a675e7713eb3a00000007515f4c4f4749430721a91cb8da4b917e054f72147e1760cfe0ef3d45090ac0f4961d84ec1996961a25e787b26bd8b50b1a99450f77a424a83513c2b33af268cd253b0587ff50c700000003515f4d05dbd8623b8652511e1eb38d38887a69eceb082f807514f09e127237c5213b401b9325b48c6c225968002318095f89d0ef9cf629b2b7f0172e03bc39aacf6ed800000007515f52414e474504b57a3805e41df328f5ca9aefa40fad5917391543b7b65c6476e60b8f72e9ad07c92f3b3e11c8feae96dedc4b14a6226ef3201244f37cfc1ee5b96781f48d2b000000075349474d415f3125001d1954a18571eaa007144c5a567bb0d2be4def08a8be918b8c05e3b27d312c59ed41e09e144eab5de77ca89a2fd783be702a47c951d3112e3de02ce6e47c000000075349474d415f3223994e6a23618e60fa01c449a7ab88378709197e186d48d604bfb6931ffb15ad11c5ec7a0700570f80088fd5198ab5d5c227f2ad2a455a6edeec024156bb7beb000000075349474d415f3300cda5845f23468a13275d18bddae27c6bb189cf9aa95b6a03a0cb6688c7e8d829639b45cf8607c525cc400b55ebf90205f2f378626dc3406cc59b2d1b474fba000000075349474d415f342d299e7928496ea2d37f10b43afd6a80c90a33b483090d18069ffa275eedb2fc2f82121e8de43dc036d99b478b6227ceef34248939987a19011f065d8b5cef5c0000000010000000000000000100000002000000030000000400000005000000060000000700000008000000090000000a0000000b0000000c0000000d0000000e0000000f`; const vk = VerificationKey.fromBuffer(Buffer.from(serialized, 'hex')); diff --git a/yarn-project/cli/README.md b/yarn-project/cli/README.md index e2ec0163948..87f643a669f 100644 --- a/yarn-project/cli/README.md +++ b/yarn-project/cli/README.md @@ -135,7 +135,7 @@ aztec-cli create-account ### deploy -Deploys a compiled Noir contract to Aztec. +Deploys a compiled Aztec.nr contract to Aztec. Syntax: @@ -145,12 +145,12 @@ aztec-cli deploy [options] Options: -- `-c, --contract-abi `: Path to the compiled Noir contract's ABI file in JSON format. You can also use one of Aztec's example contracts found in [@aztec/noir-contracts](https://www.npmjs.com/package/@aztec/noir-contracts), e.g. PrivateTokenContractAbi. You can get a full ist of the available contracts with `aztec-cli example-contracts` +- `-c, --contract-abi `: Path to the compiled Aztec.nr contract's ABI file in JSON format. You can also use one of Aztec's example contracts found in [@aztec/noir-contracts](https://www.npmjs.com/package/@aztec/noir-contracts), e.g. PrivateTokenContractAbi. You can get a full ist of the available contracts with `aztec-cli example-contracts` - `-a, --args ` (optional): Contract constructor arguments Default: []. - `-u, --rpc-url `: URL of the Aztec RPC. Default: `http://localhost:8080`. - `-k, --public-key `: Public key of the deployer. If not provided, it will check the RPC for existing ones. -This command deploys a compiled Noir contract to Aztec. It requires the path to the contract's ABI file in JSON format. Optionally, you can specify the public key of the deployer and provide constructor arguments for the contract. The command displays the address of the deployed contract. +This command deploys a compiled Aztec.nr contract to Aztec. It requires the path to the contract's ABI file in JSON format. Optionally, you can specify the public key of the deployer and provide constructor arguments for the contract. The command displays the address of the deployed contract. Example usage: diff --git a/yarn-project/cli/package.json b/yarn-project/cli/package.json index e2541e50de8..fe7da02af0b 100644 --- a/yarn-project/cli/package.json +++ b/yarn-project/cli/package.json @@ -14,8 +14,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/cli/src/index.ts b/yarn-project/cli/src/index.ts index b1ac8bb4c7c..a597a07e21f 100644 --- a/yarn-project/cli/src/index.ts +++ b/yarn-project/cli/src/index.ts @@ -148,10 +148,10 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { program .command('deploy') - .description('Deploys a compiled Noir contract to Aztec.') + .description('Deploys a compiled Aztec.nr contract to Aztec.') .argument( '', - "A compiled Noir contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", + "A compiled Aztec.nr contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", ) .option('-a, --args ', 'Contract constructor arguments', []) .option('-u, --rpc-url ', 'URL of the Aztec RPC', AZTEC_RPC_HOST || 'http://localhost:8080') @@ -360,7 +360,7 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { .option('-a, --args [functionArgs...]', 'Function arguments', []) .requiredOption( '-c, --contract-abi ', - "A compiled Noir contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", + "A compiled Aztec.nr contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", ) .requiredOption('-ca, --contract-address
', 'Aztec address of the contract.') .option('-k, --private-key ', "The sender's private key.", PRIVATE_KEY) @@ -406,7 +406,7 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { .option('-a, --args [functionArgs...]', 'Function arguments', []) .requiredOption( '-c, --contract-abi ', - "A compiled Noir contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", + "A compiled Aztec.nr contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", ) .requiredOption('-ca, --contract-address
', 'Aztec address of the contract.') .option('-f, --from ', 'Public key of the TX viewer. If empty, will try to find account in RPC.') @@ -438,7 +438,7 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { .argument('', 'The encoded hex string') .requiredOption( '-c, --contract-abi ', - "A compiled Noir contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", + "A compiled Aztec.nr contract's ABI in JSON format or name of a contract ABI exported by @aztec/noir-contracts", ) .requiredOption('-p, --parameter ', 'The name of the struct parameter to decode into') .action(async (encodedString, options) => { diff --git a/yarn-project/end-to-end/package.json b/yarn-project/end-to-end/package.json index 1e7e6a34e01..01e14a2ecb1 100644 --- a/yarn-project/end-to-end/package.json +++ b/yarn-project/end-to-end/package.json @@ -4,8 +4,6 @@ "type": "module", "exports": "./dest/index.js", "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts index efc5b8843d4..d9b31c0315e 100644 --- a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts @@ -4,21 +4,30 @@ import { Account, AuthWitnessAccountContract, AuthWitnessEntrypointWallet, - AztecAddress, CheatCodes, Fr, IAuthWitnessAccountEntrypoint, + SentTx, computeMessageSecretHash, } from '@aztec/aztec.js'; import { CircuitsWasm, CompleteAddress, FunctionSelector, GeneratorIndex, GrumpkinScalar } from '@aztec/circuits.js'; -import { pedersenPlookupCommitInputs, pedersenPlookupCompressWithHashIndex } from '@aztec/circuits.js/barretenberg'; +import { pedersenPlookupCompressWithHashIndex } from '@aztec/circuits.js/barretenberg'; import { DebugLogger } from '@aztec/foundation/log'; -import { LendingContract, NativeTokenContract, PriceFeedContract } from '@aztec/noir-contracts/types'; +import { + LendingContract, + PriceFeedContract, + SchnorrAuthWitnessAccountContract, + TokenContract, +} from '@aztec/noir-contracts/types'; import { AztecRPC, TxStatus } from '@aztec/types'; +import { jest } from '@jest/globals'; + import { setup } from './fixtures/utils.js'; +import { LendingAccount, LendingSimulator, TokenSimulator } from './simulators/index.js'; describe('e2e_lending_contract', () => { + jest.setTimeout(100_000); let aztecNode: AztecNodeService | undefined; let aztecRpcServer: AztecRPC; let wallet: AuthWitnessEntrypointWallet; @@ -26,83 +35,105 @@ describe('e2e_lending_contract', () => { let logger: DebugLogger; let cc: CheatCodes; + const TIME_JUMP = 100; + + let lendingContract: LendingContract; + let priceFeedContract: PriceFeedContract; + let collateralAsset: TokenContract; + let stableCoin: TokenContract; - const WAD = 10n ** 18n; - const BASE = 10n ** 9n; + let lendingAccount: LendingAccount; + let lendingSim: LendingSimulator; + + const waitForSuccess = async (tx: SentTx) => { + const receipt = await tx.wait(); + expect(receipt.status).toBe(TxStatus.MINED); + return receipt; + }; - const deployContracts = async (owner: AztecAddress) => { + const deployContracts = async () => { let lendingContract: LendingContract; let priceFeedContract: PriceFeedContract; - let collateralAsset: NativeTokenContract; - let stableCoin: NativeTokenContract; + let collateralAsset: TokenContract; + let stableCoin: TokenContract; { logger(`Deploying price feed contract...`); - const tx = PriceFeedContract.deploy(wallet).send(); - logger(`Tx sent with hash ${await tx.getTxHash()}`); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); + const receipt = await waitForSuccess(PriceFeedContract.deploy(wallet).send()); logger(`Price feed deployed to ${receipt.contractAddress}`); priceFeedContract = await PriceFeedContract.at(receipt.contractAddress!, wallet); } { logger(`Deploying collateral asset feed contract...`); - const tx = NativeTokenContract.deploy(wallet, 10000n, owner).send(); - logger(`Tx sent with hash ${await tx.getTxHash()}`); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); + const receipt = await waitForSuccess(TokenContract.deploy(wallet).send()); logger(`Collateral asset deployed to ${receipt.contractAddress}`); - collateralAsset = await NativeTokenContract.at(receipt.contractAddress!, wallet); + collateralAsset = await TokenContract.at(receipt.contractAddress!, wallet); } { logger(`Deploying stable coin contract...`); - const tx = NativeTokenContract.deploy(wallet, 0n, owner).send(); - logger(`Tx sent with hash ${await tx.getTxHash()}`); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); + const receipt = await waitForSuccess(TokenContract.deploy(wallet).send()); logger(`Stable coin asset deployed to ${receipt.contractAddress}`); - stableCoin = await NativeTokenContract.at(receipt.contractAddress!, wallet); + stableCoin = await TokenContract.at(receipt.contractAddress!, wallet); } { logger(`Deploying L2 public contract...`); - const tx = LendingContract.deploy(wallet).send(); - logger(`Tx sent with hash ${await tx.getTxHash()}`); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); + const receipt = await waitForSuccess(LendingContract.deploy(wallet).send()); logger(`CDP deployed at ${receipt.contractAddress}`); lendingContract = await LendingContract.at(receipt.contractAddress!, wallet); } + + await waitForSuccess(collateralAsset.methods._initialize(accounts[0]).send()); + await waitForSuccess(collateralAsset.methods.set_minter({ address: lendingContract.address }, 1).send()); + await waitForSuccess(stableCoin.methods._initialize(accounts[0]).send()); + await waitForSuccess(stableCoin.methods.set_minter({ address: lendingContract.address }, 1).send()); + return { priceFeedContract, lendingContract, collateralAsset, stableCoin }; }; - beforeEach(async () => { + beforeAll(async () => { ({ aztecNode, aztecRpcServer, logger, cheatCodes: cc } = await setup(0)); - { - const privateKey = GrumpkinScalar.random(); - const account = new Account(aztecRpcServer, privateKey, new AuthWitnessAccountContract(privateKey)); - const deployTx = await account.deploy(); - await deployTx.wait({ interval: 0.1 }); - wallet = new AuthWitnessEntrypointWallet( - aztecRpcServer, - (await account.getEntrypoint()) as unknown as IAuthWitnessAccountEntrypoint, - await account.getCompleteAddress(), - ); - accounts = await wallet.getAccounts(); - } - }, 100_000); + const privateKey = GrumpkinScalar.random(); + const account = new Account(aztecRpcServer, privateKey, new AuthWitnessAccountContract(privateKey)); + const deployTx = await account.deploy(); + await deployTx.wait({ interval: 0.1 }); + wallet = new AuthWitnessEntrypointWallet( + aztecRpcServer, + (await account.getEntrypoint()) as unknown as IAuthWitnessAccountEntrypoint, + await account.getCompleteAddress(), + ); + accounts = await wallet.getAccounts(); - afterEach(async () => { + ({ lendingContract, priceFeedContract, collateralAsset, stableCoin } = await deployContracts()); + lendingAccount = new LendingAccount(accounts[0].address, new Fr(42)); + + // Also specified in `noir-contracts/src/contracts/lending_contract/src/main.nr` + const rate = 1268391679n; + lendingSim = new LendingSimulator( + cc, + lendingAccount, + rate, + lendingContract, + new TokenSimulator(collateralAsset, logger, [lendingContract.address, ...accounts.map(a => a.address)]), + new TokenSimulator(stableCoin, logger, [lendingContract.address, ...accounts.map(a => a.address)]), + ); + }, 200_000); + + afterAll(async () => { await aztecNode?.stop(); if (aztecRpcServer instanceof AztecRPCServer) { await aztecRpcServer?.stop(); } }); + afterEach(async () => { + await lendingSim.check(); + }); + const hashPayload = async (payload: Fr[]) => { return pedersenPlookupCompressWithHashIndex( await CircuitsWasm.get(), @@ -111,265 +142,59 @@ describe('e2e_lending_contract', () => { ); }; - // Fetch a storage snapshot from the contract that we can use to compare between transitions. - const getStorageSnapshot = async ( - lendingContract: LendingContract, - collateralAsset: NativeTokenContract, - stableCoin: NativeTokenContract, - account: LendingAccount, - ) => { - logger('Fetching storage snapshot 📸 '); - const accountKey = await account.key(); - - const tot = await lendingContract.methods.get_asset(0).view(); - const privatePos = await lendingContract.methods.get_position(accountKey).view(); - const publicPos = await lendingContract.methods.get_position(account.address.toField()).view(); - const totalCollateral = await collateralAsset.methods.public_balance_of(lendingContract.address).view(); - - return { - interestAccumulator: new Fr(tot['interest_accumulator']), - lastUpdatedTs: new Fr(tot['last_updated_ts']), - privateCollateral: new Fr(privatePos['collateral']), - privateStaticDebt: new Fr(privatePos['static_debt']), - privateDebt: new Fr(privatePos['debt']), - publicCollateral: new Fr(publicPos['collateral']), - publicStaticDebt: new Fr(publicPos['static_debt']), - publicDebt: new Fr(publicPos['debt']), - totalCollateral: new Fr(totalCollateral), - stableCoinLending: new Fr(await stableCoin.methods.public_balance_of(lendingContract.address).view()), - stableCoinPublic: new Fr(await stableCoin.methods.public_balance_of(account.address).view()), - stableCoinPrivate: new Fr(await stableCoin.methods.balance_of(account.address).view()), - stableCoinSupply: new Fr(await stableCoin.methods.total_supply().view()), - }; - }; - - // Convenience struct to hold an account's address and secret that can easily be passed around. - // Contains utilities to compute the "key" for private holdings in the public state. - class LendingAccount { - public readonly address: AztecAddress; - public readonly secret: Fr; - - constructor(address: AztecAddress, secret: Fr) { - this.address = address; - this.secret = secret; - } - - public async key(): Promise { - return Fr.fromBuffer( - pedersenPlookupCommitInputs( - await CircuitsWasm.get(), - [this.address, this.secret].map(f => f.toBuffer()), - ), - ); - } - } - - const muldivDown = (a: bigint, b: bigint, c: bigint) => (a * b) / c; - - const muldivUp = (a: bigint, b: bigint, c: bigint) => { - const adder = (a * b) % c > 0n ? 1n : 0n; - return muldivDown(a, b, c) + adder; - }; - - const computeMultiplier = (rate: bigint, dt: bigint) => { - if (dt == 0n) { - return BASE; - } - - const expMinusOne = dt - 1n; - const expMinusTwo = dt > 2 ? dt - 2n : 0n; - - const basePowerTwo = muldivDown(rate, rate, WAD); - const basePowerThree = muldivDown(basePowerTwo, rate, WAD); - - const temp = dt * expMinusOne; - const secondTerm = muldivDown(temp, basePowerTwo, 2n); - const thirdTerm = muldivDown(temp * expMinusTwo, basePowerThree, 6n); - - const offset = (dt * rate + secondTerm + thirdTerm) / (WAD / BASE); - - return BASE + offset; - }; - - // Helper class that emulates the logic of the lending contract. Used to have a "twin" to check values against. - class LendingSimulator { - public accumulator: bigint = BASE; - public time: number = 0; - - private collateral: { [key: string]: Fr } = {}; - private staticDebt: { [key: string]: Fr } = {}; - private stableBalance: { [key: string]: Fr } = {}; - private repaid: bigint = 0n; - - private key: Fr = Fr.ZERO; - - constructor(private cc: CheatCodes, private account: LendingAccount, private rate: bigint) {} - - async prepare() { - this.key = await this.account.key(); - const ts = await this.cc.eth.timestamp(); - this.time = ts + 10 + (ts % 10); - await this.cc.aztec.warp(this.time); - } - - async progressTime(diff: number) { - this.time = this.time + diff; - await this.cc.aztec.warp(this.time); - this.accumulator = muldivDown(this.accumulator, computeMultiplier(this.rate, BigInt(diff)), BASE); - } - - mintStable(to: Fr, amount: bigint) { - const balance = this.stableBalance[to.toString()] ?? Fr.ZERO; - this.stableBalance[to.toString()] = new Fr(balance.value + amount); - } - - deposit(onBehalfOf: Fr, amount: bigint) { - const coll = this.collateral[onBehalfOf.toString()] ?? Fr.ZERO; - this.collateral[onBehalfOf.toString()] = new Fr(coll.value + amount); - } - - withdraw(owner: Fr, amount: bigint) { - const coll = this.collateral[owner.toString()] ?? Fr.ZERO; - this.collateral[owner.toString()] = new Fr(coll.value - amount); - } - - borrow(owner: Fr, recipient: Fr, amount: bigint) { - const staticDebtBal = this.staticDebt[owner.toString()] ?? Fr.ZERO; - const increase = muldivUp(amount, BASE, this.accumulator); - this.staticDebt[owner.toString()] = new Fr(staticDebtBal.value + increase); - - const balance = this.stableBalance[recipient.toString()] ?? Fr.ZERO; - this.stableBalance[recipient.toString()] = new Fr(balance.value + amount); - } - - repay(owner: Fr, onBehalfOf: Fr, amount: bigint) { - const staticDebtBal = this.staticDebt[onBehalfOf.toString()] ?? Fr.ZERO; - const decrease = muldivDown(amount, BASE, this.accumulator); - this.staticDebt[onBehalfOf.toString()] = new Fr(staticDebtBal.value - decrease); - - const balance = this.stableBalance[owner.toString()] ?? Fr.ZERO; - this.stableBalance[owner.toString()] = new Fr(balance.value - amount); - this.repaid += amount; - } - - check(storage: { [key: string]: Fr }) { - expect(storage['interestAccumulator']).toEqual(new Fr(this.accumulator)); - expect(storage['lastUpdatedTs']).toEqual(new Fr(this.time)); - - // Private values - const keyPriv = this.key.toString(); - expect(storage['privateCollateral']).toEqual(this.collateral[keyPriv] ?? Fr.ZERO); - expect(storage['privateStaticDebt']).toEqual(this.staticDebt[keyPriv] ?? Fr.ZERO); - expect(storage['privateDebt'].value).toEqual( - muldivUp((this.staticDebt[keyPriv] ?? Fr.ZERO).value, this.accumulator, BASE), - ); - - // Public values - const keyPub = this.account.address.toString(); - expect(storage['publicCollateral']).toEqual(this.collateral[keyPub] ?? Fr.ZERO); - expect(storage['publicStaticDebt']).toEqual(this.staticDebt[keyPub] ?? Fr.ZERO); - expect(storage['publicDebt'].value).toEqual( - muldivUp((this.staticDebt[keyPub] ?? Fr.ZERO).value, this.accumulator, BASE), - ); - - const totalCollateral = Object.values(this.collateral).reduce((a, b) => new Fr(a.value + b.value), Fr.ZERO); - expect(storage['totalCollateral']).toEqual(totalCollateral); - - expect(storage['stableCoinLending'].value).toEqual(this.repaid); - expect(storage['stableCoinPublic']).toEqual(this.stableBalance[keyPub] ?? Fr.ZERO); - - // Abusing notation and using the `keyPriv` as if an address for private holdings of stable_coin while it has the same owner in reality. - expect(storage['stableCoinPrivate']).toEqual(this.stableBalance[keyPriv] ?? Fr.ZERO); - - const totalStableSupply = Object.values(this.stableBalance).reduce((a, b) => new Fr(a.value + b.value), Fr.ZERO); - // @todo @lherskind To be updated such that we burn assets on repay instead. - expect(storage['stableCoinSupply'].value).toEqual(totalStableSupply.value + this.repaid); - } - } - - it('Full lending run-through', async () => { - // Gotta use the actual auth witness account here and not the standard wallet. - const recipientFull = accounts[0]; - const recipient = recipientFull.address; - - const { lendingContract, priceFeedContract, collateralAsset, stableCoin } = await deployContracts(recipient); - - const lendingAccount = new LendingAccount(recipient, new Fr(42)); - - const storageSnapshots: { [key: string]: { [key: string]: Fr } } = {}; - - const setPrice = async (newPrice: bigint) => { - const tx = priceFeedContract.methods.set_price(0n, newPrice).send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - }; - - await setPrice(2n * 10n ** 9n); + it('Mint assets for later usage', async () => { + await waitForSuccess(priceFeedContract.methods.set_price(0n, 2n * 10n ** 9n).send()); { - // Minting some collateral in public so we got it at hand. - const tx = collateralAsset.methods.owner_mint_pub(lendingAccount.address, 10000n).send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - - const tx2 = collateralAsset.methods.approve(lendingContract.address, 10000n).send(); - const receipt2 = await tx2.wait(); - expect(receipt2.status).toBe(TxStatus.MINED); - - // Minting some collateral in private so we got it at hand. - const secret = Fr.random(); - const secretHash = await computeMessageSecretHash(secret); - const shieldAmount = 10000n; - const tx3 = stableCoin.methods.owner_mint_priv(shieldAmount, secretHash).send(); - const receipt3 = await tx3.wait(); - expect(receipt3.status).toBe(TxStatus.MINED); - - const tx4 = stableCoin.methods.redeemShield(shieldAmount, secret, recipient).send(); - const receipt4 = await tx4.wait(); - expect(receipt4.status).toBe(TxStatus.MINED); - - const tx5 = stableCoin.methods.approve(lendingContract.address, 10000n).send(); - const receipt5 = await tx5.wait(); - expect(receipt5.status).toBe(TxStatus.MINED); + const assets = [collateralAsset, stableCoin]; + const mintAmount = 10000n; + for (const asset of assets) { + const secret = Fr.random(); + const secretHash = await computeMessageSecretHash(secret); + + const a = asset.methods.mint_public({ address: lendingAccount.address }, mintAmount).send(); + const b = asset.methods.mint_private(mintAmount, secretHash).send(); + + await Promise.all([a, b].map(waitForSuccess)); + await waitForSuccess( + asset.methods.redeem_shield({ address: lendingAccount.address }, mintAmount, secret).send(), + ); + } } - // Also specified in `noir-contracts/src/contracts/lending_contract/src/main.nr` - const rate = 1268391679n; - const lendingSim = new LendingSimulator(cc, lendingAccount, rate); - await lendingSim.prepare(); - // To handle initial mint (we use these funds to refund privately without shielding first). - lendingSim.mintStable(await lendingAccount.key(), 10000n); + lendingSim.mintStableCoinOutsideLoan(lendingAccount.address, 10000n, true); + lendingSim.stableCoin.redeemShield(lendingAccount.address, 10000n); + lendingSim.mintStableCoinOutsideLoan(lendingAccount.address, 10000n, false); - { - // Initialize the contract values, setting the interest accumulator to 1e9 and the last updated timestamp to now. - logger('Initializing contract'); - const tx = lendingContract.methods - .init(priceFeedContract.address, 8000, collateralAsset.address, stableCoin.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['initial'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, - ); + lendingSim.collateralAsset.mintPrivate(10000n); + lendingSim.collateralAsset.redeemShield(lendingAccount.address, 10000n); + lendingSim.collateralAsset.mintPublic(lendingAccount.address, 10000n); + }); - lendingSim.check(storageSnapshots['initial']); - } + it('Initialize the contract', async () => { + await lendingSim.prepare(); + logger('Initializing contract'); + await waitForSuccess( + lendingContract.methods.init(priceFeedContract.address, 8000, collateralAsset.address, stableCoin.address).send(), + ); + }); - { + describe('Deposits', () => { + it('Depositing 🥸 : 💰 -> 🏦', async () => { const depositAmount = 420n; - + const nonce = Fr.random(); const messageHash = await hashPayload([ - FunctionSelector.fromSignature('unshieldTokens(Field,Field,Field)').toField(), - recipientFull.address.toField(), + lendingContract.address.toField(), + collateralAsset.address.toField(), + FunctionSelector.fromSignature('unshield((Field),(Field),Field,Field)').toField(), + lendingAccount.address.toField(), lendingContract.address.toField(), new Fr(depositAmount), + nonce, ]); await wallet.signAndAddAuthWitness(messageHash); - await lendingSim.progressTime(10); - lendingSim.deposit(await lendingAccount.key(), depositAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.depositPrivate(lendingAccount.address, await lendingAccount.key(), depositAmount); // Make a private deposit of funds into own account. // This should: @@ -377,58 +202,76 @@ describe('e2e_lending_contract', () => { // - increase last updated timestamp. // - increase the private collateral. logger('Depositing 🥸 : 💰 -> 🏦'); - const tx = lendingContract.methods - .deposit_private(lendingAccount.secret, lendingAccount.address, 0n, depositAmount, collateralAsset.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_deposit'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods + .deposit_private( + lendingAccount.address, + depositAmount, + nonce, + lendingAccount.secret, + 0n, + collateralAsset.address, + ) + .send(), ); + }); - lendingSim.check(storageSnapshots['private_deposit']); - } - - { + it('Depositing 🥸 on behalf of recipient: 💰 -> 🏦', async () => { const depositAmount = 421n; + const nonce = Fr.random(); const messageHash = await hashPayload([ - FunctionSelector.fromSignature('unshieldTokens(Field,Field,Field)').toField(), - recipientFull.address.toField(), + lendingContract.address.toField(), + collateralAsset.address.toField(), + FunctionSelector.fromSignature('unshield((Field),(Field),Field,Field)').toField(), + lendingAccount.address.toField(), lendingContract.address.toField(), new Fr(depositAmount), + nonce, ]); await wallet.signAndAddAuthWitness(messageHash); - await lendingSim.progressTime(10); - lendingSim.deposit(recipient.toField(), depositAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.depositPrivate(lendingAccount.address, lendingAccount.address.toField(), depositAmount); // Make a private deposit of funds into another account, in this case, a public account. // This should: // - increase the interest accumulator // - increase last updated timestamp. // - increase the public collateral. logger('Depositing 🥸 on behalf of recipient: 💰 -> 🏦'); - const tx = lendingContract.methods - .deposit_private(0n, lendingAccount.address, recipient.toField(), depositAmount, collateralAsset.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_deposit_on_behalf'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods + .deposit_private( + lendingAccount.address, + depositAmount, + nonce, + 0n, + lendingAccount.address, + collateralAsset.address, + ) + .send(), ); + }); - lendingSim.check(storageSnapshots['private_deposit_on_behalf']); - } - - { + it('Depositing: 💰 -> 🏦', async () => { const depositAmount = 211n; - await lendingSim.progressTime(10); - lendingSim.deposit(recipient.toField(), depositAmount); + + const nonce = Fr.random(); + const messageHash = await hashPayload([ + lendingContract.address.toField(), + collateralAsset.address.toField(), + FunctionSelector.fromSignature('transfer_public((Field),(Field),Field,Field)').toField(), + lendingAccount.address.toField(), + lendingContract.address.toField(), + new Fr(depositAmount), + nonce, + ]); + + // Add it to the wallet as approved + const me = await SchnorrAuthWitnessAccountContract.at(accounts[0].address, wallet); + await waitForSuccess(me.methods.set_is_valid_storage(messageHash, 1).send()); + + await lendingSim.progressTime(TIME_JUMP); + lendingSim.depositPublic(lendingAccount.address, lendingAccount.address.toField(), depositAmount); // Make a public deposit of funds into self. // This should: @@ -437,24 +280,31 @@ describe('e2e_lending_contract', () => { // - increase the public collateral. logger('Depositing: 💰 -> 🏦'); - const tx = lendingContract.methods - .deposit_public(lendingAccount.address, depositAmount, collateralAsset.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['public_deposit'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods + .deposit_public(depositAmount, nonce, lendingAccount.address, collateralAsset.address) + .send(), ); - lendingSim.check(storageSnapshots['public_deposit']); - } + }); + describe('failure cases', () => { + it('calling internal _deposit function directly', async () => { + // Try to call the internal `_deposit` function directly + // This should: + // - not change any storage values. + // - fail + + await expect( + lendingContract.methods._deposit(lendingAccount.address.toField(), 42n, collateralAsset.address).simulate(), + ).rejects.toThrow(); + }); + }); + }); - { + describe('Borrow', () => { + it('Borrow 🥸 : 🏦 -> 🍌', async () => { const borrowAmount = 69n; - await lendingSim.progressTime(10); - lendingSim.borrow(await lendingAccount.key(), lendingAccount.address.toField(), borrowAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.borrow(await lendingAccount.key(), lendingAccount.address, borrowAmount); // Make a private borrow using the private account // This should: @@ -463,25 +313,15 @@ describe('e2e_lending_contract', () => { // - increase the private debt. logger('Borrow 🥸 : 🏦 -> 🍌'); - const tx = lendingContract.methods - .borrow_private(lendingAccount.secret, lendingAccount.address, borrowAmount) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_borrow'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods.borrow_private(lendingAccount.secret, lendingAccount.address, borrowAmount).send(), ); + }); - lendingSim.check(storageSnapshots['private_borrow']); - } - - { + it('Borrow: 🏦 -> 🍌', async () => { const borrowAmount = 69n; - await lendingSim.progressTime(10); - lendingSim.borrow(recipient.toField(), lendingAccount.address.toField(), borrowAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.borrow(lendingAccount.address.toField(), lendingAccount.address, borrowAmount); // Make a public borrow using the private account // This should: @@ -490,31 +330,26 @@ describe('e2e_lending_contract', () => { // - increase the public debt. logger('Borrow: 🏦 -> 🍌'); - const tx = lendingContract.methods.borrow_public(lendingAccount.address, borrowAmount).send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['public_borrow'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, - ); - - lendingSim.check(storageSnapshots['public_borrow']); - } + await waitForSuccess(lendingContract.methods.borrow_public(lendingAccount.address, borrowAmount).send()); + }); + }); - { + describe('Repay', () => { + it('Repay 🥸 : 🍌 -> 🏦', async () => { const repayAmount = 20n; + const nonce = Fr.random(); const messageHash = await hashPayload([ - FunctionSelector.fromSignature('unshieldTokens(Field,Field,Field)').toField(), - recipientFull.address.toField(), lendingContract.address.toField(), + stableCoin.address.toField(), + FunctionSelector.fromSignature('burn((Field),Field,Field)').toField(), + lendingAccount.address.toField(), new Fr(repayAmount), + nonce, ]); await wallet.signAndAddAuthWitness(messageHash); - await lendingSim.progressTime(10); - lendingSim.repay(await lendingAccount.key(), await lendingAccount.key(), repayAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.repayPrivate(lendingAccount.address, await lendingAccount.key(), repayAmount); // Make a private repay of the debt in the private account // This should: @@ -523,33 +358,28 @@ describe('e2e_lending_contract', () => { // - decrease the private debt. logger('Repay 🥸 : 🍌 -> 🏦'); - const tx = lendingContract.methods - .repay_private(lendingAccount.secret, lendingAccount.address, 0n, repayAmount, stableCoin.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_repay'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods + .repay_private(lendingAccount.address, repayAmount, nonce, lendingAccount.secret, 0n, stableCoin.address) + .send(), ); + }); - lendingSim.check(storageSnapshots['private_repay']); - } - - { + it('Repay 🥸 on behalf of public: 🍌 -> 🏦', async () => { const repayAmount = 21n; + const nonce = Fr.random(); const messageHash = await hashPayload([ - FunctionSelector.fromSignature('unshieldTokens(Field,Field,Field)').toField(), - recipientFull.address.toField(), lendingContract.address.toField(), + stableCoin.address.toField(), + FunctionSelector.fromSignature('burn((Field),Field,Field)').toField(), + lendingAccount.address.toField(), new Fr(repayAmount), + nonce, ]); await wallet.signAndAddAuthWitness(messageHash); - await lendingSim.progressTime(10); - lendingSim.repay(await lendingAccount.key(), lendingAccount.address.toField(), repayAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.repayPrivate(lendingAccount.address, lendingAccount.address.toField(), repayAmount); // Make a private repay of the debt in the public account // This should: @@ -558,25 +388,32 @@ describe('e2e_lending_contract', () => { // - decrease the public debt. logger('Repay 🥸 on behalf of public: 🍌 -> 🏦'); - const tx = lendingContract.methods - .repay_private(0n, lendingAccount.address, recipient.toField(), repayAmount, stableCoin.address) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_repay_on_behalf'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods + .repay_private(lendingAccount.address, repayAmount, nonce, 0n, lendingAccount.address, stableCoin.address) + .send(), ); + }); - lendingSim.check(storageSnapshots['private_repay_on_behalf']); - } - - { + it('Repay: 🍌 -> 🏦', async () => { const repayAmount = 20n; - await lendingSim.progressTime(10); - lendingSim.repay(lendingAccount.address.toField(), lendingAccount.address.toField(), repayAmount); + + const nonce = Fr.random(); + const messageHash = await hashPayload([ + lendingContract.address.toField(), + stableCoin.address.toField(), + FunctionSelector.fromSignature('burn_public((Field),Field,Field)').toField(), + lendingAccount.address.toField(), + new Fr(repayAmount), + nonce, + ]); + + // Add it to the wallet as approved + const me = await SchnorrAuthWitnessAccountContract.at(accounts[0].address, wallet); + await waitForSuccess(me.methods.set_is_valid_storage(messageHash, 1).send()); + + await lendingSim.progressTime(TIME_JUMP); + lendingSim.repayPublic(lendingAccount.address, lendingAccount.address.toField(), repayAmount); // Make a public repay of the debt in the public account // This should: @@ -585,32 +422,17 @@ describe('e2e_lending_contract', () => { // - decrease the public debt. logger('Repay: 🍌 -> 🏦'); - const tx = lendingContract.methods.repay_public(recipient.toField(), 20n, stableCoin.address).send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['public_repay'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods.repay_public(repayAmount, nonce, lendingAccount.address, stableCoin.address).send(), ); + }); + }); - lendingSim.check(storageSnapshots['public_repay']); - } - - { - // Withdraw more than possible to test the revert. - logger('Withdraw: trying to withdraw more than possible'); - const tx = lendingContract.methods.withdraw_public(recipient, 10n ** 9n).send({ skipPublicSimulation: true }); - await tx.isMined({ interval: 0.1 }); - const receipt = await tx.getReceipt(); - expect(receipt.status).toBe(TxStatus.DROPPED); - } - - { + describe('Withdraw', () => { + it('Withdraw: 🏦 -> 💰', async () => { const withdrawAmount = 42n; - await lendingSim.progressTime(10); - lendingSim.withdraw(recipient.toField(), withdrawAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.withdraw(lendingAccount.address.toField(), lendingAccount.address, withdrawAmount); // Withdraw funds from the public account // This should: @@ -619,23 +441,13 @@ describe('e2e_lending_contract', () => { // - decrease the public collateral. logger('Withdraw: 🏦 -> 💰'); - const tx = lendingContract.methods.withdraw_public(recipient, withdrawAmount).send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['public_withdraw'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, - ); - - lendingSim.check(storageSnapshots['public_withdraw']); - } + await waitForSuccess(lendingContract.methods.withdraw_public(lendingAccount.address, withdrawAmount).send()); + }); - { + it('Withdraw 🥸 : 🏦 -> 💰', async () => { const withdrawAmount = 42n; - await lendingSim.progressTime(10); - lendingSim.withdraw(await lendingAccount.key(), withdrawAmount); + await lendingSim.progressTime(TIME_JUMP); + lendingSim.withdraw(await lendingAccount.key(), lendingAccount.address, withdrawAmount); // Withdraw funds from the private account // This should: @@ -644,41 +456,19 @@ describe('e2e_lending_contract', () => { // - decrease the private collateral. logger('Withdraw 🥸 : 🏦 -> 💰'); - const tx = lendingContract.methods - .withdraw_private(lendingAccount.secret, lendingAccount.address, withdrawAmount) - .send(); - const receipt = await tx.wait(); - expect(receipt.status).toBe(TxStatus.MINED); - storageSnapshots['private_withdraw'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, + await waitForSuccess( + lendingContract.methods.withdraw_private(lendingAccount.secret, lendingAccount.address, withdrawAmount).send(), ); - - lendingSim.check(storageSnapshots['private_withdraw']); - } - - { - // Try to call the internal `_deposit` function directly - // This should: - // - not change any storage values. - // - fail - - const tx = lendingContract.methods - ._deposit(recipient.toField(), 42n, collateralAsset.address) - .send({ skipPublicSimulation: true }); - await tx.isMined({ interval: 0.1 }); - const receipt = await tx.getReceipt(); - expect(receipt.status).toBe(TxStatus.DROPPED); - logger('Rejected call directly to internal function 🧚 '); - storageSnapshots['attempted_internal_deposit'] = await getStorageSnapshot( - lendingContract, - collateralAsset, - stableCoin, - lendingAccount, - ); - expect(storageSnapshots['private_withdraw']).toEqual(storageSnapshots['attempted_internal_deposit']); - } - }, 650_000); + }); + + describe('failure cases', () => { + it('withdraw more than possible to revert', async () => { + // Withdraw more than possible to test the revert. + logger('Withdraw: trying to withdraw more than possible'); + await expect( + lendingContract.methods.withdraw_public(lendingAccount.address, 10n ** 9n).simulate(), + ).rejects.toThrow(); + }); + }); + }); }); diff --git a/yarn-project/end-to-end/src/e2e_pending_commitments_contract.test.ts b/yarn-project/end-to-end/src/e2e_pending_commitments_contract.test.ts index 24edd48610b..2c8d21403ee 100644 --- a/yarn-project/end-to-end/src/e2e_pending_commitments_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_pending_commitments_contract.test.ts @@ -64,7 +64,7 @@ describe('e2e_pending_commitments_contract', () => { return contract; }; - it('Noir function can "get" notes it just "inserted"', async () => { + it('Aztec.nr function can "get" notes it just "inserted"', async () => { const mintAmount = 65n; const deployedContract = await deployContract(); @@ -76,7 +76,7 @@ describe('e2e_pending_commitments_contract', () => { expect(receipt.status).toBe(TxStatus.MINED); }, 60_000); - it('Squash! Noir function can "create" and "nullify" note in the same TX', async () => { + it('Squash! Aztec.nr function can "create" and "nullify" note in the same TX', async () => { // Kernel will squash the noteHash and its nullifier. // Realistic way to describe this test is "Mint note A, then burn note A in the same transaction" const mintAmount = 65n; @@ -101,7 +101,7 @@ describe('e2e_pending_commitments_contract', () => { await expectNullifiersSquashedExcept(0); }, 60_000); - it('Squash! Noir function can "create" 2 notes and "nullify" both in the same TX', async () => { + it('Squash! Aztec.nr function can "create" 2 notes and "nullify" both in the same TX', async () => { // Kernel will squash both noteHashes and their nullifier. // Realistic way to describe this test is "Mint notes A and B, then burn both in the same transaction" const mintAmount = 65n; @@ -125,7 +125,7 @@ describe('e2e_pending_commitments_contract', () => { await expectNullifiersSquashedExcept(0); }, 60_000); - it('Squash! Noir function can "create" 2 notes and "nullify" 1 in the same TX (kernel will squash one note + nullifier)', async () => { + it('Squash! Aztec.nr function can "create" 2 notes and "nullify" 1 in the same TX (kernel will squash one note + nullifier)', async () => { // Kernel will squash one noteHash and its nullifier. // The other note will become persistent! // Realistic way to describe this test is "Mint notes A and B, then burn note A in the same transaction" @@ -150,7 +150,7 @@ describe('e2e_pending_commitments_contract', () => { await expectNullifiersSquashedExcept(0); }, 60_000); - it('Squash! Noir function can nullify a pending note and a persistent in the same TX', async () => { + it('Squash! Aztec.nr function can nullify a pending note and a persistent in the same TX', async () => { // Create 1 note in isolated TX. // Then, in a separate TX, create 1 new note and nullify BOTH notes. // In this second TX, the kernel will squash one note + nullifier, diff --git a/yarn-project/end-to-end/src/e2e_token_contract.test.ts b/yarn-project/end-to-end/src/e2e_token_contract.test.ts index 649a53cdee6..7e8defafae4 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract.test.ts @@ -4,7 +4,6 @@ import { Account, AuthWitnessAccountContract, AuthWitnessEntrypointWallet, - AztecAddress, IAuthWitnessAccountEntrypoint, computeMessageSecretHash, } from '@aztec/aztec.js'; @@ -24,6 +23,7 @@ import { AztecRPC, TxStatus } from '@aztec/types'; import { jest } from '@jest/globals'; import { setup } from './fixtures/utils.js'; +import { TokenSimulator } from './simulators/token_simulator.js'; const hashPayload = async (payload: Fr[]) => { return pedersenPlookupCompressWithHashIndex( @@ -35,95 +35,6 @@ const hashPayload = async (payload: Fr[]) => { const TIMEOUT = 60_000; -class TokenSimulator { - private balancesPrivate: Map = new Map(); - private balancePublic: Map = new Map(); - public totalSupply: bigint = 0n; - - constructor(protected token: TokenContract, protected logger: DebugLogger, protected accounts: CompleteAddress[]) {} - - public mintPrivate(to: AztecAddress, amount: bigint) { - this.totalSupply += amount; - } - - public mintPublic(to: AztecAddress, amount: bigint) { - this.totalSupply += amount; - const value = this.balancePublic.get(to) || 0n; - this.balancePublic.set(to, value + amount); - } - - public transferPublic(from: AztecAddress, to: AztecAddress, amount: bigint) { - const fromBalance = this.balancePublic.get(from) || 0n; - this.balancePublic.set(from, fromBalance - amount); - expect(fromBalance).toBeGreaterThanOrEqual(amount); - - const toBalance = this.balancePublic.get(to) || 0n; - this.balancePublic.set(to, toBalance + amount); - } - - public transferPrivate(from: AztecAddress, to: AztecAddress, amount: bigint) { - const fromBalance = this.balancesPrivate.get(from) || 0n; - expect(fromBalance).toBeGreaterThanOrEqual(amount); - this.balancesPrivate.set(from, fromBalance - amount); - - const toBalance = this.balancesPrivate.get(to) || 0n; - this.balancesPrivate.set(to, toBalance + amount); - } - - public shield(from: AztecAddress, amount: bigint) { - const fromBalance = this.balancePublic.get(from) || 0n; - expect(fromBalance).toBeGreaterThanOrEqual(amount); - this.balancePublic.set(from, fromBalance - amount); - } - - public redeemShield(to: AztecAddress, amount: bigint) { - const toBalance = this.balancesPrivate.get(to) || 0n; - this.balancesPrivate.set(to, toBalance + amount); - } - - public unshield(from: AztecAddress, to: AztecAddress, amount: bigint) { - const fromBalance = this.balancesPrivate.get(from) || 0n; - const toBalance = this.balancePublic.get(to) || 0n; - expect(fromBalance).toBeGreaterThanOrEqual(amount); - this.balancesPrivate.set(from, fromBalance - amount); - this.balancePublic.set(to, toBalance + amount); - } - - public burnPrivate(from: AztecAddress, amount: bigint) { - const fromBalance = this.balancesPrivate.get(from) || 0n; - expect(fromBalance).toBeGreaterThanOrEqual(amount); - this.balancesPrivate.set(from, fromBalance - amount); - - this.totalSupply -= amount; - } - - public burnPublic(from: AztecAddress, amount: bigint) { - const fromBalance = this.balancePublic.get(from) || 0n; - expect(fromBalance).toBeGreaterThanOrEqual(amount); - this.balancePublic.set(from, fromBalance - amount); - - this.totalSupply -= amount; - } - - public balanceOfPublic(address: AztecAddress) { - return this.balancePublic.get(address) || 0n; - } - - public balanceOfPrivate(address: AztecAddress) { - return this.balancesPrivate.get(address) || 0n; - } - - public async check() { - expect(await this.token.methods.total_supply().view()).toEqual(this.totalSupply); - - // Check that all our public matches - for (const { address } of this.accounts) { - expect(await this.token.methods.balance_of_public({ address }).view()).toEqual(this.balanceOfPublic(address)); - expect(await this.token.methods.balance_of_private({ address }).view()).toEqual(this.balanceOfPrivate(address)); - } - } -} - describe('e2e_token_contract', () => { jest.setTimeout(TIMEOUT); @@ -173,7 +84,11 @@ describe('e2e_token_contract', () => { asset = await TokenContract.at(receipt.contractAddress!, wallets[0]); } - tokenSim = new TokenSimulator(asset, logger, accounts); + tokenSim = new TokenSimulator( + asset, + logger, + accounts.map(account => account.address), + ); { const initializeTx = asset.methods._initialize({ address: accounts[0].address }).send(); @@ -299,7 +214,7 @@ describe('e2e_token_contract', () => { const tx = asset.methods.mint_private(amount, secretHash).send(); const receipt = await tx.wait(); expect(receipt.status).toBe(TxStatus.MINED); - tokenSim.mintPrivate(accounts[0].address, amount); + tokenSim.mintPrivate(amount); }); it('redeem as recipient', async () => { @@ -976,8 +891,8 @@ describe('e2e_token_contract', () => { caller.address.toField(), asset.address.toField(), FunctionSelector.fromSignature('unshield((Field),(Field),Field,Field)').toField(), - accounts[0].address.toField(), - accounts[1].address.toField(), + from.address.toField(), + to.address.toField(), new Fr(amount), nonce, ]); diff --git a/yarn-project/end-to-end/src/fixtures/cross_chain_test_harness.ts b/yarn-project/end-to-end/src/fixtures/cross_chain_test_harness.ts index ad71a3f1733..9084a112687 100644 --- a/yarn-project/end-to-end/src/fixtures/cross_chain_test_harness.ts +++ b/yarn-project/end-to-end/src/fixtures/cross_chain_test_harness.ts @@ -166,7 +166,7 @@ export class CrossChainTestHarness { async consumeMessageOnAztecAndMintSecretly(bridgeAmount: bigint, messageKey: Fr, secret: Fr) { this.logger('Consuming messages on L2 secretively'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const consumptionTx = this.l2Contract.methods .mint(bridgeAmount, this.ownerAddress, messageKey, secret, this.ethAccount.toField()) .send(); @@ -178,7 +178,7 @@ export class CrossChainTestHarness { async consumeMessageOnAztecAndMintPublicly(bridgeAmount: bigint, messageKey: Fr, secret: Fr) { this.logger('Consuming messages on L2 Publicly'); - // Call the mint tokens function on the noir contract + // Call the mint tokens function on the Aztec.nr contract const consumptionTx = this.l2Contract.methods .mintPublic(bridgeAmount, this.ownerAddress, messageKey, secret, this.ethAccount.toField()) .send(); diff --git a/yarn-project/end-to-end/src/simulators/index.ts b/yarn-project/end-to-end/src/simulators/index.ts new file mode 100644 index 00000000000..bf023483a1b --- /dev/null +++ b/yarn-project/end-to-end/src/simulators/index.ts @@ -0,0 +1,2 @@ +export * from './lending_simulator.js'; +export * from './token_simulator.js'; diff --git a/yarn-project/end-to-end/src/simulators/lending_simulator.ts b/yarn-project/end-to-end/src/simulators/lending_simulator.ts new file mode 100644 index 00000000000..37333ab4572 --- /dev/null +++ b/yarn-project/end-to-end/src/simulators/lending_simulator.ts @@ -0,0 +1,187 @@ +// Convenience struct to hold an account's address and secret that can easily be passed around. +import { CheatCodes } from '@aztec/aztec.js'; +import { AztecAddress, CircuitsWasm, Fr } from '@aztec/circuits.js'; +import { pedersenPlookupCommitInputs } from '@aztec/circuits.js/barretenberg'; +import { LendingContract } from '@aztec/noir-contracts/types'; + +import { TokenSimulator } from './token_simulator.js'; + +/** + * Contains utilities to compute the "key" for private holdings in the public state. + */ +export class LendingAccount { + /** The address that owns this account */ + public readonly address: AztecAddress; + /** The secret used for private deposits */ + public readonly secret: Fr; + + constructor(address: AztecAddress, secret: Fr) { + this.address = address; + this.secret = secret; + } + + /** + * Computes the key for the private holdings of this account. + * @returns Key in public space + */ + public async key(): Promise { + return Fr.fromBuffer( + pedersenPlookupCommitInputs( + await CircuitsWasm.get(), + [this.address, this.secret].map(f => f.toBuffer()), + ), + ); + } +} + +const WAD = 10n ** 18n; +const BASE = 10n ** 9n; + +const muldivDown = (a: bigint, b: bigint, c: bigint) => (a * b) / c; + +const muldivUp = (a: bigint, b: bigint, c: bigint) => { + const adder = (a * b) % c > 0n ? 1n : 0n; + return muldivDown(a, b, c) + adder; +}; + +const computeMultiplier = (rate: bigint, dt: bigint) => { + if (dt == 0n) { + return BASE; + } + + const expMinusOne = dt - 1n; + const expMinusTwo = dt > 2 ? dt - 2n : 0n; + + const basePowerTwo = muldivDown(rate, rate, WAD); + const basePowerThree = muldivDown(basePowerTwo, rate, WAD); + + const temp = dt * expMinusOne; + const secondTerm = muldivDown(temp, basePowerTwo, 2n); + const thirdTerm = muldivDown(temp * expMinusTwo, basePowerThree, 6n); + + const offset = (dt * rate + secondTerm + thirdTerm) / (WAD / BASE); + + return BASE + offset; +}; + +/** + * Helper class that emulates the logic of the lending contract. Used to have a "twin" to check values against. + */ +export class LendingSimulator { + /** interest rate accumulator */ + public accumulator: bigint = 0n; + /** the timestamp of the simulator*/ + public time: number = 0; + + private collateral: { [key: string]: Fr } = {}; + private staticDebt: { [key: string]: Fr } = {}; + private borrowed: bigint = 0n; + private mintedOutside: bigint = 0n; + + constructor( + private cc: CheatCodes, + private account: LendingAccount, + private rate: bigint, + /** the lending contract */ + public lendingContract: LendingContract, + /** the collateral asset used in the lending contract */ + public collateralAsset: TokenSimulator, + /** the stable-coin borrowed in the lending contract */ + public stableCoin: TokenSimulator, + ) {} + + async prepare() { + this.accumulator = BASE; + const ts = await this.cc.eth.timestamp(); + this.time = ts + 10 + (ts % 10); + await this.cc.aztec.warp(this.time); + } + + async progressTime(diff: number) { + this.time = this.time + diff; + await this.cc.aztec.warp(this.time); + this.accumulator = muldivDown(this.accumulator, computeMultiplier(this.rate, BigInt(diff)), BASE); + } + + depositPrivate(from: AztecAddress, onBehalfOf: Fr, amount: bigint) { + this.collateralAsset.unshield(from, this.lendingContract.address, amount); + this.deposit(onBehalfOf, amount); + } + + depositPublic(from: AztecAddress, onBehalfOf: Fr, amount: bigint) { + this.collateralAsset.transferPublic(from, this.lendingContract.address, amount); + this.deposit(onBehalfOf, amount); + } + + private deposit(onBehalfOf: Fr, amount: bigint) { + const coll = this.collateral[onBehalfOf.toString()] ?? Fr.ZERO; + this.collateral[onBehalfOf.toString()] = new Fr(coll.value + amount); + } + + withdraw(owner: Fr, recipient: AztecAddress, amount: bigint) { + const coll = this.collateral[owner.toString()] ?? Fr.ZERO; + this.collateral[owner.toString()] = new Fr(coll.value - amount); + this.collateralAsset.transferPublic(this.lendingContract.address, recipient, amount); + } + + borrow(owner: Fr, recipient: AztecAddress, amount: bigint) { + const staticDebtBal = this.staticDebt[owner.toString()] ?? Fr.ZERO; + const increase = muldivUp(amount, BASE, this.accumulator); + this.staticDebt[owner.toString()] = new Fr(staticDebtBal.value + increase); + + this.stableCoin.mintPublic(recipient, amount); + this.borrowed += amount; + } + + repayPrivate(from: AztecAddress, onBehalfOf: Fr, amount: bigint) { + this.stableCoin.burnPrivate(from, amount); + this.repay(onBehalfOf, onBehalfOf, amount); + } + + repayPublic(from: AztecAddress, onBehalfOf: Fr, amount: bigint) { + this.stableCoin.burnPublic(from, amount); + this.repay(onBehalfOf, onBehalfOf, amount); + } + + private repay(from: Fr, onBehalfOf: Fr, amount: bigint) { + const staticDebtBal = this.staticDebt[onBehalfOf.toString()] ?? Fr.ZERO; + const decrease = muldivDown(amount, BASE, this.accumulator); + this.staticDebt[onBehalfOf.toString()] = new Fr(staticDebtBal.value - decrease); + + this.borrowed -= amount; + } + + mintStableCoinOutsideLoan(recipient: AztecAddress, amount: bigint, priv = false) { + if (priv) { + this.stableCoin.mintPrivate(amount); + } else { + this.stableCoin.mintPublic(recipient, amount); + } + this.mintedOutside += amount; + } + + async check() { + // Run checks on both underlying assets + await this.collateralAsset.check(); + await this.stableCoin.check(); + + // Check that total collateral equals total holdings by contract. + const totalCollateral = Object.values(this.collateral).reduce((a, b) => new Fr(a.value + b.value), Fr.ZERO); + expect(totalCollateral).toEqual(new Fr(this.collateralAsset.balanceOfPublic(this.lendingContract.address))); + + expect(this.borrowed).toEqual(this.stableCoin.totalSupply - this.mintedOutside); + + const asset = await this.lendingContract.methods.get_asset(0).view(); + expect(asset['interest_accumulator']).toEqual(this.accumulator); + expect(asset['last_updated_ts']).toEqual(BigInt(this.time)); + + for (const key of [this.account.address, await this.account.key()]) { + const privatePos = await this.lendingContract.methods.get_position(key).view(); + expect(new Fr(privatePos['collateral'])).toEqual(this.collateral[key.toString()] ?? Fr.ZERO); + expect(new Fr(privatePos['static_debt'])).toEqual(this.staticDebt[key.toString()] ?? Fr.ZERO); + expect(privatePos['debt']).toEqual( + muldivUp((this.staticDebt[key.toString()] ?? Fr.ZERO).value, this.accumulator, BASE), + ); + } + } +} diff --git a/yarn-project/end-to-end/src/simulators/token_simulator.ts b/yarn-project/end-to-end/src/simulators/token_simulator.ts new file mode 100644 index 00000000000..b28c5480d6e --- /dev/null +++ b/yarn-project/end-to-end/src/simulators/token_simulator.ts @@ -0,0 +1,93 @@ +/* eslint-disable jsdoc/require-jsdoc */ +import { DebugLogger } from '@aztec/aztec.js'; +import { AztecAddress } from '@aztec/circuits.js'; +import { TokenContract } from '@aztec/noir-contracts/types'; + +export class TokenSimulator { + private balancesPrivate: Map = new Map(); + private balancePublic: Map = new Map(); + public totalSupply: bigint = 0n; + + constructor(protected token: TokenContract, protected logger: DebugLogger, protected accounts: AztecAddress[]) {} + + public mintPrivate(amount: bigint) { + this.totalSupply += amount; + } + + public mintPublic(to: AztecAddress, amount: bigint) { + this.totalSupply += amount; + const value = this.balancePublic.get(to) || 0n; + this.balancePublic.set(to, value + amount); + } + + public transferPublic(from: AztecAddress, to: AztecAddress, amount: bigint) { + const fromBalance = this.balancePublic.get(from) || 0n; + this.balancePublic.set(from, fromBalance - amount); + expect(fromBalance).toBeGreaterThanOrEqual(amount); + + const toBalance = this.balancePublic.get(to) || 0n; + this.balancePublic.set(to, toBalance + amount); + } + + public transferPrivate(from: AztecAddress, to: AztecAddress, amount: bigint) { + const fromBalance = this.balancesPrivate.get(from) || 0n; + expect(fromBalance).toBeGreaterThanOrEqual(amount); + this.balancesPrivate.set(from, fromBalance - amount); + + const toBalance = this.balancesPrivate.get(to) || 0n; + this.balancesPrivate.set(to, toBalance + amount); + } + + public shield(from: AztecAddress, amount: bigint) { + const fromBalance = this.balancePublic.get(from) || 0n; + expect(fromBalance).toBeGreaterThanOrEqual(amount); + this.balancePublic.set(from, fromBalance - amount); + } + + public redeemShield(to: AztecAddress, amount: bigint) { + const toBalance = this.balancesPrivate.get(to) || 0n; + this.balancesPrivate.set(to, toBalance + amount); + } + + public unshield(from: AztecAddress, to: AztecAddress, amount: bigint) { + const fromBalance = this.balancesPrivate.get(from) || 0n; + const toBalance = this.balancePublic.get(to) || 0n; + expect(fromBalance).toBeGreaterThanOrEqual(amount); + this.balancesPrivate.set(from, fromBalance - amount); + this.balancePublic.set(to, toBalance + amount); + } + + public burnPrivate(from: AztecAddress, amount: bigint) { + const fromBalance = this.balancesPrivate.get(from) || 0n; + expect(fromBalance).toBeGreaterThanOrEqual(amount); + this.balancesPrivate.set(from, fromBalance - amount); + + this.totalSupply -= amount; + } + + public burnPublic(from: AztecAddress, amount: bigint) { + const fromBalance = this.balancePublic.get(from) || 0n; + expect(fromBalance).toBeGreaterThanOrEqual(amount); + this.balancePublic.set(from, fromBalance - amount); + + this.totalSupply -= amount; + } + + public balanceOfPublic(address: AztecAddress) { + return this.balancePublic.get(address) || 0n; + } + + public balanceOfPrivate(address: AztecAddress) { + return this.balancesPrivate.get(address) || 0n; + } + + public async check() { + expect(await this.token.methods.total_supply().view()).toEqual(this.totalSupply); + + // Check that all our public matches + for (const address of this.accounts) { + expect(await this.token.methods.balance_of_public({ address }).view()).toEqual(this.balanceOfPublic(address)); + expect(await this.token.methods.balance_of_private({ address }).view()).toEqual(this.balanceOfPrivate(address)); + } + } +} diff --git a/yarn-project/ethereum/package.json b/yarn-project/ethereum/package.json index 82a2402ad32..90e6f2ee7c1 100644 --- a/yarn-project/ethereum/package.json +++ b/yarn-project/ethereum/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/foundation/package.json b/yarn-project/foundation/package.json index 7441da40186..3e8e058f4be 100644 --- a/yarn-project/foundation/package.json +++ b/yarn-project/foundation/package.json @@ -35,8 +35,6 @@ "./committable": "./dest/committable/index.js" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/foundation/src/abi/abi.ts b/yarn-project/foundation/src/abi/abi.ts index 0fecd88c5cd..18dd0dd2793 100644 --- a/yarn-project/foundation/src/abi/abi.ts +++ b/yarn-project/foundation/src/abi/abi.ts @@ -96,7 +96,7 @@ export interface StructType extends BasicType<'struct'> { } /** - * Noir function types. + * Aztec.nr function types. */ export enum FunctionType { SECRET = 'secret', diff --git a/yarn-project/foundation/src/abi/decoder.ts b/yarn-project/foundation/src/abi/decoder.ts index 0dfbe09708c..cece6e9d949 100644 --- a/yarn-project/foundation/src/abi/decoder.ts +++ b/yarn-project/foundation/src/abi/decoder.ts @@ -62,7 +62,7 @@ class ReturnValuesDecoder { /** * Decodes all the return values for the given function ABI. - * Noir support only single return value + * Aztec.nr support only single return value * The return value can however be simple types, structs or arrays * @returns The decoded return values. */ diff --git a/yarn-project/key-store/package.json b/yarn-project/key-store/package.json index e9b76370219..d43c019eef9 100644 --- a/yarn-project/key-store/package.json +++ b/yarn-project/key-store/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/l1-artifacts/package.json b/yarn-project/l1-artifacts/package.json index c1f000e2d95..57e271c6927 100644 --- a/yarn-project/l1-artifacts/package.json +++ b/yarn-project/l1-artifacts/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && yarn generate && tsc -b", "clean": "rm -rf ./dest ./generated .tsbuildinfo", "formatting": "run -T prettier --check ./generated && run -T eslint ./generated", diff --git a/yarn-project/merkle-tree/package.json b/yarn-project/merkle-tree/package.json index 163d6fc8dba..d551bb84868 100644 --- a/yarn-project/merkle-tree/package.json +++ b/yarn-project/merkle-tree/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/noir-compiler/README.md b/yarn-project/noir-compiler/README.md index 92558025bbb..ade6f9bfa0c 100644 --- a/yarn-project/noir-compiler/README.md +++ b/yarn-project/noir-compiler/README.md @@ -1,6 +1,6 @@ -# Aztec Noir compiler +# Aztec.nr compiler -The Aztec noir compiler compiles noir contracts using nargo and outputs Aztec formatted contract ABIs. The compiler can also generate typescript classes for each contract, as well as Noir interfaces for calling external functions. +The Aztec.nr compiler compiles Aztec.nr contracts using nargo and outputs Aztec formatted contract ABIs. The compiler can also generate typescript classes for each contract, as well as Aztec.nr interfaces for calling external functions. ## Installation diff --git a/yarn-project/noir-compiler/package.json b/yarn-project/noir-compiler/package.json index 067b9a5c6d9..d9efa71dc52 100644 --- a/yarn-project/noir-compiler/package.json +++ b/yarn-project/noir-compiler/package.json @@ -10,15 +10,13 @@ "entryPoints": [ "./src/index.ts" ], - "name": "Aztec noir compiler", + "name": "Aztec.nr compiler", "tsconfig": "./tsconfig.json" }, "bin": { "aztec-compile": "dest/cli.js" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap b/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap index 4a4607ed288..5defbe9affe 100644 --- a/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap +++ b/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap @@ -3,9 +3,167 @@ exports[`noir-compiler using nargo binary compiles the test contract 1`] = ` [ { + "debug": { + "debugSymbols": [ + "eJyrVsrJT04syczPK1ayqlYyULKKrlYqLkjMA/GKSxKLSpSsDE0MdZRS81KALFOzWh2ltMycVCC7VgdDpbEJVKGZOVydsQkWhUYGMJVGxkhKa2N1lAwH2gm1tQDKLFO0", + "eJyrVsrJT04syczPK1ayqq6tBQAz9wY7", + ], + "fileMap": { + "3": { + "path": "std/hash", + "source": "mod poseidon; + +#[foreign(sha256)] +fn sha256(_input : [u8; N]) -> [u8; 32] {} + +#[foreign(blake2s)] +fn blake2s(_input : [u8; N]) -> [u8; 32] {} + +fn pedersen(input : [Field; N]) -> [Field; 2] { + pedersen_with_separator(input, 0) +} + +#[foreign(pedersen)] +fn pedersen_with_separator(_input : [Field; N], _separator : u32) -> [Field; 2] {} + +#[foreign(hash_to_field_128_security)] +fn hash_to_field(_input : [Field; N]) -> Field {} + +#[foreign(keccak256)] +fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] {} + +// mimc-p/p implementation +// constants are (publicly generated) random numbers, for instance using keccak as a ROM. +// You must use constants generated for the native field +// Rounds number should be ~ log(p)/log(exp) +// For 254 bit primes, exponent 7 and 91 rounds seems to be recommended +fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field { + //round 0 + let mut t = x + k; + let mut h = t.pow_32(exp); + //next rounds + for i in 1 .. constants.len() { + t = h + k + constants[i]; + h = t.pow_32(exp); + }; + h + k +} + +global MIMC_BN254_ROUNDS = 91; + +//mimc implementation with hardcoded parameters for BN254 curve. +fn mimc_bn254(array: [Field; N]) -> Field { + //mimc parameters + let exponent = 7; + //generated from seed "mimc" using keccak256 + let constants: [Field; MIMC_BN254_ROUNDS] = [ + 0, + 20888961410941983456478427210666206549300505294776164667214940546594746570981, + 15265126113435022738560151911929040668591755459209400716467504685752745317193, + 8334177627492981984476504167502758309043212251641796197711684499645635709656, + 1374324219480165500871639364801692115397519265181803854177629327624133579404, + 11442588683664344394633565859260176446561886575962616332903193988751292992472, + 2558901189096558760448896669327086721003508630712968559048179091037845349145, + 11189978595292752354820141775598510151189959177917284797737745690127318076389, + 3262966573163560839685415914157855077211340576201936620532175028036746741754, + 17029914891543225301403832095880481731551830725367286980611178737703889171730, + 4614037031668406927330683909387957156531244689520944789503628527855167665518, + 19647356996769918391113967168615123299113119185942498194367262335168397100658, + 5040699236106090655289931820723926657076483236860546282406111821875672148900, + 2632385916954580941368956176626336146806721642583847728103570779270161510514, + 17691411851977575435597871505860208507285462834710151833948561098560743654671, + 11482807709115676646560379017491661435505951727793345550942389701970904563183, + 8360838254132998143349158726141014535383109403565779450210746881879715734773, + 12663821244032248511491386323242575231591777785787269938928497649288048289525, + 3067001377342968891237590775929219083706800062321980129409398033259904188058, + 8536471869378957766675292398190944925664113548202769136103887479787957959589, + 19825444354178182240559170937204690272111734703605805530888940813160705385792, + 16703465144013840124940690347975638755097486902749048533167980887413919317592, + 13061236261277650370863439564453267964462486225679643020432589226741411380501, + 10864774797625152707517901967943775867717907803542223029967000416969007792571, + 10035653564014594269791753415727486340557376923045841607746250017541686319774, + 3446968588058668564420958894889124905706353937375068998436129414772610003289, + 4653317306466493184743870159523234588955994456998076243468148492375236846006, + 8486711143589723036499933521576871883500223198263343024003617825616410932026, + 250710584458582618659378487568129931785810765264752039738223488321597070280, + 2104159799604932521291371026105311735948154964200596636974609406977292675173, + 16313562605837709339799839901240652934758303521543693857533755376563489378839, + 6032365105133504724925793806318578936233045029919447519826248813478479197288, + 14025118133847866722315446277964222215118620050302054655768867040006542798474, + 7400123822125662712777833064081316757896757785777291653271747396958201309118, + 1744432620323851751204287974553233986555641872755053103823939564833813704825, + 8316378125659383262515151597439205374263247719876250938893842106722210729522, + 6739722627047123650704294650168547689199576889424317598327664349670094847386, + 21211457866117465531949733809706514799713333930924902519246949506964470524162, + 13718112532745211817410303291774369209520657938741992779396229864894885156527, + 5264534817993325015357427094323255342713527811596856940387954546330728068658, + 18884137497114307927425084003812022333609937761793387700010402412840002189451, + 5148596049900083984813839872929010525572543381981952060869301611018636120248, + 19799686398774806587970184652860783461860993790013219899147141137827718662674, + 19240878651604412704364448729659032944342952609050243268894572835672205984837, + 10546185249390392695582524554167530669949955276893453512788278945742408153192, + 5507959600969845538113649209272736011390582494851145043668969080335346810411, + 18177751737739153338153217698774510185696788019377850245260475034576050820091, + 19603444733183990109492724100282114612026332366576932662794133334264283907557, + 10548274686824425401349248282213580046351514091431715597441736281987273193140, + 1823201861560942974198127384034483127920205835821334101215923769688644479957, + 11867589662193422187545516240823411225342068709600734253659804646934346124945, + 18718569356736340558616379408444812528964066420519677106145092918482774343613, + 10530777752259630125564678480897857853807637120039176813174150229243735996839, + 20486583726592018813337145844457018474256372770211860618687961310422228379031, + 12690713110714036569415168795200156516217175005650145422920562694422306200486, + 17386427286863519095301372413760745749282643730629659997153085139065756667205, + 2216432659854733047132347621569505613620980842043977268828076165669557467682, + 6309765381643925252238633914530877025934201680691496500372265330505506717193, + 20806323192073945401862788605803131761175139076694468214027227878952047793390, + 4037040458505567977365391535756875199663510397600316887746139396052445718861, + 19948974083684238245321361840704327952464170097132407924861169241740046562673, + 845322671528508199439318170916419179535949348988022948153107378280175750024, + 16222384601744433420585982239113457177459602187868460608565289920306145389382, + 10232118865851112229330353999139005145127746617219324244541194256766741433339, + 6699067738555349409504843460654299019000594109597429103342076743347235369120, + 6220784880752427143725783746407285094967584864656399181815603544365010379208, + 6129250029437675212264306655559561251995722990149771051304736001195288083309, + 10773245783118750721454994239248013870822765715268323522295722350908043393604, + 4490242021765793917495398271905043433053432245571325177153467194570741607167, + 19596995117319480189066041930051006586888908165330319666010398892494684778526, + 837850695495734270707668553360118467905109360511302468085569220634750561083, + 11803922811376367215191737026157445294481406304781326649717082177394185903907, + 10201298324909697255105265958780781450978049256931478989759448189112393506592, + 13564695482314888817576351063608519127702411536552857463682060761575100923924, + 9262808208636973454201420823766139682381973240743541030659775288508921362724, + 173271062536305557219323722062711383294158572562695717740068656098441040230, + 18120430890549410286417591505529104700901943324772175772035648111937818237369, + 20484495168135072493552514219686101965206843697794133766912991150184337935627, + 19155651295705203459475805213866664350848604323501251939850063308319753686505, + 11971299749478202793661982361798418342615500543489781306376058267926437157297, + 18285310723116790056148596536349375622245669010373674803854111592441823052978, + 7069216248902547653615508023941692395371990416048967468982099270925308100727, + 6465151453746412132599596984628739550147379072443683076388208843341824127379, + 16143532858389170960690347742477978826830511669766530042104134302796355145785, + 19362583304414853660976404410208489566967618125972377176980367224623492419647, + 1702213613534733786921602839210290505213503664731919006932367875629005980493, + 10781825404476535814285389902565833897646945212027592373510689209734812292327, + 4212716923652881254737947578600828255798948993302968210248673545442808456151, + 7594017890037021425366623750593200398174488805473151513558919864633711506220, + 18979889247746272055963929241596362599320706910852082477600815822482192194401, + 13602139229813231349386885113156901793661719180900395818909719758150455500533, + ]; + + let mut r = 0; + for elem in array { + let h = mimc(elem, r, constants, exponent); + r = r + elem + h; + } + r +} +", + }, + }, + }, "functions": [ { - "bytecode": "H4sIAAAAAAAA/61RQQ6DQAjEtfU9sIALt36lm67/f0GjRkzWs04ymeEykGECgAQHho1T6Dn/w48bX3DFGPoJxXug4cGs1GUxziKt5EZMX8xeTVG0zkZGavrLxtxMrHj1gk7CjRZ1XiLs/dxd2Hd7+tT9YO9037cCCmnZhZgBAAA=", + "bytecode": "H4sIAAAAAAAA/61Q0QrDMAhMuqXfo1EbfduvLCz9/y8Y66gF6Wt7cJwncsjNKaVH2pE3zq6H//r8v3luLO6n0z7iyHu5wjVgvjFrClkEC/NodSDhG6p1FWDpi6KiqHyqEg1lbdatgSHTwFWMVg8r9/0FsfMcOo49l9DxD+/NSgK4AQAA", "functionType": "secret", "isInternal": false, "name": "constructor", @@ -22,7 +180,7 @@ exports[`noir-compiler using nargo binary compiles the test contract 1`] = ` "verificationKey": "0000000200000800000000740000000f00000003515f3109623eb3c25aa5b16a1a79fd558bac7a7ce62c4560a8c537c77ce80dd339128d1d37b6582ee9e6df9567efb64313471dfa18f520f9ce53161b50dbf7731bc5f900000003515f322bc4cce83a486a92c92fd59bd84e0f92595baa639fc2ed86b00ffa0dfded2a092a669a3bdb7a273a015eda494457cc7ed5236f26cee330c290d45a33b9daa94800000003515f332729426c008c085a81bd34d8ef12dd31e80130339ef99d50013a89e4558eee6d0fa4ffe2ee7b7b62eb92608b2251ac31396a718f9b34978888789042b790a30100000003515f342be6b6824a913eb7a57b03cb1ee7bfb4de02f2f65fe8a4e97baa7766ddb353a82a8a25c49dc63778cd9fe96173f12a2bc77f3682f4c4448f98f1df82c75234a100000003515f351f85760d6ab567465aadc2f180af9eae3800e6958fec96aef53fd8a7b195d7c000c6267a0dd5cfc22b3fe804f53e266069c0e36f51885baec1e7e67650c62e170000000c515f41524954484d455449430d9d0f8ece2aa12012fa21e6e5c859e97bd5704e5c122064a66051294bc5e04213f61f54a0ebdf6fee4d4a6ecf693478191de0c2899bcd8e86a636c8d3eff43400000003515f43224a99d02c86336737c8dd5b746c40d2be6aead8393889a76a18d664029096e90f7fe81adcc92a74350eada9622ac453f49ebac24a066a1f83b394df54dfa0130000000c515f46495845445f42415345060e8a013ed289c2f9fd7473b04f6594b138ddb4b4cf6b901622a14088f04b8d2c83ff74fce56e3d5573b99c7b26d85d5046ce0c6559506acb7a675e7713eb3a00000007515f4c4f4749430721a91cb8da4b917e054f72147e1760cfe0ef3d45090ac0f4961d84ec1996961a25e787b26bd8b50b1a99450f77a424a83513c2b33af268cd253b0587ff50c700000003515f4d05dbd8623b8652511e1eb38d38887a69eceb082f807514f09e127237c5213b401b9325b48c6c225968002318095f89d0ef9cf629b2b7f0172e03bc39aacf6ed800000007515f52414e474504b57a3805e41df328f5ca9aefa40fad5917391543b7b65c6476e60b8f72e9ad07c92f3b3e11c8feae96dedc4b14a6226ef3201244f37cfc1ee5b96781f48d2b000000075349474d415f3125001d1954a18571eaa007144c5a567bb0d2be4def08a8be918b8c05e3b27d312c59ed41e09e144eab5de77ca89a2fd783be702a47c951d3112e3de02ce6e47c000000075349474d415f3223994e6a23618e60fa01c449a7ab88378709197e186d48d604bfb6931ffb15ad11c5ec7a0700570f80088fd5198ab5d5c227f2ad2a455a6edeec024156bb7beb000000075349474d415f3300cda5845f23468a13275d18bddae27c6bb189cf9aa95b6a03a0cb6688c7e8d829639b45cf8607c525cc400b55ebf90205f2f378626dc3406cc59b2d1b474fba000000075349474d415f342d299e7928496ea2d37f10b43afd6a80c90a33b483090d18069ffa275eedb2fc2f82121e8de43dc036d99b478b6227ceef34248939987a19011f065d8b5cef5c0000000010000000000000000100000002000000030000000400000005000000060000000700000008000000090000000a0000000b0000000c0000000d0000000e0000000f", }, { - "bytecode": "H4sIAAAAAAAA/6WOSwqAMAwFU0+Ub5vsvEqL6f2PIKKCIK6czcBbPGYBgAJv7m29LFhVs3GSUEeO4YZqozo5mdvGLpKu3mJEwyCVpGkhE0/K4wt/wf2r9fAOFP9TANAAAAA=", + "bytecode": "H4sIAAAAAAAA/6WPuw2AMAxEHSbyN7E7VkmEs/8IFIAUCVHxmpOuON3bAKDAm6fb7xSsqtk4Sagjx3BDtVGdnMztYBdJV28xomGQStK0kIkXZdnCX3D/+rp6nNHQ/4XYAAAA", "functionType": "open", "isInternal": false, "name": "openFunction", @@ -40,19 +198,21 @@ exports[`noir-compiler using nargo binary compiles the test contract 1`] = ` ] `; -exports[`noir-compiler using nargo binary generates noir external interface 1`] = ` +exports[`noir-compiler using nargo binary generates Aztec.nr external interface 1`] = ` "/* Autogenerated file, do not edit! */ use dep::std; -use dep::aztec::context::PrivateContext; +use dep::aztec::context::{ PrivateContext, PublicContext }; use dep::aztec::constants_gen::RETURN_VALUES_LENGTH; -struct TestContractContractInterface { + +// Interface for calling TestContract functions from a private context +struct TestContractPrivateContextInterface { address: Field, } -impl TestContractContractInterface { +impl TestContractPrivateContextInterface { fn at(address: Field) -> Self { Self { address, @@ -69,7 +229,34 @@ impl TestContractContractInterface { } } + + + + +// Interface for calling TestContract functions from a public context +struct TestContractPublicContextInterface { + address: Field, +} + +impl TestContractPublicContextInterface { + fn at(address: Field) -> Self { + Self { + address, + } + } + + fn openFunction( + self, + context: PublicContext + ) -> [Field; RETURN_VALUES_LENGTH] { + let mut serialised_args = [0; 0]; + context.call_public_function(self.address, 0x46be982e, serialised_args) + } + +} + + " `; @@ -78,12 +265,12 @@ exports[`noir-compiler using nargo binary generates typescript interface 1`] = ` /* Autogenerated file, do not edit! */ /* eslint-disable */ -import { AztecAddress, ContractBase, ContractFunctionInteraction, ContractMethod, DeployMethod, FieldLike, Wallet } from '@aztec/aztec.js'; +import { AztecAddress, CompleteAddress, ContractBase, ContractFunctionInteraction, ContractMethod, DeployMethod, FieldLike, Wallet } from '@aztec/aztec.js'; import { Fr, Point } from '@aztec/foundation/fields'; import { AztecRPC, PublicKey } from '@aztec/types'; import { ContractAbi } from '@aztec/foundation/abi'; import TestContractContractAbiJson from '../target/test.json' assert { type: 'json' }; -export const TestContractContractAbi = TestContractContractAbiJson as ContractAbi; +export const TestContractContractAbi = TestContractContractAbiJson as unknown as ContractAbi; /** * Type-safe interface for contract TestContract; @@ -91,12 +278,12 @@ export const TestContractContractAbi = TestContractContractAbiJson as ContractAb export class TestContractContract extends ContractBase { private constructor( - /** The deployed contract's address. */ - address: AztecAddress, + /** The deployed contract's complete address. */ + completeAddress: CompleteAddress, /** The wallet. */ wallet: Wallet, ) { - super(address, TestContractContractAbi, wallet); + super(completeAddress, TestContractContractAbi, wallet); } @@ -113,10 +300,11 @@ export class TestContractContract extends ContractBase { /** The wallet. */ wallet: Wallet, ) { - if ((await wallet.getContractData(address)) === undefined) { + const extendedContractData = await wallet.getExtendedContractData(address); + if (extendedContractData === undefined) { throw new Error('Contract ' + address.toString() + ' is not deployed'); } - return new TestContractContract(address, wallet); + return new TestContractContract(extendedContractData.getCompleteAddress(), wallet); } diff --git a/yarn-project/noir-compiler/src/cli/contract.ts b/yarn-project/noir-compiler/src/cli/contract.ts index 020908f0ab0..92243a5a368 100644 --- a/yarn-project/noir-compiler/src/cli/contract.ts +++ b/yarn-project/noir-compiler/src/cli/contract.ts @@ -8,7 +8,7 @@ import path, { resolve } from 'path'; import { compileUsingNargo, generateNoirContractInterface, generateTypescriptContractInterface } from '../index.js'; /** - * Registers a 'contract' command on the given commander program that compiles a Noir contract project. + * Registers a 'contract' command on the given commander program that compiles an Aztec.nr contract project. * @param program - Commander program. * @param log - Optional logging function. * @returns The program with the command registered. @@ -16,10 +16,10 @@ import { compileUsingNargo, generateNoirContractInterface, generateTypescriptCon export function compileContract(program: Command, name = 'contract', log: LogFn = () => {}): Command { return program .command(name) - .argument('', 'Path to the noir project to compile') + .argument('', 'Path to the Aztec.nr project to compile') .option('-o, --outdir ', 'Output folder for the binary artifacts, relative to the project path', 'target') .option('-ts, --typescript ', 'Optional output folder for generating typescript wrappers', undefined) - .option('-i, --interface ', 'Optional output folder for generating noir contract interface', undefined) + .option('-i, --interface ', 'Optional output folder for generating an Aztec.nr contract interface', undefined) .description('Compiles the contracts in the target project') .action( @@ -48,7 +48,9 @@ export function compileContract(program: Command, name = 'contract', log: LogFn if (noirInterface) { const noirInterfacePath = resolve(projectPath, noirInterface, `${contract.name}_interface.nr`); - log(`Writing ${contract.name} Noir external interface to ${path.relative(currentDir, noirInterfacePath)}`); + log( + `Writing ${contract.name} Aztec.nr external interface to ${path.relative(currentDir, noirInterfacePath)}`, + ); const noirWrapper = generateNoirContractInterface(contract); mkdirpSync(path.dirname(noirInterfacePath)); writeFileSync(noirInterfacePath, noirWrapper); diff --git a/yarn-project/noir-compiler/src/compile/nargo.ts b/yarn-project/noir-compiler/src/compile/nargo.ts index 790f4462b84..bba92a98617 100644 --- a/yarn-project/noir-compiler/src/compile/nargo.ts +++ b/yarn-project/noir-compiler/src/compile/nargo.ts @@ -19,7 +19,7 @@ export type CompileOpts = { }; /** - * A class that compiles noir contracts using nargo via the shell. + * A class that compiles Aztec.nr contracts using nargo via the shell. */ export class NargoContractCompiler { private log: LogFn; @@ -28,8 +28,8 @@ export class NargoContractCompiler { } /** - * Compiles the contracts in projectPath and returns the Noir artifact. - * @returns Noir artifact of the compiled contracts. + * Compiles the contracts in projectPath and returns the Aztec.nr artifact. + * @returns Aztec.nr artifact of the compiled contracts. */ public compile(): Promise { const stdio = this.opts.quiet ? 'ignore' : 'inherit'; diff --git a/yarn-project/noir-compiler/src/contract-interface-gen/abi.ts b/yarn-project/noir-compiler/src/contract-interface-gen/abi.ts index a6d32037717..ba3f02d48d3 100644 --- a/yarn-project/noir-compiler/src/contract-interface-gen/abi.ts +++ b/yarn-project/noir-compiler/src/contract-interface-gen/abi.ts @@ -6,7 +6,7 @@ import { mockVerificationKey } from '../mocked_keys.js'; import { NoirCompilationArtifacts, NoirFunctionEntry } from '../noir_artifact.js'; /** - * Generates an Aztec ABI for a Noir function build artifact. Replaces verification key with a mock value. + * Generates an Aztec ABI for a Aztec.nr function build artifact. Replaces verification key with a mock value. * @param fn - Noir function entry. * @returns Aztec ABI function entry. */ diff --git a/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts b/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts index cbd9cea1532..8f81f7697ba 100644 --- a/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts +++ b/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts @@ -134,8 +134,8 @@ function generateSerialisation(parameters: ABIParameter[]) { } /** - * Generate a function interface for a particular function of the Noir Contract being processed. This function will be a method of the ContractInterface struct being created here. - * @param functionData - Data relating to the function, which can be used to generate a callable Noir Function. + * Generate a function interface for a particular function of the Aztec.nr Contract being processed. This function will be a method of the ContractInterface struct being created here. + * @param functionData - Data relating to the function, which can be used to generate a callable Aztec.nr Function. * @param kind - Whether this interface will be used from private or public functions. * @returns A code string. */ @@ -272,7 +272,7 @@ ${contractImpl} /** * Generates the Noir code to represent an interface for calling a contract. - * @param abi - The compiled Noir artifact. + * @param abi - The compiled Aztec.nr artifact. * @returns The corresponding ts code. */ export function generateNoirContractInterface(abi: ContractAbi) { diff --git a/yarn-project/noir-compiler/src/index.test.ts b/yarn-project/noir-compiler/src/index.test.ts index 9a09d1fe8f8..804dc88da31 100644 --- a/yarn-project/noir-compiler/src/index.test.ts +++ b/yarn-project/noir-compiler/src/index.test.ts @@ -39,7 +39,7 @@ describe('noir-compiler', () => { expect(result).toMatchSnapshot(); }); - it('generates noir external interface', () => { + it('generates Aztec.nr external interface', () => { const result = generateNoirContractInterface(compiled[0]); expect(result).toMatchSnapshot(); }); diff --git a/yarn-project/noir-compiler/src/index.ts b/yarn-project/noir-compiler/src/index.ts index b7054d89577..85b52ffe7bd 100644 --- a/yarn-project/noir-compiler/src/index.ts +++ b/yarn-project/noir-compiler/src/index.ts @@ -12,7 +12,7 @@ export { generateTypescriptContractInterface } from './contract-interface-gen/ty export { generateAztecAbi }; /** - * Compile Noir contracts in project path using a nargo binary available in the shell. + * Compile Aztec.nr contracts in project path using a nargo binary available in the shell. * @param projectPath - Path to project. * @param opts - Compiler options. * @returns Compiled artifacts. diff --git a/yarn-project/noir-compiler/src/noir_artifact.ts b/yarn-project/noir-compiler/src/noir_artifact.ts index 40eed69101f..f1fab9562a7 100644 --- a/yarn-project/noir-compiler/src/noir_artifact.ts +++ b/yarn-project/noir-compiler/src/noir_artifact.ts @@ -1,9 +1,9 @@ import { ABIParameter, ABIType, DebugFileMap, DebugInfo } from '@aztec/foundation/abi'; -/** The noir function types. */ +/** The Aztec.nr function types. */ type NoirFunctionType = 'Open' | 'Secret' | 'Unconstrained'; -/** The ABI of a noir function. */ +/** The ABI of an Aztec.nr function. */ interface NoirFunctionAbi { /** The parameters of the function. */ parameters: ABIParameter[]; @@ -16,7 +16,7 @@ interface NoirFunctionAbi { } /** - * The compilation result of a noir function. + * The compilation result of an Aztec.nr function. */ export interface NoirFunctionEntry { /** The name of the function. */ @@ -36,7 +36,7 @@ export interface NoirFunctionEntry { } /** - * The compilation result of a noir contract. + * The compilation result of an Aztec.nr contract. */ export interface NoirCompiledContract { /** The name of the contract. */ @@ -48,7 +48,7 @@ export interface NoirCompiledContract { } /** - * The debug metadata of a noir contract. + * The debug metadata of an Aztec.nr contract. */ export interface NoirDebugMetadata { /** diff --git a/yarn-project/noir-contracts/README.md b/yarn-project/noir-contracts/README.md index b4631099f63..7a227dddf9b 100644 --- a/yarn-project/noir-contracts/README.md +++ b/yarn-project/noir-contracts/README.md @@ -1,4 +1,4 @@ -# Noir contracts +# Aztec.nr contracts This package contains the source code and the Aztec ABIs for the example contracts used in tests. @@ -122,7 +122,7 @@ It has prebuilt binaries and is super easy to install using `noirup` compiler_version = "0.7.1" [dependencies] - aztec = { path = "../../../../noir-libs/aztec-noir" } + aztec = { path = "../../../../aztec-nr/aztec" } ``` 4. Replace the content of the generated `example_contract/src/main.nr` file with your contract code. diff --git a/yarn-project/noir-contracts/bootstrap.sh b/yarn-project/noir-contracts/bootstrap.sh index 85414de80c6..1077490d138 100755 --- a/yarn-project/noir-contracts/bootstrap.sh +++ b/yarn-project/noir-contracts/bootstrap.sh @@ -9,7 +9,6 @@ fi # Update noir ./scripts/install_noir.sh -./scripts/install_noir_backend.sh # Use yarn script to compile and create types yarn diff --git a/yarn-project/noir-contracts/package.json b/yarn-project/noir-contracts/package.json index b9d7e5eb3fb..0739cee5976 100644 --- a/yarn-project/noir-contracts/package.json +++ b/yarn-project/noir-contracts/package.json @@ -8,8 +8,6 @@ "./types": "./dest/types/index.js" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/noir-contracts/scripts/compile.sh b/yarn-project/noir-contracts/scripts/compile.sh index 972e9652730..09c1d896f6c 100755 --- a/yarn-project/noir-contracts/scripts/compile.sh +++ b/yarn-project/noir-contracts/scripts/compile.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Compiles noir contracts in parallel, bubbling any compilation errors +# Compiles Aztec.nr contracts in parallel, bubbling any compilation errors source ./scripts/catch.sh source ./scripts/nargo_check.sh diff --git a/yarn-project/noir-contracts/scripts/get_all_libraries.sh b/yarn-project/noir-contracts/scripts/get_all_libraries.sh index e1aa684e3fa..3220187ae3c 100755 --- a/yarn-project/noir-contracts/scripts/get_all_libraries.sh +++ b/yarn-project/noir-contracts/scripts/get_all_libraries.sh @@ -1,3 +1,3 @@ #!/bin/bash -# Utility to get the names of all noir libaries located in ../noir-libs -echo $(ls -d ../noir-libs/*/Nargo.toml | sed -r "s/..\\/noir-libs\\/(.+)\\/Nargo.toml/\\1/") \ No newline at end of file +# Utility to get the names of all noir libaries located in ../aztec-nr +echo $(ls -d ../aztec-nr/*/Nargo.toml | sed -r "s/..\\/aztec-nr\\/(.+)\\/Nargo.toml/\\1/") \ No newline at end of file diff --git a/yarn-project/noir-contracts/scripts/nargo_test.sh b/yarn-project/noir-contracts/scripts/nargo_test.sh index 5635759ff73..8468c19f492 100755 --- a/yarn-project/noir-contracts/scripts/nargo_test.sh +++ b/yarn-project/noir-contracts/scripts/nargo_test.sh @@ -38,7 +38,7 @@ test() { nargo test --package ${PROJECT_NAME}_contract else echo "Testing library $PROJECT_NAME..." - cd ../noir-libs/$PROJECT_NAME + cd ../aztec-nr/$PROJECT_NAME nargo test fi } diff --git a/yarn-project/noir-contracts/src/contracts/card_game_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/card_game_contract/Nargo.toml index 58853dc1a57..566a99dc488 100644 --- a/yarn-project/noir-contracts/src/contracts/card_game_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/card_game_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} diff --git a/yarn-project/noir-contracts/src/contracts/child_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/child_contract/Nargo.toml index 013af3ce22e..fe50f619436 100644 --- a/yarn-project/noir-contracts/src/contracts/child_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/child_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/docs_example_contract/Nargo.toml index 7826fffbf0d..f5870a5a735 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr index ff8e77a10b6..94b5981e1f3 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr @@ -148,9 +148,10 @@ unconstrained fn get_total_points( // docs:start:state_vars-SetContains fn assert_contains_card( state_var: Set, - card: CardNote, + card: &mut CardNote, + nonce: Field, ) { - state_var.assert_contains_and_remove(card); + state_var.assert_contains_and_remove(card, nonce); } // docs:end:state_vars-SetContains diff --git a/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/Nargo.toml index 4b8208cc51b..e8651b9783a 100644 --- a/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/Nargo.toml @@ -5,6 +5,6 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} -easy_private_state = { path = "../../../../noir-libs/easy-private-state"} \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} +easy_private_state = { path = "../../../../aztec-nr/easy-private-state"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/Nargo.toml index 999b75a218a..b0e030b7808 100644 --- a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/escrow_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/escrow_contract/Nargo.toml index 4077357a075..6278ae9ddfb 100644 --- a/yarn-project/noir-contracts/src/contracts/escrow_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/escrow_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/import_test_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/import_test_contract/Nargo.toml index 21840bab59b..a00b14498de 100644 --- a/yarn-project/noir-contracts/src/contracts/import_test_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/import_test_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/lending_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/lending_contract/Nargo.toml index 8233a8c530c..dbdd8a1c4b2 100644 --- a/yarn-project/noir-contracts/src/contracts/lending_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/lending_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -safe_math = { path = "../../../../noir-libs/safe-math" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +safe_math = { path = "../../../../aztec-nr/safe-math" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/lending_contract/src/interfaces.nr b/yarn-project/noir-contracts/src/contracts/lending_contract/src/interfaces.nr index c79378d7ecf..f8b7a9a41b5 100644 --- a/yarn-project/noir-contracts/src/contracts/lending_contract/src/interfaces.nr +++ b/yarn-project/noir-contracts/src/contracts/lending_contract/src/interfaces.nr @@ -36,36 +36,44 @@ impl Token { Self { address } } - fn transfer_pub(self: Self, context: PublicContext, to: Field, amount: Field) { + fn transfer_public(self: Self, context: PublicContext, from: Field, to: Field, amount: Field, nonce: Field) { let _transfer_return_values = context.call_public_function( self.address, - compute_selector("transfer_pub(Field,Field)"), - [to, amount] + compute_selector("transfer_public((Field),(Field),Field,Field)"), + [from, to, amount, nonce] ); } - fn transfer_from_pub(self: Self, context: PublicContext, from: Field, to: Field, amount: Field) { - let _transfer_return_values = context.call_public_function( + fn mint_public(self: Self, context: PublicContext, to: Field, amount: Field) { + let _return_values = context.call_public_function( self.address, - compute_selector("transfer_from_pub(Field,Field,Field)"), - [from, to, amount] + compute_selector("mint_public((Field),Field)"), + [to, amount] ); } - fn owner_mint_pub(self: Self, context: PublicContext, to: Field, amount: Field) { - let _transfer_return_values = context.call_public_function( - self.address, - compute_selector("owner_mint_pub(Field,Field)"), - [to, amount] + fn burn_public(self: Self, context: PublicContext, from: Field, amount: Field, nonce: Field){ + let _return_values = context.call_public_function( + self.address, + compute_selector("burn_public((Field),Field,Field)"), + [from, amount, nonce] ); } // Private - fn unshield(self: Self, context: &mut PrivateContext, from: Field, to: Field, amount: Field) -> [Field; RETURN_VALUES_LENGTH] { + fn unshield(self: Self, context: &mut PrivateContext, from: Field, to: Field, amount: Field, nonce: Field) -> [Field; RETURN_VALUES_LENGTH] { + context.call_private_function( + self.address, + compute_selector("unshield((Field),(Field),Field,Field)"), + [from, to, amount, nonce] + ) + } + + fn burn(self: Self, context: &mut PrivateContext, from: Field, amount: Field, nonce: Field) -> [Field; RETURN_VALUES_LENGTH] { context.call_private_function( self.address, - compute_selector("unshieldTokens(Field,Field,Field)"), - [from, to, amount] + compute_selector("burn((Field),Field,Field)"), + [from, amount, nonce] ) } } diff --git a/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr index 3683aafe96d..c26af11e340 100644 --- a/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr @@ -155,17 +155,17 @@ contract Lending { asset } - // This don't need to be on behalf of self. We should be able to repay on behalf of someone else. #[aztec(private)] fn deposit_private( + from: Field, + amount: Field, + nonce: Field, secret: Field, - asset_owner: Field, on_behalf_of: Field, - amount: Field, collateral_asset: Field, ) { let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender()); - let _res = Token::at(collateral_asset).unshield(&mut context, asset_owner, context.this_address(), amount); + let _res = Token::at(collateral_asset).unshield(&mut context, from, context.this_address(), amount, nonce); // _deposit(on_behalf_of, amount, collateral_asset) let selector = compute_selector("_deposit(Field,Field,Field)"); let _callStackItem2 = context.call_public_function(context.this_address(), selector, [on_behalf_of, amount, collateral_asset]); @@ -173,13 +173,14 @@ contract Lending { #[aztec(public)] fn deposit_public( - owner: Field, amount: Field, + nonce: Field, + on_behalf_of: Field, collateral_asset: Field, ) -> Field { - Token::at(collateral_asset).transfer_from_pub(context, context.msg_sender(), context.this_address(), amount); + Token::at(collateral_asset).transfer_public(context, context.msg_sender(), context.this_address(), amount, nonce); let selector = compute_selector("_deposit(Field,Field,Field)"); - let return_values = context.call_public_function(context.this_address(), selector, [owner, amount, collateral_asset]); + let return_values = context.call_public_function(context.this_address(), selector, [on_behalf_of, amount, collateral_asset]); return_values[0] } @@ -253,7 +254,7 @@ contract Lending { // @todo @LHerskind Support both shielding and transfers (for now just transfer) let collateral_asset = storage.collateral_asset.read(); - Token::at(collateral_asset).transfer_pub(context, recipient, amount); + Token::at(collateral_asset).transfer_public(context, context.this_address(), recipient, amount, 0); 1 } @@ -304,33 +305,34 @@ contract Lending { // @todo @LHerskind Need to support both private and public minting. let stable_coin = storage.stable_coin.read(); - Token::at(stable_coin).owner_mint_pub(context, to, amount); + Token::at(stable_coin).mint_public(context, to, amount); 1 } #[aztec(private)] fn repay_private( + from: Field, + amount: Field, + nonce: Field, secret: Field, - asset_owner: Field, on_behalf_of: Field, - amount: Field, stable_coin: Field, ) { let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender()); - let _res = Token::at(stable_coin).unshield(&mut context, asset_owner, context.this_address(), amount); + let _res = Token::at(stable_coin).burn(&mut context, from, amount, nonce); let selector = compute_selector("_repay(Field,Field,Field)"); let _callStackItem = context.call_public_function(context.this_address(), selector, [on_behalf_of, amount, stable_coin]); } #[aztec(public)] fn repay_public( - owner: Field, amount: Field, + nonce: Field, + owner: Field, stable_coin: Field, ) -> Field { - // Should probably just burn the tokens actually :thinking: - Token::at(stable_coin).transfer_from_pub(context, context.msg_sender(), context.this_address(), amount); + Token::at(stable_coin).burn_public(context, context.msg_sender(), amount, nonce); let selector = compute_selector("_repay(Field,Field,Field)"); let return_values = context.call_public_function(context.this_address(), selector, [owner, amount, stable_coin]); diff --git a/yarn-project/noir-contracts/src/contracts/multi_transfer_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/multi_transfer_contract/Nargo.toml index 86574e53fc1..cccba64b2ea 100644 --- a/yarn-project/noir-contracts/src/contracts/multi_transfer_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/multi_transfer_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/native_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/native_token_contract/Nargo.toml index 42a0a9313a4..05cf9a92810 100644 --- a/yarn-project/noir-contracts/src/contracts/native_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/native_token_contract/Nargo.toml @@ -5,6 +5,6 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} non_native = { path = "../non_native_token_contract"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/native_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/native_token_contract/src/main.nr index ba2bc64737a..31dc5e610e5 100644 --- a/yarn-project/noir-contracts/src/contracts/native_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/native_token_contract/src/main.nr @@ -348,10 +348,10 @@ contract NativeToken { let storage = Storage::init(Context::private(&mut context)); let pending_shields = storage.pending_shields; - let public_note = TransparentNote::new_from_secret(amount, secret); + let mut public_note = TransparentNote::new_from_secret(amount, secret); // Ensure that the note exists in the tree and remove it. - pending_shields.assert_contains_and_remove_publicly_created(public_note); + pending_shields.assert_contains_and_remove_publicly_created(&mut public_note); // Mint the tokens let balance = storage.balances.at(owner); diff --git a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/Nargo.toml index d6c7fef03e1..5e51ed65b25 100644 --- a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr index a9fb5b021ba..719f262b505 100644 --- a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr @@ -248,10 +248,10 @@ contract NonNativeToken { let storage = Storage::init(Context::private(&mut context)); let pending_shields = storage.pending_shields; - let public_note = TransparentNote::new_from_secret(amount, secret); + let mut public_note = TransparentNote::new_from_secret(amount, secret); // Ensure that the note exists in the tree and remove it. - pending_shields.assert_contains_and_remove_publicly_created(public_note); + pending_shields.assert_contains_and_remove_publicly_created(&mut public_note); // Mint the tokens let balance = storage.balances.at(owner); diff --git a/yarn-project/noir-contracts/src/contracts/parent_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/parent_contract/Nargo.toml index 850b3ad14e5..bde7ef065d0 100644 --- a/yarn-project/noir-contracts/src/contracts/parent_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/parent_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/Nargo.toml index 1c0e84969da..c692b32fad3 100644 --- a/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} diff --git a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/Nargo.toml index 4a8af37b776..6b07ad277f4 100644 --- a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/price_feed_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/price_feed_contract/Nargo.toml index be6246ac397..b414ff04bf7 100644 --- a/yarn-project/noir-contracts/src/contracts/price_feed_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/price_feed_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/Nargo.toml index 9f21c40d77e..c41c12b4351 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/Nargo.toml @@ -5,5 +5,5 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr index 6c8a95fb33a..ff54645fa31 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr +++ b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr @@ -59,14 +59,16 @@ impl PrivateTokenAirdropPrivateContextInterface { context: &mut PrivateContext, amount: Field, secret: Field, - owner: Field + owner: Field, + nonce: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 3]; + let mut serialised_args = [0; 4]; serialised_args[0] = amount; serialised_args[1] = secret; serialised_args[2] = owner; + serialised_args[3] = nonce; - context.call_private_function(self.address, 0xd68b55c1, serialised_args) + context.call_private_function(self.address, 0xa9220f0f, serialised_args) } diff --git a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/main.nr index 2216e36ecba..c7eac5d9d4b 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/main.nr @@ -160,13 +160,14 @@ contract PrivateTokenAirdrop { fn claim( amount: Field, secret: Field, - owner: Field + owner: Field, + nonce: Field, ) { let storage = Storage::init(Context::private(&mut context)); // Remove the claim note if it exists in the set. - let note = ClaimNote::new(amount, secret); - storage.claims.assert_contains_and_remove(note); + let mut note = ClaimNote::new(amount, secret); + storage.claims.assert_contains_and_remove(&mut note, nonce); // Send the value note. let balance = storage.balances.at(owner); diff --git a/yarn-project/noir-contracts/src/contracts/private_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/private_token_contract/Nargo.toml index 0eb35564eec..f3e29ac1bf5 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/private_token_contract/Nargo.toml @@ -7,6 +7,6 @@ type = "contract" [dependencies] # highlight-next-line:importing-aztec -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} # docs:end:importing-aztec \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/public_token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/public_token_contract/Nargo.toml index 04489c04c7e..c3098dda9ee 100644 --- a/yarn-project/noir-contracts/src/contracts/public_token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/public_token_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/Nargo.toml index 84c123fadee..4ac82f6b7e6 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_auth_witness_account_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/schnorr_auth_witness_account_contract/Nargo.toml index 77bd89399b3..9ff8c965953 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_auth_witness_account_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/schnorr_auth_witness_account_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_hardcoded_account_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/schnorr_hardcoded_account_contract/Nargo.toml index 218d93ac79d..586e246467d 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_hardcoded_account_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/schnorr_hardcoded_account_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_single_key_account_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/schnorr_single_key_account_contract/Nargo.toml index d1eff41f9ae..d02343f7772 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_single_key_account_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/schnorr_single_key_account_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/test_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/test_contract/Nargo.toml index 1d564c16ddd..c4818f6ba32 100644 --- a/yarn-project/noir-contracts/src/contracts/test_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/test_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/contracts/test_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/test_contract/src/main.nr index fe9fa044e5e..d2c29d6c6e8 100644 --- a/yarn-project/noir-contracts/src/contracts/test_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/test_contract/src/main.nr @@ -44,7 +44,7 @@ contract Test { context.this_address() } - // Test codegen for noir interfaces + // Test codegen for Aztec.nr interfaces // See yarn-project/acir-simulator/src/client/private_execution.test.ts 'nested calls through autogenerated interface' // Note; this function is deliberately NOT annotated with #[aztec(private)] due to its use in tests fn testCodeGen( diff --git a/yarn-project/noir-contracts/src/contracts/token_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/token_contract/Nargo.toml index cece7de949c..6bc97909172 100644 --- a/yarn-project/noir-contracts/src/contracts/token_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/token_contract/Nargo.toml @@ -5,6 +5,6 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } -value_note = { path = "../../../../noir-libs/value-note"} -safe_math = { path = "../../../../noir-libs/safe-math" } \ No newline at end of file +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note"} +safe_math = { path = "../../../../aztec-nr/safe-math" } \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr index 677998e7d1e..b676bea7962 100644 --- a/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr @@ -244,9 +244,9 @@ contract Token { let storage = Storage::init(Context::private(&mut context)); let pending_shields = storage.pending_shields; let balance = storage.balances.at(to.address); - let public_note = TransparentNote::new_from_secret(amount, secret); + let mut public_note = TransparentNote::new_from_secret(amount, secret); - pending_shields.assert_contains_and_remove_publicly_created(public_note); + pending_shields.assert_contains_and_remove_publicly_created(&mut public_note); increment(balance, amount, to.address); 1 diff --git a/yarn-project/noir-contracts/src/contracts/uniswap_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/uniswap_contract/Nargo.toml index 21daac464fd..110b8eb98fe 100644 --- a/yarn-project/noir-contracts/src/contracts/uniswap_contract/Nargo.toml +++ b/yarn-project/noir-contracts/src/contracts/uniswap_contract/Nargo.toml @@ -5,4 +5,4 @@ compiler_version = "0.1" type = "contract" [dependencies] -aztec = { path = "../../../../noir-libs/aztec-noir" } +aztec = { path = "../../../../aztec-nr/aztec" } diff --git a/yarn-project/noir-contracts/src/scripts/copy_output.ts b/yarn-project/noir-contracts/src/scripts/copy_output.ts index 05da55f50be..68ec5ca5204 100644 --- a/yarn-project/noir-contracts/src/scripts/copy_output.ts +++ b/yarn-project/noir-contracts/src/scripts/copy_output.ts @@ -88,7 +88,7 @@ const main = () => { writeFileSync(tsInterfaceDestFilePath, generateTypescriptContractInterface(artifactJson, tsAbiImportPath)); log(`Written ${tsInterfaceDestFilePath}`); - // Write a .nr contract interface, for consumption by other Noir Contracts + // Write a .nr contract interface, for consumption by other Aztec.nr contracts if (INTERFACE_CONTRACTS.includes(name)) { const projectDirPath = `src/contracts/${projectName}`; const noirInterfaceDestFilePath = `${projectDirPath}/src/interface.nr`; @@ -96,7 +96,7 @@ const main = () => { writeFileSync(noirInterfaceDestFilePath, generateNoirContractInterface(artifactJson)); log(`Written ${noirInterfaceDestFilePath}`); } catch (err) { - log(`Error generating noir interface for ${name}: ${err}`); + log(`Error generating Aztec.nr interface for ${name}: ${err}`); } } }; diff --git a/yarn-project/noir-libs/aztec-noir/src/messaging/get_commitment_getter_data.nr b/yarn-project/noir-libs/aztec-noir/src/messaging/get_commitment_getter_data.nr deleted file mode 100644 index 07d826d41d7..00000000000 --- a/yarn-project/noir-libs/aztec-noir/src/messaging/get_commitment_getter_data.nr +++ /dev/null @@ -1,15 +0,0 @@ -use crate::oracle::get_commitment::COMMITMENT_GETTER_LENGTH; - -struct CommitmentGetterData { - message: Field, - leaf_index: Field, - root: Field, -} - -fn make_commitment_getter_data(fields: [Field; COMMITMENT_GETTER_LENGTH], start: Field) -> CommitmentGetterData { - CommitmentGetterData { - message: fields[start], - leaf_index: fields[start + 1], - root: fields[start + 2], - } -} \ No newline at end of file diff --git a/yarn-project/noir-libs/aztec-noir/src/oracle/get_commitment.nr b/yarn-project/noir-libs/aztec-noir/src/oracle/get_commitment.nr deleted file mode 100644 index 2793c003bf6..00000000000 --- a/yarn-project/noir-libs/aztec-noir/src/oracle/get_commitment.nr +++ /dev/null @@ -1,11 +0,0 @@ -// Oracle function to get a commitment, its sibling path and index, without getting its preimage. - -// commitment + index + root; -global COMMITMENT_GETTER_LENGTH = 3; - -#[oracle(getCommitment)] -fn get_commitment_oracle(_commitment: Field) -> [Field; COMMITMENT_GETTER_LENGTH] {} - -unconstrained fn get_commitment(commitment: Field) -> [Field; COMMITMENT_GETTER_LENGTH] { - get_commitment_oracle(commitment) -} diff --git a/yarn-project/p2p-bootstrap/package.json b/yarn-project/p2p-bootstrap/package.json index 89fc049dba2..646ba2c4abf 100644 --- a/yarn-project/p2p-bootstrap/package.json +++ b/yarn-project/p2p-bootstrap/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/p2p/package.json b/yarn-project/p2p/package.json index f3213003702..2b8e317e603 100644 --- a/yarn-project/p2p/package.json +++ b/yarn-project/p2p/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/package.common.json b/yarn-project/package.common.json index d6231d92f89..6b6f7471258 100644 --- a/yarn-project/package.common.json +++ b/yarn-project/package.common.json @@ -1,7 +1,5 @@ { "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/prover-client/package.json b/yarn-project/prover-client/package.json index fb946ce8d2b..40741c4cc3a 100644 --- a/yarn-project/prover-client/package.json +++ b/yarn-project/prover-client/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/rollup-provider/package.json b/yarn-project/rollup-provider/package.json index 84d68c96dc8..abb5e816970 100644 --- a/yarn-project/rollup-provider/package.json +++ b/yarn-project/rollup-provider/package.json @@ -12,8 +12,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/scripts/get_dependencies.sh b/yarn-project/scripts/get_dependencies.sh new file mode 100755 index 00000000000..60b61bbc985 --- /dev/null +++ b/yarn-project/scripts/get_dependencies.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -eu + +PROJECT_DIR=$1 + +echo yarn-project-base +jq -r ".dependencies + .devDependencies | keys | .[] | select(startswith(\"@aztec/\")) | ltrimstr(\"@aztec/\")" $PROJECT_DIR/package.json \ No newline at end of file diff --git a/yarn-project/sequencer-client/package.json b/yarn-project/sequencer-client/package.json index ab89bd8f455..1018b1e7959 100644 --- a/yarn-project/sequencer-client/package.json +++ b/yarn-project/sequencer-client/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/sequencer-client/src/simulator/public_executor.ts b/yarn-project/sequencer-client/src/simulator/public_executor.ts index bef534b6228..1296dcae50a 100644 --- a/yarn-project/sequencer-client/src/simulator/public_executor.ts +++ b/yarn-project/sequencer-client/src/simulator/public_executor.ts @@ -1,5 +1,4 @@ import { - CommitmentDataOracleInputs, CommitmentsDB, MessageLoadOracleInputs, PublicContractsDB, @@ -7,7 +6,6 @@ import { PublicStateDB, } from '@aztec/acir-simulator'; import { AztecAddress, CircuitsWasm, EthAddress, Fr, FunctionSelector, HistoricBlockData } from '@aztec/circuits.js'; -import { siloCommitment } from '@aztec/circuits.js/abis'; import { ContractDataSource, L1ToL2MessageSource, MerkleTreeId } from '@aztec/types'; import { MerkleTreeOperations, computePublicDataTreeLeafIndex } from '@aztec/world-state'; @@ -100,19 +98,7 @@ export class WorldStateDB implements CommitmentsDB { }; } - public async getCommitmentOracle(address: AztecAddress, innerCommitment: Fr): Promise { - const siloedCommitment = siloCommitment(await CircuitsWasm.get(), address, innerCommitment); - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1386): shoild be - // unique commitment that exists in tree (should be siloed and then made unique via - // nonce). Once public kernel or base rollup circuit injects nonces, this can be updated - // to use uniqueSiloedCommitment. - const index = (await this.db.findLeafIndex(MerkleTreeId.PRIVATE_DATA_TREE, siloedCommitment.toBuffer()))!; - const siblingPath = await this.db.getSiblingPath(MerkleTreeId.PRIVATE_DATA_TREE, index); - - return { - commitment: siloedCommitment, - siblingPath: siblingPath.toFieldArray(), - index, - }; + public async getCommitmentIndex(commitment: Fr): Promise { + return await this.db.findLeafIndex(MerkleTreeId.PRIVATE_DATA_TREE, commitment.toBuffer()); } } diff --git a/yarn-project/types/package.json b/yarn-project/types/package.json index 6aaac90d5e8..78977f0c5f4 100644 --- a/yarn-project/types/package.json +++ b/yarn-project/types/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/types/src/contract_database.ts b/yarn-project/types/src/contract_database.ts index 7eb2333ed88..f9b8581febb 100644 --- a/yarn-project/types/src/contract_database.ts +++ b/yarn-project/types/src/contract_database.ts @@ -3,7 +3,7 @@ import { AztecAddress } from '@aztec/foundation/aztec-address'; import { ContractDao } from './contract_dao.js'; /** - * Represents a ContractDatabase interface for managing noir contracts. + * Represents a ContractDatabase interface for managing Aztec.nr contracts. * Provides methods for adding and retrieving ContractDao objects by their associated addresses. */ export interface ContractDatabase { diff --git a/yarn-project/world-state/package.json b/yarn-project/world-state/package.json index 36ae514d0ea..67d3c5a7f36 100644 --- a/yarn-project/world-state/package.json +++ b/yarn-project/world-state/package.json @@ -11,8 +11,6 @@ "tsconfig": "./tsconfig.json" }, "scripts": { - "prepare": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json", - "prepare:check": "node ../yarn-project-base/scripts/update_build_manifest.mjs package.json --check", "build": "yarn clean && tsc -b", "build:dev": "tsc -b --watch", "clean": "rm -rf ./dest .tsbuildinfo", diff --git a/yarn-project/yarn-project-base/Dockerfile b/yarn-project/yarn-project-base/Dockerfile index ffcf3abb8c2..dca9635efdc 100644 --- a/yarn-project/yarn-project-base/Dockerfile +++ b/yarn-project/yarn-project-base/Dockerfile @@ -108,7 +108,7 @@ RUN ./scripts/generate-artifacts.sh WORKDIR /usr/src/yarn-project -# Generate noir contract artifacts +# Generate Aztec.nr contract artifacts FROM builder_ as noir_types COPY . . COPY --from=noir /usr/src/yarn-project/noir-contracts/src/contracts /usr/src/yarn-project/noir-contracts/src/contracts @@ -121,7 +121,7 @@ RUN ./scripts/types_all.sh # Run yarn build again to build the types RUN yarn build -# Take noir contract artifacts into the final build image +# Take Aztec.nr contract artifacts into the final build image FROM builder_ as final COPY . . COPY --from=noir_types /usr/src/yarn-project/noir-contracts/src/artifacts /usr/src/yarn-project/noir-contracts/src/artifacts diff --git a/yarn-project/yarn-project-base/scripts/update_build_manifest.mjs b/yarn-project/yarn-project-base/scripts/update_build_manifest.mjs deleted file mode 100644 index b915dd8733d..00000000000 --- a/yarn-project/yarn-project-base/scripts/update_build_manifest.mjs +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env node -// Updates build manifest for a package based on a package.json -import { existsSync, readFileSync, writeFileSync } from 'fs'; -import { basename, dirname, join, resolve } from 'path'; -import { cwd } from 'process'; - -// Update build_manifest.json with new dependencies -function updateBuildManifest(buildManifestFile, allDependencies, projectKey, options) { - // Check if build_manifest.json exists - if (!existsSync(buildManifestFile)) { - console.error(`Error: ${buildManifestFile} not found (cwd ${cwd()}).`); - process.exit(2); - } - - // Read build_manifest.json - const buildManifestData = JSON.parse(readFileSync(buildManifestFile, 'utf-8')); - - if (projectKey in buildManifestData) { - // Filter package names from dependencies that start with "@aztec/" - const aztecDependencies = Object.keys(allDependencies).filter(packageName => packageName.startsWith('@aztec/')); - - // Update the "dependencies" key in the corresponding section of the buildManifestData - // Take just the folder name component - // Filter out dependencies that are not themselves in the manifest: - const updatedDependencies = aztecDependencies - .map(packageName => packageName.split('/')[1]) - .filter(depProjectKey => !!buildManifestData[depProjectKey]); - - // If we are just checking, throw if dependencies don't match - if (options.checkOnly) { - const currentDependencies = buildManifestData[projectKey]['dependencies']; - if ( - updatedDependencies.length !== currentDependencies.length || - !updatedDependencies.reduce((ret, val, idx) => ret && val === currentDependencies[idx], true) - ) { - console.error( - `Dependencies for project ${projectKey} have changed and the build_manifest needs to be updated. Run yarn prepare on the yarn-project root.`, - `\n Current: ${JSON.stringify(currentDependencies)}`, - `\n Updated: ${JSON.stringify(updatedDependencies)}`, - ); - process.exit(10); - } - } - // Otherwise, update them - else { - buildManifestData[projectKey]['dependencies'] = updatedDependencies; - } - - // Write the updated data back to build_manifest.json - writeFileSync(buildManifestFile, JSON.stringify(buildManifestData, null, 2)); - } else { - console.error(`Error: '${projectKey}' not found in build_manifest.json`); - process.exit(3); - } -} - -// Entry point for the script -function main() { - try { - // Check if the path to the package.json file is provided as a command-line argument - if (process.argv.length === 2) { - console.error(`Usage: ${process.argv[0]} path/to/package.json`); - process.exit(1); - } - - const packageJsonFile = process.argv[2]; - - // Check if package.json exists - if (!existsSync(packageJsonFile)) { - console.error(`Error: ${packageJsonFile} not found.`); - process.exit(2); - } - - // Process options if any - const options = { checkOnly: false }; - for (const arg of process.argv.slice(3)) { - if (arg === '--check') { - options.checkOnly = true; - } else { - console.error(`Unknown option ${arg}`); - process.exit(3); - } - } - - // Read package.json - const packageData = JSON.parse(readFileSync(packageJsonFile, 'utf-8')); - - // Get the directory name of the directory that holds package.json - const projectKey = basename(dirname(resolve(packageJsonFile))); - - // Add the path to the build-manifest.json file - const buildManifestFile = join(dirname(packageJsonFile), '..', '..', 'build_manifest.json'); - - // Update build_manifest.json with the new dependencies - updateBuildManifest( - buildManifestFile, - { ...packageData.dependencies, ...packageData.devDependencies }, - projectKey, - options, - ); - } catch (err) { - console.error(`Failed updating ${resolve(process.argv[2])}`); - console.error(err); - } -} -main();