From d97136022b171d90d20aa5dae1dbc42341bf65f6 Mon Sep 17 00:00:00 2001 From: mverzilli Date: Wed, 4 Mar 2026 09:18:17 +0000 Subject: [PATCH 01/12] only use PREFUND_ADDRESSES on local nets --- yarn-project/aztec/src/cli/cmds/start_node.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/yarn-project/aztec/src/cli/cmds/start_node.ts b/yarn-project/aztec/src/cli/cmds/start_node.ts index ab26d4a3633c..82ef2f7b0105 100644 --- a/yarn-project/aztec/src/cli/cmds/start_node.ts +++ b/yarn-project/aztec/src/cli/cmds/start_node.ts @@ -155,8 +155,7 @@ export async function startNode( const testAccounts = nodeConfig.testAccounts ? (await getInitialTestAccountsData()).map(a => a.address) : []; const sponsoredFPCAccounts = nodeConfig.sponsoredFPC ? [await getSponsoredFPCAddress()] : []; - const prefundAddresses = (nodeConfig.prefundAddresses ?? []).map(a => AztecAddress.fromString(a)); - const initialFundedAccounts = testAccounts.concat(sponsoredFPCAccounts).concat(prefundAddresses); + const initialFundedAccounts = testAccounts.concat(sponsoredFPCAccounts); userLog(`Initial funded accounts: ${initialFundedAccounts.map(a => a.toString()).join(', ')}`); From 8796986ce6726aacef331a58af2d6c38091a8673 Mon Sep 17 00:00:00 2001 From: mverzilli Date: Wed, 4 Mar 2026 09:18:54 +0000 Subject: [PATCH 02/12] remove unused import --- yarn-project/aztec/src/cli/cmds/start_node.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/yarn-project/aztec/src/cli/cmds/start_node.ts b/yarn-project/aztec/src/cli/cmds/start_node.ts index 82ef2f7b0105..a034cf3a6f5a 100644 --- a/yarn-project/aztec/src/cli/cmds/start_node.ts +++ b/yarn-project/aztec/src/cli/cmds/start_node.ts @@ -14,7 +14,6 @@ import type { LogFn } from '@aztec/foundation/log'; import { sleep } from '@aztec/foundation/sleep'; import { ProvingJobConsumerSchema, createProvingJobBrokerClient } from '@aztec/prover-client/broker'; import { type CliPXEOptions, type PXEConfig, allPxeConfigMappings } from '@aztec/pxe/config'; -import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { AztecNodeAdminApiSchema, AztecNodeApiSchema } from '@aztec/stdlib/interfaces/client'; import { P2PApiSchema, ProverNodeApiSchema, type ProvingJobBroker } from '@aztec/stdlib/interfaces/server'; import { From 1662a7cd39ede81c1cf30d79c2ebc6ad4c494bd3 Mon Sep 17 00:00:00 2001 From: mverzilli Date: Wed, 4 Mar 2026 09:20:44 +0000 Subject: [PATCH 03/12] add comment on local-network only --- yarn-project/node-lib/src/config/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/yarn-project/node-lib/src/config/index.ts b/yarn-project/node-lib/src/config/index.ts index e6df4c979d94..1e267e481bc6 100644 --- a/yarn-project/node-lib/src/config/index.ts +++ b/yarn-project/node-lib/src/config/index.ts @@ -39,7 +39,7 @@ export const sharedNodeConfigMappings: ConfigMappingsType = { }, prefundAddresses: { env: 'PREFUND_ADDRESSES', - description: 'Comma-separated list of Aztec addresses to prefund with fee juice at genesis.', + description: 'Comma-separated list of Aztec addresses to prefund with fee juice at genesis (local network only).', parseEnv: (val: string) => val .split(',') From 20cfb3dd159d71e54365f87ffc8bf9e2f3b92d0f Mon Sep 17 00:00:00 2001 From: mverzilli Date: Wed, 4 Mar 2026 09:22:07 +0000 Subject: [PATCH 04/12] another comment --- yarn-project/ethereum/src/config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/yarn-project/ethereum/src/config.ts b/yarn-project/ethereum/src/config.ts index 6ccee3ce7c2a..ca5f53e53254 100644 --- a/yarn-project/ethereum/src/config.ts +++ b/yarn-project/ethereum/src/config.ts @@ -263,7 +263,7 @@ export const genesisStateConfigMappings: ConfigMappingsType }, prefundAddresses: { env: 'PREFUND_ADDRESSES', - description: 'Comma-separated list of Aztec addresses to prefund with fee juice at genesis.', + description: 'Comma-separated list of Aztec addresses to prefund with fee juice at genesis (local network only).', parseEnv: (val: string) => val .split(',') From 1282ec1fab060809b4db41cbebd793c51ee06d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bene=C5=A1?= Date: Wed, 4 Mar 2026 20:12:40 +0700 Subject: [PATCH 05/12] feat: aztec new supporting multiple contract crates (#21007) --- aztec-up/test/counter_contract.sh | 24 ++--- aztec-up/test/default_scaffold.sh | 48 +++++++-- docs/CLAUDE.md | 1 + .../contract_structure.md | 24 +++-- docs/docs-developers/docs/aztec-nr/index.md | 6 +- .../docs/aztec-nr/testing_contracts.md | 12 +-- .../docs/cli/aztec_cli_reference.md | 4 +- .../docs/resources/migration_notes.md | 41 +++++++ .../contract_tutorials/counter_contract.md | 16 +-- .../contract_tutorials/token_contract.md | 10 +- .../tutorials/js_tutorials/token_bridge.md | 16 +-- noir-projects/noir-contracts/Nargo.toml | 2 +- .../contracts/test/counter/Nargo.toml | 2 + .../counter_contract}/Nargo.toml | 0 .../counter_contract}/src/main.nr | 0 .../test => counter/counter_test}/Nargo.toml | 2 +- .../test => counter/counter_test}/src/lib.nr | 0 .../test/counter_contract/Nargo.toml | 2 - yarn-project/aztec/scripts/add_crate.sh | 102 ++++++++++++++++++ yarn-project/aztec/scripts/init.sh | 36 +++---- yarn-project/aztec/scripts/new.sh | 67 ++++++++---- yarn-project/aztec/scripts/setup_workspace.sh | 76 ++----------- yarn-project/aztec/src/cli/cli.ts | 6 +- .../scripts/generate-types.sh | 2 +- .../scripts/generate-types.sh | 2 +- 25 files changed, 319 insertions(+), 182 deletions(-) create mode 100644 noir-projects/noir-contracts/contracts/test/counter/Nargo.toml rename noir-projects/noir-contracts/contracts/test/{counter_contract/contract => counter/counter_contract}/Nargo.toml (100%) rename noir-projects/noir-contracts/contracts/test/{counter_contract/contract => counter/counter_contract}/src/main.nr (100%) rename noir-projects/noir-contracts/contracts/test/{counter_contract/test => counter/counter_test}/Nargo.toml (81%) rename noir-projects/noir-contracts/contracts/test/{counter_contract/test => counter/counter_test}/src/lib.nr (100%) delete mode 100644 noir-projects/noir-contracts/contracts/test/counter_contract/Nargo.toml create mode 100755 yarn-project/aztec/scripts/add_crate.sh diff --git a/aztec-up/test/counter_contract.sh b/aztec-up/test/counter_contract.sh index c4ce76350d56..c95bed113ee9 100755 --- a/aztec-up/test/counter_contract.sh +++ b/aztec-up/test/counter_contract.sh @@ -4,38 +4,38 @@ set -euo pipefail export LOG_LEVEL=silent # Execute commands as per: https://docs.aztec.network/tutorials/codealong/contract_tutorials/counter_contract -aztec new counter_contract +aztec new counter # Verify workspace structure -if [ ! -f counter_contract/Nargo.toml ]; then +if [ ! -f counter/Nargo.toml ]; then echo "Failed to create workspace Nargo.toml." exit 1 fi -if [ ! -f counter_contract/contract/Nargo.toml ] || [ ! -f counter_contract/contract/src/main.nr ]; then +if [ ! -f counter/counter_contract/Nargo.toml ] || [ ! -f counter/counter_contract/src/main.nr ]; then echo "Failed to create contract crate." exit 1 fi -if [ ! -f counter_contract/test/Nargo.toml ] || [ ! -f counter_contract/test/src/lib.nr ]; then +if [ ! -f counter/counter_test/Nargo.toml ] || [ ! -f counter/counter_test/src/lib.nr ]; then echo "Failed to create test crate." exit 1 fi -# Check counter_contract dir is owned by ubuntu. -if [ "$(stat -c %U counter_contract)" != "ubuntu" ]; then - echo "counter_contract dir is not owned by ubuntu." +# Check counter dir is owned by ubuntu. +if [ "$(stat -c %U counter)" != "ubuntu" ]; then + echo "counter dir is not owned by ubuntu." exit 1 fi # "Write" our contract over the scaffold. -cp -Rf ./aztec-packages/noir-projects/noir-contracts/contracts/test/counter_contract/* counter_contract/ -cd counter_contract -sed -i 's|\.\./\.\./\.\./\.\./\.\./|/home/ubuntu/aztec-packages/noir-projects/|g' contract/Nargo.toml test/Nargo.toml +cp -Rf ./aztec-packages/noir-projects/noir-contracts/contracts/test/counter/* counter/ +cd counter +sed -i 's|\.\./\.\./\.\./\.\./\.\./|/home/ubuntu/aztec-packages/noir-projects/|g' counter_contract/Nargo.toml counter_test/Nargo.toml # Compile the contract. aztec compile # Codegen -aztec codegen -o contract/src/artifacts target -if [ ! -d contract/src/artifacts ]; then +aztec codegen -o counter_contract/src/artifacts target +if [ ! -d counter_contract/src/artifacts ]; then echo "Failed to codegen TypeScript." exit 1 fi diff --git a/aztec-up/test/default_scaffold.sh b/aztec-up/test/default_scaffold.sh index d652bdbf8326..9eb08df644fd 100755 --- a/aztec-up/test/default_scaffold.sh +++ b/aztec-up/test/default_scaffold.sh @@ -2,35 +2,65 @@ set -euo pipefail # Tests that the default scaffold generated by `aztec new` compiles and passes its tests without any modifications. -# This catches regressions in the template files produced by setup_workspace.sh (e.g. syntax errors, stale imports, -# or API changes in aztec-nr) that would otherwise go unnoticed until a user runs `aztec new` themselves. +# Also tests that a second contract can be added to the workspace with `aztec new`. export LOG_LEVEL=silent -aztec new my_contract +aztec new my_workspace -# Verify workspace structure. -if [ ! -f my_contract/Nargo.toml ]; then +# Verify workspace structure with named crate directories. +if [ ! -f my_workspace/Nargo.toml ]; then echo "Failed to create workspace Nargo.toml." exit 1 fi -if [ ! -f my_contract/contract/Nargo.toml ] || [ ! -f my_contract/contract/src/main.nr ]; then +if [ ! -f my_workspace/my_workspace_contract/Nargo.toml ] || [ ! -f my_workspace/my_workspace_contract/src/main.nr ]; then echo "Failed to create contract crate." exit 1 fi -if [ ! -f my_contract/test/Nargo.toml ] || [ ! -f my_contract/test/src/lib.nr ]; then +if [ ! -f my_workspace/my_workspace_test/Nargo.toml ] || [ ! -f my_workspace/my_workspace_test/src/lib.nr ]; then echo "Failed to create test crate." exit 1 fi -cd my_contract +cd my_workspace # This is unfortunate as it makes the test worse but in CI setting the aztec version is 0.0.1 which doesn't exist as # a remote git tag, so we need to rewrite dependencies to use local aztec-nr. -sed -i 's|aztec = .*git.*AztecProtocol/aztec-nr.*|aztec = { path="/home/ubuntu/aztec-packages/noir-projects/aztec-nr/aztec" }|' contract/Nargo.toml test/Nargo.toml +sed -i 's|aztec = .*git.*AztecProtocol/aztec-nr.*|aztec = { path="/home/ubuntu/aztec-packages/noir-projects/aztec-nr/aztec" }|' \ + my_workspace_contract/Nargo.toml my_workspace_test/Nargo.toml # Compile the default scaffold contract. aztec compile # Run the default scaffold tests. aztec test + +# --- Test adding a second contract to the workspace --- +aztec new token + +# Verify token crates were created. +if [ ! -f token_contract/Nargo.toml ] || [ ! -f token_contract/src/main.nr ]; then + echo "Failed to create token contract crate." + exit 1 +fi +if [ ! -f token_test/Nargo.toml ] || [ ! -f token_test/src/lib.nr ]; then + echo "Failed to create token test crate." + exit 1 +fi + +# Verify workspace Nargo.toml contains all four members. +if ! grep -q '"my_workspace_contract"' Nargo.toml || \ + ! grep -q '"my_workspace_test"' Nargo.toml || \ + ! grep -q '"token_contract"' Nargo.toml || \ + ! grep -q '"token_test"' Nargo.toml; then + echo "Workspace Nargo.toml does not contain all expected members." + exit 1 +fi + +# Rewrite aztec deps for token crates too. +sed -i 's|aztec = .*git.*AztecProtocol/aztec-nr.*|aztec = { path="/home/ubuntu/aztec-packages/noir-projects/aztec-nr/aztec" }|' \ + token_contract/Nargo.toml token_test/Nargo.toml + +# Compile and test the full workspace (both contracts). +aztec compile +aztec test diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md index 58bfc28ef935..259b6065f672 100644 --- a/docs/CLAUDE.md +++ b/docs/CLAUDE.md @@ -294,6 +294,7 @@ The description should: - ❌ Legal disclaimers or license text - ❌ Direct quotes from external sources - ❌ API endpoint URLs or configuration values +- ❌ Existing migration notes in `resources/migration_notes.md` — never modify already-published migration entries. Instead, add new migration notes to the `## TBD` section at the top of the file. ## Review Output Format diff --git a/docs/docs-developers/docs/aztec-nr/framework-description/contract_structure.md b/docs/docs-developers/docs/aztec-nr/framework-description/contract_structure.md index 7a7c93b3756a..87c051771ca0 100644 --- a/docs/docs-developers/docs/aztec-nr/framework-description/contract_structure.md +++ b/docs/docs-developers/docs/aztec-nr/framework-description/contract_structure.md @@ -10,25 +10,27 @@ High-level structure of how Aztec smart contracts including the different compon ## Directory structure -When you create a new project with `aztec new`, it generates a workspace with two crates: a `contract` crate for your smart contract and a `test` crate for Noir tests. +When you create a new project with `aztec new my_project`, it generates a workspace with two crates named after your project: a `my_project_contract` crate for your smart contract and a `my_project_test` crate for Noir tests. ```text title="layout of an aztec contract project" -─── my_aztec_contract_project - ├── Nargo.toml <-- workspace root - ├── contract +─── my_project + ├── Nargo.toml <-- workspace root + ├── my_project_contract │ ├── src - │ │ └── main.nr <-- your contract - │ └── Nargo.toml <-- contract package and dependencies - └── test + │ │ └── main.nr <-- your contract + │ └── Nargo.toml <-- contract package and dependencies + └── my_project_test ├── src - │ └── lib.nr <-- your tests - └── Nargo.toml <-- test package and dependencies + │ └── lib.nr <-- your tests + └── Nargo.toml <-- test package and dependencies ``` -The workspace root `Nargo.toml` declares both crates as workspace members. The contract code lives in `contract/src/main.nr`, and tests live in a separate `test` crate that depends on the contract crate. +The workspace root `Nargo.toml` declares both crates as workspace members. The contract code lives in `my_project_contract/src/main.nr`, and tests live in a separate `my_project_test` crate that depends on the contract crate. + +You can add more contracts to an existing workspace by running `aztec new ` from inside the workspace directory. This creates a new `_contract` and `_test` crate pair and adds them to the workspace. :::warning Keep tests out of the contract crate -Do not add `#[test]` functions to the `contract` crate. Because the contract artifact depends on everything in its crate, any change — including a test-only change — forces a full recompilation of the contract. The separate `test` crate lets you iterate on tests without rebuilding the contract. See [Testing Contracts](../testing_contracts.md#keep-tests-in-the-test-crate) for details. +Do not add `#[test]` functions to the `_contract` crate. Because the contract artifact depends on everything in its crate, any change — including a test-only change — forces a full recompilation of the contract. The separate `_test` crate lets you iterate on tests without rebuilding the contract. See [Testing Contracts](../testing_contracts.md#keep-tests-in-the-test-crate) for details. ::: See the vanilla Noir docs for [more info on packages](https://noir-lang.org/docs/noir/modules_packages_crates/crates_and_packages). diff --git a/docs/docs-developers/docs/aztec-nr/index.md b/docs/docs-developers/docs/aztec-nr/index.md index 34fe5705cc8f..2292165c6757 100644 --- a/docs/docs-developers/docs/aztec-nr/index.md +++ b/docs/docs-developers/docs/aztec-nr/index.md @@ -42,15 +42,15 @@ storage.votes.insert(new_vote).deliver(vote_counter); // the vote counter accoun ### Flow -1. Write your contract and specify your contract dependencies. Create a new project with `aztec new my_project`, which sets up a workspace with a `contract` crate and a `test` crate, with the `aztec` dependency already configured. If you need additional dependencies, add them to `contract/Nargo.toml`: +1. Write your contract and specify your contract dependencies. Create a new project with `aztec new my_project`, which sets up a workspace with a `my_project_contract` crate and a `my_project_test` crate, with the `aztec` dependency already configured. If you need additional dependencies, add them to `my_project_contract/Nargo.toml`: ```toml -# contract/Nargo.toml +# my_project_contract/Nargo.toml [dependencies] aztec = { git="https://github.com/AztecProtocol/aztec-nr/", tag="#include_aztec_version", directory="aztec" } ``` -Update your `contract/src/main.nr` contract file to use the Aztec.nr macros for writing contracts. +Update your `my_project_contract/src/main.nr` contract file to use the Aztec.nr macros for writing contracts. #include_code setup /docs/examples/contracts/counter_contract/src/main.nr rust diff --git a/docs/docs-developers/docs/aztec-nr/testing_contracts.md b/docs/docs-developers/docs/aztec-nr/testing_contracts.md index a3b2c01bfade..03d19207600d 100644 --- a/docs/docs-developers/docs/aztec-nr/testing_contracts.md +++ b/docs/docs-developers/docs/aztec-nr/testing_contracts.md @@ -46,7 +46,7 @@ Always use `aztec test` instead of `nargo test`. The `TestEnvironment` requires ## Keep tests in the test crate -When you create a project with `aztec new` or `aztec init`, the generated workspace has two crates: `contract` and `test`. It is important that all tests live in the `test` crate, **not** in the `contract` crate. +When you create a project with `aztec new` or `aztec init`, the generated workspace has two crates: `_contract` and `_test`. It is important that all tests live in the `_test` crate, **not** in the `_contract` crate. If you place `#[test]` functions inside the contract crate, `aztec compile` will emit a warning: @@ -60,7 +60,7 @@ The reason is **unnecessary recompilation**: the contract artifact depends on ev ## Basic test structure -Tests live in `test/src/lib.nr` and import the contract crate by name (not `crate::`): +Tests live in `_test/src/lib.nr` and import the contract crate by name (not `crate::`): ```rust use my_contract::MyContract; @@ -88,11 +88,11 @@ unconstrained fn test_basic_flow() { ::: :::tip Organizing test files -Tests live in the separate `test` crate that `aztec new` creates. You can organize them into modules: +Tests live in the separate `_test` crate that `aztec new` creates. You can organize them into modules: -- Split tests into modules like `test/src/transfer_tests.nr`, `test/src/auth_tests.nr` -- Import them in `test/src/lib.nr` with `mod transfer_tests;`, `mod auth_tests;` -- Share setup functions in `test/src/utils.nr` +- Split tests into modules like `_test/src/transfer_tests.nr`, `_test/src/auth_tests.nr` +- Import them in `_test/src/lib.nr` with `mod transfer_tests;`, `mod auth_tests;` +- Share setup functions in `_test/src/utils.nr` ::: ## Deploying contracts diff --git a/docs/docs-developers/docs/cli/aztec_cli_reference.md b/docs/docs-developers/docs/cli/aztec_cli_reference.md index 725678e97816..a4621c23ab45 100644 --- a/docs/docs-developers/docs/cli/aztec_cli_reference.md +++ b/docs/docs-developers/docs/cli/aztec_cli_reference.md @@ -109,10 +109,10 @@ aztec [options] [command] - `get-logs [options]` - Gets all the public logs from an intersection of all the filter params. - `get-node-info [options]` - Gets the information of an Aztec node from a PXE or directly from an Aztec node. - `help [command]` - display help for command -- `init [folder] [options]` - creates a new Noir project +- `init [options]` - creates a new Noir workspace in the current directory - `inspect-contract ` - Shows list of external callable functions for a contract - `lsp` - starts the Nargo Language Server Protocol server -- `new [options]` - creates a new Noir project in a new directory +- `new [options]` - creates a new Noir workspace (or adds a contract to an existing workspace) - `parse-parameter-struct [options] ` - Helper for parsing an encoded string into a contract's parameter struct. - `preload-crs` - Preload the points data needed for proving and verifying - `propose-with-lock [options]` - Makes a proposal to governance with a lock diff --git a/docs/docs-developers/docs/resources/migration_notes.md b/docs/docs-developers/docs/resources/migration_notes.md index 63c71c0e7bbd..cc1524e30ccc 100644 --- a/docs/docs-developers/docs/resources/migration_notes.md +++ b/docs/docs-developers/docs/resources/migration_notes.md @@ -9,6 +9,47 @@ Aztec is in active development. Each version may introduce breaking changes that ## TBD +### `aztec new` crate directories are now named after the contract + +`aztec new` and `aztec init` now name the generated crate directories after the contract instead of using generic `contract/` and `test/` names. For example, `aztec new counter` now creates: + +``` +counter/ +├── Nargo.toml # [workspace] members = ["counter_contract", "counter_test"] +├── counter_contract/ +│ ├── src/main.nr +│ └── Nargo.toml # type = "contract" +└── counter_test/ + ├── src/lib.nr + └── Nargo.toml # type = "lib" +``` + +This enables adding multiple contracts to a single workspace. Running `aztec new ` inside an existing workspace (a directory with a `Nargo.toml` containing `[workspace]`) now adds a new `_contract` and `_test` crate pair to the workspace instead of creating a new directory. + +**What changed:** +- Crate directories are now `_contract/` and `_test/` instead of `contract/` and `test/`. +- Contract code is now at `_contract/src/main.nr` instead of `contract/src/main.nr`. +- Contract dependencies go in `_contract/Nargo.toml` instead of `contract/Nargo.toml`. +- Tests import the contract by its new crate name (e.g., `use counter_contract::Main;` instead of `use counter::Main;`). + +### [CLI] `--name` flag removed from `aztec new` and `aztec init` + +The `--name` flag has been removed from both `aztec new` and `aztec init`. For `aztec new`, the positional argument now serves as both the contract name and the directory name. For `aztec init`, the directory name is always used as the contract name. + +**Migration:** + +```diff +- aztec new my_project --name counter ++ aztec new counter +``` + +```diff +- aztec init --name counter ++ aztec init +``` + +**Impact**: If you were using `--name` to set a contract name different from the directory name, rename your directory or use `aztec new` with the desired contract name directly. + ### [Aztec.js] Removed `SingleKeyAccountContract` The `SchnorrSingleKeyAccount` contract and its TypeScript wrapper `SingleKeyAccountContract` have been removed. This contract was insecure: it used `ivpk_m` (incoming viewing public key) as its Schnorr signing key, meaning anyone who received a user's viewing key could sign transactions on their behalf. diff --git a/docs/docs-developers/docs/tutorials/contract_tutorials/counter_contract.md b/docs/docs-developers/docs/tutorials/contract_tutorials/counter_contract.md index 817aa4f78273..39fe64bd857f 100644 --- a/docs/docs-developers/docs/tutorials/contract_tutorials/counter_contract.md +++ b/docs/docs-developers/docs/tutorials/contract_tutorials/counter_contract.md @@ -30,20 +30,20 @@ Your structure should look like this: ```tree . |-counter -| |-Nargo.toml <-- workspace root -| |-contract +| |-Nargo.toml <-- workspace root +| |-counter_contract | | |-src | | | |-main.nr -| | |-Nargo.toml <-- contract package config -| |-test +| | |-Nargo.toml <-- contract package config +| |-counter_test | | |-src | | | |-lib.nr -| | |-Nargo.toml <-- test package config +| | |-Nargo.toml <-- test package config ``` -The `aztec new` command creates a workspace with two crates: a `contract` crate for your smart contract code and a `test` crate for Noir tests. The file `contract/src/main.nr` will soon turn into our smart contract! +The `aztec new` command creates a workspace with two crates: a `counter_contract` crate for your smart contract code and a `counter_test` crate for Noir tests. The file `counter_contract/src/main.nr` will soon turn into our smart contract! -Add the following dependency to `contract/Nargo.toml` under the existing `aztec` dependency: +Add the following dependency to `counter_contract/Nargo.toml` under the existing `aztec` dependency: ```toml [dependencies] @@ -53,7 +53,7 @@ balance_set = { git="https://github.com/AztecProtocol/aztec-nr/", tag="#include_ ## Define the functions -Go to `contract/src/main.nr`, and replace the boilerplate code with this contract initialization: +Go to `counter_contract/src/main.nr`, and replace the boilerplate code with this contract initialization: ```rust #include_code setup /docs/examples/contracts/counter_contract/src/main.nr raw diff --git a/docs/docs-developers/docs/tutorials/contract_tutorials/token_contract.md b/docs/docs-developers/docs/tutorials/contract_tutorials/token_contract.md index 98e5fdc0fb60..677f88f0dda4 100644 --- a/docs/docs-developers/docs/tutorials/contract_tutorials/token_contract.md +++ b/docs/docs-developers/docs/tutorials/contract_tutorials/token_contract.md @@ -39,8 +39,8 @@ We'll create BOB tokens with: Let's create a simple yarn + aztec.nr project: ```bash -mkdir bob_token_contract -cd bob_token_contract +mkdir bob_token +cd bob_token yarn init # This is to ensure yarn uses node_modules instead of pnp for dependency installation yarn config set nodeLinker node-modules @@ -50,7 +50,7 @@ aztec init ## Contract structure -The `aztec init` command created a workspace with two crates: a `contract` crate for your smart contract code and a `test` crate for Noir tests. In `contract/src/main.nr` we even have a proto-contract. Let's replace it with a simple starting point: +The `aztec init` command created a workspace with two crates: a `bob_token_contract` crate for your smart contract code and a `bob_token_test` crate for Noir tests. In `bob_token_contract/src/main.nr` we even have a proto-contract. Let's replace it with a simple starting point: ```rust #include_code start /docs/examples/contracts/bob_token_contract/src/main.nr raw @@ -60,7 +60,7 @@ The `aztec init` command created a workspace with two crates: a `contract` crate The `#[aztec]` macro transforms our contract code to work with Aztec's privacy protocol. -Let's make sure the Aztec.nr library is listed in our dependencies in `contract/Nargo.toml`: +Let's make sure the Aztec.nr library is listed in our dependencies in `bob_token_contract/Nargo.toml`: ```toml [package] @@ -254,7 +254,7 @@ In this case, all that the network sees (including Giggle) is just "something ha ### Updating Storage for Privacy -For something like balances, you can use a simple library called `easy_private_state` which abstracts away a custom private Note. A Note is at the core of how private state works in Aztec and you can read about it [here](../../foundational-topics/state_management.md). For now, let's just import the library in `contract/Nargo.toml`: +For something like balances, you can use a simple library called `easy_private_state` which abstracts away a custom private Note. A Note is at the core of how private state works in Aztec and you can read about it [here](../../foundational-topics/state_management.md). For now, let's just import the library in `bob_token_contract/Nargo.toml`: ```toml [dependencies] diff --git a/docs/docs-developers/docs/tutorials/js_tutorials/token_bridge.md b/docs/docs-developers/docs/tutorials/js_tutorials/token_bridge.md index f80d3c6897a5..fe4df0b37ba2 100644 --- a/docs/docs-developers/docs/tutorials/js_tutorials/token_bridge.md +++ b/docs/docs-developers/docs/tutorials/js_tutorials/token_bridge.md @@ -86,7 +86,7 @@ aztec new contracts/aztec/nft cd contracts/aztec/nft ``` -This creates a workspace with two crates: a `contract` crate for the smart contract code and a `test` crate for Noir tests. The `aztec` dependency is already configured in `contract/Nargo.toml`. +This creates a workspace with two crates: an `nft_contract` crate for the smart contract code and an `nft_test` crate for Noir tests. The `aztec` dependency is already configured in `nft_contract/Nargo.toml`. :::tip Noir Language Server @@ -96,10 +96,10 @@ If you're using VS Code, install the [Noir Language Support extension](https://m ### Create the NFT Note -First, let's create a custom note type for private NFT ownership. In the `contract/src/` directory, create a new file called `nft.nr`: +First, let's create a custom note type for private NFT ownership. In the `nft_contract/src/` directory, create a new file called `nft.nr`: ```bash -touch contract/src/nft.nr +touch nft_contract/src/nft.nr ``` In this file, you're going to create a **private note** that represents NFT ownership. This is a struct with macros that indicate it is a note that can be compared and packed: @@ -116,7 +116,7 @@ Notes are powerful concepts. Learn more about how to use them in the [state mana ### Define Storage -Back in `contract/src/main.nr`, you can now build the contract storage. You need: +Back in `nft_contract/src/main.nr`, you can now build the contract storage. You need: - **admin**: Who controls the contract (set once, never changes) - **minter**: The bridge address (set once by admin) @@ -125,7 +125,7 @@ Back in `contract/src/main.nr`, you can now build the contract storage. You need One interesting aspect of this storage configuration is the use of `DelayedPublicMutable`, which allows private functions to read and use public state. You're using it to publicly track which NFTs are already minted while keeping their owners private. Read more about `DelayedPublicMutable` in [the storage guide](../../aztec-nr/framework-description/state_variables.md). -Write the storage struct and a simple [initializer](../../foundational-topics/contract_creation.md#initialization) to set the admin in the `contract/src/main.nr` file: +Write the storage struct and a simple [initializer](../../foundational-topics/contract_creation.md#initialization) to set the admin in the `nft_contract/src/main.nr` file: @@ -213,12 +213,12 @@ aztec new nft_bridge cd nft_bridge ``` -Now add the `NFTPunk` contract dependency to `contract/Nargo.toml`. The `aztec` dependency is already there: +Now add the `NFTPunk` contract dependency to `nft_bridge_contract/Nargo.toml`. The `aztec` dependency is already there: ```toml [dependencies] aztec = { git="https://github.com/AztecProtocol/aztec-nr", tag = "#include_aztec_version", directory = "aztec" } -NFTPunk = { path = "../../nft/contract" } +NFTPunk = { path = "../../nft/nft_contract" } ``` ### Understanding Bridges @@ -232,7 +232,7 @@ This means having knowledge about the L2 NFT contract, and the bridge on the L1 ### Bridge Storage -Clean up `contract/src/main.nr` which is just a placeholder, and let's write the storage struct and the constructor. We'll use `PublicImmutable` since these values never change: +Clean up `nft_bridge_contract/src/main.nr` which is just a placeholder, and let's write the storage struct and the constructor. We'll use `PublicImmutable` since these values never change: diff --git a/noir-projects/noir-contracts/Nargo.toml b/noir-projects/noir-contracts/Nargo.toml index d48af75499ea..a3c05bd05a9c 100644 --- a/noir-projects/noir-contracts/Nargo.toml +++ b/noir-projects/noir-contracts/Nargo.toml @@ -41,7 +41,7 @@ members = [ "contracts/test/avm_test_contract", "contracts/test/benchmarking_contract", "contracts/test/child_contract", - "contracts/test/counter_contract/contract", + "contracts/test/counter/counter_contract", "contracts/test/custom_message_contract", "contracts/test/event_only_contract", "contracts/test/import_test_contract", diff --git a/noir-projects/noir-contracts/contracts/test/counter/Nargo.toml b/noir-projects/noir-contracts/contracts/test/counter/Nargo.toml new file mode 100644 index 000000000000..8bec3f6a6701 --- /dev/null +++ b/noir-projects/noir-contracts/contracts/test/counter/Nargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["counter_contract", "counter_test"] diff --git a/noir-projects/noir-contracts/contracts/test/counter_contract/contract/Nargo.toml b/noir-projects/noir-contracts/contracts/test/counter/counter_contract/Nargo.toml similarity index 100% rename from noir-projects/noir-contracts/contracts/test/counter_contract/contract/Nargo.toml rename to noir-projects/noir-contracts/contracts/test/counter/counter_contract/Nargo.toml diff --git a/noir-projects/noir-contracts/contracts/test/counter_contract/contract/src/main.nr b/noir-projects/noir-contracts/contracts/test/counter/counter_contract/src/main.nr similarity index 100% rename from noir-projects/noir-contracts/contracts/test/counter_contract/contract/src/main.nr rename to noir-projects/noir-contracts/contracts/test/counter/counter_contract/src/main.nr diff --git a/noir-projects/noir-contracts/contracts/test/counter_contract/test/Nargo.toml b/noir-projects/noir-contracts/contracts/test/counter/counter_test/Nargo.toml similarity index 81% rename from noir-projects/noir-contracts/contracts/test/counter_contract/test/Nargo.toml rename to noir-projects/noir-contracts/contracts/test/counter/counter_test/Nargo.toml index 1d5b103087e7..b587b4b2e560 100644 --- a/noir-projects/noir-contracts/contracts/test/counter_contract/test/Nargo.toml +++ b/noir-projects/noir-contracts/contracts/test/counter/counter_test/Nargo.toml @@ -7,4 +7,4 @@ type = "lib" [dependencies] aztec = { path = "../../../../../aztec-nr/aztec" } balance_set = { path = "../../../../../aztec-nr/balance-set" } -counter_contract = { path = "../contract" } +counter_contract = { path = "../counter_contract" } diff --git a/noir-projects/noir-contracts/contracts/test/counter_contract/test/src/lib.nr b/noir-projects/noir-contracts/contracts/test/counter/counter_test/src/lib.nr similarity index 100% rename from noir-projects/noir-contracts/contracts/test/counter_contract/test/src/lib.nr rename to noir-projects/noir-contracts/contracts/test/counter/counter_test/src/lib.nr diff --git a/noir-projects/noir-contracts/contracts/test/counter_contract/Nargo.toml b/noir-projects/noir-contracts/contracts/test/counter_contract/Nargo.toml deleted file mode 100644 index 3ae352f74220..000000000000 --- a/noir-projects/noir-contracts/contracts/test/counter_contract/Nargo.toml +++ /dev/null @@ -1,2 +0,0 @@ -[workspace] -members = ["contract", "test"] diff --git a/yarn-project/aztec/scripts/add_crate.sh b/yarn-project/aztec/scripts/add_crate.sh new file mode 100755 index 000000000000..fea8a4b66e42 --- /dev/null +++ b/yarn-project/aztec/scripts/add_crate.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Creates a contract+test crate pair and adds them to an existing workspace. +# Usage: add_crate.sh +# Must be called from a workspace root that already has Nargo.toml with [workspace]. + +crate_name=$1 + +if [ -z "$crate_name" ]; then + echo "Error: crate name is required" + exit 1 +fi + +if [[ "$crate_name" == *"/"* ]] || [[ "$crate_name" == *"\\"* ]]; then + echo "Error: crate name must not contain path separators" + exit 1 +fi + +contract_dir="${crate_name}_contract" +test_dir="${crate_name}_test" + +if [ -d "$contract_dir" ]; then + echo "Error: directory '$contract_dir' already exists" + exit 1 +fi +if [ -d "$test_dir" ]; then + echo "Error: directory '$test_dir' already exists" + exit 1 +fi + +# Get the actual aztec version for the git tag. +AZTEC_VERSION=$(jq -r '.version' $(dirname $0)/../package.json) + +# Create contract crate +mkdir -p "$contract_dir/src" +cat > "$contract_dir/Nargo.toml" << CEOF +[package] +name = "${crate_name}_contract" +type = "contract" + +[dependencies] +aztec = { git="https://github.com/AztecProtocol/aztec-nr", tag="v${AZTEC_VERSION}", directory="aztec" } +CEOF + +cat > "$contract_dir/src/main.nr" << 'EOF' +use aztec::macros::aztec; + +#[aztec] +pub contract Main { + use aztec::macros::functions::{external, initializer}; + + #[initializer] + #[external("private")] + fn constructor() {} +} +EOF + +# Create test crate +mkdir -p "$test_dir/src" +cat > "$test_dir/Nargo.toml" << TEOF +[package] +name = "${crate_name}_test" +type = "lib" + +[dependencies] +aztec = { git="https://github.com/AztecProtocol/aztec-nr", tag="v${AZTEC_VERSION}", directory="aztec" } +${crate_name}_contract = { path = "../${contract_dir}" } +TEOF + +cat > "$test_dir/src/lib.nr" << 'NOIR' +use aztec::test::helpers::test_environment::TestEnvironment; +use __CRATE_NAME___contract::Main; + +#[test] +unconstrained fn test_constructor() { + let mut env = TestEnvironment::new(); + let deployer = env.create_light_account(); + + // Deploy the contract with the default constructor: + let contract_address = env.deploy("@__CRATE_NAME___contract/Main").with_private_initializer( + deployer, + Main::interface().constructor(), + ); + + // Deploy without an initializer: + let contract_address = env.deploy("@__CRATE_NAME___contract/Main").without_initializer(); +} +NOIR + +sed -i "s/__CRATE_NAME__/${crate_name}/g" "$test_dir/src/lib.nr" + +# Add members to workspace Nargo.toml +if grep -q 'members\s*=\s*\[\s*\]' Nargo.toml; then + # Empty array: members = [] + sed -i "s|members\s*=\s*\[\s*\]|members = [\"${contract_dir}\", \"${test_dir}\"]|" Nargo.toml +else + # Non-empty array: add before closing ] + sed -i "s|\(members\s*=\s*\[.*\)\]|\1, \"${contract_dir}\", \"${test_dir}\"]|" Nargo.toml +fi + +echo "Created crates '${contract_dir}' and '${test_dir}'" diff --git a/yarn-project/aztec/scripts/init.sh b/yarn-project/aztec/scripts/init.sh index 3fae0e67f894..e0641a9c17fa 100755 --- a/yarn-project/aztec/scripts/init.sh +++ b/yarn-project/aztec/scripts/init.sh @@ -3,43 +3,37 @@ set -euo pipefail script_path=$(realpath $(dirname "$0")) -name_arg="" - -# Check for help first -for arg in "$@"; do - if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]; then - cat << 'EOF' +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --help|-h) + cat << 'EOF' Aztec Init - Create a new Aztec Noir project in the current directory -Usage: aztec init [OPTIONS] +Usage: aztec init Options: - --name Name of the package [default: current directory name] -h, --help Print help This command creates a new Aztec Noir project in the current directory with a workspace containing a contract crate and a test crate, and automatically adds the Aztec.nr dependency to both. -EOF - exit 0 - fi -done -# Parse arguments -while [[ $# -gt 0 ]]; do - case $1 in - --name) - name_arg="$2" - shift 2 +If a workspace already exists in the current directory, use +'aztec new ' instead to add another contract. +EOF + exit 0 ;; *) - shift + echo "Error: unexpected argument '$1'" + echo "Usage: aztec init" + echo "Run 'aztec init --help' for more information" + exit 1 ;; esac done -# Derive package name: use --name if provided, otherwise use current directory name -package_name="${name_arg:-$(basename $(pwd))}" +package_name="$(basename $(pwd))" echo "Initializing Aztec contract project..." $script_path/setup_workspace.sh "$package_name" diff --git a/yarn-project/aztec/scripts/new.sh b/yarn-project/aztec/scripts/new.sh index 37584fffae0a..9fb73277811a 100755 --- a/yarn-project/aztec/scripts/new.sh +++ b/yarn-project/aztec/scripts/new.sh @@ -3,58 +3,81 @@ set -euo pipefail script_path=$(realpath $(dirname "$0")) -name_arg="" project_path="" while [[ $# -gt 0 ]]; do case $1 in --help|-h) cat << 'EOF' -Aztec New - Create a new Aztec Noir project in a new directory +Aztec New - Create a new Aztec Noir project or add a contract to an existing workspace -Usage: aztec new [OPTIONS] +Usage: aztec new Arguments: - The path to save the new project + The name for the new contract (also used as the directory name when + creating a new workspace) Options: - --name Name of the package [default: package directory name] -h, --help Print help -This command creates a new Aztec Noir project with a workspace containing -a contract crate and a test crate, and automatically adds the Aztec.nr -dependency to both. +When run outside an existing workspace: + Creates a new directory with a workspace containing a contract crate and a + test crate, and automatically adds the Aztec.nr dependency to both. + +When run inside an existing workspace (Nargo.toml with [workspace] exists): + Adds a new contract crate and test crate to the existing workspace. EOF exit 0 ;; - --name) - name_arg="$2" - shift 2 + -*) + echo "Error: unknown option '$1'" + echo "Usage: aztec new " + echo "Run 'aztec new --help' for more information" + exit 1 ;; *) + if [ -n "$project_path" ]; then + echo "Error: unexpected argument '$1'" + echo "Usage: aztec new " + echo "Run 'aztec new --help' for more information" + exit 1 + fi project_path=$1 shift - break ;; esac done if [ -z "$project_path" ]; then - echo "Error: PATH argument is required" - echo "Usage: aztec new [OPTIONS] " + echo "Error: NAME argument is required" + echo "Usage: aztec new " echo "Run 'aztec new --help' for more information" exit 1 fi -if [ -d "$project_path" ] && [ "$(ls -A $project_path 2>/dev/null)" ]; then - echo "Error: $project_path already exists and is not empty" +package_name="$(basename $project_path)" + +# Validate that the name contains only valid Noir identifier characters +if ! [[ "$package_name" =~ ^[a-zA-Z][a-zA-Z0-9_]*$ ]]; then + echo "Error: '$package_name' is not a valid contract name" + echo "Name must start with a letter and contain only letters, digits, and underscores" exit 1 fi -# Derive package name: use --name if provided, otherwise use directory basename -package_name="${name_arg:-$(basename $project_path)}" +# Check if we're inside an existing workspace +if [ -f "Nargo.toml" ] && grep -q '\[workspace\]' Nargo.toml; then + # Add crate pair to existing workspace + echo "Adding contract '$package_name' to existing workspace..." + $script_path/add_crate.sh "$package_name" +else + # Create new workspace + if [ -d "$project_path" ] && [ "$(ls -A $project_path 2>/dev/null)" ]; then + echo "Error: $project_path already exists and is not empty" + exit 1 + fi -echo "Creating new Aztec contract project at $project_path..." -mkdir -p "$project_path" -cd "$project_path" -$script_path/setup_workspace.sh "$package_name" + echo "Creating new Aztec contract project at $project_path..." + mkdir -p "$project_path" + cd "$project_path" + $script_path/setup_workspace.sh "$package_name" +fi diff --git a/yarn-project/aztec/scripts/setup_workspace.sh b/yarn-project/aztec/scripts/setup_workspace.sh index 11ca9deb68f0..e08f1665136a 100755 --- a/yarn-project/aztec/scripts/setup_workspace.sh +++ b/yarn-project/aztec/scripts/setup_workspace.sh @@ -6,6 +6,7 @@ set -euo pipefail # Must be called from the workspace root directory. package_name=$1 +script_path=$(realpath $(dirname "$0")) if [ -z "$package_name" ]; then echo "Error: package name is required" @@ -13,76 +14,19 @@ if [ -z "$package_name" ]; then fi if [ -f "Nargo.toml" ]; then - echo "Error: Nargo.toml already exists in the current directory" + echo "Error: Nargo.toml already exists in the current directory." + echo "To add another contract crate to this workspace, use 'aztec new ' instead." exit 1 fi -# Get the actual aztec version for the git tag. -AZTEC_VERSION=$(jq -r '.version' $(dirname $0)/../package.json) - -# Create workspace root Nargo.toml +# Create workspace root Nargo.toml with empty members (add_crate.sh will populate) cat > Nargo.toml << 'EOF' [workspace] -members = ["contract", "test"] -EOF - -# Create contract crate -mkdir -p contract/src -cat > contract/Nargo.toml << CEOF -[package] -name = "${package_name}" -type = "contract" - -[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-nr", tag="v${AZTEC_VERSION}", directory="aztec" } -CEOF - -cat > contract/src/main.nr << 'EOF' -use aztec::macros::aztec; - -#[aztec] -pub contract Main { - use aztec::macros::functions::{external, initializer}; - - #[initializer] - #[external("private")] - fn constructor() {} -} +members = [] EOF -# Create test crate -mkdir -p test/src -cat > test/Nargo.toml << TEOF -[package] -name = "${package_name}_test" -type = "lib" - -[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-nr", tag="v${AZTEC_VERSION}", directory="aztec" } -${package_name} = { path = "../contract" } -TEOF - -cat > test/src/lib.nr << 'NOIR' -use aztec::test::helpers::test_environment::TestEnvironment; -use __PACKAGE_NAME__::Main; - -#[test] -unconstrained fn test_constructor() { - let mut env = TestEnvironment::new(); - let deployer = env.create_light_account(); - - // Deploy the contract with the default constructor: - let contract_address = env.deploy("@__PACKAGE_NAME__/Main").with_private_initializer( - deployer, - Main::interface().constructor(), - ); - - // Deploy without an initializer: - let contract_address = env.deploy("@__PACKAGE_NAME__/Main").without_initializer(); -} -NOIR - -sed -i "s/__PACKAGE_NAME__/${package_name}/g" test/src/lib.nr +# Create the first crate pair +$script_path/add_crate.sh "$package_name" # Create README cat > README.md << REOF @@ -96,7 +40,7 @@ An Aztec Noir contract project. aztec compile \`\`\` -This compiles the contract in \`contract/\` and outputs artifacts to \`target/\`. +This compiles all contract crates and outputs artifacts to \`target/\`. ## Test @@ -104,7 +48,7 @@ This compiles the contract in \`contract/\` and outputs artifacts to \`target/\` aztec test \`\`\` -This runs the tests in \`test/\`. +This runs all tests in the workspace. ## Generate TypeScript bindings @@ -121,4 +65,4 @@ target/ codegenCache.json GEOF -echo "Created Aztec contract workspace with crates '${package_name}' and '${package_name}_test'" +echo "Created Aztec contract workspace with crates '${package_name}_contract' and '${package_name}_test'" diff --git a/yarn-project/aztec/src/cli/cli.ts b/yarn-project/aztec/src/cli/cli.ts index 1c79cf24f294..f1c8269ef0e3 100644 --- a/yarn-project/aztec/src/cli/cli.ts +++ b/yarn-project/aztec/src/cli/cli.ts @@ -37,9 +37,9 @@ export function injectAztecCommands(program: Command, userLog: LogFn, debugLogge ` Additional commands: - init [folder] [options] creates a new Aztec Noir project. - new [options] creates a new Aztec Noir project in a new directory. - test [options] starts a TXE and runs "nargo test" using it as the oracle resolver. + init creates a new Aztec Noir workspace in the current directory. + new creates a new Aztec Noir workspace in its own directory (or creates a new contract-test crates pair and adds it to the current workspace if run in workspace). + test [options] starts a TXE and runs "nargo test" using it as the oracle resolver. `, ); } diff --git a/yarn-project/noir-contracts.js/scripts/generate-types.sh b/yarn-project/noir-contracts.js/scripts/generate-types.sh index 04ecfe03a107..ce75af14440b 100755 --- a/yarn-project/noir-contracts.js/scripts/generate-types.sh +++ b/yarn-project/noir-contracts.js/scripts/generate-types.sh @@ -12,7 +12,7 @@ fi mkdir -p $OUT_DIR # Extract contract names from Nargo.toml, excluding test contracts -CONTRACTS=$(grep "contracts/" ../../noir-projects/noir-contracts/Nargo.toml | grep -v "contracts/test/" | sed 's/.*contracts\/[^/]*\/\([^"]*\)_contract.*/\1/') +CONTRACTS=$(grep "contracts/" ../../noir-projects/noir-contracts/Nargo.toml | grep -v "contracts/test/" | sed 's/.*\/\([^/"]*\)_contract.*/\1/') # Check for .json files existence if ! ls ../../noir-projects/noir-contracts/target/*.json >/dev/null 2>&1; then diff --git a/yarn-project/noir-test-contracts.js/scripts/generate-types.sh b/yarn-project/noir-test-contracts.js/scripts/generate-types.sh index 53ad93b684a9..6890206f7e11 100755 --- a/yarn-project/noir-test-contracts.js/scripts/generate-types.sh +++ b/yarn-project/noir-test-contracts.js/scripts/generate-types.sh @@ -12,7 +12,7 @@ fi mkdir -p $OUT_DIR # Extract test contract names from Nargo.toml -TEST_CONTRACTS=$(grep "contracts/test/" ../../noir-projects/noir-contracts/Nargo.toml | sed 's/.*contracts\/test\/\([^"]*\)_contract.*/\1/') +TEST_CONTRACTS=$(grep "contracts/test/" ../../noir-projects/noir-contracts/Nargo.toml | sed 's/.*\/\([^/"]*\)_contract.*/\1/') # Check for .json files existence if ! ls ../../noir-projects/noir-contracts/target/*.json >/dev/null 2>&1; then From 3ab7b10264c54ebda48a644b8613a574c2397c63 Mon Sep 17 00:00:00 2001 From: Martin Verzilli Date: Wed, 4 Mar 2026 15:29:48 +0100 Subject: [PATCH 06/12] feat!: Expose offchain effects when simulating/sending txs (#20563) Closes F-322 --- boxes/boxes/react/src/hooks/useContract.tsx | 4 +- boxes/boxes/react/src/hooks/useNumber.tsx | 4 +- boxes/boxes/vanilla/app/embedded-wallet.ts | 2 +- boxes/boxes/vanilla/app/main.ts | 2 +- boxes/boxes/vanilla/scripts/deploy.ts | 2 +- boxes/boxes/vite/src/hooks/useContract.tsx | 4 +- boxes/boxes/vite/src/hooks/useNumber.tsx | 4 +- .../docs/resources/migration_notes.md | 91 +++++++++ docs/examples/ts/aztecjs_advanced/index.ts | 28 +-- docs/examples/ts/aztecjs_authwit/index.ts | 2 +- docs/examples/ts/aztecjs_connection/index.ts | 6 +- .../ts/aztecjs_getting_started/index.ts | 14 +- docs/examples/ts/aztecjs_testing/index.ts | 12 +- docs/examples/ts/bob_token_contract/index.ts | 14 +- .../ts/recursive_verification/index.ts | 10 +- docs/examples/ts/token_bridge/index.ts | 12 +- .../contract/components/FunctionCard.tsx | 2 +- playground/src/hooks/useTransaction.tsx | 4 +- yarn-project/aztec.js/src/api/contract.ts | 9 +- .../src/contract/base_contract_interaction.ts | 5 +- .../aztec.js/src/contract/batch_call.test.ts | 18 +- .../aztec.js/src/contract/batch_call.ts | 11 +- .../aztec.js/src/contract/contract.test.ts | 6 +- .../contract/contract_function_interaction.ts | 28 ++- .../aztec.js/src/contract/deploy_method.ts | 63 +++--- .../src/contract/interaction_options.test.ts | 81 ++++++++ .../src/contract/interaction_options.ts | 112 ++++++++--- yarn-project/aztec.js/src/utils/authwit.ts | 42 ++-- .../aztec.js/src/wallet/wallet.test.ts | 31 ++- yarn-project/aztec.js/src/wallet/wallet.ts | 23 ++- yarn-project/aztec/src/examples/token.ts | 10 +- .../aztec/src/local-network/banana_fpc.ts | 2 +- yarn-project/bot/src/amm_bot.ts | 35 ++-- yarn-project/bot/src/bot.ts | 3 +- yarn-project/bot/src/cross_chain_bot.ts | 3 +- yarn-project/bot/src/factory.ts | 33 +++- yarn-project/bot/src/utils.ts | 6 +- .../cli-wallet/src/cmds/create_account.ts | 23 ++- yarn-project/cli-wallet/src/cmds/deploy.ts | 9 +- .../cli-wallet/src/cmds/deploy_account.ts | 23 ++- yarn-project/cli-wallet/src/cmds/send.ts | 9 +- yarn-project/cli-wallet/src/cmds/simulate.ts | 2 +- .../client_flows/account_deployments.test.ts | 4 +- .../src/bench/client_flows/amm.test.ts | 2 +- .../src/bench/client_flows/bridging.test.ts | 2 +- .../client_flows/client_flows_benchmark.ts | 62 +++--- .../bench/client_flows/deployments.test.ts | 4 +- .../bench/client_flows/storage_proof.test.ts | 4 +- .../src/bench/client_flows/transfers.test.ts | 4 +- .../src/bench/node_rpc_perf.test.ts | 4 +- .../src/bench/tx_stats_bench.test.ts | 4 +- yarn-project/end-to-end/src/bench/utils.ts | 9 +- .../e2e_local_network_example.test.ts | 24 +-- .../src/composed/e2e_persistence.test.ts | 73 ++++--- .../e2e_token_bridge_tutorial_test.test.ts | 16 +- .../src/composed/ha/e2e_ha_full.test.ts | 12 +- ...e2e_multi_validator_node_key_store.test.ts | 5 +- .../end-to-end/src/devnet/e2e_smoke.test.ts | 8 +- .../end-to-end/src/e2e_2_pxes.test.ts | 4 +- .../end-to-end/src/e2e_abi_types.test.ts | 14 +- .../src/e2e_account_contracts.test.ts | 2 +- yarn-project/end-to-end/src/e2e_amm.test.ts | 69 ++++--- .../end-to-end/src/e2e_authwit.test.ts | 4 +- .../end-to-end/src/e2e_avm_simulator.test.ts | 54 +++-- .../access_control.test.ts | 8 +- .../blacklist_token_contract_test.ts | 32 +-- .../e2e_blacklist_token_contract/burn.test.ts | 70 +++++-- .../minting.test.ts | 10 +- .../shielding.test.ts | 39 +++- .../transfer_private.test.ts | 66 +++++-- .../transfer_public.test.ts | 78 ++++++-- .../unshielding.test.ts | 30 ++- .../end-to-end/src/e2e_block_building.test.ts | 66 +++---- .../end-to-end/src/e2e_card_game.test.ts | 34 ++-- .../src/e2e_contract_updates.test.ts | 18 +- .../l1_to_l2.test.ts | 4 +- .../l2_to_l1.test.ts | 10 +- .../src/e2e_crowdfunding_and_claim.test.ts | 42 ++-- .../end-to-end/src/e2e_custom_message.test.ts | 6 +- .../contract_class_registration.test.ts | 32 +-- .../e2e_deploy_contract/deploy_method.test.ts | 45 +++-- .../src/e2e_deploy_contract/legacy.test.ts | 8 +- .../private_initialization.test.ts | 16 +- .../end-to-end/src/e2e_double_spend.test.ts | 2 +- .../epochs_invalidate_block.parallel.test.ts | 2 +- .../e2e_epochs/epochs_mbps.parallel.test.ts | 4 +- .../epochs_proof_public_cross_chain.test.ts | 6 +- .../src/e2e_escrow_contract.test.ts | 9 +- .../end-to-end/src/e2e_event_logs.test.ts | 23 ++- .../end-to-end/src/e2e_event_only.test.ts | 6 +- .../src/e2e_expiration_timestamp.test.ts | 2 +- .../src/e2e_fees/account_init.test.ts | 13 +- .../end-to-end/src/e2e_fees/failures.test.ts | 6 +- .../src/e2e_fees/fee_juice_payments.test.ts | 28 +-- .../src/e2e_fees/fee_settings.test.ts | 2 +- .../end-to-end/src/e2e_fees/fees_test.ts | 12 +- .../src/e2e_fees/gas_estimation.test.ts | 23 ++- .../src/e2e_fees/private_payments.test.ts | 20 +- .../src/e2e_fees/public_payments.test.ts | 14 +- .../src/e2e_fees/sponsored_payments.test.ts | 16 +- .../src/e2e_kernelless_simulation.test.ts | 64 +++--- yarn-project/end-to-end/src/e2e_keys.test.ts | 4 +- .../src/e2e_lending_contract.test.ts | 16 +- .../end-to-end/src/e2e_mempool_limit.test.ts | 4 +- .../e2e_multi_validator_node.test.ts | 4 +- .../end-to-end/src/e2e_multiple_blobs.test.ts | 6 +- .../src/e2e_nested_contract/importer.test.ts | 4 +- .../manual_private_enqueue.test.ts | 4 +- .../e2e_nested_contract/manual_public.test.ts | 2 +- .../nested_contract_test.ts | 10 +- yarn-project/end-to-end/src/e2e_nft.test.ts | 20 +- .../end-to-end/src/e2e_note_getter.test.ts | 21 +- .../src/e2e_offchain_effect.test.ts | 30 ++- .../end-to-end/src/e2e_orderbook.test.ts | 34 +++- .../end-to-end/src/e2e_ordering.test.ts | 4 +- .../end-to-end/src/e2e_p2p/add_rollup.test.ts | 4 +- .../end-to-end/src/e2e_p2p/p2p_network.ts | 5 +- yarn-project/end-to-end/src/e2e_p2p/shared.ts | 2 +- .../end-to-end/src/e2e_partial_notes.test.ts | 3 +- .../e2e_pending_note_hashes_contract.test.ts | 2 +- .../end-to-end/src/e2e_phase_check.test.ts | 2 +- .../src/e2e_private_voting_contract.test.ts | 4 +- .../end-to-end/src/e2e_prover/client.test.ts | 6 +- .../end-to-end/src/e2e_prover/full.test.ts | 10 +- .../end-to-end/src/e2e_pruned_blocks.test.ts | 12 +- .../e2e_public_testnet_transfer.test.ts | 10 +- yarn-project/end-to-end/src/e2e_pxe.test.ts | 2 +- .../src/e2e_scope_isolation.test.ts | 14 +- .../gov_proposal.parallel.test.ts | 11 +- .../src/e2e_sequencer/reload_keystore.test.ts | 4 +- .../end-to-end/src/e2e_simple.test.ts | 2 +- .../end-to-end/src/e2e_state_vars.test.ts | 184 +++++++++++------- .../end-to-end/src/e2e_static_calls.test.ts | 4 +- .../e2e_storage_proof.test.ts | 4 +- .../end-to-end/src/e2e_synching.test.ts | 40 ++-- .../e2e_token_contract/access_control.test.ts | 8 +- .../src/e2e_token_contract/burn.test.ts | 52 +++-- .../src/e2e_token_contract/minting.test.ts | 12 +- .../private_transfer_recursion.test.ts | 14 +- .../reading_constants.test.ts | 18 +- .../e2e_token_contract/token_contract_test.ts | 24 ++- .../src/e2e_token_contract/transfer.test.ts | 12 +- .../transfer_in_private.test.ts | 38 ++-- .../transfer_in_public.test.ts | 58 +++--- .../transfer_to_private.test.ts | 8 +- .../transfer_to_public.test.ts | 24 ++- .../src/fixtures/e2e_prover_test.ts | 16 +- yarn-project/end-to-end/src/fixtures/setup.ts | 6 +- .../end-to-end/src/fixtures/token_utils.ts | 6 +- .../writing_an_account_contract.test.ts | 4 +- .../src/shared/cross_chain_test_harness.ts | 22 ++- .../src/shared/gas_portal_test_harness.ts | 2 +- .../src/shared/submit-transactions.ts | 5 +- .../end-to-end/src/shared/uniswap_l1_l2.ts | 10 +- .../src/simulators/lending_simulator.ts | 6 +- .../src/simulators/token_simulator.ts | 8 +- .../end-to-end/src/spartan/1tps.test.ts | 21 +- .../end-to-end/src/spartan/4epochs.test.ts | 35 ++-- .../end-to-end/src/spartan/n_tps.test.ts | 4 +- .../src/spartan/n_tps_prove.test.ts | 4 +- .../end-to-end/src/spartan/reorg.test.ts | 16 +- .../src/spartan/reqresp_effectiveness.test.ts | 3 +- .../src/spartan/setup_test_wallets.ts | 17 +- .../end-to-end/src/spartan/transfer.test.ts | 29 +-- yarn-project/stdlib/src/tx/simulated_tx.ts | 9 +- .../wallet-sdk/src/base-wallet/base_wallet.ts | 12 +- 166 files changed, 2002 insertions(+), 1043 deletions(-) create mode 100644 yarn-project/aztec.js/src/contract/interaction_options.test.ts diff --git a/boxes/boxes/react/src/hooks/useContract.tsx b/boxes/boxes/react/src/hooks/useContract.tsx index 5b3c7aca373f..ff180dfa5b59 100644 --- a/boxes/boxes/react/src/hooks/useContract.tsx +++ b/boxes/boxes/react/src/hooks/useContract.tsx @@ -24,10 +24,10 @@ export function useContract() { contractAddressSalt: salt, }); - const contract = await toast.promise(deploymentPromise, { + const { contract } = await toast.promise(deploymentPromise, { pending: 'Deploying contract...', success: { - render: ({ data }) => `Address: ${data.address}`, + render: ({ data }) => `Address: ${data.contract.address}`, }, error: 'Error deploying contract', }); diff --git a/boxes/boxes/react/src/hooks/useNumber.tsx b/boxes/boxes/react/src/hooks/useNumber.tsx index 8809b6555b42..7435cf5ebfa7 100644 --- a/boxes/boxes/react/src/hooks/useNumber.tsx +++ b/boxes/boxes/react/src/hooks/useNumber.tsx @@ -11,10 +11,10 @@ export function useNumber({ contract }: { contract: Contract }) { setWait(true); const defaultAccountAddress = deployerEnv.getDefaultAccountAddress(); - const viewTxReceipt = await contract!.methods + const { result } = await contract!.methods .getNumber(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); - toast(`Number is: ${viewTxReceipt.value}`); + toast(`Number is: ${result}`); setWait(false); }; diff --git a/boxes/boxes/vanilla/app/embedded-wallet.ts b/boxes/boxes/vanilla/app/embedded-wallet.ts index 04951e383ee9..bbf32271f6b5 100644 --- a/boxes/boxes/vanilla/app/embedded-wallet.ts +++ b/boxes/boxes/vanilla/app/embedded-wallet.ts @@ -162,7 +162,7 @@ export class EmbeddedWallet extends EmbeddedWalletBase { wait: { timeout: 120 }, }; - const receipt = await deployMethod.send(deployOpts); + const { receipt } = await deployMethod.send(deployOpts); logger.info('Account deployed', receipt); diff --git a/boxes/boxes/vanilla/app/main.ts b/boxes/boxes/vanilla/app/main.ts index fa55a4cae208..ddce11af435c 100644 --- a/boxes/boxes/vanilla/app/main.ts +++ b/boxes/boxes/vanilla/app/main.ts @@ -200,7 +200,7 @@ async function updateVoteTally(wallet: Wallet, from: AztecAddress) { const batchResult = await new BatchCall(wallet, payloads).simulate({ from }); - batchResult.forEach((value, i) => { + batchResult.forEach(({ result: value }, i) => { results[i + 1] = value; }); diff --git a/boxes/boxes/vanilla/scripts/deploy.ts b/boxes/boxes/vanilla/scripts/deploy.ts index b02edaa7e6b1..e0e0f971a739 100644 --- a/boxes/boxes/vanilla/scripts/deploy.ts +++ b/boxes/boxes/vanilla/scripts/deploy.ts @@ -71,7 +71,7 @@ async function deployContract(wallet: Wallet, deployer: AztecAddress) { const sponsoredPFCContract = await getSponsoredPFCContract(); - const contract = await PrivateVotingContract.deploy(wallet, deployer).send({ + const { contract } = await PrivateVotingContract.deploy(wallet, deployer).send({ from: deployer, contractAddressSalt: salt, fee: { diff --git a/boxes/boxes/vite/src/hooks/useContract.tsx b/boxes/boxes/vite/src/hooks/useContract.tsx index 5b3c7aca373f..ff180dfa5b59 100644 --- a/boxes/boxes/vite/src/hooks/useContract.tsx +++ b/boxes/boxes/vite/src/hooks/useContract.tsx @@ -24,10 +24,10 @@ export function useContract() { contractAddressSalt: salt, }); - const contract = await toast.promise(deploymentPromise, { + const { contract } = await toast.promise(deploymentPromise, { pending: 'Deploying contract...', success: { - render: ({ data }) => `Address: ${data.address}`, + render: ({ data }) => `Address: ${data.contract.address}`, }, error: 'Error deploying contract', }); diff --git a/boxes/boxes/vite/src/hooks/useNumber.tsx b/boxes/boxes/vite/src/hooks/useNumber.tsx index 8809b6555b42..7435cf5ebfa7 100644 --- a/boxes/boxes/vite/src/hooks/useNumber.tsx +++ b/boxes/boxes/vite/src/hooks/useNumber.tsx @@ -11,10 +11,10 @@ export function useNumber({ contract }: { contract: Contract }) { setWait(true); const defaultAccountAddress = deployerEnv.getDefaultAccountAddress(); - const viewTxReceipt = await contract!.methods + const { result } = await contract!.methods .getNumber(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); - toast(`Number is: ${viewTxReceipt.value}`); + toast(`Number is: ${result}`); setWait(false); }; diff --git a/docs/docs-developers/docs/resources/migration_notes.md b/docs/docs-developers/docs/resources/migration_notes.md index cc1524e30ccc..c6ced5fa03ff 100644 --- a/docs/docs-developers/docs/resources/migration_notes.md +++ b/docs/docs-developers/docs/resources/migration_notes.md @@ -9,6 +9,97 @@ Aztec is in active development. Each version may introduce breaking changes that ## TBD +### [Aztec.js] `simulate()`, `send()`, and deploy return types changed to always return objects + +All SDK interaction methods now return structured objects that include offchain output alongside the primary result. This affects `.simulate()`, `.send()`, deploy `.send()`, and `Wallet.sendTx()`. + +**Impact**: Every call site that uses `.simulate()`, `.send()`, or deploy must destructure the result. This is a mechanical transformation. Custom wallet implementations must update `sendTx()` to return the new object shapes, using `extractOffchainOutput` to decode offchain messages from raw effects. + +The offchain output includes two fields: + +- `offchainEffects` — raw offchain effects emitted during execution, other than `offchainMessages` +- `offchainMessages` — decoded messages intended for specific recipients + +We are making this change now so in the future we can add more fields to the responses of this APIs without breaking backwards compatibility, +so this won't ever happen again. + +**`simulate()` — always returns `{ result, offchainEffects, offchainMessages }` object:** + +```diff +- const value = await contract.methods.foo(args).simulate({ from: sender }); ++ const { result: value } = await contract.methods.foo(args).simulate({ from: sender }); +``` + +When using `includeMetadata` or `fee.estimateGas`, `stats` and `estimatedGas` are also available as optional fields on the same object: + +```diff +- const { stats, estimatedGas } = await contract.methods.foo(args).simulate({ ++ const sim = await contract.methods.foo(args).simulate({ + from: sender, + includeMetadata: true, + }); ++ const stats = sim.stats!; ++ const estimatedGas = sim.estimatedGas!; +``` + +`SimulationReturn` is no longer a generic conditional type — it's a single flat type with optional `stats` and `estimatedGas` fields. + +**`send()` — returns `{ receipt, offchainEffects, offchainMessages }` object:** + +```diff +- const receipt = await contract.methods.foo(args).send({ from: sender }); ++ const { receipt } = await contract.methods.foo(args).send({ from: sender }); +``` + +When using `NO_WAIT`, returns `{ txHash, offchainEffects, offchainMessages }` instead of a bare `TxHash`: + +```diff +- const txHash = await contract.methods.foo(args).send({ from: sender, wait: NO_WAIT }); ++ const { txHash } = await contract.methods.foo(args).send({ from: sender, wait: NO_WAIT }); +``` + +Offchain messages emitted by the transaction are available on the result: + +```typescript +const { receipt, offchainMessages } = await contract.methods.foo(args).send({ from: sender }); +for (const msg of offchainMessages) { + console.log(`Message for ${msg.recipient} from contract ${msg.contractAddress}:`, msg.payload); +} +``` + +**Deploy — returns `{ contract, receipt, offchainEffects, offchainMessages }` object:** + +```diff +- const myContract = await MyContract.deploy(wallet, ...args).send({ from: sender }); ++ const { contract: myContract } = await MyContract.deploy(wallet, ...args).send({ from: sender }); +``` + +The deploy receipt is also available via `receipt` if needed (e.g. for `receipt.txHash` or `receipt.transactionFee`). + +**Custom wallet implementations — `sendTx()` must return objects:** + +If you implement the `Wallet` interface (or extend `BaseWallet`), the `sendTx()` method must now return objects that include offchain output. Use `extractOffchainOutput` to split raw effects into decoded messages and remaining effects: + +```diff ++ import { extractOffchainOutput } from '@aztec/aztec.js/contracts'; + + async sendTx(executionPayload, opts) { + const provenTx = await this.pxe.proveTx(...); ++ const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects()); + const tx = await provenTx.toTx(); + const txHash = tx.getTxHash(); + await this.aztecNode.sendTx(tx); + + if (opts.wait === NO_WAIT) { +- return txHash; ++ return { txHash, ...offchainOutput }; + } + const receipt = await waitForTx(this.aztecNode, txHash, opts.wait); +- return receipt; ++ return { receipt, ...offchainOutput }; + } +``` + ### `aztec new` crate directories are now named after the contract `aztec new` and `aztec init` now name the generated crate directories after the contract instead of using generic `contract/` and `test/` names. For example, `aztec new counter` now creates: diff --git a/docs/examples/ts/aztecjs_advanced/index.ts b/docs/examples/ts/aztecjs_advanced/index.ts index 77418ea37395..84dec7eb87d9 100644 --- a/docs/examples/ts/aztecjs_advanced/index.ts +++ b/docs/examples/ts/aztecjs_advanced/index.ts @@ -30,7 +30,7 @@ const [aliceAddress, bobAddress] = await Promise.all( // docs:start:deploy_basic_local // wallet and aliceAddress are from the connection guide // Deploy with constructor arguments -const token = await TokenContract.deploy( +const { contract: token } = await TokenContract.deploy( wallet, aliceAddress, "TestToken", @@ -49,7 +49,7 @@ await wallet.registerContract(sponsoredFPCInstance, SponsoredFPCContract.artifac const sponsoredPaymentMethod = new SponsoredFeePaymentMethod(sponsoredFPCInstance.address); // wallet is from the connection guide; sponsoredPaymentMethod is from the fees guide -const sponsoredContract = await TokenContract.deploy( +const { contract: sponsoredContract } = await TokenContract.deploy( wallet, aliceAddress, "SponsoredToken", @@ -62,7 +62,7 @@ const sponsoredContract = await TokenContract.deploy( // wallet and aliceAddress are from the connection guide const customSalt = Fr.random(); -const saltedContract = await TokenContract.deploy( +const { contract: saltedContract } = await TokenContract.deploy( wallet, aliceAddress, "SaltedToken", @@ -95,7 +95,7 @@ console.log(`Contract will deploy at: ${predictedAddress}`); // token is from the deployment step above; aliceAddress is from the connection guide try { // Try calling a view function - const balance = await token.methods + const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); console.log("Contract is callable, balance:", balance); @@ -132,7 +132,7 @@ await token.methods // docs:start:no_wait_deploy // Use NO_WAIT to get the transaction hash immediately and track deployment -const txHash = await TokenContract.deploy( +const { txHash } = await TokenContract.deploy( wallet, aliceAddress, "AnotherToken", @@ -152,7 +152,7 @@ console.log(`Deployed in block ${receipt.blockNumber}`); // docs:start:no_wait_transaction // Use NO_WAIT for regular transactions too -const transferTxHash = await token.methods +const { txHash: transferTxHash } = await token.methods .transfer(bobAddress, 100n) .send({ from: aliceAddress, wait: NO_WAIT }); @@ -170,7 +170,7 @@ const batch = new BatchCall(wallet, [ token.methods.transfer(bobAddress, 200n), ]); -const batchReceipt = await batch.send({ from: aliceAddress }); +const { receipt: batchReceipt } = await batch.send({ from: aliceAddress }); console.log(`Batch executed in block ${batchReceipt.blockNumber}`); // docs:end:batch_call @@ -197,7 +197,7 @@ console.log( // docs:start:query_tx_status // Query transaction status after sending without waiting -const statusTxHash = await token.methods +const { txHash: statusTxHash } = await token.methods .transfer(bobAddress, 10n) .send({ from: aliceAddress, wait: NO_WAIT }); @@ -211,7 +211,7 @@ console.log(`Transaction fee: ${txReceipt.transactionFee}`); // docs:start:deploy_with_dependencies // Deploy contracts with dependencies - deploy sequentially and pass addresses -const baseToken = await TokenContract.deploy( +const { contract: baseToken } = await TokenContract.deploy( wallet, aliceAddress, "BaseToken", @@ -220,7 +220,7 @@ const baseToken = await TokenContract.deploy( ).send({ from: aliceAddress }); // A second contract could reference the first (example pattern) -const derivedToken = await TokenContract.deploy( +const { contract: derivedToken } = await TokenContract.deploy( wallet, baseToken.address, // Use first contract's address as admin "DerivedToken", @@ -237,13 +237,13 @@ console.log(`Derived token at: ${derivedToken.address.toString()}`); const contracts = await Promise.all([ TokenContract.deploy(wallet, aliceAddress, "Token1", "T1", 18).send({ from: aliceAddress, - }), + }).then(({ contract }) => contract), TokenContract.deploy(wallet, aliceAddress, "Token2", "T2", 18).send({ from: aliceAddress, - }), + }).then(({ contract }) => contract), TokenContract.deploy(wallet, aliceAddress, "Token3", "T3", 18).send({ from: aliceAddress, - }), + }).then(({ contract }) => contract), ]); console.log(`Contract 1 at: ${contracts[0].address}`); @@ -253,7 +253,7 @@ console.log(`Contract 3 at: ${contracts[2].address}`); // docs:start:skip_initialization // Deploy without running the constructor using skipInitialization -const delayedToken = await TokenContract.deploy( +const { contract: delayedToken } = await TokenContract.deploy( wallet, aliceAddress, "DelayedToken", diff --git a/docs/examples/ts/aztecjs_authwit/index.ts b/docs/examples/ts/aztecjs_authwit/index.ts index ed7df03e109a..565333a38b6d 100644 --- a/docs/examples/ts/aztecjs_authwit/index.ts +++ b/docs/examples/ts/aztecjs_authwit/index.ts @@ -25,7 +25,7 @@ const [aliceAddress, bobAddress] = await Promise.all( }), ); -const tokenContract = await TokenContract.deploy( +const { contract: tokenContract } = await TokenContract.deploy( wallet, aliceAddress, "TestToken", diff --git a/docs/examples/ts/aztecjs_connection/index.ts b/docs/examples/ts/aztecjs_connection/index.ts index 827efeae1211..a014603037d9 100644 --- a/docs/examples/ts/aztecjs_connection/index.ts +++ b/docs/examples/ts/aztecjs_connection/index.ts @@ -112,7 +112,7 @@ const claim = await portalManager.bridgeTokensPublic( // docs:start:deploy_contract import { TokenContract } from "@aztec/noir-contracts.js/Token"; -const token = await TokenContract.deploy( +const { contract: token } = await TokenContract.deploy( wallet, aliceAddress, "TestToken", @@ -124,7 +124,7 @@ console.log(`Token deployed at: ${token.address.toString()}`); // docs:end:deploy_contract // docs:start:send_transaction -const receipt = await token.methods +const { receipt } = await token.methods .mint_to_public(aliceAddress, 1000n) .send({ from: aliceAddress }); @@ -133,7 +133,7 @@ console.log(`Transaction fee: ${receipt.transactionFee}`); // docs:end:send_transaction // docs:start:simulate_function -const balance = await token.methods +const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); diff --git a/docs/examples/ts/aztecjs_getting_started/index.ts b/docs/examples/ts/aztecjs_getting_started/index.ts index 6c526e4dd1da..2338115e1e4b 100644 --- a/docs/examples/ts/aztecjs_getting_started/index.ts +++ b/docs/examples/ts/aztecjs_getting_started/index.ts @@ -13,7 +13,7 @@ await wallet.createSchnorrAccount(bob.secret, bob.salt); // docs:start:deploy import { TokenContract } from "@aztec/noir-contracts.js/Token"; -const token = await TokenContract.deploy( +const { contract: token } = await TokenContract.deploy( wallet, alice.address, "TokenName", @@ -29,11 +29,11 @@ await token.methods // docs:end:mint // docs:start:check_balances -let aliceBalance = await token.methods +let { result: aliceBalance } = await token.methods .balance_of_private(alice.address) .simulate({ from: alice.address }); console.log(`Alice's balance: ${aliceBalance}`); -let bobBalance = await token.methods +let { result: bobBalance } = await token.methods .balance_of_private(bob.address) .simulate({ from: bob.address }); console.log(`Bob's balance: ${bobBalance}`); @@ -41,9 +41,9 @@ console.log(`Bob's balance: ${bobBalance}`); // docs:start:transfer await token.methods.transfer(bob.address, 10).send({ from: alice.address }); -bobBalance = await token.methods +({ result: bobBalance } = await token.methods .balance_of_private(bob.address) - .simulate({ from: bob.address }); + .simulate({ from: bob.address })); console.log(`Bob's balance: ${bobBalance}`); // docs:end:transfer @@ -55,8 +55,8 @@ await token.methods.set_minter(bob.address, true).send({ from: alice.address }); await token.methods .mint_to_private(bob.address, 100) .send({ from: bob.address }); -bobBalance = await token.methods +({ result: bobBalance } = await token.methods .balance_of_private(bob.address) - .simulate({ from: bob.address }); + .simulate({ from: bob.address })); console.log(`Bob's balance: ${bobBalance}`); // docs:end:bob_mints diff --git a/docs/examples/ts/aztecjs_testing/index.ts b/docs/examples/ts/aztecjs_testing/index.ts index 930d756b853e..827b19e5d6d5 100644 --- a/docs/examples/ts/aztecjs_testing/index.ts +++ b/docs/examples/ts/aztecjs_testing/index.ts @@ -26,7 +26,7 @@ async function setup() { }), ); - token = await TokenContract.deploy( + ({ contract: token } = await TokenContract.deploy( wallet, aliceAddress, "Test", @@ -34,7 +34,7 @@ async function setup() { 18, ).send({ from: aliceAddress, - }); + })); } // Test: mints tokens to an account @@ -43,7 +43,7 @@ async function testMintTokens() { .mint_to_public(aliceAddress, 1000n) .send({ from: aliceAddress }); - const balance = await token.methods + const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); @@ -63,10 +63,10 @@ async function testTransferTokens() { // Transfer to bob using public transfer await token.methods.transfer_in_public(aliceAddress, bobAddress, 100n, 0n).send({ from: aliceAddress }); - const aliceBalance = await token.methods + const { result: aliceBalance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); - const bobBalance = await token.methods + const { result: bobBalance } = await token.methods .balance_of_public(bobAddress) .simulate({ from: bobAddress }); @@ -77,7 +77,7 @@ async function testTransferTokens() { // Test: reverts when transferring more than balance async function testRevertOnOverTransfer() { - const balance = await token.methods + const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); diff --git a/docs/examples/ts/bob_token_contract/index.ts b/docs/examples/ts/bob_token_contract/index.ts index ec71b47da703..9b154e1279a3 100644 --- a/docs/examples/ts/bob_token_contract/index.ts +++ b/docs/examples/ts/bob_token_contract/index.ts @@ -15,16 +15,20 @@ async function getBalances( await Promise.all([ contract.methods .public_balance_of(aliceAddress) - .simulate({ from: aliceAddress }), + .simulate({ from: aliceAddress }) + .then(({ result }) => result), contract.methods .private_balance_of(aliceAddress) - .simulate({ from: aliceAddress }), + .simulate({ from: aliceAddress }) + .then(({ result }) => result), contract.methods .public_balance_of(bobAddress) - .simulate({ from: bobAddress }), + .simulate({ from: bobAddress }) + .then(({ result }) => result), contract.methods .private_balance_of(bobAddress) - .simulate({ from: bobAddress }), + .simulate({ from: bobAddress }) + .then(({ result }) => result), ]).then( ([ alicePublicBalance, @@ -69,7 +73,7 @@ async function main() { const aliceAddress = aliceAccountManager.address; const bobClinicAddress = bobClinicAccountManager.address; - const bobToken = await BobTokenContract.deploy(wallet).send({ + const { contract: bobToken } = await BobTokenContract.deploy(wallet).send({ from: giggleAddress, }); diff --git a/docs/examples/ts/recursive_verification/index.ts b/docs/examples/ts/recursive_verification/index.ts index 37597276d764..4ded9c585249 100644 --- a/docs/examples/ts/recursive_verification/index.ts +++ b/docs/examples/ts/recursive_verification/index.ts @@ -65,7 +65,7 @@ async function main() { // Step 2: Deploy ValueNotEqual contract // Constructor args: initial counter (10), owner, VK hash - const valueNotEqual = await ValueNotEqualContract.deploy( + const { contract: valueNotEqual } = await ValueNotEqualContract.deploy( wallet, 10, // Initial counter value accounts[0].item, // Owner address @@ -84,9 +84,9 @@ async function main() { // Step 3: Read initial counter value // simulate() executes without submitting a transaction - let counterValue = await valueNotEqual.methods + let counterValue = (await valueNotEqual.methods .get_counter(accounts[0].item) - .simulate({ from: accounts[0].item }); + .simulate({ from: accounts[0].item })).result; console.log(`Counter value: ${counterValue}`); // Should be 10 // Step 4: Call increment() with proof data @@ -107,9 +107,9 @@ async function main() { await interaction.send(opts); // Step 6: Read updated counter - counterValue = await valueNotEqual.methods + counterValue = (await valueNotEqual.methods .get_counter(accounts[0].item) - .simulate({ from: accounts[0].item }); + .simulate({ from: accounts[0].item })).result; console.log(`Counter value: ${counterValue}`); // Should be 11 assert(counterValue === 11n, "Counter should be 11 after verification"); diff --git a/docs/examples/ts/token_bridge/index.ts b/docs/examples/ts/token_bridge/index.ts index 74ad78653034..81c410bae820 100644 --- a/docs/examples/ts/token_bridge/index.ts +++ b/docs/examples/ts/token_bridge/index.ts @@ -69,11 +69,11 @@ console.log(`NFTPortal: ${portalAddress}\n`); // docs:start:deploy_l2_contracts console.log("Deploying L2 contracts...\n"); -const l2Nft = await NFTPunkContract.deploy(aztecWallet, account.address).send({ +const { contract: l2Nft } = await NFTPunkContract.deploy(aztecWallet, account.address).send({ from: account.address, }); -const l2Bridge = await NFTBridgeContract.deploy( +const { contract: l2Bridge } = await NFTBridgeContract.deploy( aztecWallet, l2Nft.address, ).send({ from: account.address }); @@ -222,7 +222,7 @@ await mine2Blocks(aztecWallet, account.address); // Check notes before claiming (should be 0) console.log("Checking notes before claim..."); -const notesBefore = await l2Nft.methods +const { result: notesBefore } = await l2Nft.methods .notes_of(account.address) .simulate({ from: account.address }); console.log(` Notes count: ${notesBefore}`); @@ -235,7 +235,7 @@ console.log("NFT claimed on L2\n"); // Check notes after claiming (should be 1) console.log("Checking notes after claim..."); -const notesAfterClaim = await l2Nft.methods +const { result: notesAfterClaim } = await l2Nft.methods .notes_of(account.address) .simulate({ from: account.address }); console.log(` Notes count: ${notesAfterClaim}\n`); @@ -249,7 +249,7 @@ await mine2Blocks(aztecWallet, account.address); const recipientEthAddress = EthAddress.fromString(ownerEthAddress); -const exitReceipt = await l2Bridge.methods +const { receipt: exitReceipt } = await l2Bridge.methods .exit(new Fr(Number(tokenId)), recipientEthAddress) .send({ from: account.address }); @@ -257,7 +257,7 @@ console.log(`Exit message sent (block: ${exitReceipt.blockNumber})\n`); // Check notes after burning (should be 0 again) console.log("Checking notes after burn..."); -const notesAfterBurn = await l2Nft.methods +const { result: notesAfterBurn } = await l2Nft.methods .notes_of(account.address) .simulate({ from: account.address }); console.log(` Notes count: ${notesAfterBurn}\n`); diff --git a/playground/src/components/contract/components/FunctionCard.tsx b/playground/src/components/contract/components/FunctionCard.tsx index 6f4c9e5415a2..21f3b2696b2e 100644 --- a/playground/src/components/contract/components/FunctionCard.tsx +++ b/playground/src/components/contract/components/FunctionCard.tsx @@ -90,7 +90,7 @@ export function FunctionCard({ fn, contract, contractArtifact, onSendTxRequested let result; try { const call = contract.methods[fnName](...parameters); - result = await call.simulate({ from, skipFeeEnforcement: true }); + ({ result } = await call.simulate({ from, skipFeeEnforcement: true })); const stringResult = JSON.stringify(result, (key, value) => { if (typeof value === 'bigint') { return value.toString(); diff --git a/playground/src/hooks/useTransaction.tsx b/playground/src/hooks/useTransaction.tsx index 202c6017481f..9f1e6832e6c2 100644 --- a/playground/src/hooks/useTransaction.tsx +++ b/playground/src/hooks/useTransaction.tsx @@ -47,10 +47,10 @@ export function useTransaction() { if (interaction instanceof DeployMethod) { const { from, fee, ...deployOpts } = opts as DeployOptions; - txHash = await interaction.send({ from, fee, ...deployOpts, wait: NO_WAIT }); + ({ txHash } = await interaction.send({ from, fee, ...deployOpts, wait: NO_WAIT })); } else { const { from, fee, authWitnesses, capsules } = opts as SendInteractionOptions; - txHash = await interaction.send({ from, fee, authWitnesses, capsules, wait: NO_WAIT }); + ({ txHash } = await interaction.send({ from, fee, authWitnesses, capsules, wait: NO_WAIT })); } setCurrentTx({ diff --git a/yarn-project/aztec.js/src/api/contract.ts b/yarn-project/aztec.js/src/api/contract.ts index d3e9a692c67f..37481a99f94f 100644 --- a/yarn-project/aztec.js/src/api/contract.ts +++ b/yarn-project/aztec.js/src/api/contract.ts @@ -48,6 +48,8 @@ export { ContractFunctionInteraction } from '../contract/contract_function_inter export { NO_WAIT, type NoWait, + type OffchainMessage, + type OffchainOutput, type RequestInteractionOptions, type SendInteractionOptions, type ProfileInteractionOptions, @@ -56,7 +58,11 @@ export { type InteractionWaitOptions, type GasSettingsOption, type SendReturn, - type SimulationReturn, + type SimulationResult, + type TxSendResultImmediate, + type TxSendResultMined, + emptyOffchainOutput, + extractOffchainOutput, toProfileOptions, toSendOptions, toSimulateOptions, @@ -67,6 +73,7 @@ export { ContractBase, type ContractMethod, type ContractStorageLayout } from '. export { BatchCall } from '../contract/batch_call.js'; export { type DeployOptions, + type DeployResultMined, type DeployReturn, type DeployTxReceipt, type DeployWaitOptions, diff --git a/yarn-project/aztec.js/src/contract/base_contract_interaction.ts b/yarn-project/aztec.js/src/contract/base_contract_interaction.ts index 8e47f1eb7cfe..12983df3a0ea 100644 --- a/yarn-project/aztec.js/src/contract/base_contract_interaction.ts +++ b/yarn-project/aztec.js/src/contract/base_contract_interaction.ts @@ -9,6 +9,7 @@ import { type SendInteractionOptions, type SendInteractionOptionsWithoutWait, type SendReturn, + type TxSendResultMined, toSendOptions, } from './interaction_options.js'; @@ -41,8 +42,8 @@ export abstract class BaseContractInteraction { * the AztecAddress of the sender, optional fee configuration, and optional wait settings * @returns TReturn (if wait is undefined/WaitOpts) or TxHash (if wait is NO_WAIT) */ - // Overload for when wait is not specified at all - returns TReturn - public send(options: SendInteractionOptionsWithoutWait): Promise; + // Overload for when wait is not specified at all - returns { receipt: TReturn, offchainEffects } + public send(options: SendInteractionOptionsWithoutWait): Promise>; // Generic overload for explicit wait values // eslint-disable-next-line jsdoc/require-jsdoc public send( diff --git a/yarn-project/aztec.js/src/contract/batch_call.test.ts b/yarn-project/aztec.js/src/contract/batch_call.test.ts index 976884e68745..bcb976b1729c 100644 --- a/yarn-project/aztec.js/src/contract/batch_call.test.ts +++ b/yarn-project/aztec.js/src/contract/batch_call.test.ts @@ -119,6 +119,7 @@ describe('BatchCall', () => { nested: [{ values: privateReturnValues }], } as any); txSimResult.getPublicReturnValues.mockReturnValue([{ values: publicReturnValues }] as any); + Object.defineProperty(txSimResult, 'offchainEffects', { value: [] }); // Mock wallet.batch to return both utility results and simulateTx result wallet.batch.mockResolvedValue([ @@ -166,13 +167,13 @@ describe('BatchCall', () => { expect(results).toHaveLength(4); // First utility - decoded from Fr[] to bigint (single field returns the value directly, not as array) - expect(results[0]).toEqual(utilityResult1.result[0].toBigInt()); + expect(results[0].result).toEqual(utilityResult1.result[0].toBigInt()); // Results[1] will be the decoded private values (decoded from privateReturnValues) - expect(results[1]).toEqual(privateReturnValues.map(v => v.toBigInt())); // Private call (decoded) + expect(results[1].result).toEqual(privateReturnValues.map(v => v.toBigInt())); // Private call (decoded) // Second utility - decoded from Fr[] to bigint - expect(results[2]).toEqual(utilityResult2.result[0].toBigInt()); + expect(results[2].result).toEqual(utilityResult2.result[0].toBigInt()); // Results[3] will be the decoded public value (single value is returned directly, not as array) - expect(results[3]).toEqual(publicReturnValues[0].toBigInt()); // Public call (decoded) + expect(results[3].result).toEqual(publicReturnValues[0].toBigInt()); // Public call (decoded) }); it('should handle only utility calls without calling simulateTx', async () => { @@ -215,8 +216,8 @@ describe('BatchCall', () => { // Verify results - decoded from Fr[] to bigint expect(results).toHaveLength(2); - expect(results[0]).toEqual(utilityResult1.result[0].toBigInt()); - expect(results[1]).toEqual(utilityResult2.result[0].toBigInt()); + expect(results[0].result).toEqual(utilityResult1.result[0].toBigInt()); + expect(results[1].result).toEqual(utilityResult2.result[0].toBigInt()); }); it('should handle only private/public calls using wallet.batch with simulateTx', async () => { @@ -236,6 +237,7 @@ describe('BatchCall', () => { nested: [{ values: privateReturnValues }], } as any); txSimResult.getPublicReturnValues.mockReturnValue([{ values: publicReturnValues }] as any); + Object.defineProperty(txSimResult, 'offchainEffects', { value: [] }); wallet.batch.mockResolvedValue([{ name: 'simulateTx', result: txSimResult }] as any); @@ -259,8 +261,8 @@ describe('BatchCall', () => { // Verify results (decoded) expect(results).toHaveLength(2); - expect(results[0]).toEqual(privateReturnValues[0].toBigInt()); // Single value returned directly - expect(results[1]).toEqual(publicReturnValues[0].toBigInt()); // Single value returned directly + expect(results[0].result).toEqual(privateReturnValues[0].toBigInt()); // Single value returned directly + expect(results[1].result).toEqual(publicReturnValues[0].toBigInt()); // Single value returned directly }); it('should handle empty batch', async () => { diff --git a/yarn-project/aztec.js/src/contract/batch_call.ts b/yarn-project/aztec.js/src/contract/batch_call.ts index cd112be6f59b..c1d5d183880c 100644 --- a/yarn-project/aztec.js/src/contract/batch_call.ts +++ b/yarn-project/aztec.js/src/contract/batch_call.ts @@ -6,6 +6,7 @@ import { BaseContractInteraction } from './base_contract_interaction.js'; import { type RequestInteractionOptions, type SimulateInteractionOptions, + extractOffchainOutput, toSimulateOptions, } from './interaction_options.js'; @@ -108,7 +109,10 @@ export class BatchCall extends BaseContractInteraction { const wrappedResult = batchResults[i]; if (wrappedResult.name === 'executeUtility') { const rawReturnValues = (wrappedResult.result as UtilityExecutionResult).result; - results[resultIndex] = rawReturnValues ? decodeFromAbi(call.returnTypes, rawReturnValues) : []; + results[resultIndex] = { + result: rawReturnValues ? decodeFromAbi(call.returnTypes, rawReturnValues) : [], + offchainEffects: [], + }; } } @@ -127,7 +131,10 @@ export class BatchCall extends BaseContractInteraction { ? simulatedTx.getPrivateReturnValues()?.nested?.[resultIndex].values : simulatedTx.getPublicReturnValues()?.[resultIndex].values; - results[callIndex] = rawReturnValues ? decodeFromAbi(call.returnTypes, rawReturnValues) : []; + results[callIndex] = { + result: rawReturnValues ? decodeFromAbi(call.returnTypes, rawReturnValues) : [], + ...extractOffchainOutput(simulatedTx.offchainEffects), + }; }); } } diff --git a/yarn-project/aztec.js/src/contract/contract.test.ts b/yarn-project/aztec.js/src/contract/contract.test.ts index 28005f6ecbfc..36519b918f7c 100644 --- a/yarn-project/aztec.js/src/contract/contract.test.ts +++ b/yarn-project/aztec.js/src/contract/contract.test.ts @@ -136,7 +136,7 @@ describe('Contract Class', () => { wallet.simulateTx.mockResolvedValue(mockTxSimulationResult); account.createTxExecutionRequest.mockResolvedValue(mockTxRequest); wallet.registerContract.mockResolvedValue(contractInstance); - wallet.sendTx.mockResolvedValue(mockTxReceipt); + wallet.sendTx.mockResolvedValue({ receipt: mockTxReceipt, offchainEffects: [], offchainMessages: [] }); wallet.executeUtility.mockResolvedValue(mockUtilityResultValue); }); @@ -144,7 +144,7 @@ describe('Contract Class', () => { const fooContract = Contract.at(contractAddress, defaultArtifact, wallet); const param0 = 12; const param1 = 345n; - const receipt = await fooContract.methods.bar(param0, param1).send({ from: account.getAddress() }); + const { receipt } = await fooContract.methods.bar(param0, param1).send({ from: account.getAddress() }); expect(receipt).toBe(mockTxReceipt); expect(wallet.sendTx).toHaveBeenCalledTimes(1); @@ -152,7 +152,7 @@ describe('Contract Class', () => { it('should call view on a utility function', async () => { const fooContract = Contract.at(contractAddress, defaultArtifact, wallet); - const result = await fooContract.methods.qux(123n).simulate({ from: account.getAddress() }); + const { result } = await fooContract.methods.qux(123n).simulate({ from: account.getAddress() }); expect(wallet.executeUtility).toHaveBeenCalledTimes(1); expect(wallet.executeUtility).toHaveBeenCalledWith( expect.objectContaining({ name: 'qux', to: contractAddress }), diff --git a/yarn-project/aztec.js/src/contract/contract_function_interaction.ts b/yarn-project/aztec.js/src/contract/contract_function_interaction.ts index a087d85f0525..30d553d55151 100644 --- a/yarn-project/aztec.js/src/contract/contract_function_interaction.ts +++ b/yarn-project/aztec.js/src/contract/contract_function_interaction.ts @@ -8,7 +8,7 @@ import { } from '@aztec/stdlib/abi'; import type { AuthWitness } from '@aztec/stdlib/auth-witness'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; -import { type Capsule, type HashedValues, type TxProfileResult, collectOffchainEffects } from '@aztec/stdlib/tx'; +import type { Capsule, HashedValues, TxProfileResult } from '@aztec/stdlib/tx'; import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx'; import type { Wallet } from '../wallet/wallet.js'; @@ -18,7 +18,9 @@ import { type ProfileInteractionOptions, type RequestInteractionOptions, type SimulateInteractionOptions, - type SimulationReturn, + type SimulationResult, + emptyOffchainOutput, + extractOffchainOutput, toProfileOptions, toSimulateOptions, } from './interaction_options.js'; @@ -97,17 +99,9 @@ export class ContractFunctionInteraction extends BaseContractInteraction { * function or a rich object containing extra metadata, such as estimated gas costs (if requested via options), * execution statistics and emitted offchain effects */ - public async simulate( - options: T, - ): Promise['estimateGas']>>; - // eslint-disable-next-line jsdoc/require-jsdoc - public async simulate( - options: T, - ): Promise>; - // eslint-disable-next-line jsdoc/require-jsdoc public async simulate( - options: SimulateInteractionOptions, - ): Promise> { + options: SimulateInteractionOptions = {} as SimulateInteractionOptions, + ): Promise { // docs:end:simulate if (this.functionDao.functionType == FunctionType.UTILITY) { const call = await this.getFunctionCall(); @@ -122,11 +116,11 @@ export class ContractFunctionInteraction extends BaseContractInteraction { if (options.includeMetadata) { return { stats: utilityResult.stats, + ...emptyOffchainOutput(), result: returnValue, }; - } else { - return returnValue; } + return { result: returnValue, ...emptyOffchainOutput() }; } const executionPayload = await this.request(options); @@ -148,6 +142,7 @@ export class ContractFunctionInteraction extends BaseContractInteraction { } const returnValue = rawReturnValues ? decodeFromAbi(this.functionDao.returnTypes, rawReturnValues) : []; + const offchainOutput = extractOffchainOutput(simulatedTx.offchainEffects); if (options.includeMetadata || options.fee?.estimateGas) { const { gasLimits, teardownGasLimits } = getGasLimits(simulatedTx, options.fee?.estimatedGasPadding); @@ -156,13 +151,12 @@ export class ContractFunctionInteraction extends BaseContractInteraction { ); return { stats: simulatedTx.stats, - offchainEffects: collectOffchainEffects(simulatedTx.privateExecutionResult), + ...offchainOutput, result: returnValue, estimatedGas: { gasLimits, teardownGasLimits }, }; - } else { - return returnValue; } + return { result: returnValue, ...offchainOutput }; } /** diff --git a/yarn-project/aztec.js/src/contract/deploy_method.ts b/yarn-project/aztec.js/src/contract/deploy_method.ts index c91e54b34dbd..98249acefed4 100644 --- a/yarn-project/aztec.js/src/contract/deploy_method.ts +++ b/yarn-project/aztec.js/src/contract/deploy_method.ts @@ -9,14 +9,7 @@ import { getContractInstanceFromInstantiationParams, } from '@aztec/stdlib/contract'; import type { PublicKeys } from '@aztec/stdlib/keys'; -import { - type Capsule, - HashedValues, - TxHash, - type TxProfileResult, - type TxReceipt, - collectOffchainEffects, -} from '@aztec/stdlib/tx'; +import { type Capsule, HashedValues, type TxProfileResult, type TxReceipt } from '@aztec/stdlib/tx'; import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx'; import { publishContractClass } from '../deployment/publish_class.js'; @@ -29,11 +22,15 @@ import { getGasLimits } from './get_gas_limits.js'; import { NO_WAIT, type NoWait, + type OffchainOutput, type ProfileInteractionOptions, type RequestInteractionOptions, type SendInteractionOptionsWithoutWait, type SimulationInteractionFeeOptions, - type SimulationReturn, + type SimulationResult, + type TxSendResultImmediate, + type TxSendResultMined, + extractOffchainOutput, toProfileOptions, toSendOptions, toSimulateOptions, @@ -130,20 +127,32 @@ export type DeployTxReceipt = TxR instance: ContractInstanceWithAddress; }; +/** Wait options that request a full receipt instead of just the contract instance. */ +type WaitWithReturnReceipt = { + /** Request the full receipt instead of just the contract instance. */ + returnReceipt: true; +}; + /** * Represents the result type of deploying a contract. * - If wait is NO_WAIT, returns TxHash immediately. * - If wait has returnReceipt: true, returns DeployTxReceipt after waiting. * - Otherwise (undefined or DeployWaitOptions without returnReceipt), returns TContract after waiting. */ +/** Result of deploying a contract when waiting for mining (default case). */ +export type DeployResultMined = { + /** The deployed contract instance. */ + contract: TContract; + /** The deploy transaction receipt. */ + receipt: DeployTxReceipt; +} & OffchainOutput; + +/** Conditional return type for deploy based on wait options. */ export type DeployReturn = W extends NoWait - ? TxHash - : W extends { - // eslint-disable-next-line jsdoc/require-jsdoc - returnReceipt: true; - } - ? DeployTxReceipt - : TContract; + ? TxSendResultImmediate + : W extends WaitWithReturnReceipt + ? TxSendResultMined> + : DeployResultMined; /** * Contract interaction for deployment. @@ -343,8 +352,7 @@ export class DeployMethod extends * @returns TxHash (if wait is NO_WAIT), TContract (if wait is undefined or doesn't have returnReceipt), or DeployTxReceipt (if wait.returnReceipt is true) */ // Overload for when wait is not specified at all - returns the contract - public override send(options: DeployOptionsWithoutWait): Promise; - // Generic overload for explicit wait values + public override send(options: DeployOptionsWithoutWait): Promise>; // eslint-disable-next-line jsdoc/require-jsdoc public override send( options: DeployOptions, @@ -355,12 +363,15 @@ export class DeployMethod extends const sendOptions = this.convertDeployOptionsToSendOptions(options); if (options.wait === NO_WAIT) { - const txHash = await this.wallet.sendTx(executionPayload, sendOptions as SendOptions); - this.log.debug(`Sent deployment tx ${txHash.hash} of ${this.artifact.name} contract`); - return txHash; + const result = await this.wallet.sendTx(executionPayload, sendOptions as SendOptions); + this.log.debug(`Sent deployment tx ${result.txHash.hash} of ${this.artifact.name} contract`); + return result; } - const receipt = await this.wallet.sendTx(executionPayload, sendOptions as SendOptions); + const { receipt, ...offchainOutput } = await this.wallet.sendTx( + executionPayload, + sendOptions as SendOptions, + ); this.log.debug(`Deployed ${this.artifact.name} contract in tx ${receipt.txHash}`); // Attach contract instance @@ -369,10 +380,10 @@ export class DeployMethod extends // Return full receipt if requested, otherwise just the contract if (options.wait && typeof options.wait === 'object' && options.wait.returnReceipt) { - return { ...receipt, contract, instance }; + return { receipt: { ...receipt, contract, instance }, ...offchainOutput }; } - return contract; + return { contract, receipt, ...offchainOutput }; } /** @@ -401,7 +412,7 @@ export class DeployMethod extends * @returns A simulation result object containing metadata of the execution, including gas * estimations (if requested via options), execution statistics and emitted offchain effects */ - public async simulate(options: SimulateDeployOptions): Promise> { + public async simulate(options: SimulateDeployOptions): Promise { const executionPayload = await this.request(this.convertDeployOptionsToRequestOptions(options)); const simulatedTx = await this.wallet.simulateTx( executionPayload, @@ -414,7 +425,7 @@ export class DeployMethod extends ); return { stats: simulatedTx.stats!, - offchainEffects: collectOffchainEffects(simulatedTx.privateExecutionResult), + ...extractOffchainOutput(simulatedTx.offchainEffects), result: undefined, estimatedGas: { gasLimits, teardownGasLimits }, }; diff --git a/yarn-project/aztec.js/src/contract/interaction_options.test.ts b/yarn-project/aztec.js/src/contract/interaction_options.test.ts new file mode 100644 index 000000000000..7818299a3854 --- /dev/null +++ b/yarn-project/aztec.js/src/contract/interaction_options.test.ts @@ -0,0 +1,81 @@ +import { Fr } from '@aztec/foundation/curves/bn254'; +import { AztecAddress } from '@aztec/stdlib/aztec-address'; +import { OFFCHAIN_MESSAGE_IDENTIFIER, type OffchainEffect } from '@aztec/stdlib/tx'; + +import { extractOffchainOutput } from './interaction_options.js'; + +describe('extractOffchainOutput', () => { + const makeEffect = (data: Fr[], contractAddress?: AztecAddress): OffchainEffect => ({ + data, + contractAddress: contractAddress ?? AztecAddress.fromField(Fr.random()), + }); + + const makeMessageEffect = async (recipient?: AztecAddress, payload?: Fr[], contractAddress?: AztecAddress) => + makeEffect( + [ + OFFCHAIN_MESSAGE_IDENTIFIER, + (recipient ?? (await AztecAddress.random())).toField(), + ...(payload ?? [Fr.random()]), + ], + contractAddress, + ); + + it('returns empty output for empty input', () => { + const result = extractOffchainOutput([]); + expect(result.offchainEffects).toEqual([]); + expect(result.offchainMessages).toEqual([]); + }); + + it('keeps non-message effects as-is', () => { + const effects = [makeEffect([Fr.random(), Fr.random()]), makeEffect([Fr.random()])]; + const result = extractOffchainOutput(effects); + expect(result.offchainEffects).toEqual(effects); + expect(result.offchainMessages).toEqual([]); + }); + + it('extracts a message effect into offchainMessages', async () => { + const recipient = await AztecAddress.random(); + const payload = [Fr.random(), Fr.random(), Fr.random()]; + const contractAddress = await AztecAddress.random(); + const effect = await makeMessageEffect(recipient, payload, contractAddress); + + const result = extractOffchainOutput([effect]); + + expect(result.offchainEffects).toEqual([]); + expect(result.offchainMessages).toHaveLength(1); + expect(result.offchainMessages[0]).toEqual({ + recipient, + payload, + contractAddress, + }); + }); + + it('splits a mixed array of effects and messages', async () => { + const plainEffect1 = makeEffect([Fr.random()]); + const plainEffect2 = makeEffect([Fr.random(), Fr.random()]); + const messageEffect = await makeMessageEffect(); + + const result = extractOffchainOutput([plainEffect1, messageEffect, plainEffect2]); + + expect(result.offchainEffects).toEqual([plainEffect1, plainEffect2]); + expect(result.offchainMessages).toHaveLength(1); + }); + + it('handles multiple message effects', async () => { + const msg1 = await makeMessageEffect(); + const msg2 = await makeMessageEffect(); + + const result = extractOffchainOutput([msg1, msg2]); + + expect(result.offchainEffects).toEqual([]); + expect(result.offchainMessages).toHaveLength(2); + }); + + it('does not treat an effect as a message if data has only the identifier (no recipient)', () => { + const effect = makeEffect([OFFCHAIN_MESSAGE_IDENTIFIER]); + const result = extractOffchainOutput([effect]); + + expect(result.offchainEffects).toEqual([effect]); + expect(result.offchainMessages).toEqual([]); + }); +}); diff --git a/yarn-project/aztec.js/src/contract/interaction_options.ts b/yarn-project/aztec.js/src/contract/interaction_options.ts index b3655f825fa2..2554f944d9a0 100644 --- a/yarn-project/aztec.js/src/contract/interaction_options.ts +++ b/yarn-project/aztec.js/src/contract/interaction_options.ts @@ -1,8 +1,16 @@ +import type { Fr } from '@aztec/foundation/curves/bn254'; import type { FieldsOf } from '@aztec/foundation/types'; import type { AuthWitness } from '@aztec/stdlib/auth-witness'; -import type { AztecAddress } from '@aztec/stdlib/aztec-address'; +import { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { GasSettings } from '@aztec/stdlib/gas'; -import type { Capsule, OffchainEffect, SimulationStats, TxHash, TxReceipt } from '@aztec/stdlib/tx'; +import { + type Capsule, + OFFCHAIN_MESSAGE_IDENTIFIER, + type OffchainEffect, + type SimulationStats, + type TxHash, + type TxReceipt, +} from '@aztec/stdlib/tx'; import type { FeePaymentMethod } from '../fee/fee_payment_method.js'; import type { ProfileOptions, SendOptions, SimulateOptions } from '../wallet/index.js'; @@ -116,8 +124,8 @@ export type SimulateInteractionOptions = Omit & { skipTxValidation?: boolean; /** Whether to ensure the fee payer is not empty and has enough balance to pay for the fee. */ skipFeeEnforcement?: boolean; - /** Whether to include metadata such as offchain effects and performance statistics (e.g. timing information of the different circuits and oracles) in - * the simulation result, instead of just the return value of the function */ + /** Whether to include metadata such as performance statistics (e.g. timing information of the different circuits and oracles) and gas estimation + * in the simulation result, in addition to the return value and offchain effects */ includeMetadata?: boolean; }; @@ -131,31 +139,89 @@ export type ProfileInteractionOptions = SimulateInteractionOptions & { skipProofGeneration?: boolean; }; +/** A message emitted during execution or proving, to be delivered offchain. */ +export type OffchainMessage = { + /** The intended recipient of the message. */ + recipient: AztecAddress; + /** The message payload (typically encrypted). */ + payload: Fr[]; + /** The contract that emitted the message. */ + contractAddress: AztecAddress; +}; + +/** Groups all unproven outputs from private execution that are returned to the client. */ +export type OffchainOutput = { + /** Raw offchain effects emitted during execution. */ + offchainEffects: OffchainEffect[]; + /** Messages emitted during execution, to be delivered offchain. */ + offchainMessages: OffchainMessage[]; +}; + /** - * Represents the result type of a simulation. - * By default, it will just be the return value of the simulated function - * If `includeMetadata` is set to true in `SimulateInteractionOptions` on the input of `simulate(...)`, - * it will provide extra information. - */ -export type SimulationReturn = T extends true - ? { - /** Additional stats about the simulation */ - stats: SimulationStats; - /** Offchain effects generated during the simulation */ - offchainEffects: OffchainEffect[]; - /** Return value of the function */ - result: any; - /** Gas estimation results */ - estimatedGas: Pick; + * Splits an array of offchain effects into decoded offchain messages and remaining effects. + * Effects whose data starts with `OFFCHAIN_MESSAGE_IDENTIFIER` are parsed as messages and removed + * from the effects array. + */ +export function extractOffchainOutput(effects: OffchainEffect[]): OffchainOutput { + const offchainEffects: OffchainEffect[] = []; + const offchainMessages: OffchainMessage[] = []; + + for (const effect of effects) { + if (effect.data.length >= 2 && effect.data[0].equals(OFFCHAIN_MESSAGE_IDENTIFIER)) { + offchainMessages.push({ + recipient: AztecAddress.fromField(effect.data[1]), + payload: effect.data.slice(2), + contractAddress: effect.contractAddress, + }); + } else { + offchainEffects.push(effect); } - : any; + } + + return { offchainEffects, offchainMessages }; +} + +/** + * Returns an empty `OffchainOutput` (no effects, no messages). + */ +export function emptyOffchainOutput(): OffchainOutput { + return { offchainEffects: [], offchainMessages: [] }; +} + +/** + * Represents the result of a simulation. + * Always includes the return value and offchain output. + * When `includeMetadata` or `fee.estimateGas` is set, also includes stats and gas estimation. + */ +export type SimulationResult = { + /** Return value of the function */ + result: any; + /** Additional stats about the simulation. Present when `includeMetadata` is set. */ + stats?: SimulationStats; + /** Gas estimation results. Present when `includeMetadata` or `fee.estimateGas` is set. */ + estimatedGas?: Pick; +} & OffchainOutput; + +/** Result of sendTx when not waiting for mining. */ +export type TxSendResultImmediate = { + /** The hash of the sent transaction. */ + txHash: TxHash; +} & OffchainOutput; + +/** Result of sendTx when waiting for mining. */ +export type TxSendResultMined = { + /** The transaction receipt. */ + receipt: TReturn; +} & OffchainOutput; /** * Represents the result type of sending a transaction. - * If `wait` is NO_WAIT, returns TxHash immediately without waiting. - * If `wait` is undefined or WaitOpts, returns TReturn (defaults to TxReceipt) after waiting. + * If `wait` is NO_WAIT, returns TxSendResultImmediate. + * Otherwise returns TxSendResultMined. */ -export type SendReturn = T extends NoWait ? TxHash : TReturn; +export type SendReturn = T extends NoWait + ? TxSendResultImmediate + : TxSendResultMined; /** * Transforms and cleans up the higher level SendInteractionOptions defined by the interaction into diff --git a/yarn-project/aztec.js/src/utils/authwit.ts b/yarn-project/aztec.js/src/utils/authwit.ts index d0d8b9f1c088..67ac5edf627c 100644 --- a/yarn-project/aztec.js/src/utils/authwit.ts +++ b/yarn-project/aztec.js/src/utils/authwit.ts @@ -5,7 +5,7 @@ import { type ABIParameterVisibility, type FunctionAbi, type FunctionCall, Funct import { AuthWitness, computeInnerAuthWitHash, computeOuterAuthWitHash } from '@aztec/stdlib/auth-witness'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import { computeVarArgsHash } from '@aztec/stdlib/hash'; -import type { TxHash, TxProfileResult, TxReceipt } from '@aztec/stdlib/tx'; +import type { TxProfileResult } from '@aztec/stdlib/tx'; import { ContractFunctionInteraction } from '../contract/contract_function_interaction.js'; import type { @@ -15,7 +15,8 @@ import type { SendInteractionOptionsWithoutWait, SendReturn, SimulateInteractionOptions, - SimulationReturn, + SimulationResult, + TxSendResultMined, } from '../contract/interaction_options.js'; import type { Wallet } from '../wallet/index.js'; @@ -189,10 +190,12 @@ export async function lookupValidity( errorTypes: {}, } as FunctionAbi; try { - results.isValidInPrivate = (await new ContractFunctionInteraction(wallet, onBehalfOf, lookupValidityAbi, [ - consumer, - innerHash, - ]).simulate({ from: onBehalfOf, authWitnesses: [witness] })) as boolean; + results.isValidInPrivate = ( + await new ContractFunctionInteraction(wallet, onBehalfOf, lookupValidityAbi, [consumer, innerHash]).simulate({ + from: onBehalfOf, + authWitnesses: [witness], + }) + ).result as boolean; // TODO: Narrow down the error to make sure simulation failed due to an invalid authwit // eslint-disable-next-line no-empty } catch {} @@ -219,12 +222,12 @@ export async function lookupValidity( returnTypes: [{ kind: 'boolean' }], errorTypes: {}, } as FunctionAbi; - results.isValidInPublic = (await new ContractFunctionInteraction( - wallet, - ProtocolContractAddress.AuthRegistry, - isConsumableAbi, - [onBehalfOf, messageHash], - ).simulate({ from: onBehalfOf })) as boolean; + results.isValidInPublic = ( + await new ContractFunctionInteraction(wallet, ProtocolContractAddress.AuthRegistry, isConsumableAbi, [ + onBehalfOf, + messageHash, + ]).simulate({ from: onBehalfOf }) + ).result as boolean; return results; } @@ -262,14 +265,10 @@ export class SetPublicAuthwitContractInteraction extends ContractFunctionInterac * @param options - An optional object containing additional configuration for the transaction. * @returns The result of the transaction as returned by the contract function. */ - public override simulate( - options: Omit, - ): Promise>; - // eslint-disable-next-line jsdoc/require-jsdoc public override simulate( - options: Omit = {}, - ): Promise> { - return super.simulate({ ...options, from: this.from }); + options: Omit = {} as Omit, + ): Promise { + return super.simulate({ ...options, from: this.from } as SimulateInteractionOptions); } /** @@ -290,8 +289,7 @@ export class SetPublicAuthwitContractInteraction extends ContractFunctionInterac * @param options - An optional object containing 'fee' options information * @returns A TxReceipt (if wait is true/undefined) or TxHash (if wait is false) */ - // Overload for when wait is not specified at all - returns TxReceipt - public override send(options?: Omit): Promise; + public override send(options?: Omit): Promise; // Generic overload for explicit wait values // eslint-disable-next-line jsdoc/require-jsdoc public override send( @@ -300,7 +298,7 @@ export class SetPublicAuthwitContractInteraction extends ContractFunctionInterac // eslint-disable-next-line jsdoc/require-jsdoc public override send( options?: Omit, 'from'>, - ): Promise { + ): Promise> { return super.send({ ...options, from: this.from }); } diff --git a/yarn-project/aztec.js/src/wallet/wallet.test.ts b/yarn-project/aztec.js/src/wallet/wallet.test.ts index 298f279b07b3..44e11dc8f9a9 100644 --- a/yarn-project/aztec.js/src/wallet/wallet.test.ts +++ b/yarn-project/aztec.js/src/wallet/wallet.test.ts @@ -11,6 +11,7 @@ import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract'; import { PublicKeys } from '@aztec/stdlib/keys'; import { ExecutionPayload, + type OffchainEffect, TxHash, TxProfileResult, TxReceipt, @@ -18,7 +19,12 @@ import { UtilityExecutionResult, } from '@aztec/stdlib/tx'; -import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '../contract/interaction_options.js'; +import { + type InteractionWaitOptions, + NO_WAIT, + type OffchainMessage, + type SendReturn, +} from '../contract/interaction_options.js'; import type { AppCapabilities, WalletCapabilities } from './capabilities.js'; import type { Aliased, @@ -209,12 +215,14 @@ describe('WalletSchema', () => { const resultWithWait = await context.client.sendTx(exec, { from: await AztecAddress.random(), }); - expect(resultWithWait).toBeInstanceOf(TxReceipt); + expect(resultWithWait.receipt).toBeInstanceOf(TxReceipt); + expect(resultWithWait.offchainEffects).toEqual([]); const resultWithoutWait = await context.client.sendTx(exec, { from: await AztecAddress.random(), wait: NO_WAIT, }); - expect(resultWithoutWait).toBeInstanceOf(TxHash); + expect(resultWithoutWait.txHash).toBeInstanceOf(TxHash); + expect(resultWithoutWait.offchainEffects).toEqual([]); }); it('createAuthWit', async () => { @@ -363,7 +371,10 @@ describe('WalletSchema', () => { expect(results[8]).toEqual({ name: 'simulateTx', result: expect.any(TxSimulationResult) }); expect(results[9]).toEqual({ name: 'executeUtility', result: expect.any(UtilityExecutionResult) }); expect(results[10]).toEqual({ name: 'profileTx', result: expect.any(TxProfileResult) }); - expect(results[11]).toEqual({ name: 'sendTx', result: expect.any(TxReceipt) }); + expect(results[11]).toEqual({ + name: 'sendTx', + result: { receipt: expect.any(TxReceipt), offchainEffects: [], offchainMessages: [] }, + }); expect(results[12]).toEqual({ name: 'createAuthWit', result: expect.any(AuthWitness) }); }); }); @@ -456,9 +467,17 @@ class MockWallet implements Wallet { opts: SendOptions, ): Promise> { if (opts.wait === NO_WAIT) { - return Promise.resolve(TxHash.random()) as Promise>; + return Promise.resolve({ + txHash: TxHash.random(), + offchainEffects: [] as OffchainEffect[], + offchainMessages: [] as OffchainMessage[], + }) as Promise>; } - return Promise.resolve(TxReceipt.empty()) as Promise>; + return Promise.resolve({ + receipt: TxReceipt.empty(), + offchainEffects: [] as OffchainEffect[], + offchainMessages: [] as OffchainMessage[], + }) as Promise>; } createAuthWit(_from: AztecAddress, _messageHashOrIntent: any): Promise { diff --git a/yarn-project/aztec.js/src/wallet/wallet.ts b/yarn-project/aztec.js/src/wallet/wallet.ts index f4c3c296ee5b..0e48f2f42726 100644 --- a/yarn-project/aztec.js/src/wallet/wallet.ts +++ b/yarn-project/aztec.js/src/wallet/wallet.ts @@ -492,6 +492,22 @@ export const WalletCapabilitiesSchema = z.object({ expiresAt: optional(z.number()), }); +const OffchainEffectSchema = z.object({ + data: z.array(schemas.Fr), + contractAddress: schemas.AztecAddress, +}); + +const OffchainMessageSchema = z.object({ + recipient: schemas.AztecAddress, + payload: z.array(schemas.Fr), + contractAddress: schemas.AztecAddress, +}); + +const OffchainOutputSchema = z.object({ + offchainEffects: z.array(OffchainEffectSchema), + offchainMessages: z.array(OffchainMessageSchema), +}); + /** * Record of all wallet method schemas (excluding batch). * This is the single source of truth for method schemas - batch schemas are derived from this. @@ -535,7 +551,12 @@ const WalletMethodSchemas = { sendTx: z .function() .args(ExecutionPayloadSchema, SendOptionsSchema) - .returns(z.union([TxHash.schema, TxReceipt.schema])), + .returns( + z.union([ + z.object({ txHash: TxHash.schema }).merge(OffchainOutputSchema), + z.object({ receipt: TxReceipt.schema }).merge(OffchainOutputSchema), + ]), + ), createAuthWit: z.function().args(schemas.AztecAddress, MessageHashOrIntentSchema).returns(AuthWitness.schema), requestCapabilities: z.function().args(AppCapabilitiesSchema).returns(WalletCapabilitiesSchema), }; diff --git a/yarn-project/aztec/src/examples/token.ts b/yarn-project/aztec/src/examples/token.ts index 2a99d350c314..1e7e2077910d 100644 --- a/yarn-project/aztec/src/examples/token.ts +++ b/yarn-project/aztec/src/examples/token.ts @@ -32,7 +32,9 @@ async function main() { logger.info(`Fetched Alice and Bob accounts: ${alice.toString()}, ${bob.toString()}`); logger.info('Deploying Token...'); - const token = await TokenContract.deploy(wallet, alice, 'TokenName', 'TokenSymbol', 18).send({ from: alice }); + const { contract: token } = await TokenContract.deploy(wallet, alice, 'TokenName', 'TokenSymbol', 18).send({ + from: alice, + }); logger.info('Token deployed'); // Mint tokens to Alice @@ -41,7 +43,7 @@ async function main() { logger.info(`${ALICE_MINT_BALANCE} tokens were successfully minted by Alice and transferred to private`); - const balanceAfterMint = await token.methods.balance_of_private(alice).simulate({ from: alice }); + const { result: balanceAfterMint } = await token.methods.balance_of_private(alice).simulate({ from: alice }); logger.info(`Tokens successfully minted. New Alice's balance: ${balanceAfterMint}`); // We will now transfer tokens from Alice to Bob @@ -49,10 +51,10 @@ async function main() { await token.methods.transfer(bob, TRANSFER_AMOUNT).send({ from: alice }); // Check the new balances - const aliceBalance = await token.methods.balance_of_private(alice).simulate({ from: alice }); + const { result: aliceBalance } = await token.methods.balance_of_private(alice).simulate({ from: alice }); logger.info(`Alice's balance ${aliceBalance}`); - const bobBalance = await token.methods.balance_of_private(bob).simulate({ from: bob }); + const { result: bobBalance } = await token.methods.balance_of_private(bob).simulate({ from: bob }); logger.info(`Bob's balance ${bobBalance}`); } diff --git a/yarn-project/aztec/src/local-network/banana_fpc.ts b/yarn-project/aztec/src/local-network/banana_fpc.ts index 5ccb73d8746f..e5363e0eda73 100644 --- a/yarn-project/aztec/src/local-network/banana_fpc.ts +++ b/yarn-project/aztec/src/local-network/banana_fpc.ts @@ -48,7 +48,7 @@ export async function getBananaFPCAddress(initialAccounts: InitialAccountData[]) export async function setupBananaFPC(initialAccounts: InitialAccountData[], wallet: Wallet, log: LogFn) { const bananaCoinAddress = await getBananaCoinAddress(initialAccounts); const admin = getBananaAdmin(initialAccounts); - const [bananaCoin, fpc] = await Promise.all([ + const [{ contract: bananaCoin }, { contract: fpc }] = await Promise.all([ TokenContract.deploy(wallet, admin, bananaCoinArgs.name, bananaCoinArgs.symbol, bananaCoinArgs.decimal).send({ from: admin, contractAddressSalt: BANANA_COIN_SALT, diff --git a/yarn-project/bot/src/amm_bot.ts b/yarn-project/bot/src/amm_bot.ts index 362470479518..21461c775d90 100644 --- a/yarn-project/bot/src/amm_bot.ts +++ b/yarn-project/bot/src/amm_bot.ts @@ -71,12 +71,14 @@ export class AmmBot extends BaseBot { .getFunctionCall(), }); - const amountOutMin = await amm.methods - .get_amount_out_for_exact_in( - await tokenIn.methods.balance_of_public(amm.address).simulate({ from: this.defaultAccountAddress }), - await tokenOut.methods.balance_of_public(amm.address).simulate({ from: this.defaultAccountAddress }), - amountIn, - ) + const { result: tokenInBalance } = await tokenIn.methods + .balance_of_public(amm.address) + .simulate({ from: this.defaultAccountAddress }); + const { result: tokenOutBalance } = await tokenOut.methods + .balance_of_public(amm.address) + .simulate({ from: this.defaultAccountAddress }); + const { result: amountOutMin } = await amm.methods + .get_amount_out_for_exact_in(tokenInBalance, tokenOutBalance, amountIn) .simulate({ from: this.defaultAccountAddress }); const swapExactTokensInteraction = amm.methods @@ -89,7 +91,8 @@ export class AmmBot extends BaseBot { this.log.verbose(`Sending transaction`, logCtx); this.log.info(`Tx. Balances: ${jsonStringify(balances)}`, { ...logCtx, balances }); - return swapExactTokensInteraction.send({ ...opts, wait: NO_WAIT }); + const { txHash } = await swapExactTokensInteraction.send({ ...opts, wait: NO_WAIT }); + return txHash; } protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise { @@ -110,15 +113,17 @@ export class AmmBot extends BaseBot { } private async getPublicBalanceFor(address: AztecAddress, from?: AztecAddress): Promise { - return { - token0: await this.token0.methods.balance_of_public(address).simulate({ from: from ?? address }), - token1: await this.token1.methods.balance_of_public(address).simulate({ from: from ?? address }), - }; + const { result: token0 } = await this.token0.methods.balance_of_public(address).simulate({ from: from ?? address }); + const { result: token1 } = await this.token1.methods.balance_of_public(address).simulate({ from: from ?? address }); + return { token0, token1 }; } private async getPrivateBalanceFor(address: AztecAddress, from?: AztecAddress): Promise { - return { - token0: await this.token0.methods.balance_of_private(address).simulate({ from: from ?? address }), - token1: await this.token1.methods.balance_of_private(address).simulate({ from: from ?? address }), - }; + const { result: token0 } = await this.token0.methods + .balance_of_private(address) + .simulate({ from: from ?? address }); + const { result: token1 } = await this.token1.methods + .balance_of_private(address) + .simulate({ from: from ?? address }); + return { token0, token1 }; } } diff --git a/yarn-project/bot/src/bot.ts b/yarn-project/bot/src/bot.ts index dce40d2194ad..c2128b2a219e 100644 --- a/yarn-project/bot/src/bot.ts +++ b/yarn-project/bot/src/bot.ts @@ -76,7 +76,8 @@ export class Bot extends BaseBot { await batch.simulate({ from: this.defaultAccountAddress }); this.log.verbose(`Sending transaction`, logCtx); - return batch.send({ ...opts, wait: NO_WAIT }); + const { txHash } = await batch.send({ ...opts, wait: NO_WAIT }); + return txHash; } public async getBalances() { diff --git a/yarn-project/bot/src/cross_chain_bot.ts b/yarn-project/bot/src/cross_chain_bot.ts index 0165b5a778a8..ea4a6c365c29 100644 --- a/yarn-project/bot/src/cross_chain_bot.ts +++ b/yarn-project/bot/src/cross_chain_bot.ts @@ -140,7 +140,8 @@ export class CrossChainBot extends BaseBot { const opts = await this.getSendMethodOpts(batch); this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx); - return batch.send({ ...opts, wait: NO_WAIT }); + const { txHash } = await batch.send({ ...opts, wait: NO_WAIT }); + return txHash; } protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise { diff --git a/yarn-project/bot/src/factory.ts b/yarn-project/bot/src/factory.ts index 970dd845ec69..e22663cebe43 100644 --- a/yarn-project/bot/src/factory.ts +++ b/yarn-project/bot/src/factory.ts @@ -231,7 +231,7 @@ export class BotFactory { const gasSettings = GasSettings.default({ maxFeesPerGas }); await this.withNoMinTxsPerBlock(async () => { - const txHash = await deployMethod.send({ + const { txHash } = await deployMethod.send({ from: AztecAddress.ZERO, fee: { gasSettings, paymentMethod }, wait: NO_WAIT, @@ -302,7 +302,7 @@ export class BotFactory { await deploy.register(); } else { this.log.info(`Deploying token contract at ${address.toString()}`); - const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT }); + const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT }); this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`); await this.withNoMinTxsPerBlock(async () => { await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds }); @@ -343,7 +343,7 @@ export class BotFactory { const amm = AMMContract.at(instance.address, this.wallet); this.log.info(`AMM deployed at ${amm.address}`); - const minterReceipt = await lpToken.methods + const { receipt: minterReceipt } = await lpToken.methods .set_minter(amm.address, true) .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } }); this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`); @@ -362,9 +362,18 @@ export class BotFactory { ): Promise { const getPrivateBalances = () => Promise.all([ - token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }), - token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }), - lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }), + token0.methods + .balance_of_private(liquidityProvider) + .simulate({ from: liquidityProvider }) + .then(r => r.result), + token1.methods + .balance_of_private(liquidityProvider) + .simulate({ from: liquidityProvider }) + .then(r => r.result), + lpToken.methods + .balance_of_private(liquidityProvider) + .simulate({ from: liquidityProvider }) + .then(r => r.result), ]); const authwitNonce = Fr.random(); @@ -405,14 +414,14 @@ export class BotFactory { .getFunctionCall(), }); - const mintReceipt = await new BatchCall(this.wallet, [ + const { receipt: mintReceipt } = await new BatchCall(this.wallet, [ token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE), token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE), ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } }); this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`); - const addLiquidityReceipt = await amm.methods + const { receipt: addLiquidityReceipt } = await amm.methods .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce) .send({ from: liquidityProvider, @@ -443,7 +452,7 @@ export class BotFactory { } else { this.log.info(`Deploying contract ${name} at ${address.toString()}`); await this.withNoMinTxsPerBlock(async () => { - const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT }); + const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT }); this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`); return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds }); }); @@ -488,7 +497,11 @@ export class BotFactory { // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply). const additionalScopes = isStandardToken ? undefined : [token.address]; await this.withNoMinTxsPerBlock(async () => { - const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, additionalScopes, wait: NO_WAIT }); + const { txHash } = await new BatchCall(token.wallet, calls).send({ + from: minter, + additionalScopes, + wait: NO_WAIT, + }); this.log.info(`Sent token mint tx with hash ${txHash.toString()}`); return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds }); }); diff --git a/yarn-project/bot/src/utils.ts b/yarn-project/bot/src/utils.ts index 1bd0b7f6b743..807d34be95ab 100644 --- a/yarn-project/bot/src/utils.ts +++ b/yarn-project/bot/src/utils.ts @@ -15,8 +15,8 @@ export async function getBalances( who: AztecAddress, from?: AztecAddress, ): Promise<{ privateBalance: bigint; publicBalance: bigint }> { - const privateBalance = await token.methods.balance_of_private(who).simulate({ from: from ?? who }); - const publicBalance = await token.methods.balance_of_public(who).simulate({ from: from ?? who }); + const { result: privateBalance } = await token.methods.balance_of_private(who).simulate({ from: from ?? who }); + const { result: publicBalance } = await token.methods.balance_of_public(who).simulate({ from: from ?? who }); return { privateBalance, publicBalance }; } @@ -25,7 +25,7 @@ export async function getPrivateBalance( who: AztecAddress, from?: AztecAddress, ): Promise { - const privateBalance = await token.methods.get_balance(who).simulate({ from: from ?? who }); + const { result: privateBalance } = await token.methods.get_balance(who).simulate({ from: from ?? who }); return privateBalance; } diff --git a/yarn-project/cli-wallet/src/cmds/create_account.ts b/yarn-project/cli-wallet/src/cmds/create_account.ts index 64b730b95aa1..2e317c6a7799 100644 --- a/yarn-project/cli-wallet/src/cmds/create_account.ts +++ b/yarn-project/cli-wallet/src/cmds/create_account.ts @@ -83,10 +83,13 @@ export async function createAccount( }; const deployMethod = await account.getDeployMethod(); - const { estimatedGas, stats } = await deployMethod.simulate({ + const sim = await deployMethod.simulate({ ...deployAccountOpts, fee: { ...deployAccountOpts.fee, estimateGas: true }, }); + // estimateGas: true guarantees these fields are present + const estimatedGas = sim.estimatedGas!; + const stats = sim.stats!; if (feeOpts.estimateOnly) { if (json) { @@ -109,7 +112,7 @@ export async function createAccount( if (!json) { log(`\nWaiting for account contract deployment...`); } - const result = await deployMethod.send({ + const sendOpts = { ...deployAccountOpts, fee: deployAccountOpts.fee ? { @@ -117,18 +120,20 @@ export async function createAccount( gasSettings: estimatedGas, } : undefined, - wait: wait ? { timeout: DEFAULT_TX_TIMEOUT_S, returnReceipt: true } : NO_WAIT, - }); - const isReceipt = (data: TxReceipt | TxHash): data is TxReceipt => 'txHash' in data; - if (isReceipt(result)) { - txReceipt = result; - txHash = result.txHash; + }; + if (wait) { + const { receipt } = await deployMethod.send({ + ...sendOpts, + wait: { timeout: DEFAULT_TX_TIMEOUT_S, returnReceipt: true }, + }); + txReceipt = receipt; + txHash = receipt.txHash; out.txReceipt = { status: txReceipt.status, transactionFee: txReceipt.transactionFee, }; } else { - txHash = result; + ({ txHash } = await deployMethod.send({ ...sendOpts, wait: NO_WAIT })); } debugLogger.debug(`Account contract tx sent with hash ${txHash.toString()}`); out.txHash = txHash; diff --git a/yarn-project/cli-wallet/src/cmds/deploy.ts b/yarn-project/cli-wallet/src/cmds/deploy.ts index 0de9615aa276..edc7e5db29a9 100644 --- a/yarn-project/cli-wallet/src/cmds/deploy.ts +++ b/yarn-project/cli-wallet/src/cmds/deploy.ts @@ -71,10 +71,13 @@ export async function deploy( skipInstancePublication, }; - const { estimatedGas, stats } = await deploy.simulate({ + const sim = await deploy.simulate({ ...deployOpts, fee: { ...deployOpts.fee, estimateGas: true }, }); + // estimateGas: true guarantees these fields are present + const estimatedGas = sim.estimatedGas!; + const stats = sim.stats!; if (feeOpts.estimateOnly) { if (json) { @@ -98,7 +101,7 @@ export async function deploy( const instance = await deploy.getInstance(); if (wait) { - const receipt = await deploy.send({ ...deployOpts, wait: { timeout, returnReceipt: true } }); + const { receipt } = await deploy.send({ ...deployOpts, wait: { timeout, returnReceipt: true } }); const txHash = receipt.txHash; debugLogger.debug(`Deploy tx sent with hash ${txHash.toString()}`); out.hash = txHash; @@ -121,7 +124,7 @@ export async function deploy( }; } } else { - const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT }); + const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT }); debugLogger.debug(`Deploy tx sent with hash ${txHash.toString()}`); out.hash = txHash; diff --git a/yarn-project/cli-wallet/src/cmds/deploy_account.ts b/yarn-project/cli-wallet/src/cmds/deploy_account.ts index f18037e7cbb6..4667fa6f12c6 100644 --- a/yarn-project/cli-wallet/src/cmds/deploy_account.ts +++ b/yarn-project/cli-wallet/src/cmds/deploy_account.ts @@ -63,10 +63,13 @@ export async function deployAccount( }; const deployMethod = await account.getDeployMethod(); - const { estimatedGas, stats } = await deployMethod.simulate({ + const sim = await deployMethod.simulate({ ...deployAccountOpts, fee: { ...deployAccountOpts.fee, estimateGas: true }, }); + // estimateGas: true guarantees these fields are present + const estimatedGas = sim.estimatedGas!; + const stats = sim.stats!; if (feeOpts.estimateOnly) { if (json) { @@ -89,7 +92,7 @@ export async function deployAccount( if (!json) { log(`\nWaiting for account contract deployment...`); } - const result = await deployMethod.send({ + const sendOpts = { ...deployAccountOpts, fee: deployAccountOpts.fee ? { @@ -97,18 +100,20 @@ export async function deployAccount( gasSettings: estimatedGas, } : undefined, - wait: wait ? { timeout: DEFAULT_TX_TIMEOUT_S, returnReceipt: true } : NO_WAIT, - }); - const isReceipt = (data: TxReceipt | TxHash): data is TxReceipt => 'txHash' in data; - if (isReceipt(result)) { - txReceipt = result; - txHash = result.txHash; + }; + if (wait) { + const { receipt } = await deployMethod.send({ + ...sendOpts, + wait: { timeout: DEFAULT_TX_TIMEOUT_S, returnReceipt: true }, + }); + txReceipt = receipt; + txHash = receipt.txHash; out.txReceipt = { status: txReceipt.status, transactionFee: txReceipt.transactionFee, }; } else { - txHash = result; + ({ txHash } = await deployMethod.send({ ...sendOpts, wait: NO_WAIT })); } debugLogger.debug(`Account contract tx sent with hash ${txHash.toString()}`); out.txHash = txHash; diff --git a/yarn-project/cli-wallet/src/cmds/send.ts b/yarn-project/cli-wallet/src/cmds/send.ts index 4059db13a93b..4cc3c69b4505 100644 --- a/yarn-project/cli-wallet/src/cmds/send.ts +++ b/yarn-project/cli-wallet/src/cmds/send.ts @@ -37,10 +37,13 @@ export async function send( authWitnesses, }; - const { estimatedGas, stats } = await call.simulate({ + const sim = await call.simulate({ ...sendOptions, fee: { ...sendOptions.fee, estimateGas: true }, }); + // estimateGas: true guarantees these fields are present + const estimatedGas = sim.estimatedGas!; + const stats = sim.stats!; if (feeOpts.estimateOnly) { return; @@ -52,7 +55,7 @@ export async function send( if (wait) { try { - const receipt = await call.send({ + const { receipt } = await call.send({ ...sendOptions, fee: { ...sendOptions.fee, gasSettings: estimatedGas }, wait: { timeout: DEFAULT_TX_TIMEOUT_S }, @@ -74,7 +77,7 @@ export async function send( throw err; } } else { - const txHash = await call.send({ + const { txHash } = await call.send({ ...sendOptions, fee: { ...sendOptions.fee, gasSettings: estimatedGas }, wait: NO_WAIT, diff --git a/yarn-project/cli-wallet/src/cmds/simulate.ts b/yarn-project/cli-wallet/src/cmds/simulate.ts index 2443428df708..aec161b4ab33 100644 --- a/yarn-project/cli-wallet/src/cmds/simulate.ts +++ b/yarn-project/cli-wallet/src/cmds/simulate.ts @@ -38,7 +38,7 @@ export async function simulate( }); if (verbose) { await printAuthorizations( - simulationResult.offchainEffects!, + simulationResult.offchainEffects, async (address: AztecAddress) => { const metadata = await wallet.getContractMetadata(address); if (!metadata.instance) { diff --git a/yarn-project/end-to-end/src/bench/client_flows/account_deployments.test.ts b/yarn-project/end-to-end/src/bench/client_flows/account_deployments.test.ts index db57a7b52d9b..e38eb09f7c9f 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/account_deployments.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/account_deployments.test.ts @@ -91,8 +91,8 @@ describe('Deployment benchmark', () => { if (process.env.SANITY_CHECKS) { // Ensure we paid a fee - const tx = await deploymentInteraction.send({ ...options, wait: { returnReceipt: true } }); - expect(tx.transactionFee!).toBeGreaterThan(0n); + const { receipt } = await deploymentInteraction.send({ ...options, wait: { returnReceipt: true } }); + expect(receipt.transactionFee!).toBeGreaterThan(0n); } }); } diff --git a/yarn-project/end-to-end/src/bench/client_flows/amm.test.ts b/yarn-project/end-to-end/src/bench/client_flows/amm.test.ts index 22ca27be3eee..44a5652b484f 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/amm.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/amm.test.ts @@ -199,7 +199,7 @@ describe('AMM benchmark', () => { ); if (process.env.SANITY_CHECKS) { - const tx = await addLiquidityInteraction.send({ from: benchysAddress }); + const { receipt: tx } = await addLiquidityInteraction.send({ from: benchysAddress }); expect(tx.transactionFee!).toBeGreaterThan(0n); } diff --git a/yarn-project/end-to-end/src/bench/client_flows/bridging.test.ts b/yarn-project/end-to-end/src/bench/client_flows/bridging.test.ts index 0800c709ea82..27aa73ef8e39 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/bridging.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/bridging.test.ts @@ -106,7 +106,7 @@ describe('Bridging benchmark', () => { if (process.env.SANITY_CHECKS) { // Ensure we paid a fee - const tx = await claimInteraction.send(options); + const { receipt: tx } = await claimInteraction.send(options); expect(tx.transactionFee!).toBeGreaterThan(0n); // 4. Check the balance diff --git a/yarn-project/end-to-end/src/bench/client_flows/client_flows_benchmark.ts b/yarn-project/end-to-end/src/bench/client_flows/client_flows_benchmark.ts index 689cfc2dcfef..96c1c7741364 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/client_flows_benchmark.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/client_flows_benchmark.ts @@ -162,11 +162,15 @@ export class ClientFlowsBenchmark { /** Admin mints bananaCoin tokens privately to the target address and redeems them. */ async mintPrivateBananas(amount: bigint, address: AztecAddress) { - const balanceBefore = await this.bananaCoin.methods.balance_of_private(address).simulate({ from: address }); + const { result: balanceBefore } = await this.bananaCoin.methods + .balance_of_private(address) + .simulate({ from: address }); await mintTokensToPrivate(this.bananaCoin, this.adminAddress, address, amount); - const balanceAfter = await this.bananaCoin.methods.balance_of_private(address).simulate({ from: address }); + const { result: balanceAfter } = await this.bananaCoin.methods + .balance_of_private(address) + .simulate({ from: address }); expect(balanceAfter).toEqual(balanceBefore + amount); } @@ -242,13 +246,12 @@ export class ClientFlowsBenchmark { async applyDeployBananaToken() { this.logger.info('Applying banana token deployment'); - const { contract: bananaCoin, instance: bananaCoinInstance } = await BananaCoin.deploy( - this.adminWallet, - this.adminAddress, - 'BC', - 'BC', - 18n, - ).send({ from: this.adminAddress, wait: { returnReceipt: true } }); + const { + receipt: { contract: bananaCoin, instance: bananaCoinInstance }, + } = await BananaCoin.deploy(this.adminWallet, this.adminAddress, 'BC', 'BC', 18n).send({ + from: this.adminAddress, + wait: { returnReceipt: true }, + }); this.logger.info(`BananaCoin deployed at ${bananaCoin.address}`); this.bananaCoin = bananaCoin; this.bananaCoinInstance = bananaCoinInstance; @@ -256,13 +259,12 @@ export class ClientFlowsBenchmark { async applyDeployCandyBarToken() { this.logger.info('Applying candy bar token deployment'); - const { contract: candyBarCoin, instance: candyBarCoinInstance } = await TokenContract.deploy( - this.adminWallet, - this.adminAddress, - 'CBC', - 'CBC', - 18n, - ).send({ from: this.adminAddress, wait: { returnReceipt: true } }); + const { + receipt: { contract: candyBarCoin, instance: candyBarCoinInstance }, + } = await TokenContract.deploy(this.adminWallet, this.adminAddress, 'CBC', 'CBC', 18n).send({ + from: this.adminAddress, + wait: { returnReceipt: true }, + }); this.logger.info(`CandyBarCoin deployed at ${candyBarCoin.address}`); this.candyBarCoin = candyBarCoin; this.candyBarCoinInstance = candyBarCoinInstance; @@ -274,11 +276,12 @@ export class ClientFlowsBenchmark { expect((await this.context.wallet.getContractMetadata(feeJuiceContract.address)).isContractPublished).toBe(true); const bananaCoin = this.bananaCoin; - const { contract: bananaFPC, instance: bananaFPCInstance } = await FPCContract.deploy( - this.adminWallet, - bananaCoin.address, - this.adminAddress, - ).send({ from: this.adminAddress, wait: { returnReceipt: true } }); + const { + receipt: { contract: bananaFPC, instance: bananaFPCInstance }, + } = await FPCContract.deploy(this.adminWallet, bananaCoin.address, this.adminAddress).send({ + from: this.adminAddress, + wait: { returnReceipt: true }, + }); this.logger.info(`BananaPay deployed at ${bananaFPC.address}`); @@ -341,14 +344,15 @@ export class ClientFlowsBenchmark { public async applyDeployAmm() { this.logger.info('Applying AMM deployment'); - const { contract: liquidityToken, instance: liquidityTokenInstance } = await TokenContract.deploy( - this.adminWallet, - this.adminAddress, - 'LPT', - 'LPT', - 18n, - ).send({ from: this.adminAddress, wait: { returnReceipt: true } }); - const { contract: amm, instance: ammInstance } = await AMMContract.deploy( + const { + receipt: { contract: liquidityToken, instance: liquidityTokenInstance }, + } = await TokenContract.deploy(this.adminWallet, this.adminAddress, 'LPT', 'LPT', 18n).send({ + from: this.adminAddress, + wait: { returnReceipt: true }, + }); + const { + receipt: { contract: amm, instance: ammInstance }, + } = await AMMContract.deploy( this.adminWallet, this.bananaCoin.address, this.candyBarCoin.address, diff --git a/yarn-project/end-to-end/src/bench/client_flows/deployments.test.ts b/yarn-project/end-to-end/src/bench/client_flows/deployments.test.ts index 124e0b0cbbae..f75f4d011751 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/deployments.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/deployments.test.ts @@ -86,8 +86,8 @@ describe('Deployment benchmark', () => { if (process.env.SANITY_CHECKS) { // Ensure we paid a fee - const tx = await deploymentInteraction.send({ ...options, wait: { returnReceipt: true } }); - expect(tx.transactionFee!).toBeGreaterThan(0n); + const { receipt } = await deploymentInteraction.send({ ...options, wait: { returnReceipt: true } }); + expect(receipt.transactionFee!).toBeGreaterThan(0n); } }); }); diff --git a/yarn-project/end-to-end/src/bench/client_flows/storage_proof.test.ts b/yarn-project/end-to-end/src/bench/client_flows/storage_proof.test.ts index 00d431a4bc40..c46f17ccf444 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/storage_proof.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/storage_proof.test.ts @@ -34,7 +34,7 @@ describe('Storage proof benchmark', () => { await t.applyFPCSetup(); await t.applyDeploySponsoredFPC(); - const deployed = await StorageProofTestContract.deploy(t.adminWallet).send({ + const { receipt: deployed } = await StorageProofTestContract.deploy(t.adminWallet).send({ from: t.adminAddress, wait: { returnReceipt: true }, }); @@ -106,7 +106,7 @@ describe('Storage proof benchmark', () => { ); if (process.env.SANITY_CHECKS) { - const tx = await interaction.send(options); + const { receipt: tx } = await interaction.send(options); expect(tx.transactionFee!).toBeGreaterThan(0n); expect(tx.hasExecutionSucceeded()).toBe(true); } diff --git a/yarn-project/end-to-end/src/bench/client_flows/transfers.test.ts b/yarn-project/end-to-end/src/bench/client_flows/transfers.test.ts index 77c8149072b7..df7222e067db 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/transfers.test.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/transfers.test.ts @@ -151,7 +151,7 @@ describe('Transfer benchmark', () => { if (process.env.SANITY_CHECKS) { // Ensure we paid a fee - const tx = await transferInteraction.send(options); + const { receipt: tx } = await transferInteraction.send(options); expect(tx.transactionFee!).toBeGreaterThan(0n); // Sanity checks @@ -179,7 +179,7 @@ describe('Transfer benchmark', () => { */ expect(txEffects!.data.noteHashes.length).toBe(2 + (benchmarkingPaymentMethod === 'private_fpc' ? 2 : 0)); - const senderBalance = await asset.methods + const { result: senderBalance } = await asset.methods .balance_of_private(benchysAddress) .simulate({ from: benchysAddress }); expect(senderBalance).toEqual(expectedChange); diff --git a/yarn-project/end-to-end/src/bench/node_rpc_perf.test.ts b/yarn-project/end-to-end/src/bench/node_rpc_perf.test.ts index a0362bf60e56..7f7cac22f729 100644 --- a/yarn-project/end-to-end/src/bench/node_rpc_perf.test.ts +++ b/yarn-project/end-to-end/src/bench/node_rpc_perf.test.ts @@ -152,9 +152,9 @@ describe('e2e_node_rpc_perf', () => { })); logger.info('Deploying token contract...'); - tokenContract = await TokenContract.deploy(wallet, ownerAddress, 'TestToken', 'TST', 18n).send({ + ({ contract: tokenContract } = await TokenContract.deploy(wallet, ownerAddress, 'TestToken', 'TST', 18n).send({ from: ownerAddress, - }); + })); contractAddress = tokenContract.address; logger.info(`Token contract deployed at ${contractAddress}`); diff --git a/yarn-project/end-to-end/src/bench/tx_stats_bench.test.ts b/yarn-project/end-to-end/src/bench/tx_stats_bench.test.ts index 54d51c3ce6da..e69ffed1efc2 100644 --- a/yarn-project/end-to-end/src/bench/tx_stats_bench.test.ts +++ b/yarn-project/end-to-end/src/bench/tx_stats_bench.test.ts @@ -65,12 +65,12 @@ describe('transaction benchmarks', () => { } = t); // Create the two transactions - const privateBalance = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); + const { result: privateBalance } = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); const privateSendAmount = privateBalance / 10n; expect(privateSendAmount).toBeGreaterThan(0n); const privateInteraction = provenAsset.methods.transfer(recipient, privateSendAmount); - const publicBalance = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); + const { result: publicBalance } = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); const publicSendAmount = publicBalance / 10n; expect(publicSendAmount).toBeGreaterThan(0n); const publicInteraction = provenAsset.methods.transfer_in_public(sender, recipient, publicSendAmount, 0); diff --git a/yarn-project/end-to-end/src/bench/utils.ts b/yarn-project/end-to-end/src/bench/utils.ts index 370baefc8b6c..7daa924782df 100644 --- a/yarn-project/end-to-end/src/bench/utils.ts +++ b/yarn-project/end-to-end/src/bench/utils.ts @@ -25,7 +25,7 @@ export async function benchmarkSetup( ) { const context = await setup(1, { ...opts, telemetryConfig: { benchmark: true } }); const defaultAccountAddress = context.accounts[0]; - const contract = await BenchmarkingContract.deploy(context.wallet).send({ from: defaultAccountAddress }); + const { contract } = await BenchmarkingContract.deploy(context.wallet).send({ from: defaultAccountAddress }); context.logger.info(`Deployed benchmarking contract at ${contract.address}`); const sequencer = (context.aztecNode as AztecNodeService).getSequencer()!; const telemetry = context.telemetryClient as BenchmarkTelemetryClient; @@ -149,7 +149,12 @@ export async function sendTxs( context.logger.info(`Creating ${txCount} txs`); const [from] = context.accounts; context.logger.info(`Sending ${txCount} txs`); - return Promise.all(calls.map(call => call.send({ from, wait: NO_WAIT }))); + return Promise.all( + calls.map(async call => { + const { txHash } = await call.send({ from, wait: NO_WAIT }); + return txHash; + }), + ); } export async function waitTxs(txs: TxHash[], context: EndToEndContext, txWaitOpts?: WaitOpts) { diff --git a/yarn-project/end-to-end/src/composed/e2e_local_network_example.test.ts b/yarn-project/end-to-end/src/composed/e2e_local_network_example.test.ts index 951c3e0152c4..7bd8d64e0fad 100644 --- a/yarn-project/end-to-end/src/composed/e2e_local_network_example.test.ts +++ b/yarn-project/end-to-end/src/composed/e2e_local_network_example.test.ts @@ -71,10 +71,10 @@ describe('e2e_local_network_example', () => { ////////////// QUERYING THE TOKEN BALANCE FOR EACH ACCOUNT ////////////// - let aliceBalance = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice }); + let { result: aliceBalance } = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice }); logger.info(`Alice's balance ${aliceBalance}`); - let bobBalance = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob }); + let { result: bobBalance } = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob }); logger.info(`Bob's balance ${bobBalance}`); expect(aliceBalance).toBe(initialSupply); @@ -88,10 +88,10 @@ describe('e2e_local_network_example', () => { await tokenContract.methods.transfer(bob, transferQuantity).send({ from: alice }); // Check the new balances - aliceBalance = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice }); + ({ result: aliceBalance } = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice })); logger.info(`Alice's balance ${aliceBalance}`); - bobBalance = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob }); + ({ result: bobBalance } = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob })); logger.info(`Bob's balance ${bobBalance}`); expect(aliceBalance).toBe(initialSupply - transferQuantity); @@ -108,10 +108,10 @@ describe('e2e_local_network_example', () => { await mintTokensToPrivate(tokenContract, bob, bob, mintQuantity); // Check the new balances - aliceBalance = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice }); + ({ result: aliceBalance } = await tokenContract.methods.balance_of_private(alice).simulate({ from: alice })); logger.info(`Alice's balance ${aliceBalance}`); - bobBalance = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob }); + ({ result: bobBalance } = await tokenContract.methods.balance_of_private(bob).simulate({ from: bob })); logger.info(`Bob's balance ${bobBalance}`); expect(aliceBalance).toBe(initialSupply - transferQuantity); @@ -188,7 +188,7 @@ describe('e2e_local_network_example', () => { const maxFeesPerGas = (await node.getCurrentMinFees()).mul(1.5); const gasSettings = GasSettings.default({ maxFeesPerGas }); const paymentMethod = new PrivateFeePaymentMethod(bananaFPCAddress, alice, wallet, gasSettings); - const receiptForAlice = await bananaCoin.methods + const { receipt: receiptForAlice } = await bananaCoin.methods .transfer(bob, amountTransferToBob) .send({ from: alice, fee: { paymentMethod } }); // docs:end:private_fpc_payment @@ -196,11 +196,11 @@ describe('e2e_local_network_example', () => { logger.info(`Transaction fee: ${transactionFee}`); // Check the balances - const aliceBalance = await bananaCoin.methods.balance_of_private(alice).simulate({ from: alice }); + const { result: aliceBalance } = await bananaCoin.methods.balance_of_private(alice).simulate({ from: alice }); logger.info(`Alice's balance: ${aliceBalance}`); expect(aliceBalance).toEqual(mintAmount - transactionFee - amountTransferToBob); - const bobBalance = await bananaCoin.methods.balance_of_private(bob).simulate({ from: bob }); + const { result: bobBalance } = await bananaCoin.methods.balance_of_private(bob).simulate({ from: bob }); logger.info(`Bob's balance: ${bobBalance}`); expect(bobBalance).toEqual(amountTransferToBob); @@ -214,16 +214,16 @@ describe('e2e_local_network_example', () => { // const sponsoredPaymentMethod = await SponsoredFeePaymentMethod.new(pxe); const initialFPCFeeJuice = await getFeeJuiceBalance(sponsoredFPC, node); - const receiptForBob = await bananaCoin.methods + const { receipt: receiptForBob } = await bananaCoin.methods .transfer(alice, amountTransferToAlice) .send({ from: bob, fee: { paymentMethod: sponsoredPaymentMethod } }); // docs:end:sponsored_fpc_payment // Check the balances - const aliceNewBalance = await bananaCoin.methods.balance_of_private(alice).simulate({ from: alice }); + const { result: aliceNewBalance } = await bananaCoin.methods.balance_of_private(alice).simulate({ from: alice }); logger.info(`Alice's new balance: ${aliceNewBalance}`); expect(aliceNewBalance).toEqual(aliceBalance + amountTransferToAlice); - const bobNewBalance = await bananaCoin.methods.balance_of_private(bob).simulate({ from: bob }); + const { result: bobNewBalance } = await bananaCoin.methods.balance_of_private(bob).simulate({ from: bob }); logger.info(`Bob's new balance: ${bobNewBalance}`); expect(bobNewBalance).toEqual(bobBalance - amountTransferToAlice); diff --git a/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts b/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts index 40a53ad5f254..3f60809d3f8f 100644 --- a/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts +++ b/yarn-project/end-to-end/src/composed/e2e_persistence.test.ts @@ -68,7 +68,9 @@ describe('Aztec persistence', () => { owner = initialFundedAccounts[0]; ownerAddress = owner.address; - const { contract, instance } = await TokenBlacklistContract.deploy(wallet, ownerAddress).send({ + const { + receipt: { contract, instance }, + } = await TokenBlacklistContract.deploy(wallet, ownerAddress).send({ from: ownerAddress, wait: { returnReceipt: true }, }); @@ -84,7 +86,7 @@ describe('Aztec persistence', () => { const secret = Fr.random(); - const mintTxReceipt = await contract.methods + const { receipt: mintTxReceipt } = await contract.methods .mint_private(1000n, await computeSecretHash(secret)) .send({ from: ownerAddress }); @@ -139,19 +141,29 @@ describe('Aztec persistence', () => { it('correctly restores private notes', async () => { // test for >0 instead of exact value so test isn't dependent on run order await expect( - contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress }), + contract.methods + .balance_of_private(ownerAddress) + .simulate({ from: ownerAddress }) + .then(r => r.result), ).resolves.toBeGreaterThan(0n); }); it('correctly restores public storage', async () => { - await expect(contract.methods.total_supply().simulate({ from: ownerAddress })).resolves.toBeGreaterThan(0n); + await expect( + contract.methods + .total_supply() + .simulate({ from: ownerAddress }) + .then(r => r.result), + ).resolves.toBeGreaterThan(0n); }); it('tracks new notes for the owner', async () => { - const balance = await contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress }); + const { result: balance } = await contract.methods + .balance_of_private(ownerAddress) + .simulate({ from: ownerAddress }); const secret = Fr.random(); - const mintTxReceipt = await contract.methods + const { receipt: mintTxReceipt } = await contract.methods .mint_private(1000n, await computeSecretHash(secret)) .send({ from: ownerAddress }); await addPendingShieldNoteToPXE( @@ -165,9 +177,12 @@ describe('Aztec persistence', () => { await contract.methods.redeem_shield(ownerAddress, 1000n, secret).send({ from: ownerAddress }); - await expect(contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress })).resolves.toEqual( - balance + 1000n, - ); + await expect( + contract.methods + .balance_of_private(ownerAddress) + .simulate({ from: ownerAddress }) + .then(r => r.result), + ).resolves.toEqual(balance + 1000n); }); it('allows spending of private notes', async () => { @@ -175,13 +190,13 @@ describe('Aztec persistence', () => { const otherAccount = await context.wallet.createSchnorrAccount(account.secret, account.salt); const otherAddress = otherAccount.address; - const initialOwnerBalance = await contract.methods + const { result: initialOwnerBalance } = await contract.methods .balance_of_private(ownerAddress) .simulate({ from: ownerAddress }); await contract.methods.transfer(ownerAddress, otherAddress, 500n, 0).send({ from: ownerAddress }); - const [ownerBalance, targetBalance] = await Promise.all([ + const [{ result: ownerBalance }, { result: targetBalance }] = await Promise.all([ contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress }), contract.methods.balance_of_private(otherAddress).simulate({ from: otherAddress }), ]); @@ -224,16 +239,24 @@ describe('Aztec persistence', () => { it("pxe does not have owner's private notes", async () => { await context.wallet.registerContract(contractInstance, TokenBlacklistContract.artifact); const contract = TokenBlacklistContract.at(contractAddress, wallet); - await expect(contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress })).resolves.toEqual( - 0n, - ); + await expect( + contract.methods + .balance_of_private(ownerAddress) + .simulate({ from: ownerAddress }) + .then(r => r.result), + ).resolves.toEqual(0n); }); it('has access to public storage', async () => { await context.wallet.registerContract(contractInstance, TokenBlacklistContract.artifact); const contract = TokenBlacklistContract.at(contractAddress, wallet); - await expect(contract.methods.total_supply().simulate({ from: ownerAddress })).resolves.toBeGreaterThan(0n); + await expect( + contract.methods + .total_supply() + .simulate({ from: ownerAddress }) + .then(r => r.result), + ).resolves.toBeGreaterThan(0n); }); it('pxe restores notes after registering the owner', async () => { @@ -245,7 +268,10 @@ describe('Aztec persistence', () => { // check that notes total more than 0 so that this test isn't dependent on run order await expect( - contract.methods.balance_of_private(ownerAddress).simulate({ from: ownerAddress }), + contract.methods + .balance_of_private(ownerAddress) + .simulate({ from: ownerAddress }) + .then(r => r.result), ).resolves.toBeGreaterThan(0n); }); }); @@ -274,7 +300,7 @@ describe('Aztec persistence', () => { // mint some tokens with a secret we know and redeem later on a separate PXE secret = Fr.random(); mintAmount = 1000n; - const mintTxReceipt = await contract.methods + const { receipt: mintTxReceipt } = await contract.methods .mint_private(mintAmount, await computeSecretHash(secret)) .send({ from: ownerAddress }); mintTxHash = mintTxReceipt.txHash; @@ -301,9 +327,12 @@ describe('Aztec persistence', () => { }); it("restores owner's public balance", async () => { - await expect(contract.methods.balance_of_public(ownerAddress).simulate({ from: ownerAddress })).resolves.toEqual( - revealedAmount, - ); + await expect( + contract.methods + .balance_of_public(ownerAddress) + .simulate({ from: ownerAddress }) + .then(r => r.result), + ).resolves.toEqual(revealedAmount); }); it('allows consuming transparent note created on another PXE', async () => { @@ -317,12 +346,12 @@ describe('Aztec persistence', () => { aztecNode, ); - const balanceBeforeRedeem = await contract.methods + const { result: balanceBeforeRedeem } = await contract.methods .balance_of_private(ownerAddress) .simulate({ from: ownerAddress }); await contract.methods.redeem_shield(ownerAddress, mintAmount, secret).send({ from: ownerAddress }); - const balanceAfterRedeem = await contract.methods + const { result: balanceAfterRedeem } = await contract.methods .balance_of_private(ownerAddress) .simulate({ from: ownerAddress }); diff --git a/yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts b/yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts index 923b14ea06f8..3a4b9932e270 100644 --- a/yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts +++ b/yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts @@ -100,7 +100,13 @@ describe('e2e_cross_chain_messaging token_bridge_tutorial_test', () => { // Deploy L2 token contract // docs:start:deploy-l2-token - const l2TokenContract = await TokenContract.deploy(wallet, ownerAztecAddress, 'L2 Token', 'L2', 18).send({ + const { contract: l2TokenContract } = await TokenContract.deploy( + wallet, + ownerAztecAddress, + 'L2 Token', + 'L2', + 18, + ).send({ from: ownerAztecAddress, }); logger.info(`L2 token contract deployed at ${l2TokenContract.address}`); @@ -130,7 +136,7 @@ describe('e2e_cross_chain_messaging token_bridge_tutorial_test', () => { // docs:end:deploy-portal // Deploy L2 bridge contract // docs:start:deploy-l2-bridge - const l2BridgeContract = await TokenBridgeContract.deploy( + const { contract: l2BridgeContract } = await TokenBridgeContract.deploy( wallet, l2TokenContract.address, l1PortalContractAddress, @@ -175,7 +181,7 @@ describe('e2e_cross_chain_messaging token_bridge_tutorial_test', () => { await l2BridgeContract.methods .claim_public(ownerAztecAddress, MINT_AMOUNT, claim.claimSecret, claim.messageLeafIndex) .send({ from: ownerAztecAddress }); - const balance = await l2TokenContract.methods + const { result: balance } = await l2TokenContract.methods .balance_of_public(ownerAztecAddress) .simulate({ from: ownerAztecAddress }); logger.info(`Public L2 balance of ${ownerAztecAddress} is ${balance}`); @@ -206,12 +212,12 @@ describe('e2e_cross_chain_messaging token_bridge_tutorial_test', () => { l2BridgeContract.address, EthAddress.ZERO, ); - const l2TxReceipt = await l2BridgeContract.methods + const { receipt: l2TxReceipt } = await l2BridgeContract.methods .exit_to_l1_public(EthAddress.fromString(ownerEthAddress), withdrawAmount, EthAddress.ZERO, authwitNonce) .send({ from: ownerAztecAddress }); await waitForProven(node, l2TxReceipt, { provenTimeout: 500 }); - const newL2Balance = await l2TokenContract.methods + const { result: newL2Balance } = await l2TokenContract.methods .balance_of_public(ownerAztecAddress) .simulate({ from: ownerAztecAddress }); logger.info(`New L2 balance of ${ownerAztecAddress} is ${newL2Balance}`); diff --git a/yarn-project/end-to-end/src/composed/ha/e2e_ha_full.test.ts b/yarn-project/end-to-end/src/composed/ha/e2e_ha_full.test.ts index 286d4f5c2271..2bc0799dacde 100644 --- a/yarn-project/end-to-end/src/composed/ha/e2e_ha_full.test.ts +++ b/yarn-project/end-to-end/src/composed/ha/e2e_ha_full.test.ts @@ -321,7 +321,7 @@ describe('HA Full Setup', () => { const sender = ownerAddress; logger.info(`Deploying contract from ${sender}`); - const receipt = await deployer.deploy(ownerAddress, sender, 1).send({ + const { receipt } = await deployer.deploy(ownerAddress, sender, 1).send({ from: ownerAddress, contractAddressSalt: new Fr(BigInt(1)), skipClassPublication: true, @@ -442,7 +442,7 @@ describe('HA Full Setup', () => { // Send a transaction to trigger block building which will also trigger voting logger.info('Sending transaction to trigger block building...'); const deployer = new ContractDeployer(StatefulTestContractArtifact, wallet); - const receipt = await deployer.deploy(ownerAddress, ownerAddress, 42).send({ + const { receipt } = await deployer.deploy(ownerAddress, ownerAddress, 42).send({ from: ownerAddress, contractAddressSalt: Fr.random(), wait: { returnReceipt: true }, @@ -604,12 +604,12 @@ describe('HA Full Setup', () => { skipInstancePublication: true, wait: { returnReceipt: true }, }); - expect(receipt.blockNumber).toBeDefined(); - const [block] = await aztecNode.getCheckpointedBlocks(receipt.blockNumber!, 1); + expect(receipt.receipt.blockNumber).toBeDefined(); + const [block] = await aztecNode.getCheckpointedBlocks(receipt.receipt.blockNumber!, 1); const [cp] = await aztecNode.getCheckpoints(block!.checkpointNumber, 1); const att = cp.attestations.filter(a => !a.signature.isEmpty()); expect(att.length).toBeGreaterThanOrEqual(quorum); - logger.info(`Phase 2: block ${receipt.blockNumber}, ${att.length} attestations (quorum ${quorum})`); + logger.info(`Phase 2: block ${receipt.receipt.blockNumber}, ${att.length} attestations (quorum ${quorum})`); } finally { // Restore each node's saved initial keystore so subsequent tests see original state for (let i = 0; i < NODE_COUNT; i++) { @@ -642,7 +642,7 @@ describe('HA Full Setup', () => { logger.info(`Active nodes: ${haNodeServices.length - killedNodes.length}/${NODE_COUNT}`); const deployer = new ContractDeployer(StatefulTestContractArtifact, wallet); - const receipt = await deployer.deploy(ownerAddress, ownerAddress, i + 100).send({ + const { receipt } = await deployer.deploy(ownerAddress, ownerAddress, i + 100).send({ from: ownerAddress, contractAddressSalt: new Fr(BigInt(i + 100)), skipClassPublication: true, diff --git a/yarn-project/end-to-end/src/composed/web3signer/e2e_multi_validator_node_key_store.test.ts b/yarn-project/end-to-end/src/composed/web3signer/e2e_multi_validator_node_key_store.test.ts index ce44c4ecd9c4..ff0bf8f94e9b 100644 --- a/yarn-project/end-to-end/src/composed/web3signer/e2e_multi_validator_node_key_store.test.ts +++ b/yarn-project/end-to-end/src/composed/web3signer/e2e_multi_validator_node_key_store.test.ts @@ -400,7 +400,10 @@ describe('e2e_multi_validator_node', () => { }); const settledTransactions = await Promise.all( - sentTransactionPromises.map(async sentTransactionPromise => waitForTx(aztecNode, await sentTransactionPromise)), + sentTransactionPromises.map(async sentTransactionPromise => { + const { txHash } = await sentTransactionPromise; + return waitForTx(aztecNode, txHash); + }), ); await Promise.all( diff --git a/yarn-project/end-to-end/src/devnet/e2e_smoke.test.ts b/yarn-project/end-to-end/src/devnet/e2e_smoke.test.ts index 2ce5cf1fef9d..6b985b3a0242 100644 --- a/yarn-project/end-to-end/src/devnet/e2e_smoke.test.ts +++ b/yarn-project/end-to-end/src/devnet/e2e_smoke.test.ts @@ -138,7 +138,7 @@ describe('End-to-end tests for devnet', () => { const l2AccountDeployMethod = await l2AccountManager.getDeployMethod(); - const txReceipt = await l2AccountDeployMethod.send({ + const { receipt: txReceipt } = await l2AccountDeployMethod.send({ from: AztecAddress.ZERO, fee: { paymentMethod: new FeeJuicePaymentMethodWithClaim(l2AccountAddress, { @@ -172,7 +172,9 @@ describe('End-to-end tests for devnet', () => { expect(txReceipt.isMined() && txReceipt.hasExecutionSucceeded()).toBe(true); const feeJuice = FeeJuiceContract.at((await node.getNodeInfo()).protocolContractAddresses.feeJuice, wallet); - const balance = await feeJuice.methods.balance_of_public(l2AccountAddress).simulate({ from: l2AccountAddress }); + const { result: balance } = await feeJuice.methods + .balance_of_public(l2AccountAddress) + .simulate({ from: l2AccountAddress }); expect(balance).toEqual(amount - txReceipt.transactionFee!); }); @@ -253,7 +255,7 @@ describe('End-to-end tests for devnet', () => { async function advanceChainWithEmptyBlocks(wallet: TestWallet) { const [fundedAccountAddress] = await registerInitialLocalNetworkAccountsInWallet(wallet); - const test = await TestContract.deploy(wallet).send({ + const { contract: test } = await TestContract.deploy(wallet).send({ from: fundedAccountAddress, universalDeploy: true, skipClassPublication: true, diff --git a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts index e7c6b83ebe8b..fb18c816774d 100644 --- a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts +++ b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts @@ -97,7 +97,9 @@ describe('e2e_2_pxes', () => { const deployChildContractViaServerA = async () => { logger.info(`Deploying Child contract...`); - const { instance } = await ChildContract.deploy(walletA).send({ + const { + receipt: { instance }, + } = await ChildContract.deploy(walletA).send({ from: accountAAddress, wait: { returnReceipt: true }, }); diff --git a/yarn-project/end-to-end/src/e2e_abi_types.test.ts b/yarn-project/end-to-end/src/e2e_abi_types.test.ts index d970d9c105b2..a7702f78c720 100644 --- a/yarn-project/end-to-end/src/e2e_abi_types.test.ts +++ b/yarn-project/end-to-end/src/e2e_abi_types.test.ts @@ -29,19 +29,19 @@ describe('AbiTypes', () => { wallet, accounts: [defaultAccountAddress], } = await setup(1)); - abiTypesContract = await AbiTypesContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: abiTypesContract } = await AbiTypesContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); it('passes public parameters', async () => { - const minResult = await abiTypesContract.methods + const { result: minResult } = await abiTypesContract.methods .return_public_parameters(false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }) .simulate({ from: defaultAccountAddress }); expect(minResult).toEqual([false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }]); - const maxResult = await abiTypesContract.methods + const { result: maxResult } = await abiTypesContract.methods .return_public_parameters(true, MAX_FIELD_VALUE, U64_MAX, I64_MAX, { w: MAX_FIELD_VALUE, x: true, @@ -60,13 +60,13 @@ describe('AbiTypes', () => { }); it('passes private parameters', async () => { - const minResult = await abiTypesContract.methods + const { result: minResult } = await abiTypesContract.methods .return_private_parameters(false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }) .simulate({ from: defaultAccountAddress }); expect(minResult).toEqual([false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }]); - const maxResult = await abiTypesContract.methods + const { result: maxResult } = await abiTypesContract.methods .return_private_parameters(true, MAX_FIELD_VALUE, U64_MAX, I64_MAX, { w: MAX_FIELD_VALUE, x: true, @@ -85,13 +85,13 @@ describe('AbiTypes', () => { }); it('passes utility parameters', async () => { - const minResult = await abiTypesContract.methods + const { result: minResult } = await abiTypesContract.methods .return_utility_parameters(false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }) .simulate({ from: defaultAccountAddress }); expect(minResult).toEqual([false, 0n, 0n, I64_MIN, { w: 0n, x: false, y: 0n, z: I64_MIN }]); - const maxResult = await abiTypesContract.methods + const { result: maxResult } = await abiTypesContract.methods .return_utility_parameters(true, MAX_FIELD_VALUE, U64_MAX, I64_MAX, { w: MAX_FIELD_VALUE, x: true, diff --git a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts index 71c8498a1057..185d4ca73cb4 100644 --- a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts +++ b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts @@ -64,7 +64,7 @@ const itShouldBehaveLikeAnAccountContract = ( await deployMethod.send({ from: AztecAddress.ZERO }); } - child = await ChildContract.deploy(wallet).send({ from: address }); + ({ contract: child } = await ChildContract.deploy(wallet).send({ from: address })); }); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_amm.test.ts b/yarn-project/end-to-end/src/e2e_amm.test.ts index 79f640236665..b92c5e9dc683 100644 --- a/yarn-project/end-to-end/src/e2e_amm.test.ts +++ b/yarn-project/end-to-end/src/e2e_amm.test.ts @@ -49,9 +49,9 @@ describe('AMM', () => { ({ contract: token1 } = await deployToken(wallet, adminAddress, 0n, logger)); ({ contract: liquidityToken } = await deployToken(wallet, adminAddress, 0n, logger)); - amm = await AMMContract.deploy(wallet, token0.address, token1.address, liquidityToken.address).send({ + ({ contract: amm } = await AMMContract.deploy(wallet, token0.address, token1.address, liquidityToken.address).send({ from: adminAddress, - }); + })); // TODO(#9480): consider deploying the token by some factory when the AMM is deployed, and making the AMM be the // minter there. @@ -81,15 +81,15 @@ describe('AMM', () => { async function getAmmBalances(): Promise { return { - token0: await token0.methods.balance_of_public(amm.address).simulate({ from: adminAddress }), - token1: await token1.methods.balance_of_public(amm.address).simulate({ from: adminAddress }), + token0: (await token0.methods.balance_of_public(amm.address).simulate({ from: adminAddress })).result, + token1: (await token1.methods.balance_of_public(amm.address).simulate({ from: adminAddress })).result, }; } async function getWalletBalances(lp: AztecAddress): Promise { return { - token0: await token0.methods.balance_of_private(lp).simulate({ from: lp }), - token1: await token1.methods.balance_of_private(lp).simulate({ from: lp }), + token0: (await token0.methods.balance_of_private(lp).simulate({ from: lp })).result, + token1: (await token1.methods.balance_of_private(lp).simulate({ from: lp })).result, }; } @@ -146,11 +146,13 @@ describe('AMM', () => { // Liquidity tokens should also be minted for the liquidity provider, as well as locked at the zero address. const expectedLiquidityTokens = (INITIAL_AMM_TOTAL_SUPPLY * 99n) / 100n; expect( - await liquidityToken.methods - .balance_of_private(liquidityProviderAddress) - .simulate({ from: liquidityProviderAddress }), + ( + await liquidityToken.methods + .balance_of_private(liquidityProviderAddress) + .simulate({ from: liquidityProviderAddress }) + ).result, ).toEqual(expectedLiquidityTokens); - expect(await liquidityToken.methods.total_supply().simulate({ from: adminAddress })).toEqual( + expect((await liquidityToken.methods.total_supply().simulate({ from: adminAddress })).result).toEqual( INITIAL_AMM_TOTAL_SUPPLY, ); }); @@ -162,7 +164,8 @@ describe('AMM', () => { const ammBalancesBefore = await getAmmBalances(); const lpBalancesBefore = await getWalletBalances(otherLiquidityProviderAddress); - const liquidityTokenSupplyBefore = await liquidityToken.methods.total_supply().simulate({ from: adminAddress }); + const liquidityTokenSupplyBefore = (await liquidityToken.methods.total_supply().simulate({ from: adminAddress })) + .result; // The pool currently has the same number of tokens for token0 and token1, since that is the ratio the first // liquidity provider used. Our maximum values have a different ratio (6:5 instead of 1:1), so we will end up @@ -214,11 +217,15 @@ describe('AMM', () => { (liquidityTokenSupplyBefore * (ammBalancesBefore.token0 + expectedAmount0)) / ammBalancesBefore.token0; const expectedLiquidityTokens = expectedTotalSupply - INITIAL_AMM_TOTAL_SUPPLY; - expect(await liquidityToken.methods.total_supply().simulate({ from: adminAddress })).toEqual(expectedTotalSupply); + expect((await liquidityToken.methods.total_supply().simulate({ from: adminAddress })).result).toEqual( + expectedTotalSupply, + ); expect( - await liquidityToken.methods - .balance_of_private(otherLiquidityProviderAddress) - .simulate({ from: otherLiquidityProviderAddress }), + ( + await liquidityToken.methods + .balance_of_private(otherLiquidityProviderAddress) + .simulate({ from: otherLiquidityProviderAddress }) + ).result, ).toEqual(expectedLiquidityTokens); }); @@ -239,9 +246,11 @@ describe('AMM', () => { // We compute the expected amount out and set it as the minimum. In a real-life scenario we'd choose a slightly // lower value to account for slippage, but since we're the only actor interacting with the AMM we can afford to // just pass the exact value. Of course any lower value would also suffice. - const amountOutMin = await amm.methods - .get_amount_out_for_exact_in(ammBalancesBefore.token0, ammBalancesBefore.token1, amountIn) - .simulate({ from: swapperAddress }); + const amountOutMin = ( + await amm.methods + .get_amount_out_for_exact_in(ammBalancesBefore.token0, ammBalancesBefore.token1, amountIn) + .simulate({ from: swapperAddress }) + ).result; const swapExactTokensInteraction = amm.methods .swap_exact_tokens_for_tokens(token0.address, token1.address, amountIn, amountOutMin, nonceForAuthwits) @@ -264,9 +273,11 @@ describe('AMM', () => { // query the contract for how much token0 we'd get if we sent our entire token1 balance, and then request exactly // that amount. This would fail in a real-life scenario since we'd need to account for slippage, but we can do it // in this test environment since there's nobody else interacting with the AMM. - const amountOut = await amm.methods - .get_amount_out_for_exact_in(ammBalancesBefore.token1, ammBalancesBefore.token0, swapperBalancesBefore.token1) - .simulate({ from: swapperAddress }); + const amountOut = ( + await amm.methods + .get_amount_out_for_exact_in(ammBalancesBefore.token1, ammBalancesBefore.token0, swapperBalancesBefore.token1) + .simulate({ from: swapperAddress }) + ).result; const amountInMax = swapperBalancesBefore.token1; // Swaps also transfer tokens into the AMM, so we provide an authwit for the full amount in (any change will be @@ -299,9 +310,11 @@ describe('AMM', () => { it('remove liquidity', async () => { // We now withdraw all of the tokens of one of the liquidity providers by burning their entire liquidity token // balance. - const liquidityTokenBalance = await liquidityToken.methods - .balance_of_private(otherLiquidityProviderAddress) - .simulate({ from: otherLiquidityProviderAddress }); + const liquidityTokenBalance = ( + await liquidityToken.methods + .balance_of_private(otherLiquidityProviderAddress) + .simulate({ from: otherLiquidityProviderAddress }) + ).result; // Because private burning requires first transferring the tokens into the AMM, we again need to provide an // authwit. @@ -328,9 +341,11 @@ describe('AMM', () => { // The liquidity provider should have no remaining liquidity tokens, and should have recovered the value they // originally deposited. expect( - await liquidityToken.methods - .balance_of_private(otherLiquidityProviderAddress) - .simulate({ from: otherLiquidityProviderAddress }), + ( + await liquidityToken.methods + .balance_of_private(otherLiquidityProviderAddress) + .simulate({ from: otherLiquidityProviderAddress }) + ).result, ).toEqual(0n); // We now assert that the liquidity provider ended up with more tokens than they began with. These extra tokens diff --git a/yarn-project/end-to-end/src/e2e_authwit.test.ts b/yarn-project/end-to-end/src/e2e_authwit.test.ts index bc74c8373ad8..a2e470e4d876 100644 --- a/yarn-project/end-to-end/src/e2e_authwit.test.ts +++ b/yarn-project/end-to-end/src/e2e_authwit.test.ts @@ -34,8 +34,8 @@ describe('e2e_authwit_tests', () => { } = await setup(2)); await ensureAccountContractsPublished(wallet, [account1Address, account2Address]); - auth = await AuthWitTestContract.deploy(wallet).send({ from: account1Address }); - authwitProxy = await GenericProxyContract.deploy(wallet).send({ from: account1Address }); + ({ contract: auth } = await AuthWitTestContract.deploy(wallet).send({ from: account1Address })); + ({ contract: authwitProxy } = await GenericProxyContract.deploy(wallet).send({ from: account1Address })); }); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_avm_simulator.test.ts b/yarn-project/end-to-end/src/e2e_avm_simulator.test.ts index 07782ca8dd71..b40af1162298 100644 --- a/yarn-project/end-to-end/src/e2e_avm_simulator.test.ts +++ b/yarn-project/end-to-end/src/e2e_avm_simulator.test.ts @@ -36,11 +36,13 @@ describe('e2e_avm_simulator', () => { let secondAvmContract: AvmTestContract; beforeEach(async () => { - ({ contract: avmContract, instance: avmContractInstance } = await AvmTestContract.deploy(wallet).send({ + ({ + receipt: { contract: avmContract, instance: avmContractInstance }, + } = await AvmTestContract.deploy(wallet).send({ from: defaultAccountAddress, wait: { returnReceipt: true }, })); - secondAvmContract = await AvmTestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: secondAvmContract } = await AvmTestContract.deploy(wallet).send({ from: defaultAccountAddress })); }); describe('Assertions & error enriching', () => { @@ -117,16 +119,18 @@ describe('e2e_avm_simulator', () => { describe('Storage', () => { it('Modifies storage (Field)', async () => { await avmContract.methods.set_storage_single(20n).send({ from: defaultAccountAddress }); - expect(await avmContract.methods.read_storage_single().simulate({ from: defaultAccountAddress })).toEqual(20n); + expect( + (await avmContract.methods.read_storage_single().simulate({ from: defaultAccountAddress })).result, + ).toEqual(20n); }); it('Modifies storage (Map)', async () => { const address = AztecAddress.fromBigInt(9090n); await avmContract.methods.set_storage_map(address, 100).send({ from: defaultAccountAddress }); await avmContract.methods.add_storage_map(address, 100).send({ from: defaultAccountAddress }); - expect(await avmContract.methods.read_storage_map(address).simulate({ from: defaultAccountAddress })).toEqual( - 200n, - ); + expect( + (await avmContract.methods.read_storage_map(address).simulate({ from: defaultAccountAddress })).result, + ).toEqual(200n); }); it('Preserves storage across enqueued public calls', async () => { @@ -137,15 +141,15 @@ describe('e2e_avm_simulator', () => { avmContract.methods.add_storage_map(address, 100), ]).send({ from: defaultAccountAddress }); // On a separate tx, we check the result. - expect(await avmContract.methods.read_storage_map(address).simulate({ from: defaultAccountAddress })).toEqual( - 200n, - ); + expect( + (await avmContract.methods.read_storage_map(address).simulate({ from: defaultAccountAddress })).result, + ).toEqual(200n); }); }); describe('Contract instance', () => { it('Works', async () => { - const tx = await avmContract.methods + const { receipt: tx } = await avmContract.methods .test_get_contract_instance_matches( avmContract.address, avmContractInstance.deployer, @@ -160,17 +164,21 @@ describe('e2e_avm_simulator', () => { describe('Nullifiers', () => { // Nullifier will not yet be siloed by the kernel. it('Emit and check in the same tx', async () => { - const tx = await avmContract.methods.emit_nullifier_and_check(123456).send({ from: defaultAccountAddress }); + const { receipt: tx } = await avmContract.methods + .emit_nullifier_and_check(123456) + .send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); }); // Nullifier will have been siloed by the kernel, but we check against the unsiloed one. it('Emit and check in separate tx', async () => { const nullifier = new Fr(123456); - let tx = await avmContract.methods.new_nullifier(nullifier).send({ from: defaultAccountAddress }); + let { receipt: tx } = await avmContract.methods.new_nullifier(nullifier).send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); - tx = await avmContract.methods.assert_nullifier_exists(nullifier).send({ from: defaultAccountAddress }); + ({ receipt: tx } = await avmContract.methods + .assert_nullifier_exists(nullifier) + .send({ from: defaultAccountAddress })); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); }); @@ -204,7 +212,9 @@ describe('e2e_avm_simulator', () => { it('Nested CALL instruction to non-existent contract returns failure, but caller can recover', async () => { // The nested call reverts (returns failure), but the caller doesn't HAVE to rethrow. - const tx = await avmContract.methods.nested_call_to_nothing_recovers().send({ from: defaultAccountAddress }); + const { receipt: tx } = await avmContract.methods + .nested_call_to_nothing_recovers() + .send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); }); it('Should NOT be able to emit the same unsiloed nullifier from the same contract', async () => { @@ -218,7 +228,7 @@ describe('e2e_avm_simulator', () => { it('Should be able to emit different unsiloed nullifiers from the same contract', async () => { const nullifier = new Fr(1); - const tx = await avmContract.methods + const { receipt: tx } = await avmContract.methods .create_different_nullifier_in_nested_call(avmContract.address, nullifier) .send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); @@ -226,7 +236,7 @@ describe('e2e_avm_simulator', () => { it('Should be able to emit the same unsiloed nullifier from two different contracts', async () => { const nullifier = new Fr(1); - const tx = await avmContract.methods + const { receipt: tx } = await avmContract.methods .create_same_nullifier_in_nested_call(secondAvmContract.address, nullifier) .send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); @@ -234,7 +244,7 @@ describe('e2e_avm_simulator', () => { it('Should be able to emit different unsiloed nullifiers from two different contracts', async () => { const nullifier = new Fr(1); - const tx = await avmContract.methods + const { receipt: tx } = await avmContract.methods .create_different_nullifier_in_nested_call(secondAvmContract.address, nullifier) .send({ from: defaultAccountAddress }); expect(tx.executionResult).toEqual(TxExecutionResult.SUCCESS); @@ -246,14 +256,16 @@ describe('e2e_avm_simulator', () => { let avmContract: AvmInitializerTestContract; beforeEach(async () => { - avmContract = await AvmInitializerTestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: avmContract } = await AvmInitializerTestContract.deploy(wallet).send({ + from: defaultAccountAddress, + })); }); describe('Storage', () => { it('Read immutable (initialized) storage (Field)', async () => { - expect(await avmContract.methods.read_storage_immutable().simulate({ from: defaultAccountAddress })).toEqual( - 42n, - ); + expect( + (await avmContract.methods.read_storage_immutable().simulate({ from: defaultAccountAddress })).result, + ).toEqual(42n); }); }); }); diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/access_control.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/access_control.test.ts index 97e8bbb19c23..76f015066d44 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/access_control.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/access_control.test.ts @@ -23,7 +23,7 @@ describe('e2e_blacklist_token_contract access control', () => { await t.crossTimestampOfChange(); - expect(await t.asset.methods.get_roles(t.adminAddress).simulate({ from: t.adminAddress })).toEqual( + expect((await t.asset.methods.get_roles(t.adminAddress).simulate({ from: t.adminAddress })).result).toEqual( adminMinterRole.toNoirStruct(), ); }); @@ -34,7 +34,7 @@ describe('e2e_blacklist_token_contract access control', () => { await t.crossTimestampOfChange(); - expect(await t.asset.methods.get_roles(t.otherAddress).simulate({ from: t.adminAddress })).toEqual( + expect((await t.asset.methods.get_roles(t.otherAddress).simulate({ from: t.adminAddress })).result).toEqual( adminRole.toNoirStruct(), ); }); @@ -45,7 +45,7 @@ describe('e2e_blacklist_token_contract access control', () => { await t.crossTimestampOfChange(); - expect(await t.asset.methods.get_roles(t.otherAddress).simulate({ from: t.adminAddress })).toEqual( + expect((await t.asset.methods.get_roles(t.otherAddress).simulate({ from: t.adminAddress })).result).toEqual( noRole.toNoirStruct(), ); }); @@ -58,7 +58,7 @@ describe('e2e_blacklist_token_contract access control', () => { await t.crossTimestampOfChange(); - expect(await t.asset.methods.get_roles(t.blacklistedAddress).simulate({ from: t.adminAddress })).toEqual( + expect((await t.asset.methods.get_roles(t.blacklistedAddress).simulate({ from: t.adminAddress })).result).toEqual( blacklistRole.toNoirStruct(), ); }); diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts index 22cad7213ca5..5fc0640a8079 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/blacklist_token_contract_test.ts @@ -107,20 +107,24 @@ export class BlacklistTokenContractTest { await publicDeployAccounts(this.wallet, [this.adminAddress, this.otherAddress, this.blacklistedAddress]); this.logger.verbose(`Deploying TokenContract...`); - this.asset = await TokenBlacklistContract.deploy(this.wallet, this.adminAddress).send({ + ({ contract: this.asset } = await TokenBlacklistContract.deploy(this.wallet, this.adminAddress).send({ from: this.adminAddress, - }); + })); this.logger.verbose(`Token deployed to ${this.asset.address}`); this.logger.verbose(`Deploying bad account...`); - this.badAccount = await InvalidAccountContract.deploy(this.wallet).send({ from: this.adminAddress }); + ({ contract: this.badAccount } = await InvalidAccountContract.deploy(this.wallet).send({ + from: this.adminAddress, + })); this.logger.verbose(`Deployed to ${this.badAccount.address}.`); // Deploy a proxy contract for "on behalf of other" tests. The note owner must be the tx sender // (so their notes are in scope), but msg_sender in the target must differ from the note owner // to trigger authwit validation. The proxy forwards calls so that msg_sender != tx sender. this.logger.verbose(`Deploying generic proxy...`); - this.authwitProxy = await GenericProxyContract.deploy(this.wallet).send({ from: this.adminAddress }); + ({ contract: this.authwitProxy } = await GenericProxyContract.deploy(this.wallet).send({ + from: this.adminAddress, + })); this.logger.verbose(`Deployed to ${this.authwitProxy.address}.`); await this.crossTimestampOfChange(); @@ -133,9 +137,9 @@ export class BlacklistTokenContractTest { [this.adminAddress, this.otherAddress, this.blacklistedAddress], ); - expect(await this.asset.methods.get_roles(this.adminAddress).simulate({ from: this.adminAddress })).toEqual( - new Role().withAdmin().toNoirStruct(), - ); + expect( + (await this.asset.methods.get_roles(this.adminAddress).simulate({ from: this.adminAddress })).result, + ).toEqual(new Role().withAdmin().toNoirStruct()); } async setup() { @@ -189,9 +193,9 @@ export class BlacklistTokenContractTest { await this.crossTimestampOfChange(); - expect(await this.asset.methods.get_roles(this.adminAddress).simulate({ from: this.adminAddress })).toEqual( - adminMinterRole.toNoirStruct(), - ); + expect( + (await this.asset.methods.get_roles(this.adminAddress).simulate({ from: this.adminAddress })).result, + ).toEqual(adminMinterRole.toNoirStruct()); this.logger.verbose(`Minting ${amount} publicly...`); await asset.methods.mint_public(this.adminAddress, amount).send({ from: this.adminAddress }); @@ -199,7 +203,7 @@ export class BlacklistTokenContractTest { this.logger.verbose(`Minting ${amount} privately...`); const secret = Fr.random(); const secretHash = await computeSecretHash(secret); - const receipt = await asset.methods.mint_private(amount, secretHash).send({ from: this.adminAddress }); + const { receipt } = await asset.methods.mint_private(amount, secretHash).send({ from: this.adminAddress }); await this.addPendingShieldNoteToPXE(asset, this.adminAddress, amount, secretHash, receipt.txHash); await asset.methods.redeem_shield(this.adminAddress, amount, secret).send({ from: this.adminAddress }); @@ -207,20 +211,20 @@ export class BlacklistTokenContractTest { tokenSim.mintPublic(this.adminAddress, amount); - const publicBalance = await asset.methods + const { result: publicBalance } = await asset.methods .balance_of_public(this.adminAddress) .simulate({ from: this.adminAddress }); this.logger.verbose(`Public balance of wallet 0: ${publicBalance}`); expect(publicBalance).toEqual(this.tokenSim.balanceOfPublic(this.adminAddress)); tokenSim.mintPrivate(this.adminAddress, amount); - const privateBalance = await asset.methods + const { result: privateBalance } = await asset.methods .balance_of_private(this.adminAddress) .simulate({ from: this.adminAddress }); this.logger.verbose(`Private balance of wallet 0: ${privateBalance}`); expect(privateBalance).toEqual(tokenSim.balanceOfPrivate(this.adminAddress)); - const totalSupply = await asset.methods.total_supply().simulate({ from: this.adminAddress }); + const { result: totalSupply } = await asset.methods.total_supply().simulate({ from: this.adminAddress }); this.logger.verbose(`Total supply: ${totalSupply}`); expect(totalSupply).toEqual(tokenSim.totalSupply); } diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/burn.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/burn.test.ts index 6028b6173922..9b8b28204e15 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/burn.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/burn.test.ts @@ -27,7 +27,10 @@ describe('e2e_blacklist_token_contract burn', () => { describe('public', () => { it('burn less than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.burn_public(adminAddress, amount, 0).send({ from: adminAddress }); @@ -36,7 +39,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); @@ -61,7 +67,10 @@ describe('e2e_blacklist_token_contract burn', () => { describe('failure cases', () => { it('burn more than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = 0; await expect( @@ -70,7 +79,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); const authwitNonce = 1; @@ -82,7 +94,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of other without "approval"', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); await expect( @@ -91,7 +106,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -109,7 +127,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -138,7 +159,10 @@ describe('e2e_blacklist_token_contract burn', () => { describe('private', () => { it('burn less than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.burn(adminAddress, amount, 0).send({ from: adminAddress }); @@ -146,7 +170,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -166,7 +193,10 @@ describe('e2e_blacklist_token_contract burn', () => { describe('failure cases', () => { it('burn more than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; expect(amount).toBeGreaterThan(0n); await expect(asset.methods.burn(adminAddress, amount, 0).simulate({ from: adminAddress })).rejects.toThrow( @@ -175,7 +205,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); await expect(asset.methods.burn(adminAddress, amount, 1).simulate({ from: adminAddress })).rejects.toThrow( @@ -184,7 +217,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -199,7 +235,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('burn on behalf of other without approval', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -218,7 +257,10 @@ describe('e2e_blacklist_token_contract burn', () => { }); it('on behalf of other (invalid designated caller)', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts index f1386cfa812a..3e704d342355 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/minting.test.ts @@ -86,9 +86,11 @@ describe('e2e_blacklist_token_contract mint', () => { describe('Mint flow', () => { it('mint_private as minter and redeem as recipient', async () => { - const balanceBefore = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balanceBefore } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); - const receipt = await asset.methods.mint_private(amount, secretHash).send({ from: adminAddress }); + const { receipt } = await asset.methods.mint_private(amount, secretHash).send({ from: adminAddress }); txHash = receipt.txHash; await t.addPendingShieldNoteToPXE(asset, adminAddress, amount, secretHash, txHash); @@ -96,7 +98,9 @@ describe('e2e_blacklist_token_contract mint', () => { await asset.methods.redeem_shield(adminAddress, amount, secret).send({ from: adminAddress }); tokenSim.mintPrivate(adminAddress, amount); - const balanceAfter = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balanceAfter } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); expect(balanceAfter).toBe(balanceBefore + amount); }); }); diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/shielding.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/shielding.test.ts index b09cb1d9b9c2..7ac49c276345 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/shielding.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/shielding.test.ts @@ -31,11 +31,14 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of self', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub / 2n; expect(amount).toBeGreaterThan(0n); - const receipt = await asset.methods.shield(adminAddress, amount, secretHash, 0).send({ from: adminAddress }); + const { receipt } = await asset.methods.shield(adminAddress, amount, secretHash, 0).send({ from: adminAddress }); // Redeem it await t.addPendingShieldNoteToPXE(asset, adminAddress, amount, secretHash, receipt.txHash); @@ -47,7 +50,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of other', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -61,7 +67,7 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { ); await validateActionInteraction.send(); - const receipt = await action.send({ from: otherAddress }); + const { receipt } = await action.send({ from: otherAddress }); // Check that replaying the shield should fail! await expect( @@ -79,7 +85,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { describe('failure cases', () => { it('on behalf of self (more than balance)', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub + 1n; expect(amount).toBeGreaterThan(0n); @@ -89,7 +98,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of self (invalid authwit nonce)', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub + 1n; expect(amount).toBeGreaterThan(0n); @@ -101,7 +113,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of other (more than balance)', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -119,7 +134,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of other (wrong designated caller)', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balancePub = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePub + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -137,7 +155,10 @@ describe('e2e_blacklist_token_contract shield + redeem_shield', () => { }); it('on behalf of other (without approval)', async () => { - const balance = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts index 87fc616cd1e3..88bbbf428fd5 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts @@ -26,7 +26,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer less than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const tokenTransferInteraction = asset.methods.transfer(adminAddress, otherAddress, amount, 0); @@ -35,7 +38,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer to self', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); @@ -44,7 +50,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -64,7 +73,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { describe('failure cases', () => { it('transfer more than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; expect(amount).toBeGreaterThan(0n); @@ -74,7 +86,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); @@ -86,8 +101,14 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_private(otherAddress).simulate({ from: otherAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); + const balance1 = await asset.methods + .balance_of_private(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -99,8 +120,18 @@ describe('e2e_blacklist_token_contract transfer private', () => { await expect( simulateThroughAuthwitProxy(t.authwitProxy, action, { from: adminAddress, authWitnesses: [witness] }), ).rejects.toThrow('Assertion failed: Balance too low'); - expect(await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_private(otherAddress).simulate({ from: otherAddress })).toEqual(balance1); + expect( + await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result), + ).toEqual(balance0); + expect( + await asset.methods + .balance_of_private(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result), + ).toEqual(balance1); }); it.skip('transfer into account to overflow', () => { @@ -111,7 +142,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer on behalf of other without approval', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -130,7 +164,10 @@ describe('e2e_blacklist_token_contract transfer private', () => { }); it('transfer on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -148,7 +185,12 @@ describe('e2e_blacklist_token_contract transfer private', () => { await expect( simulateThroughAuthwitProxy(t.authwitProxy, action, { from: adminAddress, authWitnesses: [witness] }), ).rejects.toThrow(`Unknown auth witness for message hash ${expectedMessageHash.toString()}`); - expect(await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); + expect( + await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result), + ).toEqual(balance0); }); it('transfer from a blacklisted account', async () => { diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts index c5d23f421bbd..2862a3c735e7 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts @@ -24,7 +24,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer less than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.transfer_public(adminAddress, otherAddress, amount, 0).send({ from: adminAddress }); @@ -33,7 +36,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer to self', async () => { - const balance = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.transfer_public(adminAddress, adminAddress, amount, 0).send({ from: adminAddress }); @@ -42,7 +48,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); @@ -68,7 +77,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { describe('failure cases', () => { it('transfer more than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = 0; await expect( @@ -79,7 +91,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 - 1n; const authwitNonce = 1; await expect( @@ -92,7 +107,10 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer on behalf of other without "approval"', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); await expect( @@ -103,8 +121,14 @@ describe('e2e_blacklist_token_contract transfer public', () => { }); it('transfer more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_public(otherAddress).simulate({ from: otherAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); + const balance1 = await asset.methods + .balance_of_public(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -121,13 +145,29 @@ describe('e2e_blacklist_token_contract transfer public', () => { // Perform the transfer await expect(action.simulate({ from: otherAddress })).rejects.toThrow(U128_UNDERFLOW_ERROR); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_public(otherAddress).simulate({ from: otherAddress })).toEqual(balance1); + expect( + await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result), + ).toEqual(balance0); + expect( + await asset.methods + .balance_of_public(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result), + ).toEqual(balance1); }); it('transfer on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_public(otherAddress).simulate({ from: otherAddress }); + const balance0 = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); + const balance1 = await asset.methods + .balance_of_public(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -145,8 +185,18 @@ describe('e2e_blacklist_token_contract transfer public', () => { // Perform the transfer await expect(action.simulate({ from: otherAddress })).rejects.toThrow(/unauthorized/); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_public(otherAddress).simulate({ from: otherAddress })).toEqual(balance1); + expect( + await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result), + ).toEqual(balance0); + expect( + await asset.methods + .balance_of_public(otherAddress) + .simulate({ from: otherAddress }) + .then(r => r.result), + ).toEqual(balance1); }); it.skip('transfer into account to overflow', () => { diff --git a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/unshielding.test.ts b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/unshielding.test.ts index ae10ada9661d..9547b5b992dd 100644 --- a/yarn-project/end-to-end/src/e2e_blacklist_token_contract/unshielding.test.ts +++ b/yarn-project/end-to-end/src/e2e_blacklist_token_contract/unshielding.test.ts @@ -26,7 +26,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { }); it('on behalf of self', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv / 2n; expect(amount).toBeGreaterThan(0n); @@ -36,7 +39,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { }); it('on behalf of other', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -56,7 +62,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { describe('failure cases', () => { it('on behalf of self (more than balance)', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv + 1n; expect(amount).toBeGreaterThan(0n); @@ -66,7 +75,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { }); it('on behalf of self (invalid authwit nonce)', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv + 1n; expect(amount).toBeGreaterThan(0n); @@ -78,7 +90,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { }); it('on behalf of other (more than balance)', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -93,7 +108,10 @@ describe('e2e_blacklist_token_contract unshielding', () => { }); it('on behalf of other (invalid designated caller)', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const balancePriv0 = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }) + .then(r => r.result); const amount = balancePriv0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_block_building.test.ts b/yarn-project/end-to-end/src/e2e_block_building.test.ts index 1eb7fe94be37..ce8df2f1085c 100644 --- a/yarn-project/end-to-end/src/e2e_block_building.test.ts +++ b/yarn-project/end-to-end/src/e2e_block_building.test.ts @@ -106,7 +106,7 @@ describe('e2e_block_building', () => { logger.info(` Total txs to send: ${TX_COUNT}`); logger.info(` Expected minimum blocks: ${EXPECTED_BLOCKS}`); - const contract = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); + const { contract } = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); logger.info(`Deployed stateful test contract at ${contract.address}`); // Configure sequencer with a small delay per tx and enforce timetable @@ -184,7 +184,7 @@ describe('e2e_block_building', () => { it('assembles a block with multiple txs with public fns', async () => { // First deploy the contract - const contract = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); + const { contract } = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); // Assemble N contract deployment txs // We need to create them sequentially since we cannot have parallel calls to a circuit @@ -213,8 +213,8 @@ describe('e2e_block_building', () => { // Skipped since we only use it to manually test number of invocations to world-state. it.skip('builds blocks with multiple public fns after multiple nullifier insertions', async () => { // First deploy the contracts - const contract = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); - const another = await TestContract.deploy(wallet).send({ from: ownerAddress }); + const { contract } = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); + const { contract: another } = await TestContract.deploy(wallet).send({ from: ownerAddress }); await aztecNodeAdmin.setConfig({ minTxsPerBlock: 16, maxTxsPerBlock: 16 }); @@ -268,23 +268,18 @@ describe('e2e_block_building', () => { const highPriority = new GasFees(100, 100); const lowPriority = new GasFees(1, 1); - const deployTxHash = await deployMethod.send({ - from: ownerAddress, - fee: { gasSettings: { maxPriorityFeesPerGas: highPriority } }, - wait: NO_WAIT, - }); - const callTxHash = await callInteraction.send({ - from: ownerAddress, - fee: { gasSettings: { maxPriorityFeesPerGas: lowPriority } }, - wait: NO_WAIT, - }); - - const [deployTxReceipt, callTxReceipt] = await Promise.all([ - waitForTx(aztecNode, deployTxHash), - waitForTx(aztecNode, callTxHash), + const [deployResult, callResult] = await Promise.all([ + deployMethod.send({ + from: ownerAddress, + fee: { gasSettings: { maxPriorityFeesPerGas: highPriority } }, + }), + callInteraction.send({ + from: ownerAddress, + fee: { gasSettings: { maxPriorityFeesPerGas: lowPriority } }, + }), ]); - expect(deployTxReceipt.blockNumber).toEqual(callTxReceipt.blockNumber); + expect(deployResult.receipt.blockNumber).toEqual(callResult.receipt.blockNumber); }); }); @@ -299,7 +294,7 @@ describe('e2e_block_building', () => { wallet, accounts: [ownerAddress], } = await setup(1)); - contract = await TestContract.deploy(wallet).send({ from: ownerAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: ownerAddress })); logger.info(`Test contract deployed at ${contract.address}`); }); @@ -427,7 +422,7 @@ describe('e2e_block_building', () => { } = await setup(1)); logger.info(`Deploying test contract`); - testContract = await TestContract.deploy(wallet).send({ from: ownerAddress }); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: ownerAddress })); }, 60_000); afterAll(() => teardown()); @@ -531,9 +526,11 @@ describe('e2e_block_building', () => { })); logger.info('Deploying token contract'); - const token = await TokenContract.deploy(wallet, ownerAddress, 'TokenName', 'TokenSymbol', 18).send({ - from: ownerAddress, - }); + const { contract: token } = await TokenContract.deploy(wallet, ownerAddress, 'TokenName', 'TokenSymbol', 18).send( + { + from: ownerAddress, + }, + ); logger.info('Updating txs per block to 4'); await aztecNodeAdmin.setConfig({ minTxsPerBlock: 4, maxTxsPerBlock: 4 }); @@ -566,7 +563,7 @@ describe('e2e_block_building', () => { accounts: [ownerAddress], } = context); - const testContract = await TestContract.deploy(wallet).send({ from: ownerAddress }); + const { contract: testContract } = await TestContract.deploy(wallet).send({ from: ownerAddress }); logger.warn(`Test contract deployed at ${testContract.address}`); // We want the sequencer to wait until both txs have arrived (so minTxsPerBlock=2), but agree to build @@ -585,7 +582,8 @@ describe('e2e_block_building', () => { ]); const batches = times(2, makeBatch); - const txHashes = await Promise.all(batches.map(batch => batch.send({ from: ownerAddress, wait: NO_WAIT }))); + const txHashResults = await Promise.all(batches.map(batch => batch.send({ from: ownerAddress, wait: NO_WAIT }))); + const txHashes = txHashResults.map(({ txHash }) => txHash); logger.warn(`Sent two txs to test contract`, { txs: txHashes.map(hash => hash.toString()) }); await Promise.race(txHashes.map(txHash => waitForTx(aztecNode, txHash, { timeout: 60 }))); @@ -617,7 +615,7 @@ describe('e2e_block_building', () => { accounts: [ownerAddress], } = await setup(1)); - contract = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress }); + ({ contract } = await StatefulTestContract.deploy(wallet, ownerAddress, 1).send({ from: ownerAddress })); initialBlockNumber = await aztecNode.getBlockNumber(); logger.info(`Stateful test contract deployed at ${contract.address}`); @@ -641,15 +639,15 @@ describe('e2e_block_building', () => { // Send a tx to the contract that creates a note. This tx will be reorgd but re-included, // since it is being built against a proven block number. logger.info('Sending initial tx'); - const tx1 = await contract.methods.create_note(ownerAddress, 20).send({ from: ownerAddress }); + const { receipt: tx1 } = await contract.methods.create_note(ownerAddress, 20).send({ from: ownerAddress }); expect(tx1.blockNumber).toEqual(initialBlockNumber + 1); - expect(await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).toEqual(21n); + expect((await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).result).toEqual(21n); // And send a second one, which won't be re-included. logger.info('Sending second tx'); - const tx2 = await contract.methods.create_note(ownerAddress, 30).send({ from: ownerAddress }); + const { receipt: tx2 } = await contract.methods.create_note(ownerAddress, 30).send({ from: ownerAddress }); expect(tx2.blockNumber).toEqual(initialBlockNumber + 2); - expect(await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).toEqual(51n); + expect((await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).result).toEqual(51n); logger.info('Advancing past the proof submission window'); @@ -684,12 +682,12 @@ describe('e2e_block_building', () => { expect(newTx1Receipt.blockHash).not.toEqual(tx1.blockHash); // PXE should have cleared out the 30-note from tx2, but reapplied the 20-note from tx1 - expect(await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).toEqual(21n); + expect((await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).result).toEqual(21n); // And we should be able to send a new tx on the new chain logger.info('Sending new tx on reorgd chain'); - const tx3 = await contract.methods.create_note(ownerAddress, 10).send({ from: ownerAddress }); - expect(await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).toEqual(31n); + const { receipt: tx3 } = await contract.methods.create_note(ownerAddress, 10).send({ from: ownerAddress }); + expect((await contract.methods.summed_values(ownerAddress).simulate({ from: ownerAddress })).result).toEqual(31n); expect(tx3.blockNumber).toBeGreaterThanOrEqual(newTx1Receipt.blockNumber! + 1); }); }); diff --git a/yarn-project/end-to-end/src/e2e_card_game.test.ts b/yarn-project/end-to-end/src/e2e_card_game.test.ts index 56e05017370b..6f387d27e51c 100644 --- a/yarn-project/end-to-end/src/e2e_card_game.test.ts +++ b/yarn-project/end-to-end/src/e2e_card_game.test.ts @@ -104,7 +104,7 @@ describe('e2e_card_game', () => { const deployContract = async () => { logger.debug(`Deploying L2 contract...`); - contract = await CardGameContract.deploy(wallet).send({ from: firstPlayer }); + ({ contract } = await CardGameContract.deploy(wallet).send({ from: firstPlayer })); logger.info(`L2 contract deployed at ${contract.address}`); }; @@ -113,7 +113,9 @@ describe('e2e_card_game', () => { // docs:start:send_tx await contract.methods.buy_pack(seed).send({ from: firstPlayer }); // docs:end:send_tx - const collection = await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer }); + const { result: collection } = await contract.methods + .view_collection_cards(firstPlayer, 0) + .simulate({ from: firstPlayer }); const expected = await getPackedCards(0, seed); expect(boundedVecToArray(collection)).toMatchObject(expected); }); @@ -128,7 +130,7 @@ describe('e2e_card_game', () => { contract.methods.buy_pack(seed).send({ from: secondPlayer }), ]); firstPlayerCollection = boundedVecToArray( - await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer }), + (await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer })).result, ); }); @@ -143,11 +145,13 @@ describe('e2e_card_game', () => { .send({ from: secondPlayer }), ).rejects.toThrow(`Not all cards were removed`); - const collection = await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer }); + const { result: collection } = await contract.methods + .view_collection_cards(firstPlayer, 0) + .simulate({ from: firstPlayer }); expect(boundedVecToArray(collection)).toHaveLength(1); expect(boundedVecToArray(collection)).toMatchObject([firstPlayerCollection[1]]); - expect((await contract.methods.view_game(GAME_ID).simulate({ from: firstPlayer })) as Game).toMatchObject({ + expect((await contract.methods.view_game(GAME_ID).simulate({ from: firstPlayer })).result as Game).toMatchObject({ players: [ { address: firstPlayer, @@ -169,9 +173,8 @@ describe('e2e_card_game', () => { it('should start games', async () => { const secondPlayerCollection = boundedVecToArray( - (await contract.methods - .view_collection_cards(secondPlayer, 0) - .simulate({ from: secondPlayer })) as NoirBoundedVec, + (await contract.methods.view_collection_cards(secondPlayer, 0).simulate({ from: secondPlayer })) + .result as NoirBoundedVec, ); await Promise.all([ @@ -185,7 +188,7 @@ describe('e2e_card_game', () => { await contract.methods.start_game(GAME_ID).send({ from: firstPlayer }); - expect((await contract.methods.view_game(GAME_ID).simulate({ from: firstPlayer })) as Game).toMatchObject({ + expect((await contract.methods.view_game(GAME_ID).simulate({ from: firstPlayer })).result as Game).toMatchObject({ players: expect.arrayContaining([ { address: firstPlayer, @@ -220,15 +223,15 @@ describe('e2e_card_game', () => { ]); firstPlayerCollection = boundedVecToArray( - await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer }), + (await contract.methods.view_collection_cards(firstPlayer, 0).simulate({ from: firstPlayer })).result, ); secondPlayerCollection = boundedVecToArray( - await contract.methods.view_collection_cards(secondPlayer, 0).simulate({ from: secondPlayer }), + (await contract.methods.view_collection_cards(secondPlayer, 0).simulate({ from: secondPlayer })).result, ); thirdPlayerCOllection = boundedVecToArray( - await contract.methods.view_collection_cards(thirdPlayer, 0).simulate({ from: thirdPlayer }), + (await contract.methods.view_collection_cards(thirdPlayer, 0).simulate({ from: thirdPlayer })).result, ); }); @@ -240,7 +243,7 @@ describe('e2e_card_game', () => { } async function playGame(playerDecks: { address: AztecAddress; deck: Card[] }[], id = GAME_ID) { - const initialGameState = (await contract.methods.view_game(id).simulate({ from: firstPlayer })) as Game; + const initialGameState = (await contract.methods.view_game(id).simulate({ from: firstPlayer })).result as Game; const players = initialGameState.players.map(player => player.address); const cards = players.map( player => playerDecks.find(playerDeckEntry => playerDeckEntry.address.equals(player))!.deck, @@ -254,7 +257,7 @@ describe('e2e_card_game', () => { } } - const finalGameState = (await contract.methods.view_game(id).simulate({ from: firstPlayer })) as Game; + const finalGameState = (await contract.methods.view_game(id).simulate({ from: firstPlayer })).result as Game; expect(finalGameState.finished).toBe(true); return finalGameState; @@ -285,7 +288,8 @@ describe('e2e_card_game', () => { await contract.methods.claim_cards(GAME_ID, game.rounds_cards.map(cardToField)).send({ from: winner }); const winnerCollection = boundedVecToArray( - (await contract.methods.view_collection_cards(winner, 0).simulate({ from: winner })) as NoirBoundedVec, + (await contract.methods.view_collection_cards(winner, 0).simulate({ from: winner })) + .result as NoirBoundedVec, ); const winnerGameDeck = [winnerCollection[0], winnerCollection[3]]; diff --git a/yarn-project/end-to-end/src/e2e_contract_updates.test.ts b/yarn-project/end-to-end/src/e2e_contract_updates.test.ts index 10bf16f3e987..e34cedae2e97 100644 --- a/yarn-project/end-to-end/src/e2e_contract_updates.test.ts +++ b/yarn-project/end-to-end/src/e2e_contract_updates.test.ts @@ -110,7 +110,9 @@ describe('e2e_contract_updates', () => { } sequencer = maybeSequencer; - ({ contract, instance } = await UpdatableContract.deploy(wallet, constructorArgs[0]).send({ + ({ + receipt: { contract, instance }, + } = await UpdatableContract.deploy(wallet, constructorArgs[0]).send({ from: defaultAccountAddress, contractAddressSalt: salt, wait: { returnReceipt: true }, @@ -126,9 +128,10 @@ describe('e2e_contract_updates', () => { it('should update the contract', async () => { expect( - await contract.methods.get_private_value(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + (await contract.methods.get_private_value(defaultAccountAddress).simulate({ from: defaultAccountAddress })) + .result, ).toEqual(INITIAL_UPDATABLE_CONTRACT_VALUE); - expect(await contract.methods.get_public_value().simulate({ from: defaultAccountAddress })).toEqual( + expect((await contract.methods.get_public_value().simulate({ from: defaultAccountAddress })).result).toEqual( INITIAL_UPDATABLE_CONTRACT_VALUE, ); await contract.methods.update_to(updatedContractClassId).send({ from: defaultAccountAddress }); @@ -141,18 +144,19 @@ describe('e2e_contract_updates', () => { await updatedContract.methods.set_private_value().send({ from: defaultAccountAddress }); // Read state that was changed by the previous tx expect( - await updatedContract.methods.get_private_value(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + (await updatedContract.methods.get_private_value(defaultAccountAddress).simulate({ from: defaultAccountAddress })) + .result, ).toEqual(UPDATED_CONTRACT_PUBLIC_VALUE); // Call a public method with a new implementation await updatedContract.methods.set_public_value().send({ from: defaultAccountAddress }); - expect(await updatedContract.methods.get_public_value().simulate({ from: defaultAccountAddress })).toEqual( + expect((await updatedContract.methods.get_public_value().simulate({ from: defaultAccountAddress })).result).toEqual( UPDATED_CONTRACT_PUBLIC_VALUE, ); }); it('should change the update delay and then update the contract', async () => { - expect(await contract.methods.get_update_delay().simulate({ from: defaultAccountAddress })).toEqual( + expect((await contract.methods.get_update_delay().simulate({ from: defaultAccountAddress })).result).toEqual( BigInt(DEFAULT_TEST_UPDATE_DELAY), ); @@ -161,7 +165,7 @@ describe('e2e_contract_updates', () => { .set_update_delay(BigInt(DEFAULT_TEST_UPDATE_DELAY) + 1n) .send({ from: defaultAccountAddress }); - expect(await contract.methods.get_update_delay().simulate({ from: defaultAccountAddress })).toEqual( + expect((await contract.methods.get_update_delay().simulate({ from: defaultAccountAddress })).result).toEqual( BigInt(DEFAULT_TEST_UPDATE_DELAY) + 1n, ); diff --git a/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l1_to_l2.test.ts b/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l1_to_l2.test.ts index e83b195c5f84..e074e5a9239c 100644 --- a/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l1_to_l2.test.ts +++ b/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l1_to_l2.test.ts @@ -34,7 +34,7 @@ describe('e2e_cross_chain_messaging l1_to_l2', () => { await t.setup(); ({ logger: log, crossChainTestHarness, wallet, user1Address, aztecNode } = t); - testContract = await TestContract.deploy(wallet).send({ from: user1Address }); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: user1Address })); }, 300_000); afterEach(async () => { @@ -219,7 +219,7 @@ describe('e2e_cross_chain_messaging l1_to_l2', () => { // On public, we actually send the tx and check that it reverts due to the missing message. // This advances the block too as a side-effect. Note that we do not rely on a simulation since the cross chain messages // do not get added at the beginning of the block during node_simulatePublicCalls (maybe they should?). - const receipt = await consume().send({ from: user1Address, wait: { dontThrowOnRevert: true } }); + const { receipt } = await consume().send({ from: user1Address, wait: { dontThrowOnRevert: true } }); expect(receipt.executionResult).toEqual(TxExecutionResult.APP_LOGIC_REVERTED); await t.context.watcher.markAsProven(); } diff --git a/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l2_to_l1.test.ts b/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l2_to_l1.test.ts index 7432bd33d4f3..d747d3ef6666 100644 --- a/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l2_to_l1.test.ts +++ b/yarn-project/end-to-end/src/e2e_cross_chain_messaging/l2_to_l1.test.ts @@ -43,7 +43,7 @@ describe('e2e_cross_chain_messaging l2_to_l1', () => { version = BigInt(await rollup.getVersion()); - contract = await TestContract.deploy(wallet).send({ from: user1Address }); + ({ contract } = await TestContract.deploy(wallet).send({ from: user1Address })); }); afterAll(async () => { @@ -60,7 +60,7 @@ describe('e2e_cross_chain_messaging l2_to_l1', () => { // Configure the node to be able to rollup only 1 tx. await aztecNodeAdmin.setConfig({ minTxsPerBlock: 1 }); - const txReceipt = await new BatchCall(wallet, [ + const { receipt: txReceipt } = await new BatchCall(wallet, [ contract.methods.create_l2_to_l1_message_arbitrary_recipient_private(contents[0], recipient), contract.methods.create_l2_to_l1_message_arbitrary_recipient_public(contents[1], recipient), ]).send({ from: user1Address }); @@ -92,7 +92,7 @@ describe('e2e_cross_chain_messaging l2_to_l1', () => { await aztecNodeAdmin.setConfig({ minTxsPerBlock: 2 }); // Send the 2 txs. - const [noMessageReceipt, withMessageReceipt] = await Promise.all([ + const [{ receipt: noMessageReceipt }, { receipt: withMessageReceipt }] = await Promise.all([ contract.methods.emit_nullifier(Fr.random()).send({ from: user1Address }), contract.methods .create_l2_to_l1_message_arbitrary_recipient_private(content, recipient) @@ -119,7 +119,7 @@ describe('e2e_cross_chain_messaging l2_to_l1', () => { const call0 = createBatchCall(wallet, tx0.recipients, tx0.contents); const call1 = createBatchCall(wallet, tx1.recipients, tx1.contents); - const [l2TxReceipt0, l2TxReceipt1] = await Promise.all([ + const [{ receipt: l2TxReceipt0 }, { receipt: l2TxReceipt1 }] = await Promise.all([ call0.send({ from: user1Address }), call1.send({ from: user1Address }), ]); @@ -173,7 +173,7 @@ describe('e2e_cross_chain_messaging l2_to_l1', () => { const call1 = createBatchCall(wallet, tx1.recipients, tx1.contents); const call2 = createBatchCall(wallet, tx2.recipients, tx2.contents); - const [l2TxReceipt0, l2TxReceipt1, l2TxReceipt2] = await Promise.all([ + const [{ receipt: l2TxReceipt0 }, { receipt: l2TxReceipt1 }, { receipt: l2TxReceipt2 }] = await Promise.all([ call0.send({ from: user1Address }), call1.send({ from: user1Address }), call2.send({ from: user1Address }), diff --git a/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts b/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts index 5f892e4c2e11..1b99f2b3657e 100644 --- a/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts +++ b/yarn-project/end-to-end/src/e2e_crowdfunding_and_claim.test.ts @@ -62,22 +62,22 @@ describe('e2e_crowdfunding_and_claim', () => { // We set the deadline to a week from now deadline = (await cheatCodes.eth.timestamp()) + 7 * 24 * 60 * 60; - donationToken = await TokenContract.deploy( + ({ contract: donationToken } = await TokenContract.deploy( wallet, operatorAddress, donationTokenMetadata.name, donationTokenMetadata.symbol, donationTokenMetadata.decimals, - ).send({ from: operatorAddress }); + ).send({ from: operatorAddress })); logger.info(`Donation Token deployed to ${donationToken.address}`); - rewardToken = await TokenContract.deploy( + ({ contract: rewardToken } = await TokenContract.deploy( wallet, operatorAddress, rewardTokenMetadata.name, rewardTokenMetadata.symbol, rewardTokenMetadata.decimals, - ).send({ from: operatorAddress }); + ).send({ from: operatorAddress })); logger.info(`Reward Token deployed to ${rewardToken.address}`); // We deploy the Crowdfunding contract as an escrow contract (i.e. with populated public keys that make it @@ -94,16 +94,20 @@ describe('e2e_crowdfunding_and_claim', () => { ); const crowdfundingInstance = await crowdfundingDeployment.getInstance(); await wallet.registerContract(crowdfundingInstance, CrowdfundingContract.artifact, crowdfundingSecretKey); - crowdfundingContract = await crowdfundingDeployment.send({ + ({ contract: crowdfundingContract } = await crowdfundingDeployment.send({ from: operatorAddress, // The contract constructor initializes private storage vars that need the contract's own nullifier key. additionalScopes: [crowdfundingInstance.address], - }); + })); logger.info(`Crowdfunding contract deployed at ${crowdfundingContract.address}`); - claimContract = await ClaimContract.deploy(wallet, crowdfundingContract.address, rewardToken.address).send({ + ({ contract: claimContract } = await ClaimContract.deploy( + wallet, + crowdfundingContract.address, + rewardToken.address, + ).send({ from: operatorAddress, - }); + })); logger.info(`Claim contract deployed at ${claimContract.address}`); await rewardToken.methods.set_minter(claimContract.address, true).send({ from: operatorAddress }); @@ -133,7 +137,7 @@ describe('e2e_crowdfunding_and_claim', () => { // The donor should have exactly one note const pageIndex = 0; - const notes = await crowdfundingContract.methods + const { result: notes } = await crowdfundingContract.methods .get_donation_notes(donor1Address, pageIndex) .simulate({ from: donor1Address }); expect(notes.len).toEqual(1n); @@ -146,10 +150,12 @@ describe('e2e_crowdfunding_and_claim', () => { } // Since the RWT is minted 1:1 with the DNT, the balance of the reward token should be equal to the donation amount - const balanceRWT = await rewardToken.methods.balance_of_public(donor1Address).simulate({ from: operatorAddress }); + const { result: balanceRWT } = await rewardToken.methods + .balance_of_public(donor1Address) + .simulate({ from: operatorAddress }); expect(balanceRWT).toEqual(donationAmount); - const balanceDNTBeforeWithdrawal = await donationToken.methods + const { result: balanceDNTBeforeWithdrawal } = await donationToken.methods .balance_of_private(operatorAddress) .simulate({ from: operatorAddress }); expect(balanceDNTBeforeWithdrawal).toEqual(0n); @@ -160,7 +166,7 @@ describe('e2e_crowdfunding_and_claim', () => { // Withdraw nullifies the contract's own token notes, which requires its nullifier key. .send({ from: operatorAddress, additionalScopes: [crowdfundingContract.address] }); - const balanceDNTAfterWithdrawal = await donationToken.methods + const { result: balanceDNTAfterWithdrawal } = await donationToken.methods .balance_of_private(operatorAddress) .simulate({ from: operatorAddress }); @@ -191,7 +197,7 @@ describe('e2e_crowdfunding_and_claim', () => { // The donor should have exactly one note const pageIndex = 0; - const notes = await crowdfundingContract.methods + const { result: notes } = await crowdfundingContract.methods .get_donation_notes(donorAddress, pageIndex) .simulate({ from: donorAddress }); expect(notes.len).toEqual(1n); @@ -230,11 +236,11 @@ describe('e2e_crowdfunding_and_claim', () => { const otherCrowdfundingInstance = await otherCrowdfundingDeployment.getInstance(); await wallet.registerContract(otherCrowdfundingInstance, CrowdfundingContract.artifact, crowdfundingSecretKey); - otherCrowdfundingContract = await otherCrowdfundingDeployment.send({ + ({ contract: otherCrowdfundingContract } = await otherCrowdfundingDeployment.send({ from: operatorAddress, // The contract constructor initializes private storage vars that need the contract's own nullifier key. additionalScopes: [otherCrowdfundingInstance.address], - }); + })); logger.info(`Crowdfunding contract deployed at ${otherCrowdfundingContract.address}`); } @@ -254,11 +260,11 @@ describe('e2e_crowdfunding_and_claim', () => { // 3) Get the donation note const pageIndex = 0; - const notes = await otherCrowdfundingContract.methods + const { result: notes2 } = await otherCrowdfundingContract.methods .get_donation_notes(donor1Address, pageIndex) .simulate({ from: donor1Address }); - expect(notes.len).toEqual(1n); - const otherContractNote = notes.storage[0]; + expect(notes2.len).toEqual(1n); + const otherContractNote = notes2.storage[0]; // 4) Try to claim rewards using note from other contract await expect( diff --git a/yarn-project/end-to-end/src/e2e_custom_message.test.ts b/yarn-project/end-to-end/src/e2e_custom_message.test.ts index ce29ec91dae1..0ff387019d2e 100644 --- a/yarn-project/end-to-end/src/e2e_custom_message.test.ts +++ b/yarn-project/end-to-end/src/e2e_custom_message.test.ts @@ -26,7 +26,7 @@ describe('CustomMessage - Multi-Log Pattern', () => { accounts: [account], } = await setup(1)); await ensureAccountContractsPublished(wallet, [account]); - contract = await CustomMessageContract.deploy(wallet).send({ from: account }); + ({ contract } = await CustomMessageContract.deploy(wallet).send({ from: account })); }); afterAll(() => teardown()); @@ -34,7 +34,7 @@ describe('CustomMessage - Multi-Log Pattern', () => { it('reassembles a multi-log event from multiple private logs', async () => { const values = [Fr.random(), Fr.random(), Fr.random(), Fr.random()]; - const tx = await contract.methods + const { receipt: tx } = await contract.methods .emit_multi_log_event(values[0], values[1], values[2], values[3], account) .send({ from: account }); @@ -56,7 +56,7 @@ describe('CustomMessage - Multi-Log Pattern', () => { const valuesA = [Fr.random(), Fr.random(), Fr.random(), Fr.random()]; const valuesB = [Fr.random(), Fr.random(), Fr.random(), Fr.random()]; - const tx = await new BatchCall(wallet, [ + const { receipt: tx } = await new BatchCall(wallet, [ contract.methods.emit_multi_log_event(valuesA[0], valuesA[1], valuesA[2], valuesA[3], account), contract.methods.emit_multi_log_event(valuesB[0], valuesB[1], valuesB[2], valuesB[3], account), ]).send({ from: account }); diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract/contract_class_registration.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract/contract_class_registration.test.ts index fc5a57f84fe6..37da34dd7f3c 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract/contract_class_registration.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract/contract_class_registration.test.ts @@ -37,7 +37,7 @@ describe('e2e_deploy_contract contract class registration', () => { ({ logger, wallet, aztecNode, defaultAccountAddress } = await t.setup()); artifact = StatefulTestContract.artifact; publicationTxReceipt = await publishContractClass(wallet, artifact).then(c => - c.send({ from: defaultAccountAddress }), + c.send({ from: defaultAccountAddress }).then(({ receipt }) => receipt), ); contractClass = await getContractClassFromArtifact(artifact); expect(await aztecNode.getContractClass(contractClass.id)).toBeDefined(); @@ -47,7 +47,7 @@ describe('e2e_deploy_contract contract class registration', () => { describe('publishing a contract class', () => { it('emits public bytecode', async () => { - const publicationTxReceipt = await publishContractClass(wallet, TestContract.artifact).then(c => + const { receipt: publicationTxReceipt } = await publishContractClass(wallet, TestContract.artifact).then(c => c.send({ from: defaultAccountAddress }), ); const logs = await aztecNode.getContractClassLogs({ txHash: publicationTxReceipt.txHash }); @@ -149,19 +149,23 @@ describe('e2e_deploy_contract contract class registration', () => { it('calls a public function with no init check on the deployed instance', async () => { const whom = await AztecAddress.random(); await contract.methods.increment_public_value_no_init_check(whom, 10).send({ from: defaultAccountAddress }); - const stored = await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress }); + const { result: stored } = await contract.methods + .get_public_value(whom) + .simulate({ from: defaultAccountAddress }); expect(stored).toEqual(10n); }); it('refuses to call a public function with init check if the instance is not initialized', async () => { const whom = await AztecAddress.random(); - const receipt = await contract.methods + const { receipt } = await contract.methods .increment_public_value(whom, 10) .send({ from: defaultAccountAddress, wait: { dontThrowOnRevert: true } }); expect(receipt.executionResult).toEqual(TxExecutionResult.APP_LOGIC_REVERTED); // Meanwhile we check we didn't increment the value - expect(await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress })).toEqual(0n); + expect( + (await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress })).result, + ).toEqual(0n); }); it('refuses to initialize the instance with wrong args via a private function', async () => { @@ -174,7 +178,9 @@ describe('e2e_deploy_contract contract class registration', () => { await contract.methods.constructor(...initArgs).send({ from: defaultAccountAddress }); const whom = await AztecAddress.random(); await contract.methods.increment_public_value(whom, 10).send({ from: defaultAccountAddress }); - const stored = await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress }); + const { result: stored } = await contract.methods + .get_public_value(whom) + .simulate({ from: defaultAccountAddress }); expect(stored).toEqual(10n); }); @@ -195,18 +201,22 @@ describe('e2e_deploy_contract contract class registration', () => { it('refuses to initialize the instance with wrong args via a public function', async () => { const whom = await AztecAddress.random(); - const receipt = await contract.methods + const { receipt } = await contract.methods .public_constructor(whom, 43) .send({ from: defaultAccountAddress, wait: { dontThrowOnRevert: true } }); expect(receipt.executionResult).toEqual(TxExecutionResult.APP_LOGIC_REVERTED); - expect(await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress })).toEqual(0n); + expect( + (await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress })).result, + ).toEqual(0n); }); it('initializes the contract and calls a public function', async () => { await contract.methods.public_constructor(...initArgs).send({ from: defaultAccountAddress }); const whom = await AztecAddress.random(); await contract.methods.increment_public_value(whom, 10).send({ from: defaultAccountAddress }); - const stored = await contract.methods.get_public_value(whom).simulate({ from: defaultAccountAddress }); + const { result: stored } = await contract.methods + .get_public_value(whom) + .simulate({ from: defaultAccountAddress }); expect(stored).toEqual(10n); }); @@ -228,7 +238,7 @@ describe('e2e_deploy_contract contract class registration', () => { // Register the instance to be deployed in the pxe await wallet.registerContract(instance, artifact); // Set up the contract that calls the deployer (which happens to be the TestContract) and call it - const deployer = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + const { contract: deployer } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); await deployer.methods.publish_contract_instance(instance.address).send({ from: defaultAccountAddress }); }); @@ -243,7 +253,7 @@ describe('e2e_deploy_contract contract class registration', () => { ).rejects.toThrow(/not deployed/); // This time, don't throw on revert and confirm that the tx is included // despite reverting in app logic because of the call to a non-existent contract - const tx = await instance.methods + const { receipt: tx } = await instance.methods .increment_public_value_no_init_check(whom, 10) .send({ from: defaultAccountAddress, wait: { dontThrowOnRevert: true } }); expect(tx.executionResult).toEqual(TxExecutionResult.APP_LOGIC_REVERTED); diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract/deploy_method.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract/deploy_method.test.ts index 3d81fda867be..ed7cfba703fb 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract/deploy_method.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract/deploy_method.test.ts @@ -40,12 +40,14 @@ describe('e2e_deploy_contract deploy method', () => { const owner = defaultAccountAddress; logger.debug(`Deploying stateful test contract`); // docs:start:deploy_basic - const contract = await StatefulTestContract.deploy(wallet, owner, 42).send({ from: defaultAccountAddress }); + const { contract } = await StatefulTestContract.deploy(wallet, owner, 42).send({ from: defaultAccountAddress }); // docs:end:deploy_basic - expect(await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).toEqual(42n); + expect((await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).result).toEqual(42n); logger.debug(`Calling public method on stateful test contract at ${contract.address.toString()}`); await contract.methods.increment_public_value(owner, 84).send({ from: defaultAccountAddress }); - expect(await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).toEqual(84n); + expect((await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).result).toEqual( + 84n, + ); // docs:start:verify_deployment const metadata = await wallet.getContractMetadata(contract.address); const classMetadata = await wallet.getContractClassMetadata(metadata.instance!.currentContractClassId); @@ -58,28 +60,30 @@ describe('e2e_deploy_contract deploy method', () => { const owner = defaultAccountAddress; // docs:start:deploy_universal const opts = { universalDeploy: true, from: defaultAccountAddress }; - const contract = await StatefulTestContract.deploy(wallet, owner, 42).send(opts); + const { contract } = await StatefulTestContract.deploy(wallet, owner, 42).send(opts); // docs:end:deploy_universal - expect(await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).toEqual(42n); + expect((await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).result).toEqual(42n); await contract.methods.increment_public_value(owner, 84).send({ from: defaultAccountAddress }); - expect(await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).toEqual(84n); + expect((await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).result).toEqual( + 84n, + ); }); it('publicly deploys and calls a public function from the constructor', async () => { const owner = defaultAccountAddress; // docs:start:deploy_token - const token = await TokenContract.deploy(wallet, owner, 'TOKEN', 'TKN', 18).send({ + const { contract: token } = await TokenContract.deploy(wallet, owner, 'TOKEN', 'TKN', 18).send({ from: defaultAccountAddress, }); // docs:end:deploy_token - expect(await token.methods.is_minter(owner).simulate({ from: defaultAccountAddress })).toEqual(true); + expect((await token.methods.is_minter(owner).simulate({ from: defaultAccountAddress })).result).toEqual(true); }); it('publicly deploys and initializes via a public function', async () => { const owner = defaultAccountAddress; logger.debug(`Deploying contract via a public constructor`); // docs:start:deploy_with_opts - const contract = await StatefulTestContract.deployWithOpts( + const { contract } = await StatefulTestContract.deployWithOpts( { wallet, method: 'public_constructor' }, owner, 42, @@ -87,29 +91,31 @@ describe('e2e_deploy_contract deploy method', () => { from: defaultAccountAddress, }); // docs:end:deploy_with_opts - expect(await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).toEqual(42n); + expect((await contract.methods.get_public_value(owner).simulate({ from: defaultAccountAddress })).result).toEqual( + 42n, + ); logger.debug(`Calling a private function to ensure the contract was properly initialized`); await contract.methods.create_note(owner, 30).send({ from: defaultAccountAddress }); - expect(await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).toEqual(30n); + expect((await contract.methods.summed_values(owner).simulate({ from: defaultAccountAddress })).result).toEqual(30n); }); it('deploys a contract with a default initializer not named constructor', async () => { logger.debug(`Deploying contract with a default initializer named initialize`); const opts = { skipClassPublication: true, skipInstancePublication: true, from: defaultAccountAddress }; - const contract = await CounterContract.deploy(wallet, 10, defaultAccountAddress).send(opts); + const { contract } = await CounterContract.deploy(wallet, 10, defaultAccountAddress).send(opts); logger.debug(`Calling a function to ensure the contract was properly initialized`); await contract.methods.increment_twice(defaultAccountAddress).send({ from: defaultAccountAddress }); - expect(await contract.methods.get_counter(defaultAccountAddress).simulate({ from: defaultAccountAddress })).toEqual( - 12n, - ); + expect( + (await contract.methods.get_counter(defaultAccountAddress).simulate({ from: defaultAccountAddress })).result, + ).toEqual(12n); }); it('publicly deploys a contract with no constructor', async () => { logger.debug(`Deploying contract with no constructor`); - const contract = await NoConstructorContract.deploy(wallet).send({ from: defaultAccountAddress }); + const { contract } = await NoConstructorContract.deploy(wallet).send({ from: defaultAccountAddress }); const arbitraryValue = 42; logger.debug(`Call a public function to check that it was publicly deployed`); - const receipt = await contract.methods.emit_public(arbitraryValue).send({ from: defaultAccountAddress }); + const { receipt } = await contract.methods.emit_public(arbitraryValue).send({ from: defaultAccountAddress }); const logs = await aztecNode.getPublicLogs({ txHash: receipt.txHash }); expect(logs.logs[0].log.getEmittedFields()).toEqual([new Fr(arbitraryValue)]); }); @@ -162,7 +168,10 @@ describe('e2e_deploy_contract deploy method', () => { const publicCallTxPromise = publicCall.send({ from: defaultAccountAddress, wait: { timeout: 600 } }); logger.debug('Deploying a contract and calling a public function in the same block'); - const [deployTxReceipt, publicCallTxReceipt] = await Promise.all([deployTxPromise, publicCallTxPromise]); + const [{ receipt: deployTxReceipt }, { receipt: publicCallTxReceipt }] = await Promise.all([ + deployTxPromise, + publicCallTxPromise, + ]); expect(deployTxReceipt.blockNumber).toEqual(publicCallTxReceipt.blockNumber); }, 300_000); diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract/legacy.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract/legacy.test.ts index 55f638be25f6..9d16aeb08bb0 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract/legacy.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract/legacy.test.ts @@ -36,7 +36,7 @@ describe('e2e_deploy_contract legacy', () => { deployer: defaultAccountAddress, }); const deployer = new ContractDeployer(TestContractArtifact, wallet); - const receipt = await deployer + const { receipt } = await deployer .deploy() .send({ from: defaultAccountAddress, contractAddressSalt: salt, wait: { returnReceipt: true } }); expect(receipt.contract.address).toEqual(deploymentData.address); @@ -65,7 +65,7 @@ describe('e2e_deploy_contract legacy', () => { for (let index = 0; index < 2; index++) { logger.info(`Deploying contract ${index + 1}...`); - const receipt = await deployer + const { receipt } = await deployer .deploy() .send({ from: defaultAccountAddress, contractAddressSalt: Fr.random(), wait: { returnReceipt: true } }); logger.info(`Sending TX to contract ${index + 1}...`); @@ -113,8 +113,8 @@ describe('e2e_deploy_contract legacy', () => { expect(goodTxPromiseResult.status).toBe('fulfilled'); expect(badTxReceiptResult.status).toBe('fulfilled'); // but reverted - const goodTxReceipt = goodTxPromiseResult.status === 'fulfilled' ? goodTxPromiseResult.value : null; - const badTxReceipt = badTxReceiptResult.status === 'fulfilled' ? badTxReceiptResult.value : null; + const goodTxReceipt = goodTxPromiseResult.status === 'fulfilled' ? goodTxPromiseResult.value.receipt : null; + const badTxReceipt = badTxReceiptResult.status === 'fulfilled' ? badTxReceiptResult.value.receipt : null; // Both the good and bad transactions are included expect(goodTxReceipt).toBeDefined(); diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract/private_initialization.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract/private_initialization.test.ts index f1af8d9c9adf..a6814602e130 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract/private_initialization.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract/private_initialization.test.ts @@ -31,7 +31,7 @@ describe('e2e_deploy_contract private initialization', () => { // The function has a noinitcheck flag so it can be called without initialization. it('executes a noinitcheck function in an uninitialized contract', async () => { const contract = await t.registerContract(wallet, TestContract); - const receipt = await contract.methods.emit_nullifier(10).send({ from: defaultAccountAddress }); + const { receipt } = await contract.methods.emit_nullifier(10).send({ from: defaultAccountAddress }); const txEffects = await aztecNode.getTxEffect(receipt.txHash); const expected = await siloNullifier(contract.address, new Fr(10)); @@ -45,11 +45,11 @@ describe('e2e_deploy_contract private initialization', () => { const contract = await t.registerContract(wallet, NoConstructorContract); await expect( contract.methods.is_private_mutable_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), - ).resolves.toEqual(false); + ).resolves.toEqual(expect.objectContaining({ result: false })); await contract.methods.initialize_private_mutable(42).send({ from: defaultAccountAddress }); await expect( contract.methods.is_private_mutable_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), - ).resolves.toEqual(true); + ).resolves.toEqual(expect.objectContaining({ result: true })); }); // Tests privately initializing an undeployed contract. Also requires pxe registration in advance. @@ -60,10 +60,10 @@ describe('e2e_deploy_contract private initialization', () => { logger.info(`Calling the constructor for ${contract.address}`); await contract.methods.constructor(...initArgs).send({ from: defaultAccountAddress }); logger.info(`Checking if the constructor was run for ${contract.address}`); - expect(await contract.methods.summed_values(owner).simulate({ from: owner })).toEqual(42n); + expect((await contract.methods.summed_values(owner).simulate({ from: owner })).result).toEqual(42n); logger.info(`Calling a private function that requires initialization on ${contract.address}`); await contract.methods.create_note(owner, 10).send({ from: defaultAccountAddress }); - expect(await contract.methods.summed_values(owner).simulate({ from: owner })).toEqual(52n); + expect((await contract.methods.summed_values(owner).simulate({ from: owner })).result).toEqual(52n); }); // Tests privately initializing multiple undeployed contracts on the same tx through an account contract. @@ -75,8 +75,8 @@ describe('e2e_deploy_contract private initialization', () => { ); const calls = contracts.map((c, i) => c.methods.constructor(...initArgs[i])); await new BatchCall(wallet, calls).send({ from: defaultAccountAddress }); - expect(await contracts[0].methods.summed_values(owner).simulate({ from: owner })).toEqual(42n); - expect(await contracts[1].methods.summed_values(owner).simulate({ from: owner })).toEqual(52n); + expect((await contracts[0].methods.summed_values(owner).simulate({ from: owner })).result).toEqual(42n); + expect((await contracts[1].methods.summed_values(owner).simulate({ from: owner })).result).toEqual(52n); }); it('initializes and calls a private function in a single tx', async () => { @@ -89,7 +89,7 @@ describe('e2e_deploy_contract private initialization', () => { ]); logger.info(`Executing constructor and private function in batch at ${contract.address}`); await batch.send({ from: defaultAccountAddress }); - expect(await contract.methods.summed_values(owner).simulate({ from: owner })).toEqual(52n); + expect((await contract.methods.summed_values(owner).simulate({ from: owner })).result).toEqual(52n); }); it('refuses to initialize a contract twice', async () => { diff --git a/yarn-project/end-to-end/src/e2e_double_spend.test.ts b/yarn-project/end-to-end/src/e2e_double_spend.test.ts index 6b4e2053b380..3cc69dec717d 100644 --- a/yarn-project/end-to-end/src/e2e_double_spend.test.ts +++ b/yarn-project/end-to-end/src/e2e_double_spend.test.ts @@ -25,7 +25,7 @@ describe('e2e_double_spend', () => { logger, } = await setup(1)); - contract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); logger.info(`Test contract deployed at ${contract.address}`); }); diff --git a/yarn-project/end-to-end/src/e2e_epochs/epochs_invalidate_block.parallel.test.ts b/yarn-project/end-to-end/src/e2e_epochs/epochs_invalidate_block.parallel.test.ts index e4740dde721d..220face468aa 100644 --- a/yarn-project/end-to-end/src/e2e_epochs/epochs_invalidate_block.parallel.test.ts +++ b/yarn-project/end-to-end/src/e2e_epochs/epochs_invalidate_block.parallel.test.ts @@ -238,7 +238,7 @@ describe('e2e_epochs/epochs_invalidate_block', () => { // Send a few transactions so the sequencer builds multiple blocks in the checkpoint // We'll later check that the first tx at least was picked up and mined logger.warn('Sending multiple transactions to trigger block building'); - const [sentTx] = await timesAsync(8, i => + const [{ txHash: sentTx }] = await timesAsync(8, i => testContract.methods.emit_nullifier(BigInt(i + 1)).send({ from: context.accounts[0], wait: NO_WAIT }), ); diff --git a/yarn-project/end-to-end/src/e2e_epochs/epochs_mbps.parallel.test.ts b/yarn-project/end-to-end/src/e2e_epochs/epochs_mbps.parallel.test.ts index 247a56d44ae9..ff94a94fca77 100644 --- a/yarn-project/end-to-end/src/e2e_epochs/epochs_mbps.parallel.test.ts +++ b/yarn-project/end-to-end/src/e2e_epochs/epochs_mbps.parallel.test.ts @@ -117,8 +117,8 @@ describe('e2e_epochs/epochs_mbps', () => { // Unlike emit_nullifier (which has #[noinitcheck]), cross-chain methods require a deployed contract. if (deployCrossChainContract) { logger.warn(`Deploying cross-chain test contract before stopping initial sequencer`); - crossChainContract = await TestContract.deploy(wallet).send({ from }); - logger.warn(`Cross-chain test contract deployed at ${crossChainContract.address}`); + ({ contract: crossChainContract } = await TestContract.deploy(wallet).send({ from })); + logger.warn(`Cross-chain test contract deployed at ${crossChainContract!.address}`); } // Halt block building in initial aztec node, which was not set up as a validator. diff --git a/yarn-project/end-to-end/src/e2e_epochs/epochs_proof_public_cross_chain.test.ts b/yarn-project/end-to-end/src/e2e_epochs/epochs_proof_public_cross_chain.test.ts index 846cd5f82b96..bc5a6c18eb57 100644 --- a/yarn-project/end-to-end/src/e2e_epochs/epochs_proof_public_cross_chain.test.ts +++ b/yarn-project/end-to-end/src/e2e_epochs/epochs_proof_public_cross_chain.test.ts @@ -46,7 +46,7 @@ describe('e2e_epochs/epochs_proof_public_cross_chain', () => { // Deploy a contract that consumes L1 to L2 messages await context.aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 }); logger.warn(`Deploying test contract`); - const testContract = await TestContract.deploy(context.wallet).send({ from: context.accounts[0] }); + const { contract: testContract } = await TestContract.deploy(context.wallet).send({ from: context.accounts[0] }); logger.warn(`Test contract deployed at ${testContract.address}`); // Send an l1 to l2 message to be consumed from the contract @@ -64,7 +64,7 @@ describe('e2e_epochs/epochs_proof_public_cross_chain', () => { // And we consume the message using the test contract. It's important that we don't wait for the membership witness // to be available, since we want to test the scenario where the message becomes available on the same block the tx lands. logger.warn(`Consuming message ${message.content.toString()} from the contract at ${testContract.address}`); - const txReceipt = await testContract.methods + const { receipt: txReceipt } = await testContract.methods .consume_message_from_arbitrary_sender_public( message.content, secret, @@ -90,7 +90,7 @@ describe('e2e_epochs/epochs_proof_public_cross_chain', () => { expect(provenBlockNumber).toBeGreaterThanOrEqual(txReceipt.blockNumber!); // Should not be able to consume the message again. - const failedReceipt = await testContract.methods + const { receipt: failedReceipt } = await testContract.methods .consume_message_from_arbitrary_sender_public( message.content, secret, diff --git a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts index a9fd2e501887..949e5eb6e15c 100644 --- a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts @@ -42,11 +42,16 @@ describe('e2e_escrow_contract', () => { const escrowInstance = await escrowDeployment.getInstance(); await wallet.registerContract(escrowInstance, EscrowContract.artifact, escrowSecretKey); // The contract constructor initializes private storage vars that need the contract's own nullifier key. - escrowContract = await escrowDeployment.send({ from: owner, additionalScopes: [escrowInstance.address] }); + ({ contract: escrowContract } = await escrowDeployment.send({ + from: owner, + additionalScopes: [escrowInstance.address], + })); logger.info(`Escrow contract deployed at ${escrowContract.address}`); // Deploy Token contract and mint funds for the escrow contract - token = await TokenContract.deploy(wallet, owner, 'TokenName', 'TokenSymbol', 18).send({ from: owner }); + ({ contract: token } = await TokenContract.deploy(wallet, owner, 'TokenName', 'TokenSymbol', 18).send({ + from: owner, + })); await mintTokensToPrivate(token, owner, escrowContract.address, 100n); diff --git a/yarn-project/end-to-end/src/e2e_event_logs.test.ts b/yarn-project/end-to-end/src/e2e_event_logs.test.ts index 4645fc1dcc77..64d89526709f 100644 --- a/yarn-project/end-to-end/src/e2e_event_logs.test.ts +++ b/yarn-project/end-to-end/src/e2e_event_logs.test.ts @@ -47,7 +47,7 @@ describe('Logs', () => { await ensureAccountContractsPublished(wallet, [account1Address, account2Address]); log.warn(`Deploying test contract`); - testLogContract = await TestLogContract.deploy(wallet).send({ from: account1Address }); + ({ contract: testLogContract } = await TestLogContract.deploy(wallet).send({ from: account1Address })); }); afterAll(() => teardown()); @@ -57,9 +57,12 @@ describe('Logs', () => { const preimages = makeTuple(5, makeTuple.bind(undefined, 4, Fr.random)) as Tuple, 5>; const txs = await Promise.all( - preimages.map(preimage => - testLogContract.methods.emit_encrypted_events(account2Address, preimage).send({ from: account1Address }), - ), + preimages.map(async preimage => { + const { receipt } = await testLogContract.methods + .emit_encrypted_events(account2Address, preimage) + .send({ from: account1Address }); + return receipt; + }), ); const firstBlockNumber = Math.min(...txs.map(tx => tx.blockNumber!)); @@ -124,13 +127,13 @@ describe('Logs', () => { const preimage = makeTuple(5, makeTuple.bind(undefined, 4, Fr.random)) as Tuple, 5>; let i = 0; - const firstTx = await testLogContract.methods + const { receipt: firstTx } = await testLogContract.methods .emit_unencrypted_events(preimage[i]) .send({ from: account1Address }); await timesParallel(3, () => testLogContract.methods.emit_unencrypted_events(preimage[++i]).send({ from: account1Address }), ); - const lastTx = await testLogContract.methods + const { receipt: lastTx } = await testLogContract.methods .emit_unencrypted_events(preimage[++i]) .send({ from: account1Address }); @@ -181,7 +184,9 @@ describe('Logs', () => { const c = await AztecAddress.random(); const extra = Fr.random(); - const tx = await testLogContract.methods.emit_nested_event(a, b, c, extra).send({ from: account1Address }); + const { receipt: tx } = await testLogContract.methods + .emit_nested_event(a, b, c, extra) + .send({ from: account1Address }); const collectedEvents = await getPublicEvents( aztecNode, @@ -212,7 +217,7 @@ describe('Logs', () => { const tx1NumLogs = 10; { // Call the private function that emits two encrypted logs per call and recursively nests 4 times - const tx = await testLogContract.methods + const { receipt: tx } = await testLogContract.methods .emit_encrypted_events_nested(account2Address, 4) .send({ from: account1Address }); @@ -231,7 +236,7 @@ describe('Logs', () => { const tx2NumLogs = 6; { // Call the private function that emits two encrypted logs per call and recursively nests 2 times - const tx = await testLogContract.methods + const { receipt: tx } = await testLogContract.methods .emit_encrypted_events_nested(account2Address, 2) .send({ from: account1Address }); diff --git a/yarn-project/end-to-end/src/e2e_event_only.test.ts b/yarn-project/end-to-end/src/e2e_event_only.test.ts index 7dd0c3859451..d2b036f601a0 100644 --- a/yarn-project/end-to-end/src/e2e_event_only.test.ts +++ b/yarn-project/end-to-end/src/e2e_event_only.test.ts @@ -26,14 +26,16 @@ describe('EventOnly', () => { accounts: [defaultAccountAddress], } = await setup(1)); await ensureAccountContractsPublished(wallet, [defaultAccountAddress]); - eventOnlyContract = await EventOnlyContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: eventOnlyContract } = await EventOnlyContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); it('emits and retrieves a private event for a contract with no notes', async () => { const value = Fr.random(); - const tx = await eventOnlyContract.methods.emit_event_for_msg_sender(value).send({ from: defaultAccountAddress }); + const { receipt: tx } = await eventOnlyContract.methods + .emit_event_for_msg_sender(value) + .send({ from: defaultAccountAddress }); const events = await wallet.getPrivateEvents(EventOnlyContract.events.TestEvent, { contractAddress: eventOnlyContract.address, diff --git a/yarn-project/end-to-end/src/e2e_expiration_timestamp.test.ts b/yarn-project/end-to-end/src/e2e_expiration_timestamp.test.ts index 78e3be77ee02..18240f671298 100644 --- a/yarn-project/end-to-end/src/e2e_expiration_timestamp.test.ts +++ b/yarn-project/end-to-end/src/e2e_expiration_timestamp.test.ts @@ -25,7 +25,7 @@ describe('e2e_expiration_timestamp', () => { aztecNode, accounts: [defaultAccountAddress], } = await setup()); - contract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_fees/account_init.test.ts b/yarn-project/end-to-end/src/e2e_fees/account_init.test.ts index 966882ad638a..a02e539963db 100644 --- a/yarn-project/end-to-end/src/e2e_fees/account_init.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/account_init.test.ts @@ -89,10 +89,7 @@ describe('e2e_fees account_init', () => { const [bobsInitialGas] = await t.getGasBalanceFn(bobsAddress); expect(bobsInitialGas).toEqual(mintAmount); - const tx = await bobsDeployMethod.send({ - from: AztecAddress.ZERO, - wait: { returnReceipt: true }, - }); + const { receipt: tx } = await bobsDeployMethod.send({ from: AztecAddress.ZERO, wait: { returnReceipt: true } }); expect(tx.transactionFee!).toBeGreaterThan(0n); await expect(t.getGasBalanceFn(bobsAddress)).resolves.toEqual([bobsInitialGas - tx.transactionFee!]); @@ -101,7 +98,7 @@ describe('e2e_fees account_init', () => { it('pays natively in the Fee Juice by bridging funds themselves', async () => { const claim = await t.feeJuiceBridgeTestHarness.prepareTokensOnL1(bobsAddress); const paymentMethod = new FeeJuicePaymentMethodWithClaim(bobsAddress, claim); - const tx = await bobsDeployMethod.send({ + const { receipt: tx } = await bobsDeployMethod.send({ from: AztecAddress.ZERO, fee: { paymentMethod }, wait: { returnReceipt: true }, @@ -121,7 +118,7 @@ describe('e2e_fees account_init', () => { const maxFeesPerGas = (await aztecNode.getCurrentMinFees()).mul(1.5); const gasSettings = GasSettings.default({ maxFeesPerGas }); const paymentMethod = new PrivateFeePaymentMethod(bananaFPC.address, bobsAddress, wallet, gasSettings); - const tx = await bobsDeployMethod.send({ + const { receipt: tx } = await bobsDeployMethod.send({ from: AztecAddress.ZERO, fee: { paymentMethod }, wait: { returnReceipt: true }, @@ -150,7 +147,7 @@ describe('e2e_fees account_init', () => { const maxFeesPerGas = (await aztecNode.getCurrentMinFees()).mul(1.5); const gasSettings = GasSettings.default({ maxFeesPerGas }); const paymentMethod = new PublicFeePaymentMethod(bananaFPC.address, bobsAddress, wallet, gasSettings); - const tx = await bobsDeployMethod.send({ + const { receipt: tx } = await bobsDeployMethod.send({ from: AztecAddress.ZERO, skipInstancePublication: false, fee: { paymentMethod }, @@ -183,7 +180,7 @@ describe('e2e_fees account_init', () => { await t.mintPrivateBananas(mintedBananas, bobsAddress); const [aliceBalanceBefore] = await t.getGasBalanceFn(aliceAddress); - const tx = await SchnorrAccountContractInterface.deployWithPublicKeys( + const { receipt: tx } = await SchnorrAccountContractInterface.deployWithPublicKeys( bobsPublicKeys, wallet, bobsSigningPubKey.x, diff --git a/yarn-project/end-to-end/src/e2e_fees/failures.test.ts b/yarn-project/end-to-end/src/e2e_fees/failures.test.ts index 0c4c54c5032c..440f1949acf8 100644 --- a/yarn-project/end-to-end/src/e2e_fees/failures.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/failures.test.ts @@ -84,7 +84,7 @@ describe('e2e_fees failures', () => { const currentSequencerRewards = await t.getCoinbaseSequencerRewards(); - const txReceipt = await bananaCoin.methods + const { receipt: txReceipt } = await bananaCoin.methods .transfer_in_public(aliceAddress, sequencerAddress, outrageousPublicAmountAliceDoesNotHave, 0) .send({ from: aliceAddress, @@ -187,7 +187,7 @@ describe('e2e_fees failures', () => { ); // if we skip simulation, it includes the failed TX - const txReceipt = await bananaCoin.methods + const { receipt: txReceipt } = await bananaCoin.methods .transfer_in_public(aliceAddress, sequencerAddress, outrageousPublicAmountAliceDoesNotHave, 0) .send({ from: aliceAddress, @@ -285,7 +285,7 @@ describe('e2e_fees failures', () => { }), ).rejects.toThrow(); - const receipt = await bananaCoin.methods + const { receipt } = await bananaCoin.methods .mint_to_public(aliceAddress, 1n) // random operation .send({ from: aliceAddress, diff --git a/yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts b/yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts index a3509eb164eb..c8ba437bcdcf 100644 --- a/yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts @@ -43,7 +43,9 @@ describe('e2e_fees Fee Juice payments', () => { describe('without initial funds', () => { beforeAll(async () => { - expect(await feeJuiceContract.methods.balance_of_public(bobAddress).simulate({ from: bobAddress })).toEqual(0n); + expect( + (await feeJuiceContract.methods.balance_of_public(bobAddress).simulate({ from: bobAddress })).result, + ).toEqual(0n); }); it('fails to simulate a tx', async () => { @@ -63,10 +65,12 @@ describe('e2e_fees Fee Juice payments', () => { it('claims bridged funds and pays with them on the same tx', async () => { const claim = await t.feeJuiceBridgeTestHarness.prepareTokensOnL1(bobAddress); const paymentMethod = new FeeJuicePaymentMethodWithClaim(bobAddress, claim); - const receipt = await feeJuiceContract.methods + const { receipt } = await feeJuiceContract.methods .check_balance(0n) .send({ from: bobAddress, fee: { gasSettings, paymentMethod } }); - const endBalance = await feeJuiceContract.methods.balance_of_public(bobAddress).simulate({ from: bobAddress }); + const { result: endBalance } = await feeJuiceContract.methods + .balance_of_public(bobAddress) + .simulate({ from: bobAddress }); expect(endBalance).toBeGreaterThan(0n); expect(endBalance).toBeLessThan(claim.claimAmount); @@ -76,28 +80,30 @@ describe('e2e_fees Fee Juice payments', () => { describe('with initial funds', () => { it('sends tx with payment in Fee Juice with public calls', async () => { - const initialBalance = await feeJuiceContract.methods + const { result: initialBalance } = await feeJuiceContract.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); - const { transactionFee } = await bananaCoin.methods + const { + receipt: { transactionFee }, + } = await bananaCoin.methods .transfer_in_public(aliceAddress, bobAddress, 1n, 0n) .send({ fee: { gasSettings }, from: aliceAddress }); expect(transactionFee).toBeGreaterThan(0n); - const endBalance = await feeJuiceContract.methods + const { result: endBalance } = await feeJuiceContract.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); expect(endBalance).toBeLessThan(initialBalance); }); it('sends tx fee payment in Fee Juice with no public calls', async () => { - const initialBalance = await feeJuiceContract.methods + const { result: initialBalance } = await feeJuiceContract.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); - const { transactionFee } = await bananaCoin.methods - .transfer(bobAddress, 1n) - .send({ fee: { gasSettings }, from: aliceAddress }); + const { + receipt: { transactionFee }, + } = await bananaCoin.methods.transfer(bobAddress, 1n).send({ fee: { gasSettings }, from: aliceAddress }); expect(transactionFee).toBeGreaterThan(0n); - const endBalance = await feeJuiceContract.methods + const { result: endBalance } = await feeJuiceContract.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); expect(endBalance).toBeLessThan(initialBalance); diff --git a/yarn-project/end-to-end/src/e2e_fees/fee_settings.test.ts b/yarn-project/end-to-end/src/e2e_fees/fee_settings.test.ts index 5ac0ec444727..83fe2d1b837b 100644 --- a/yarn-project/end-to-end/src/e2e_fees/fee_settings.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/fee_settings.test.ts @@ -26,7 +26,7 @@ describe('e2e_fees fee settings', () => { await t.setup(); ({ aliceAddress, wallet, gasSettings, cheatCodes, aztecNode } = t); - testContract = await TestContract.deploy(wallet).send({ from: aliceAddress }); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: aliceAddress })); gasSettings = { ...gasSettings, maxFeesPerGas: undefined }; }); diff --git a/yarn-project/end-to-end/src/e2e_fees/fees_test.ts b/yarn-project/end-to-end/src/e2e_fees/fees_test.ts index d810c896ffc1..d43093bc0034 100644 --- a/yarn-project/end-to-end/src/e2e_fees/fees_test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/fees_test.ts @@ -157,11 +157,15 @@ export class FeesTest { /** Alice mints bananaCoin tokens privately to the target address and redeems them. */ async mintPrivateBananas(amount: bigint, address: AztecAddress) { - const balanceBefore = await this.bananaCoin.methods.balance_of_private(address).simulate({ from: address }); + const { result: balanceBefore } = await this.bananaCoin.methods + .balance_of_private(address) + .simulate({ from: address }); await mintTokensToPrivate(this.bananaCoin, this.aliceAddress, address, amount); - const balanceAfter = await this.bananaCoin.methods.balance_of_private(address).simulate({ from: address }); + const { result: balanceAfter } = await this.bananaCoin.methods + .balance_of_private(address) + .simulate({ from: address }); expect(balanceAfter).toEqual(balanceBefore + amount); } @@ -223,7 +227,7 @@ export class FeesTest { async applyDeployBananaToken() { this.logger.info('Applying deploy banana token setup'); - const bananaCoin = await BananaCoin.deploy(this.wallet, this.aliceAddress, 'BC', 'BC', 18n).send({ + const { contract: bananaCoin } = await BananaCoin.deploy(this.wallet, this.aliceAddress, 'BC', 'BC', 18n).send({ from: this.aliceAddress, }); this.logger.info(`BananaCoin deployed at ${bananaCoin.address}`); @@ -244,7 +248,7 @@ export class FeesTest { expect((await this.wallet.getContractMetadata(feeJuiceContract.address)).isContractPublished).toBe(true); const bananaCoin = this.bananaCoin; - const bananaFPC = await FPCContract.deploy(this.wallet, bananaCoin.address, this.fpcAdmin).send({ + const { contract: bananaFPC } = await FPCContract.deploy(this.wallet, bananaCoin.address, this.fpcAdmin).send({ from: this.aliceAddress, }); diff --git a/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts b/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts index 417cdb495cd0..b456cd167784 100644 --- a/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/gas_estimation.test.ts @@ -88,9 +88,13 @@ describe('e2e_fees gas_estimation', () => { paymentMethod?: FeePaymentMethod, ) => Promise.all( - [GasSettings.from({ ...gasSettings, ...limits }), gasSettings].map(gasSettings => - makeTransferRequest().send({ from: aliceAddress, fee: { gasSettings, paymentMethod } }), - ), + [GasSettings.from({ ...gasSettings, ...limits }), gasSettings].map(async gasSettings => { + const { receipt } = await makeTransferRequest().send({ + from: aliceAddress, + fee: { gasSettings, paymentMethod }, + }); + return receipt; + }), ); const logGasEstimate = (estimatedGas: Pick) => @@ -100,10 +104,11 @@ describe('e2e_fees gas_estimation', () => { }); it('estimates gas with Fee Juice payment method', async () => { - const { estimatedGas } = await makeTransferRequest().simulate({ + const sim = await makeTransferRequest().simulate({ from: aliceAddress, fee: { gasSettings, estimateGas: true, estimatedGasPadding: 0 }, }); + const estimatedGas = sim.estimatedGas!; logGasEstimate(estimatedGas); const sequencer = t.context.sequencer!.getSequencer(); @@ -143,10 +148,11 @@ describe('e2e_fees gas_estimation', () => { ); const paymentMethod = new PublicFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettingsForEstimation); - const { estimatedGas } = await makeTransferRequest().simulate({ + const sim2 = await makeTransferRequest().simulate({ from: aliceAddress, fee: { paymentMethod, estimatedGasPadding: 0, estimateGas: true }, }); + const estimatedGas = sim2.estimatedGas!; logGasEstimate(estimatedGas); const [withEstimate, withoutEstimate] = await sendTransfers(estimatedGas, paymentMethod); @@ -184,7 +190,7 @@ describe('e2e_fees gas_estimation', () => { }; }; - const { estimatedGas } = await deployMethod().simulate({ + const sim3 = await deployMethod().simulate({ from: aliceAddress, skipClassPublication: true, fee: { @@ -192,12 +198,13 @@ describe('e2e_fees gas_estimation', () => { estimatedGasPadding: 0, }, }); + const estimatedGas = sim3.estimatedGas!; logGasEstimate(estimatedGas); - const [withEstimate, withoutEstimate] = (await Promise.all([ + const [{ receipt: withEstimate }, { receipt: withoutEstimate }] = (await Promise.all([ deployMethod().send(deployOpts(estimatedGas)), deployMethod().send(deployOpts()), - ])) as unknown as DeployTxReceipt[]; + ])) as unknown as { receipt: DeployTxReceipt }[]; // Estimation should yield that teardown has no cost, so should send the tx with zero for teardown expect(withEstimate.transactionFee!).toEqual(withoutEstimate.transactionFee!); diff --git a/yarn-project/end-to-end/src/e2e_fees/private_payments.test.ts b/yarn-project/end-to-end/src/e2e_fees/private_payments.test.ts index ebb72b1f9b3e..9563d02815da 100644 --- a/yarn-project/end-to-end/src/e2e_fees/private_payments.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/private_payments.test.ts @@ -155,7 +155,7 @@ describe('e2e_fees private_payment', () => { * increase Alice's private banana balance by feeAmount by finalizing partial note */ const newlyMintedBananas = 10n; - const tx = await bananaCoin.methods.mint_to_private(aliceAddress, newlyMintedBananas).send({ + const { receipt: tx } = await bananaCoin.methods.mint_to_private(aliceAddress, newlyMintedBananas).send({ from: aliceAddress, fee: { paymentMethod: new PrivateFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettings), @@ -200,12 +200,14 @@ describe('e2e_fees private_payment', () => { * increase Alice's private banana balance by feeAmount by finalizing partial note */ const amountTransferredToPrivate = 1n; - const tx = await bananaCoin.methods.transfer_to_private(aliceAddress, amountTransferredToPrivate).send({ - from: aliceAddress, - fee: { - paymentMethod: new PrivateFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettings), - }, - }); + const { receipt: tx } = await bananaCoin.methods + .transfer_to_private(aliceAddress, amountTransferredToPrivate) + .send({ + from: aliceAddress, + fee: { + paymentMethod: new PrivateFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettings), + }, + }); const feeAmount = tx.transactionFee!; @@ -249,7 +251,7 @@ describe('e2e_fees private_payment', () => { * increase sequencer/fee recipient/FPC admin private banana balance by feeAmount by finalizing partial note * increase Alice's private banana balance by feeAmount by finalizing partial note */ - const tx = await new BatchCall(wallet, [ + const { receipt: tx } = await new BatchCall(wallet, [ bananaCoin.methods.transfer(bobAddress, amountTransferredInPrivate), bananaCoin.methods.transfer_to_private(aliceAddress, amountTransferredToPrivate), ]).send({ @@ -283,7 +285,7 @@ describe('e2e_fees private_payment', () => { it('rejects txs that dont have enough balance to cover gas costs', async () => { // deploy a copy of bananaFPC but don't fund it! - const bankruptFPC = await FPCContract.deploy(wallet, bananaCoin.address, aliceAddress).send({ + const { contract: bankruptFPC } = await FPCContract.deploy(wallet, bananaCoin.address, aliceAddress).send({ from: aliceAddress, }); diff --git a/yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts b/yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts index 51e9109a90dc..b059938777db 100644 --- a/yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts @@ -59,12 +59,14 @@ describe('e2e_fees public_payment', () => { it('pays fees for tx that make public transfer', async () => { const bananasToSendToBob = 10n; - const tx = await bananaCoin.methods.transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0).send({ - from: aliceAddress, - fee: { - paymentMethod: new PublicFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettings), - }, - }); + const { receipt: tx } = await bananaCoin.methods + .transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0) + .send({ + from: aliceAddress, + fee: { + paymentMethod: new PublicFeePaymentMethod(bananaFPC.address, aliceAddress, wallet, gasSettings), + }, + }); const feeAmount = tx.transactionFee!; diff --git a/yarn-project/end-to-end/src/e2e_fees/sponsored_payments.test.ts b/yarn-project/end-to-end/src/e2e_fees/sponsored_payments.test.ts index aac9aaa557ee..ec9726d9d129 100644 --- a/yarn-project/end-to-end/src/e2e_fees/sponsored_payments.test.ts +++ b/yarn-project/end-to-end/src/e2e_fees/sponsored_payments.test.ts @@ -56,13 +56,15 @@ describe('e2e_fees sponsored_public_payment', () => { it('pays fees for tx that makes a public transfer', async () => { // docs:start:sponsored_fpc_simple const bananasToSendToBob = 10n; - const tx = await bananaCoin.methods.transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0).send({ - from: aliceAddress, - fee: { - gasSettings, - paymentMethod: new SponsoredFeePaymentMethod(sponsoredFPC.address), - }, - }); + const { receipt: tx } = await bananaCoin.methods + .transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0) + .send({ + from: aliceAddress, + fee: { + gasSettings, + paymentMethod: new SponsoredFeePaymentMethod(sponsoredFPC.address), + }, + }); // docs:end:sponsored_fpc_simple const feeAmount = tx.transactionFee!; diff --git a/yarn-project/end-to-end/src/e2e_kernelless_simulation.test.ts b/yarn-project/end-to-end/src/e2e_kernelless_simulation.test.ts index d424b78be5f1..4cdd919dacad 100644 --- a/yarn-project/end-to-end/src/e2e_kernelless_simulation.test.ts +++ b/yarn-project/end-to-end/src/e2e_kernelless_simulation.test.ts @@ -51,9 +51,9 @@ describe('Kernelless simulation', () => { ({ contract: token1 } = await deployToken(wallet, adminAddress, 0n, logger)); ({ contract: liquidityToken } = await deployToken(wallet, adminAddress, 0n, logger)); - amm = await AMMContract.deploy(wallet, token0.address, token1.address, liquidityToken.address).send({ + ({ contract: amm } = await AMMContract.deploy(wallet, token0.address, token1.address, liquidityToken.address).send({ from: adminAddress, - }); + })); await liquidityToken.methods.set_minter(amm.address, true).send({ from: adminAddress }); @@ -75,15 +75,15 @@ describe('Kernelless simulation', () => { async function getWalletBalances(lpAddress: AztecAddress): Promise { return { - token0: await token0.methods.balance_of_private(lpAddress).simulate({ from: lpAddress }), - token1: await token1.methods.balance_of_private(lpAddress).simulate({ from: lpAddress }), + token0: (await token0.methods.balance_of_private(lpAddress).simulate({ from: lpAddress })).result, + token1: (await token1.methods.balance_of_private(lpAddress).simulate({ from: lpAddress })).result, }; } async function getAmmBalances(): Promise { return { - token0: await token0.methods.balance_of_public(amm.address).simulate({ from: adminAddress }), - token1: await token1.methods.balance_of_public(amm.address).simulate({ from: adminAddress }), + token0: (await token0.methods.balance_of_public(amm.address).simulate({ from: adminAddress })).result, + token1: (await token1.methods.balance_of_public(amm.address).simulate({ from: adminAddress })).result, }; } @@ -224,7 +224,7 @@ describe('Kernelless simulation', () => { const nonceForAuthwits = Fr.random(); - const amountOutMin = await amm.methods + const { result: amountOutMin } = await amm.methods .get_amount_out_for_exact_in(ammBalancesBefore.token0, ammBalancesBefore.token1, amountIn) .simulate({ from: swapperAddress }); @@ -237,10 +237,12 @@ describe('Kernelless simulation', () => { ); wallet.enableSimulatedSimulations(); - const { estimatedGas: swapKernellessGas } = await swapExactTokensInteraction.simulate({ - from: swapperAddress, - includeMetadata: true, - }); + const swapKernellessGas = ( + await swapExactTokensInteraction.simulate({ + from: swapperAddress, + includeMetadata: true, + }) + ).estimatedGas!; const swapAuthwit = await wallet.createAuthWit(swapperAddress, { caller: amm.address, @@ -248,11 +250,13 @@ describe('Kernelless simulation', () => { }); wallet.disableSimulatedSimulations(); - const { estimatedGas: swapWithKernelsGas } = await swapExactTokensInteraction.simulate({ - from: swapperAddress, - includeMetadata: true, - authWitnesses: [swapAuthwit], - }); + const swapWithKernelsGas = ( + await swapExactTokensInteraction.simulate({ + from: swapperAddress, + includeMetadata: true, + authWitnesses: [swapAuthwit], + }) + ).estimatedGas!; logger.info(`Kernelless gas: L2=${swapKernellessGas.gasLimits.l2Gas} DA=${swapKernellessGas.gasLimits.daGas}`); logger.info( @@ -268,7 +272,9 @@ describe('Kernelless simulation', () => { let pendingNoteHashesContract: PendingNoteHashesContract; beforeAll(async () => { - pendingNoteHashesContract = await PendingNoteHashesContract.deploy(wallet).send({ from: adminAddress }); + ({ contract: pendingNoteHashesContract } = await PendingNoteHashesContract.deploy(wallet).send({ + from: adminAddress, + })); }); it('squashing produces same gas estimates as with-kernels path', async () => { @@ -283,16 +289,20 @@ describe('Kernelless simulation', () => { ); wallet.enableSimulatedSimulations(); - const { estimatedGas: kernellessGas } = await interaction.simulate({ - from: adminAddress, - includeMetadata: true, - }); + const kernellessGas = ( + await interaction.simulate({ + from: adminAddress, + includeMetadata: true, + }) + ).estimatedGas!; wallet.disableSimulatedSimulations(); - const { estimatedGas: withKernelsGas } = await interaction.simulate({ - from: adminAddress, - includeMetadata: true, - }); + const withKernelsGas = ( + await interaction.simulate({ + from: adminAddress, + includeMetadata: true, + }) + ).estimatedGas!; logger.info(`Kernelless gas: L2=${kernellessGas.gasLimits.l2Gas} DA=${kernellessGas.gasLimits.daGas}`); logger.info(`With kernels gas: L2=${withKernelsGas.gasLimits.l2Gas} DA=${withKernelsGas.gasLimits.daGas}`); @@ -306,7 +316,9 @@ describe('Kernelless simulation', () => { let pendingNoteHashesContract: PendingNoteHashesContract; beforeAll(async () => { - pendingNoteHashesContract = await PendingNoteHashesContract.deploy(wallet).send({ from: adminAddress }); + ({ contract: pendingNoteHashesContract } = await PendingNoteHashesContract.deploy(wallet).send({ + from: adminAddress, + })); }); it('verifies settled read requests against the note hash tree', async () => { diff --git a/yarn-project/end-to-end/src/e2e_keys.test.ts b/yarn-project/end-to-end/src/e2e_keys.test.ts index 82ecf79ca366..9e56bb423b87 100644 --- a/yarn-project/end-to-end/src/e2e_keys.test.ts +++ b/yarn-project/end-to-end/src/e2e_keys.test.ts @@ -45,7 +45,7 @@ describe('Keys', () => { initialFundedAccounts, } = await setup(1)); - testContract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); secret = initialFundedAccounts[0].secret; }); @@ -125,7 +125,7 @@ describe('Keys', () => { const expectedOvskApp = await computeAppSecretKey(ovskM, testContract.address, 'ov'); // Get the ovsk_app via the test contract - const ovskAppBigInt = await testContract.methods + const { result: ovskAppBigInt } = await testContract.methods .get_ovsk_app(ovpkMHash) .simulate({ from: defaultAccountAddress }); const ovskApp = new Fr(ovskAppBigInt); 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 5c143383ebb1..22c1964fe1f8 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 @@ -39,11 +39,13 @@ describe('e2e_lending_contract', () => { const deployContracts = async () => { logger.info(`Deploying price feed contract...`); - const priceFeedContract = await PriceFeedContract.deploy(wallet).send({ from: defaultAccountAddress }); + const { contract: priceFeedContract } = await PriceFeedContract.deploy(wallet).send({ + from: defaultAccountAddress, + }); logger.info(`Price feed deployed to ${priceFeedContract.address}`); logger.info(`Deploying collateral asset feed contract...`); - const collateralAsset = await TokenContract.deploy( + const { contract: collateralAsset } = await TokenContract.deploy( wallet, defaultAccountAddress, 'TokenName', @@ -53,13 +55,19 @@ describe('e2e_lending_contract', () => { logger.info(`Collateral asset deployed to ${collateralAsset.address}`); logger.info(`Deploying stable coin contract...`); - const stableCoin = await TokenContract.deploy(wallet, defaultAccountAddress, 'TokenName', 'TokenSymbol', 18).send({ + const { contract: stableCoin } = await TokenContract.deploy( + wallet, + defaultAccountAddress, + 'TokenName', + 'TokenSymbol', + 18, + ).send({ from: defaultAccountAddress, }); logger.info(`Stable coin asset deployed to ${stableCoin.address}`); logger.info(`Deploying L2 public contract...`); - const lendingContract = await LendingContract.deploy(wallet).send({ from: defaultAccountAddress }); + const { contract: lendingContract } = await LendingContract.deploy(wallet).send({ from: defaultAccountAddress }); logger.info(`CDP deployed at ${lendingContract.address}`); await collateralAsset.methods.set_minter(lendingContract.address, true).send({ from: defaultAccountAddress }); diff --git a/yarn-project/end-to-end/src/e2e_mempool_limit.test.ts b/yarn-project/end-to-end/src/e2e_mempool_limit.test.ts index 8ce86ab42188..f46ff8a3a165 100644 --- a/yarn-project/end-to-end/src/e2e_mempool_limit.test.ts +++ b/yarn-project/end-to-end/src/e2e_mempool_limit.test.ts @@ -31,9 +31,9 @@ describe('e2e_mempool_limit', () => { throw new Error('Aztec node admin API must be available for this test'); } - token = await TokenContract.deploy(wallet, defaultAccountAddress, 'TEST', 'T', 18).send({ + ({ contract: token } = await TokenContract.deploy(wallet, defaultAccountAddress, 'TEST', 'T', 18).send({ from: defaultAccountAddress, - }); + })); await token.methods.mint_to_public(defaultAccountAddress, 10n ** 18n).send({ from: defaultAccountAddress }); }); diff --git a/yarn-project/end-to-end/src/e2e_multi_validator/e2e_multi_validator_node.test.ts b/yarn-project/end-to-end/src/e2e_multi_validator/e2e_multi_validator_node.test.ts index 35dccd29e152..47ec290401f2 100644 --- a/yarn-project/end-to-end/src/e2e_multi_validator/e2e_multi_validator_node.test.ts +++ b/yarn-project/end-to-end/src/e2e_multi_validator/e2e_multi_validator_node.test.ts @@ -114,7 +114,7 @@ describe('e2e_multi_validator_node', () => { const sender = ownerAddress; logger.info(`Deploying contract from ${sender}`); - const tx = await deployer.deploy(ownerAddress, sender, 1).send({ + const { receipt: tx } = await deployer.deploy(ownerAddress, sender, 1).send({ from: ownerAddress, contractAddressSalt: new Fr(BigInt(1)), skipClassPublication: true, @@ -177,7 +177,7 @@ describe('e2e_multi_validator_node', () => { logger.info(`Deploying contract from ${sender}`); const deployer = new ContractDeployer(artifact, wallet); - const tx = await deployer.deploy(ownerAddress, sender, 1).send({ + const { receipt: tx } = await deployer.deploy(ownerAddress, sender, 1).send({ from: ownerAddress, contractAddressSalt: new Fr(BigInt(1)), skipClassPublication: true, diff --git a/yarn-project/end-to-end/src/e2e_multiple_blobs.test.ts b/yarn-project/end-to-end/src/e2e_multiple_blobs.test.ts index f447cb54d557..c4da4436f003 100644 --- a/yarn-project/end-to-end/src/e2e_multiple_blobs.test.ts +++ b/yarn-project/end-to-end/src/e2e_multiple_blobs.test.ts @@ -36,7 +36,7 @@ describe('e2e_multiple_blobs', () => { } = await setup(1)); aztecNodeAdmin = maybeAztecNodeAdmin!; - contract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); @@ -68,10 +68,10 @@ describe('e2e_multiple_blobs', () => { expect(provenTxs.length).toBe(TX_COUNT); // Send them simultaneously to be picked up by the sequencer - const txHashes = await Promise.all(provenTxs.map(tx => tx.send({ from: defaultAccountAddress, wait: NO_WAIT }))); + const sendResults = await Promise.all(provenTxs.map(tx => tx.send({ from: defaultAccountAddress, wait: NO_WAIT }))); // Wait for all to be mined const receipts = await Promise.all( - txHashes.map(txHash => { + sendResults.map(({ txHash }) => { return waitForTx(aztecNode, txHash); }), ); diff --git a/yarn-project/end-to-end/src/e2e_nested_contract/importer.test.ts b/yarn-project/end-to-end/src/e2e_nested_contract/importer.test.ts index 27449075dfe9..aab6d6fb59c4 100644 --- a/yarn-project/end-to-end/src/e2e_nested_contract/importer.test.ts +++ b/yarn-project/end-to-end/src/e2e_nested_contract/importer.test.ts @@ -15,8 +15,8 @@ describe('e2e_nested_contract manual', () => { }); beforeEach(async () => { - importerContract = await ImportTestContract.deploy(wallet).send({ from: defaultAccountAddress }); - testContract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: importerContract } = await ImportTestContract.deploy(wallet).send({ from: defaultAccountAddress })); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(async () => { diff --git a/yarn-project/end-to-end/src/e2e_nested_contract/manual_private_enqueue.test.ts b/yarn-project/end-to-end/src/e2e_nested_contract/manual_private_enqueue.test.ts index ac9512f43421..0e19664a5662 100644 --- a/yarn-project/end-to-end/src/e2e_nested_contract/manual_private_enqueue.test.ts +++ b/yarn-project/end-to-end/src/e2e_nested_contract/manual_private_enqueue.test.ts @@ -19,8 +19,8 @@ describe('e2e_nested_contract manual_enqueue', () => { }); beforeEach(async () => { - parentContract = await ParentContract.deploy(wallet).send({ from: defaultAccountAddress }); - childContract = await ChildContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: parentContract } = await ParentContract.deploy(wallet).send({ from: defaultAccountAddress })); + ({ contract: childContract } = await ChildContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(async () => { diff --git a/yarn-project/end-to-end/src/e2e_nested_contract/manual_public.test.ts b/yarn-project/end-to-end/src/e2e_nested_contract/manual_public.test.ts index 3b47116fcb96..a699ea8f1764 100644 --- a/yarn-project/end-to-end/src/e2e_nested_contract/manual_public.test.ts +++ b/yarn-project/end-to-end/src/e2e_nested_contract/manual_public.test.ts @@ -48,7 +48,7 @@ describe('e2e_nested_contract manual', () => { parentContract.methods.enqueue_call_to_child(childContract.address, pubSetValueSelector, 40n), ]; - const tx = await new BatchCall(wallet, actions).send({ from: defaultAccountAddress }); + const { receipt: tx } = await new BatchCall(wallet, actions).send({ from: defaultAccountAddress }); const extendedLogs = ( await aztecNode.getPublicLogs({ fromBlock: tx.blockNumber!, diff --git a/yarn-project/end-to-end/src/e2e_nested_contract/nested_contract_test.ts b/yarn-project/end-to-end/src/e2e_nested_contract/nested_contract_test.ts index 5632daf6c133..769db81c1ba0 100644 --- a/yarn-project/end-to-end/src/e2e_nested_contract/nested_contract_test.ts +++ b/yarn-project/end-to-end/src/e2e_nested_contract/nested_contract_test.ts @@ -65,9 +65,11 @@ export class NestedContractTest { async applyManual() { this.logger.info('Deploying parent and child contracts'); - const parentContract = await ParentContract.deploy(this.wallet).send({ from: this.defaultAccountAddress }); - const childContract = await ChildContract.deploy(this.wallet).send({ from: this.defaultAccountAddress }); - this.parentContract = parentContract; - this.childContract = childContract; + ({ contract: this.parentContract } = await ParentContract.deploy(this.wallet).send({ + from: this.defaultAccountAddress, + })); + ({ contract: this.childContract } = await ChildContract.deploy(this.wallet).send({ + from: this.defaultAccountAddress, + })); } } diff --git a/yarn-project/end-to-end/src/e2e_nft.test.ts b/yarn-project/end-to-end/src/e2e_nft.test.ts index 35a2e8c7310d..7e7f8da1079a 100644 --- a/yarn-project/end-to-end/src/e2e_nft.test.ts +++ b/yarn-project/end-to-end/src/e2e_nft.test.ts @@ -33,7 +33,9 @@ describe('NFT', () => { ({ teardown, wallet, accounts } = await setup(4)); [adminAddress, minterAddress, user1Address, user2Address] = accounts; - nftContract = await NFTContract.deploy(wallet, adminAddress, 'FROG', 'FRG').send({ from: adminAddress }); + ({ contract: nftContract } = await NFTContract.deploy(wallet, adminAddress, 'FROG', 'FRG').send({ + from: adminAddress, + })); }); afterAll(() => teardown()); @@ -41,13 +43,15 @@ describe('NFT', () => { // NOTE: This test is sequential and each test case depends on the previous one it('sets minter', async () => { await nftContract.methods.set_minter(minterAddress, true).send({ from: adminAddress }); - const isMinterAMinter = await nftContract.methods.is_minter(minterAddress).simulate({ from: minterAddress }); + const { result: isMinterAMinter } = await nftContract.methods + .is_minter(minterAddress) + .simulate({ from: minterAddress }); expect(isMinterAMinter).toBe(true); }); it('minter mints to a user', async () => { await nftContract.methods.mint(user1Address, TOKEN_ID).send({ from: minterAddress }); - const ownerAfterMint = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); + const { result: ownerAfterMint } = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); expect(ownerAfterMint).toEqual(user1Address); }); @@ -57,7 +61,7 @@ describe('NFT', () => { const recipient = user2Address; await nftContract.methods.transfer_to_private(recipient, TOKEN_ID).send({ from: user1Address }); - const publicOwnerAfter = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); + const { result: publicOwnerAfter } = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); expect(publicOwnerAfter).toEqual(AztecAddress.ZERO); }); @@ -74,19 +78,21 @@ describe('NFT', () => { it('transfers to public', async () => { await nftContract.methods.transfer_to_public(user1Address, user2Address, TOKEN_ID, 0).send({ from: user1Address }); - const publicOwnerAfter = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); + const { result: publicOwnerAfter } = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user1Address }); expect(publicOwnerAfter).toEqual(user2Address); }); it('transfers in public', async () => { await nftContract.methods.transfer_in_public(user2Address, user1Address, TOKEN_ID, 0).send({ from: user2Address }); - const publicOwnerAfter = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user2Address }); + const { result: publicOwnerAfter } = await nftContract.methods.owner_of(TOKEN_ID).simulate({ from: user2Address }); expect(publicOwnerAfter).toEqual(user1Address); }); const getPrivateNfts = async (owner: AztecAddress) => { - const [nfts, pageLimitReached] = await nftContract.methods.get_private_nfts(owner, 0).simulate({ from: owner }); + const { + result: [nfts, pageLimitReached], + } = await nftContract.methods.get_private_nfts(owner, 0).simulate({ from: owner }); if (pageLimitReached) { throw new Error('Page limit reached and pagination not implemented in test'); } diff --git a/yarn-project/end-to-end/src/e2e_note_getter.test.ts b/yarn-project/end-to-end/src/e2e_note_getter.test.ts index d8192b71827c..c48c9f291a53 100644 --- a/yarn-project/end-to-end/src/e2e_note_getter.test.ts +++ b/yarn-project/end-to-end/src/e2e_note_getter.test.ts @@ -34,7 +34,7 @@ describe('e2e_note_getter', () => { let contract: NoteGetterContract; beforeAll(async () => { - contract = await NoteGetterContract.deploy(wallet).send({ from: defaultAddress }); + ({ contract } = await NoteGetterContract.deploy(wallet).send({ from: defaultAddress })); }); it('inserts notes from 0-9, then makes multiple queries specifying the total suite of comparators', async () => { @@ -47,7 +47,14 @@ describe('e2e_note_getter', () => { // We insert a note with value 5 twice to better test the comparators await contract.methods.insert_note(5).send({ from: defaultAddress }); - const [returnEq, returnNeq, returnLt, returnGt, returnLte, returnGte] = await Promise.all([ + const [ + { result: returnEq }, + { result: returnNeq }, + { result: returnLt }, + { result: returnGt }, + { result: returnLte }, + { result: returnGte }, + ] = await Promise.all([ contract.methods.read_note_values(defaultAddress, Comparator.EQ, 5).simulate({ from: defaultAddress }), contract.methods.read_note_values(defaultAddress, Comparator.NEQ, 5).simulate({ from: defaultAddress }), contract.methods.read_note_values(defaultAddress, Comparator.LT, 5).simulate({ from: defaultAddress }), @@ -78,7 +85,7 @@ describe('e2e_note_getter', () => { const makeTxHybrid = false; beforeAll(async () => { - contract = await TestContract.deploy(wallet).send({ from: defaultAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAddress })); owner = defaultAddress; }); @@ -93,10 +100,10 @@ describe('e2e_note_getter', () => { }); async function assertNoteIsReturned(storageSlot: number, expectedValue: number, activeOrNullified: boolean) { - const viewNotesResult = await contract.methods + const { result: viewNotesResult } = await contract.methods .call_view_notes(owner, storageSlot, activeOrNullified) .simulate({ from: defaultAddress }); - const getNotesResult = await contract.methods + const { result: getNotesResult } = await contract.methods .call_get_notes(owner, storageSlot, activeOrNullified) .simulate({ from: defaultAddress }); @@ -155,10 +162,10 @@ describe('e2e_note_getter', () => { await contract.methods.call_destroy_note(owner, storageSlot).send({ from: defaultAddress }); // We now fetch multiple notes, and get both the active and the nullified one. - const viewNotesManyResult = await contract.methods + const { result: viewNotesManyResult } = await contract.methods .call_view_notes_many(owner, storageSlot, activeOrNullified) .simulate({ from: defaultAddress }); - const getNotesManyResult = await contract.methods + const { result: getNotesManyResult } = await contract.methods .call_get_notes_many(owner, storageSlot, activeOrNullified) .simulate({ from: defaultAddress }); diff --git a/yarn-project/end-to-end/src/e2e_offchain_effect.test.ts b/yarn-project/end-to-end/src/e2e_offchain_effect.test.ts index 624433699dd6..9968050c18b7 100644 --- a/yarn-project/end-to-end/src/e2e_offchain_effect.test.ts +++ b/yarn-project/end-to-end/src/e2e_offchain_effect.test.ts @@ -33,12 +33,34 @@ describe('e2e_offchain_effect', () => { accounts: [defaultAccountAddress], aztecNode, } = await setup(1)); - contract1 = await OffchainEffectContract.deploy(wallet).send({ from: defaultAccountAddress }); - contract2 = await OffchainEffectContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: contract1 } = await OffchainEffectContract.deploy(wallet).send({ from: defaultAccountAddress })); + ({ contract: contract2 } = await OffchainEffectContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); + it('should return offchain effects from send()', async () => { + const effects = Array(2) + .fill(null) + .map(() => ({ + data: [Fr.random(), Fr.random(), Fr.random(), Fr.random(), Fr.random()], + // eslint-disable-next-line camelcase + next_contract: contract1.address, + })); + + const { receipt, offchainEffects } = await contract1.methods + .emit_offchain_effects(effects) + .send({ from: defaultAccountAddress }); + + expect(receipt.hasExecutionSucceeded()).toBe(true); + // Effects are popped from the end of the BoundedVec, so they come out reversed + expect(offchainEffects).toHaveLength(2); + expect(offchainEffects[0].contractAddress).toEqual(contract1.address); + expect(offchainEffects[0].data).toEqual(effects[1].data); + expect(offchainEffects[1].contractAddress).toEqual(contract1.address); + expect(offchainEffects[1].data).toEqual(effects[0].data); + }); + it('should emit offchain effects', async () => { const effects = Array(3) .fill(null) @@ -164,7 +186,9 @@ describe('e2e_offchain_effect', () => { .simulate({ from: defaultAccountAddress }); // Get the note value - const noteValue = await contract1.methods.get_note_value(owner).simulate({ from: defaultAccountAddress }); + const { result: noteValue } = await contract1.methods + .get_note_value(owner) + .simulate({ from: defaultAccountAddress }); expect(noteValue).toBe(value); }); }); diff --git a/yarn-project/end-to-end/src/e2e_orderbook.test.ts b/yarn-project/end-to-end/src/e2e_orderbook.test.ts index 1ac98d5ae223..22efa02edd17 100644 --- a/yarn-project/end-to-end/src/e2e_orderbook.test.ts +++ b/yarn-project/end-to-end/src/e2e_orderbook.test.ts @@ -52,9 +52,9 @@ describe('Orderbook', () => { ({ contract: token0 } = await deployToken(wallet, adminAddress, 0n, logger)); ({ contract: token1 } = await deployToken(wallet, adminAddress, 0n, logger)); - orderbook = await OrderbookContract.deploy(wallet, token0.address, token1.address).send({ + ({ contract: orderbook } = await OrderbookContract.deploy(wallet, token0.address, token1.address).send({ from: adminAddress, - }); + })); // Mint tokens to maker and taker await mintTokensToPrivate(token0, adminAddress, makerAddress, bidAmount); @@ -95,7 +95,9 @@ describe('Orderbook', () => { orderId = orderCreatedEvents[0].event.order_id; // Get order from orderbook and verify details - const [order, isFulfilled] = await orderbook.methods.get_order(orderId).simulate({ from: adminAddress }); + const { + result: [order, isFulfilled], + } = await orderbook.methods.get_order(orderId).simulate({ from: adminAddress }); expect(order.bid_amount).toEqual(bidAmount); expect(order.ask_amount).toEqual(askAmount); expect(order.bid_token_is_zero).toBeTrue(); @@ -103,10 +105,12 @@ describe('Orderbook', () => { // At this point, bidAmount of token0 should be transferred to the public balance of the orderbook and maker // should have 0. - const orderbookBalances0 = await token0.methods + const { result: orderbookBalances0 } = await token0.methods .balance_of_public(orderbook.address) .simulate({ from: makerAddress }); - const makerBalances0 = await token0.methods.balance_of_private(makerAddress).simulate({ from: makerAddress }); + const { result: makerBalances0 } = await token0.methods + .balance_of_private(makerAddress) + .simulate({ from: makerAddress }); expect(orderbookBalances0).toEqual(bidAmount); expect(makerBalances0).toEqual(0n); }); @@ -142,10 +146,18 @@ describe('Orderbook', () => { expect(orderFulfilledEvents[0].event.order_id).toEqual(orderId); // Verify balances after order fulfillment - const makerBalances0 = await token0.methods.balance_of_private(makerAddress).simulate({ from: makerAddress }); - const makerBalances1 = await token1.methods.balance_of_private(makerAddress).simulate({ from: makerAddress }); - const takerBalances0 = await token0.methods.balance_of_private(takerAddress).simulate({ from: takerAddress }); - const takerBalances1 = await token1.methods.balance_of_private(takerAddress).simulate({ from: takerAddress }); + const { result: makerBalances0 } = await token0.methods + .balance_of_private(makerAddress) + .simulate({ from: makerAddress }); + const { result: makerBalances1 } = await token1.methods + .balance_of_private(makerAddress) + .simulate({ from: makerAddress }); + const { result: takerBalances0 } = await token0.methods + .balance_of_private(takerAddress) + .simulate({ from: takerAddress }); + const { result: takerBalances1 } = await token1.methods + .balance_of_private(takerAddress) + .simulate({ from: takerAddress }); // Full maker token 0 balance should be transferred to taker and hence maker should have 0 expect(makerBalances0).toEqual(0n); @@ -157,7 +169,9 @@ describe('Orderbook', () => { expect(takerBalances1).toEqual(0n); // Verify that the order is fulfilled - const [_, isFulfilled] = await orderbook.methods.get_order(orderId).simulate({ from: adminAddress }); + const { + result: [_, isFulfilled], + } = await orderbook.methods.get_order(orderId).simulate({ from: adminAddress }); expect(isFulfilled).toBeTrue(); }); }); diff --git a/yarn-project/end-to-end/src/e2e_ordering.test.ts b/yarn-project/end-to-end/src/e2e_ordering.test.ts index fb310765f04e..56f8df05058a 100644 --- a/yarn-project/end-to-end/src/e2e_ordering.test.ts +++ b/yarn-project/end-to-end/src/e2e_ordering.test.ts @@ -56,8 +56,8 @@ describe('e2e_ordering', () => { let pubSetValueSelector: FunctionSelector; beforeEach(async () => { - parent = await ParentContract.deploy(wallet).send({ from: defaultAccountAddress }); - child = await ChildContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: parent } = await ParentContract.deploy(wallet).send({ from: defaultAccountAddress })); + ({ contract: child } = await ChildContract.deploy(wallet).send({ from: defaultAccountAddress })); pubSetValueSelector = await child.methods.pub_set_value.selector(); }, TIMEOUT); diff --git a/yarn-project/end-to-end/src/e2e_p2p/add_rollup.test.ts b/yarn-project/end-to-end/src/e2e_p2p/add_rollup.test.ts index a1964ef8f74b..786b2c9aa7a5 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/add_rollup.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/add_rollup.test.ts @@ -285,7 +285,7 @@ describe('e2e_p2p_add_rollup', () => { const aliceAddress = aliceAccountManager.address; - const testContract = await TestContract.deploy(wallet).send({ from: aliceAddress }); + const { contract: testContract } = await TestContract.deploy(wallet).send({ from: aliceAddress }); const [secret, secretHash] = await generateClaimSecret(); @@ -304,7 +304,7 @@ describe('e2e_p2p_add_rollup', () => { // We poll isL1ToL2MessageSynced endpoint until the message is available await retryUntil(async () => await node.isL1ToL2MessageSynced(msgHash), 'message sync', 10); - const receipt = await testContract.methods + const { receipt } = await testContract.methods .create_l2_to_l1_message_arbitrary_recipient_private(contentOutFromRollup, ethRecipient) .send({ from: aliceAddress }); diff --git a/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts b/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts index 6e90af2fad87..83e18d1bc4ea 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts @@ -323,8 +323,9 @@ export class P2PNetworkTest { throw new Error('Call setupAccount before deploying spam contract'); } - const spamContract = await SpamContract.deploy(this.wallet).send({ from: this.defaultAccountAddress! }); - this.spamContract = spamContract; + ({ contract: this.spamContract } = await SpamContract.deploy(this.wallet).send({ + from: this.defaultAccountAddress!, + })); } async removeInitialNode() { diff --git a/yarn-project/end-to-end/src/e2e_p2p/shared.ts b/yarn-project/end-to-end/src/e2e_p2p/shared.ts index b4bf13758ef9..656313537ec8 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/shared.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/shared.ts @@ -42,7 +42,7 @@ export const submitComplexTxsTo = async ( const spamCount = 15; for (let i = 0; i < numTxs; i++) { const method = spamContract.methods.spam(seed + BigInt(i * spamCount), spamCount, !!opts.callPublic); - const txHash = await method.send({ from, wait: NO_WAIT }); + const { txHash } = await method.send({ from, wait: NO_WAIT }); logger.info(`Tx sent with hash ${txHash.toString()}`); txs.push(txHash); } diff --git a/yarn-project/end-to-end/src/e2e_partial_notes.test.ts b/yarn-project/end-to-end/src/e2e_partial_notes.test.ts index 104d7ef3b215..8742a20129a0 100644 --- a/yarn-project/end-to-end/src/e2e_partial_notes.test.ts +++ b/yarn-project/end-to-end/src/e2e_partial_notes.test.ts @@ -43,7 +43,8 @@ describe('partial notes', () => { it('mint to private', async () => { await mintTokensToPrivate(token0, adminAddress, liquidityProviderAddress, INITIAL_TOKEN_BALANCE); expect( - await token0.methods.balance_of_private(liquidityProviderAddress).simulate({ from: liquidityProviderAddress }), + (await token0.methods.balance_of_private(liquidityProviderAddress).simulate({ from: liquidityProviderAddress })) + .result, ).toEqual(INITIAL_TOKEN_BALANCE); }); }); diff --git a/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts b/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts index 60960712c619..e69a176d72e7 100644 --- a/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_pending_note_hashes_contract.test.ts @@ -75,7 +75,7 @@ describe('e2e_pending_note_hashes_contract', () => { const deployContract = async () => { logger.debug(`Deploying L2 contract...`); - contract = await PendingNoteHashesContract.deploy(wallet).send({ from: owner }); + ({ contract } = await PendingNoteHashesContract.deploy(wallet).send({ from: owner })); logger.info(`L2 contract deployed at ${contract.address}`); return contract; }; diff --git a/yarn-project/end-to-end/src/e2e_phase_check.test.ts b/yarn-project/end-to-end/src/e2e_phase_check.test.ts index 03ba19047c61..581611cbbd71 100644 --- a/yarn-project/end-to-end/src/e2e_phase_check.test.ts +++ b/yarn-project/end-to-end/src/e2e_phase_check.test.ts @@ -35,7 +35,7 @@ describe('Phase check', () => { accounts: [defaultAccountAddress], } = await setup(1, { genesisPublicData: [genesisBalanceEntry] })); - contract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); sponsoredFPC = await SponsoredFPCNoEndSetupContract.deploy(wallet).register({ contractAddressSalt: new Fr(SPONSORED_FPC_SALT), }); diff --git a/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts b/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts index 86809063a08c..6a60739c2d36 100644 --- a/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_private_voting_contract.test.ts @@ -25,7 +25,7 @@ describe('e2e_voting_contract', () => { accounts: [owner], } = await setup(1)); - votingContract = await PrivateVotingContract.deploy(wallet, owner).send({ from: owner }); + ({ contract: votingContract } = await PrivateVotingContract.deploy(wallet, owner).send({ from: owner })); logger.info(`Counter contract deployed at ${votingContract.address}`); }); @@ -40,7 +40,7 @@ describe('e2e_voting_contract', () => { await votingContract.methods.start_vote(electionId).send({ from: owner }); await votingContract.methods.cast_vote(electionId, candidate).send({ from: owner }); - expect(await votingContract.methods.get_tally(electionId, candidate).simulate({ from: owner })).toBe(1n); + expect((await votingContract.methods.get_tally(electionId, candidate).simulate({ from: owner })).result).toBe(1n); // We try voting again, but our TX is dropped due to trying to emit duplicate nullifiers // first confirm that it fails simulation diff --git a/yarn-project/end-to-end/src/e2e_prover/client.test.ts b/yarn-project/end-to-end/src/e2e_prover/client.test.ts index 7ff197d01a71..aef6fcd86af6 100644 --- a/yarn-project/end-to-end/src/e2e_prover/client.test.ts +++ b/yarn-project/end-to-end/src/e2e_prover/client.test.ts @@ -71,12 +71,14 @@ describe('client_prover', () => { ); // Create the two transactions - const privateBalance = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); + const { result: privateBalance } = await provenAsset.methods + .balance_of_private(sender) + .simulate({ from: sender }); const privateSendAmount = privateBalance / 10n; expect(privateSendAmount).toBeGreaterThan(0n); const privateInteraction = provenAsset.methods.transfer(recipient, privateSendAmount); - const publicBalance = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); + const { result: publicBalance } = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); const publicSendAmount = publicBalance / 10n; expect(publicSendAmount).toBeGreaterThan(0n); const publicInteraction = provenAsset.methods.transfer_in_public(sender, recipient, publicSendAmount, 0); diff --git a/yarn-project/end-to-end/src/e2e_prover/full.test.ts b/yarn-project/end-to-end/src/e2e_prover/full.test.ts index eb3dc3e82529..7d70a5b443d2 100644 --- a/yarn-project/end-to-end/src/e2e_prover/full.test.ts +++ b/yarn-project/end-to-end/src/e2e_prover/full.test.ts @@ -87,12 +87,14 @@ describe('full_prover', () => { ); // Create the two transactions - const privateBalance = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); + const { result: privateBalance } = await provenAsset.methods + .balance_of_private(sender) + .simulate({ from: sender }); const privateSendAmount = privateBalance / 10n; expect(privateSendAmount).toBeGreaterThan(0n); const privateInteraction = provenAsset.methods.transfer(recipient, privateSendAmount); - const publicBalance = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); + const { result: publicBalance } = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); const publicSendAmount = publicBalance / 10n; expect(publicSendAmount).toBeGreaterThan(0n); const publicInteraction = provenAsset.methods.transfer_in_public(sender, recipient, publicSendAmount, 0); @@ -180,12 +182,12 @@ describe('full_prover', () => { return; } // Create the two transactions - const privateBalance = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); + const { result: privateBalance } = await provenAsset.methods.balance_of_private(sender).simulate({ from: sender }); const privateSendAmount = privateBalance / 20n; expect(privateSendAmount).toBeGreaterThan(0n); const firstPrivateInteraction = provenAsset.methods.transfer(recipient, privateSendAmount); - const publicBalance = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); + const { result: publicBalance } = await provenAsset.methods.balance_of_public(sender).simulate({ from: sender }); const publicSendAmount = publicBalance / 10n; expect(publicSendAmount).toBeGreaterThan(0n); const publicInteraction = provenAsset.methods.transfer_in_public(sender, recipient, publicSendAmount, 0); diff --git a/yarn-project/end-to-end/src/e2e_pruned_blocks.test.ts b/yarn-project/end-to-end/src/e2e_pruned_blocks.test.ts index 50a8db649dd6..02db37673052 100644 --- a/yarn-project/end-to-end/src/e2e_pruned_blocks.test.ts +++ b/yarn-project/end-to-end/src/e2e_pruned_blocks.test.ts @@ -53,7 +53,7 @@ describe('e2e_pruned_blocks', () => { aztecProofSubmissionEpochs: 1024, // effectively do not reorg })); - token = await TokenContract.deploy(wallet, admin, 'TEST', '$TST', 18).send({ from: admin }); + ({ contract: token } = await TokenContract.deploy(wallet, admin, 'TEST', '$TST', 18).send({ from: admin })); logger.info(`L2 token contract deployed at ${token.address}`); }); @@ -76,7 +76,9 @@ describe('e2e_pruned_blocks', () => { // mint transaction that the node will drop the block corresponding to the first mint, resulting in errors if PXE // tried to access any historical information related to it (which it shouldn't). - const firstMintReceipt = await token.methods.mint_to_private(sender, MINT_AMOUNT / 2n).send({ from: admin }); + const { receipt: firstMintReceipt } = await token.methods + .mint_to_private(sender, MINT_AMOUNT / 2n) + .send({ from: admin }); const firstMintTxEffect = await aztecNode.getTxEffect(firstMintReceipt.txHash); // mint_to_private should create just one new note with the minted amount @@ -122,7 +124,9 @@ describe('e2e_pruned_blocks', () => { await token.methods.transfer(recipient, MINT_AMOUNT).send({ from: sender }); - expect(await token.methods.balance_of_private(recipient).simulate({ from: recipient })).toEqual(MINT_AMOUNT); - expect(await token.methods.balance_of_private(sender).simulate({ from: sender })).toEqual(0n); + expect((await token.methods.balance_of_private(recipient).simulate({ from: recipient })).result).toEqual( + MINT_AMOUNT, + ); + expect((await token.methods.balance_of_private(sender).simulate({ from: sender })).result).toEqual(0n); }); }); diff --git a/yarn-project/end-to-end/src/e2e_public_testnet/e2e_public_testnet_transfer.test.ts b/yarn-project/end-to-end/src/e2e_public_testnet/e2e_public_testnet_transfer.test.ts index 708254faba14..551304e259bd 100644 --- a/yarn-project/end-to-end/src/e2e_public_testnet/e2e_public_testnet_transfer.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_testnet/e2e_public_testnet_transfer.test.ts @@ -60,7 +60,7 @@ describe(`deploys and transfers a private only token`, () => { ); const tokenInstance = await tokenDeployment.getInstance(); await wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey); - const token = await tokenDeployment.send({ + const { contract: token } = await tokenDeployment.send({ from: deployerAddress, // The contract constructor initializes private storage vars that need the contract's own nullifier key. additionalScopes: [tokenInstance.address], @@ -78,8 +78,12 @@ describe(`deploys and transfers a private only token`, () => { logger.info(`Transfer completed`); - const balanceDeployer = await token.methods.get_balance(deployerAddress).simulate({ from: deployerAddress }); - const balanceRecipient = await token.methods.get_balance(recipientAddress).simulate({ from: recipientAddress }); + const { result: balanceDeployer } = await token.methods + .get_balance(deployerAddress) + .simulate({ from: deployerAddress }); + const { result: balanceRecipient } = await token.methods + .get_balance(recipientAddress) + .simulate({ from: recipientAddress }); logger.info(`Deployer balance: ${balanceDeployer}, Recipient balance: ${balanceRecipient}`); diff --git a/yarn-project/end-to-end/src/e2e_pxe.test.ts b/yarn-project/end-to-end/src/e2e_pxe.test.ts index 5f86fc373e11..efeb60c27cbe 100644 --- a/yarn-project/end-to-end/src/e2e_pxe.test.ts +++ b/yarn-project/end-to-end/src/e2e_pxe.test.ts @@ -21,7 +21,7 @@ describe('e2e_pxe', () => { wallet, accounts: [defaultAccountAddress], } = await setup()); - contract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); diff --git a/yarn-project/end-to-end/src/e2e_scope_isolation.test.ts b/yarn-project/end-to-end/src/e2e_scope_isolation.test.ts index c84eeadc62b0..5c8e4e2fdfc2 100644 --- a/yarn-project/end-to-end/src/e2e_scope_isolation.test.ts +++ b/yarn-project/end-to-end/src/e2e_scope_isolation.test.ts @@ -21,7 +21,7 @@ describe('e2e scope isolation', () => { ({ teardown, wallet, accounts } = await setup(3)); [alice, bob, charlie] = accounts; - contract = await ScopeTestContract.deploy(wallet).send({ from: alice }); + ({ contract } = await ScopeTestContract.deploy(wallet).send({ from: alice })); // Alice and bob create a note for themselves (used by multiple tests below) await contract.methods.create_note(alice, Number(ALICE_NOTE_VALUE)).send({ from: alice }); @@ -32,7 +32,7 @@ describe('e2e scope isolation', () => { describe('external private', () => { it('owner can read own notes', async () => { - const value = await contract.methods.read_note(alice).simulate({ from: alice }); + const { result: value } = await contract.methods.read_note(alice).simulate({ from: alice }); expect(value).toEqual(ALICE_NOTE_VALUE); }); @@ -47,8 +47,8 @@ describe('e2e scope isolation', () => { }); it('each account can access their isolated state on a shared wallet', async () => { - const aliceValue = await contract.methods.read_note(alice).simulate({ from: alice }); - const bobValue = await contract.methods.read_note(bob).simulate({ from: bob }); + const { result: aliceValue } = await contract.methods.read_note(alice).simulate({ from: alice }); + const { result: bobValue } = await contract.methods.read_note(bob).simulate({ from: bob }); expect(aliceValue).toEqual(ALICE_NOTE_VALUE); expect(bobValue).toEqual(BOB_NOTE_VALUE); @@ -57,7 +57,7 @@ describe('e2e scope isolation', () => { describe('external utility', () => { it('owner can read own notes', async () => { - const value = await contract.methods.read_note_utility(alice).simulate({ from: alice }); + const { result: value } = await contract.methods.read_note_utility(alice).simulate({ from: alice }); expect(value).toEqual(ALICE_NOTE_VALUE); }); @@ -74,8 +74,8 @@ describe('e2e scope isolation', () => { }); it('each account can access their isolated state on a shared wallet', async () => { - const aliceValue = await contract.methods.read_note_utility(alice).simulate({ from: alice }); - const bobValue = await contract.methods.read_note_utility(bob).simulate({ from: bob }); + const { result: aliceValue } = await contract.methods.read_note_utility(alice).simulate({ from: alice }); + const { result: bobValue } = await contract.methods.read_note_utility(bob).simulate({ from: bob }); expect(aliceValue).toEqual(ALICE_NOTE_VALUE); expect(bobValue).toEqual(BOB_NOTE_VALUE); diff --git a/yarn-project/end-to-end/src/e2e_sequencer/gov_proposal.parallel.test.ts b/yarn-project/end-to-end/src/e2e_sequencer/gov_proposal.parallel.test.ts index b223bc086f1f..8795dc257a6f 100644 --- a/yarn-project/end-to-end/src/e2e_sequencer/gov_proposal.parallel.test.ts +++ b/yarn-project/end-to-end/src/e2e_sequencer/gov_proposal.parallel.test.ts @@ -112,7 +112,7 @@ describe('e2e_gov_proposal', () => { // Deploy a test contract to send msgs via the outbox, since this increases // gas cost of a proposal, which has triggered oog errors in the past. - testContract = await TestContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract: testContract } = await TestContract.deploy(wallet).send({ from: defaultAccountAddress })); logger.warn(`Deployed test contract at ${testContract.address}`); await cheatCodes.rollup.advanceToEpoch(EpochNumber(4)); @@ -169,11 +169,12 @@ describe('e2e_gov_proposal', () => { // since we wait for the txs to be mined, and do so `roundDuration` times. // Simultaneously, we should be voting for the proposal in every slot. for (let i = 0; i < roundDuration; i++) { - const txHashes = await timesAsync(TXS_PER_BLOCK, () => - testContract.methods + const txHashes = await timesAsync(TXS_PER_BLOCK, async () => { + const { txHash } = await testContract.methods .create_l2_to_l1_message_arbitrary_recipient_private(Fr.random(), EthAddress.random()) - .send({ from: defaultAccountAddress, wait: NO_WAIT }), - ); + .send({ from: defaultAccountAddress, wait: NO_WAIT }); + return txHash; + }); await Promise.all( txHashes.map((hash, j) => { logger.info(`Waiting for tx ${i}-${j}: ${hash} to be mined`); diff --git a/yarn-project/end-to-end/src/e2e_sequencer/reload_keystore.test.ts b/yarn-project/end-to-end/src/e2e_sequencer/reload_keystore.test.ts index 09deed9db69d..667728c4056b 100644 --- a/yarn-project/end-to-end/src/e2e_sequencer/reload_keystore.test.ts +++ b/yarn-project/end-to-end/src/e2e_sequencer/reload_keystore.test.ts @@ -130,7 +130,7 @@ describe('e2e_reload_keystore', () => { // Send a tx and verify the block uses the initial coinbase const deployer = new ContractDeployer(artifact, wallet); - const sentTx1 = await deployer.deploy(ownerAddress, ownerAddress, 1).send({ + const { txHash: sentTx1 } = await deployer.deploy(ownerAddress, ownerAddress, 1).send({ from: ownerAddress, contractAddressSalt: new Fr(1), skipClassPublication: true, @@ -197,7 +197,7 @@ describe('e2e_reload_keystore', () => { // Whichever validator is the proposer, its coinbase must be from the reloaded keystore. const allNewCoinbasesLower = newCoinbases.map(c => c.toString().toLowerCase()); - const sentTx2 = await deployer.deploy(ownerAddress, ownerAddress, 2).send({ + const { txHash: sentTx2 } = await deployer.deploy(ownerAddress, ownerAddress, 2).send({ from: ownerAddress, contractAddressSalt: new Fr(2), skipClassPublication: true, diff --git a/yarn-project/end-to-end/src/e2e_simple.test.ts b/yarn-project/end-to-end/src/e2e_simple.test.ts index 0fcedb023202..1dbfe5861776 100644 --- a/yarn-project/end-to-end/src/e2e_simple.test.ts +++ b/yarn-project/end-to-end/src/e2e_simple.test.ts @@ -72,7 +72,7 @@ describe('e2e_simple', () => { const deployer = new ContractDeployer(artifact, wallet); const sender = ownerAddress; - const txReceipt = await deployer.deploy(ownerAddress, sender, 1).send({ + const { receipt: txReceipt } = await deployer.deploy(ownerAddress, sender, 1).send({ from: ownerAddress, contractAddressSalt: new Fr(BigInt(1)), skipClassPublication: true, diff --git a/yarn-project/end-to-end/src/e2e_state_vars.test.ts b/yarn-project/end-to-end/src/e2e_state_vars.test.ts index c5b8d6f0635b..6d2f58a7f37d 100644 --- a/yarn-project/end-to-end/src/e2e_state_vars.test.ts +++ b/yarn-project/end-to-end/src/e2e_state_vars.test.ts @@ -33,7 +33,7 @@ describe('e2e_state_vars', () => { wallet, accounts: [defaultAccountAddress], } = await setup(1)); - contract = await StateVarsContract.deploy(wallet).send({ from: defaultAccountAddress }); + ({ contract } = await StateVarsContract.deploy(wallet).send({ from: defaultAccountAddress })); }); afterAll(() => teardown()); @@ -51,7 +51,7 @@ describe('e2e_state_vars', () => { await contract.methods.initialize_public_immutable(1).send({ from: defaultAccountAddress }); - const read = await contract.methods.get_public_immutable().simulate({ from: defaultAccountAddress }); + const { result: read } = await contract.methods.get_public_immutable().simulate({ from: defaultAccountAddress }); expect(read).toEqual({ account: defaultAccountAddress, value: read.value }); }); @@ -62,11 +62,13 @@ describe('e2e_state_vars', () => { // 2. A constrained private function that calls another private function that reads. // The indirect, adds 1 to the point to ensure that we are returning the correct value. - const [a, b, c] = await new BatchCall(wallet, [ - contract.methods.get_public_immutable_constrained_private(), - contract.methods.get_public_immutable_constrained_private_indirect(), - contract.methods.get_public_immutable(), - ]).simulate({ from: defaultAccountAddress }); + const [a, b, c] = ( + await new BatchCall(wallet, [ + contract.methods.get_public_immutable_constrained_private(), + contract.methods.get_public_immutable_constrained_private_indirect(), + contract.methods.get_public_immutable(), + ]).simulate({ from: defaultAccountAddress }) + ).map((r: any) => r.result); expect(a).toEqual(c); expect(b).toEqual({ account: c.account, value: c.value + 1n }); @@ -79,11 +81,13 @@ describe('e2e_state_vars', () => { // 2. A constrained public function that calls another public function that reads. // The indirect, adds 1 to the point to ensure that we are returning the correct value. - const [a, b, c] = await new BatchCall(wallet, [ - contract.methods.get_public_immutable_constrained_public(), - contract.methods.get_public_immutable_constrained_public_indirect(), - contract.methods.get_public_immutable(), - ]).simulate({ from: defaultAccountAddress }); + const [a, b, c] = ( + await new BatchCall(wallet, [ + contract.methods.get_public_immutable_constrained_public(), + contract.methods.get_public_immutable_constrained_public_indirect(), + contract.methods.get_public_immutable(), + ]).simulate({ from: defaultAccountAddress }) + ).map((r: any) => r.result); expect(a).toEqual(c); expect(b).toEqual({ account: c.account, value: c.value + 1n }); @@ -95,10 +99,10 @@ describe('e2e_state_vars', () => { // Reads the value using a utility function checking the return values with: // 1. A constrained public function that reads 5 times directly (going beyond the previous 4 Field return value) - const a = await contract.methods + const { result: a } = await contract.methods .get_public_immutable_constrained_public_multiple() .simulate({ from: defaultAccountAddress }); - const c = await contract.methods.get_public_immutable().simulate({ from: defaultAccountAddress }); + const { result: c } = await contract.methods.get_public_immutable().simulate({ from: defaultAccountAddress }); expect(a).toEqual([c, c, c, c, c]); }); @@ -115,9 +119,11 @@ describe('e2e_state_vars', () => { describe('PrivateMutable', () => { it('fail to read uninitialized PrivateMutable', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(false); await expect( contract.methods.get_private_mutable(defaultAccountAddress).simulate({ from: defaultAccountAddress }), @@ -126,12 +132,14 @@ describe('e2e_state_vars', () => { it('initialize PrivateMutable', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(false); // Send the transaction and wait for it to be mined (wait function throws if the tx is not mined) - const txReceipt = await contract.methods + const { receipt: txReceipt } = await contract.methods .initialize_private(RANDOMNESS, VALUE) .send({ from: defaultAccountAddress }); @@ -140,50 +148,60 @@ describe('e2e_state_vars', () => { // 1 for the tx, another for the initializer expect(txEffects?.data.nullifiers.length).toEqual(2); expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); }); it('fail to reinitialize', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); await expect( contract.methods.initialize_private(RANDOMNESS, VALUE).send({ from: defaultAccountAddress }), ).rejects.toThrow(); expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); }); it('read initialized PrivateMutable', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); - const { value } = await contract.methods - .get_private_mutable(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }); + const { + result: { value }, + } = await contract.methods.get_private_mutable(defaultAccountAddress).simulate({ from: defaultAccountAddress }); expect(value).toEqual(VALUE); }); it('replace with same value', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); - const noteBefore = await contract.methods + const { result: noteBefore } = await contract.methods .get_private_mutable(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); - const txReceipt = await contract.methods + const { receipt: txReceipt } = await contract.methods .update_private_mutable(RANDOMNESS, VALUE) .send({ from: defaultAccountAddress }); @@ -193,7 +211,7 @@ describe('e2e_state_vars', () => { // 1 for the tx, another for the nullifier of the previous note expect(txEffects?.data.nullifiers.length).toEqual(2); - const noteAfter = await contract.methods + const { result: noteAfter } = await contract.methods .get_private_mutable(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); @@ -202,11 +220,13 @@ describe('e2e_state_vars', () => { it('replace PrivateMutable with other values', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); - const txReceipt = await contract.methods + const { receipt: txReceipt } = await contract.methods .update_private_mutable(RANDOMNESS + 2n, VALUE + 1n) .send({ from: defaultAccountAddress }); @@ -216,22 +236,26 @@ describe('e2e_state_vars', () => { // 1 for the tx, another for the nullifier of the previous note expect(txEffects?.data.nullifiers.length).toEqual(2); - const { value } = await contract.methods - .get_private_mutable(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }); + const { + result: { value }, + } = await contract.methods.get_private_mutable(defaultAccountAddress).simulate({ from: defaultAccountAddress }); expect(value).toEqual(VALUE + 1n); }); it('replace PrivateMutable dependent on prior value', async () => { expect( - await contract.methods - .is_private_mutable_initialized(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_private_mutable_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); - const noteBefore = await contract.methods + const { result: noteBefore } = await contract.methods .get_private_mutable(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); - const txReceipt = await contract.methods.increase_private_value().send({ from: defaultAccountAddress }); + const { receipt: txReceipt } = await contract.methods + .increase_private_value() + .send({ from: defaultAccountAddress }); const txEffects = await aztecNode.getTxEffect(txReceipt.txHash); @@ -239,9 +263,9 @@ describe('e2e_state_vars', () => { // 1 for the tx, another for the nullifier of the previous note expect(txEffects?.data.nullifiers.length).toEqual(2); - const { value } = await contract.methods - .get_private_mutable(defaultAccountAddress) - .simulate({ from: defaultAccountAddress }); + const { + result: { value }, + } = await contract.methods.get_private_mutable(defaultAccountAddress).simulate({ from: defaultAccountAddress }); expect(value).toEqual(noteBefore.value + 1n); }); }); @@ -249,7 +273,11 @@ describe('e2e_state_vars', () => { describe('PrivateImmutable', () => { it('fail to read uninitialized PrivateImmutable', async () => { expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(false); await expect( contract.methods.view_private_immutable(defaultAccountAddress).simulate({ from: defaultAccountAddress }), @@ -258,9 +286,13 @@ describe('e2e_state_vars', () => { it('initialize PrivateImmutable', async () => { expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(false); - const txReceipt = await contract.methods + const { receipt: txReceipt } = await contract.methods .initialize_private_immutable(RANDOMNESS, VALUE) .send({ from: defaultAccountAddress }); @@ -270,27 +302,45 @@ describe('e2e_state_vars', () => { // 1 for the tx, another for the initializer expect(txEffects?.data.nullifiers.length).toEqual(2); expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); }); it('fail to reinitialize', async () => { expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); await expect( contract.methods.initialize_private_immutable(RANDOMNESS, VALUE).send({ from: defaultAccountAddress }), ).rejects.toThrow(); expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); }); it('read initialized PrivateImmutable', async () => { expect( - await contract.methods.is_priv_imm_initialized(defaultAccountAddress).simulate({ from: defaultAccountAddress }), + ( + await contract.methods + .is_priv_imm_initialized(defaultAccountAddress) + .simulate({ from: defaultAccountAddress }) + ).result, ).toEqual(true); - const { value } = await contract.methods + const { + result: { value }, + } = await contract.methods .view_private_immutable(defaultAccountAddress) .simulate({ from: defaultAccountAddress }); expect(value).toEqual(VALUE); @@ -310,9 +360,9 @@ describe('e2e_state_vars', () => { beforeAll(async () => { // We use the auth contract here because has a nice, clear, simple implementation of Delayed Public Mutable - authContract = await AuthContract.deploy(wallet, defaultAccountAddress).send({ + ({ contract: authContract } = await AuthContract.deploy(wallet, defaultAccountAddress).send({ from: defaultAccountAddress, - }); + })); if (aztecSlotDuration !== 72) { throw new Error( diff --git a/yarn-project/end-to-end/src/e2e_static_calls.test.ts b/yarn-project/end-to-end/src/e2e_static_calls.test.ts index 9576d39f7845..1e2cc3117f1b 100644 --- a/yarn-project/end-to-end/src/e2e_static_calls.test.ts +++ b/yarn-project/end-to-end/src/e2e_static_calls.test.ts @@ -21,8 +21,8 @@ describe('e2e_static_calls', () => { accounts: [owner], } = await setup()); sender = owner; - parentContract = await StaticParentContract.deploy(wallet).send({ from: owner }); - childContract = await StaticChildContract.deploy(wallet).send({ from: owner }); + ({ contract: parentContract } = await StaticParentContract.deploy(wallet).send({ from: owner })); + ({ contract: childContract } = await StaticChildContract.deploy(wallet).send({ from: owner })); // We create a note in the set, such that later reads doesn't fail due to get_notes returning 0 notes await childContract.methods.private_set_value(42n, owner, sender).send({ from: owner }); diff --git a/yarn-project/end-to-end/src/e2e_storage_proof/e2e_storage_proof.test.ts b/yarn-project/end-to-end/src/e2e_storage_proof/e2e_storage_proof.test.ts index cdee4c492b29..70c6ce8b0b8f 100644 --- a/yarn-project/end-to-end/src/e2e_storage_proof/e2e_storage_proof.test.ts +++ b/yarn-project/end-to-end/src/e2e_storage_proof/e2e_storage_proof.test.ts @@ -13,7 +13,7 @@ describe('Storage proof', () => { beforeAll(async () => { ctx = await setup(1); - contract = await StorageProofTestContract.deploy(ctx.wallet).send({ from: ctx.accounts[0] }); + ({ contract } = await StorageProofTestContract.deploy(ctx.wallet).send({ from: ctx.accounts[0] })); }); afterAll(async () => { @@ -26,7 +26,7 @@ describe('Storage proof', () => { ctx.logger.info('Sending storage proof TX...'); - const receipt = await contract.methods + const { receipt } = await contract.methods .storage_proof(ethAddress, slotKey, slotContents, root) .with({ capsules }) .send({ from: ctx.accounts[0] }); diff --git a/yarn-project/end-to-end/src/e2e_synching.test.ts b/yarn-project/end-to-end/src/e2e_synching.test.ts index 76a54cd05832..c93560f43064 100644 --- a/yarn-project/end-to-end/src/e2e_synching.test.ts +++ b/yarn-project/end-to-end/src/e2e_synching.test.ts @@ -203,7 +203,7 @@ class TestVariant { ); this.contractAddresses.push(accountManager.address); const deployMethod = await accountManager.getDeployMethod(); - const txHash = await deployMethod.send({ + const { txHash } = await deployMethod.send({ from: deployAccount, skipClassPublication: true, skipInstancePublication: true, @@ -218,7 +218,9 @@ class TestVariant { for (let i = 0; i < this.txCount; i++) { const recipient = this.accounts[(i + 1) % this.txCount]; const tk = TokenContract.at(this.token.address, this.wallet); - txHashes.push(await tk.methods.transfer(recipient, 1n).send({ from: this.accounts[i], wait: NO_WAIT })); + txHashes.push( + (await tk.methods.transfer(recipient, 1n).send({ from: this.accounts[i], wait: NO_WAIT })).txHash, + ); } return txHashes; } else if (this.txComplexity == TxComplexity.PublicTransfer) { @@ -229,7 +231,7 @@ class TestVariant { const recipient = this.accounts[(i + 1) % this.txCount]; const tk = TokenContract.at(this.token.address, this.wallet); txHashes.push( - await tk.methods.transfer_in_public(sender, recipient, 1n, 0).send({ from: sender, wait: NO_WAIT }), + (await tk.methods.transfer_in_public(sender, recipient, 1n, 0).send({ from: sender, wait: NO_WAIT })).txHash, ); } return txHashes; @@ -247,7 +249,7 @@ class TestVariant { ]); this.seed += 100n; - txHashes.push(await batch.send({ from: this.accounts[0], wait: NO_WAIT })); + txHashes.push((await batch.send({ from: this.accounts[0], wait: NO_WAIT })).txHash); } return txHashes; } else { @@ -340,10 +342,16 @@ describe('e2e_synching', () => { variant.setWallet(wallet); // Deploy a token, such that we could use it - const token = await TokenContract.deploy(wallet, defaultAccountAddress, 'TestToken', 'TST', 18n).send({ + const { contract: token } = await TokenContract.deploy( + wallet, + defaultAccountAddress, + 'TestToken', + 'TST', + 18n, + ).send({ from: defaultAccountAddress, }); - const spam = await SpamContract.deploy(wallet).send({ from: defaultAccountAddress }); + const { contract: spam } = await SpamContract.deploy(wallet).send({ from: defaultAccountAddress }); variant.setToken(token); variant.setSpam(spam); @@ -542,15 +550,21 @@ describe('e2e_synching', () => { const defaultAccountAddress = (await variant.deployAccounts(opts.initialFundedAccounts!.slice(0, 1)))[0]; contracts.push( - await TokenContract.deploy(wallet, defaultAccountAddress, 'TestToken', 'TST', 18n).send({ - from: defaultAccountAddress, - }), + ( + await TokenContract.deploy(wallet, defaultAccountAddress, 'TestToken', 'TST', 18n).send({ + from: defaultAccountAddress, + }) + ).contract, + ); + contracts.push( + (await SchnorrHardcodedAccountContract.deploy(wallet).send({ from: defaultAccountAddress })).contract, ); - contracts.push(await SchnorrHardcodedAccountContract.deploy(wallet).send({ from: defaultAccountAddress })); contracts.push( - await TokenContract.deploy(wallet, defaultAccountAddress, 'TestToken', 'TST', 18n).send({ - from: defaultAccountAddress, - }), + ( + await TokenContract.deploy(wallet, defaultAccountAddress, 'TestToken', 'TST', 18n).send({ + from: defaultAccountAddress, + }) + ).contract, ); await watcher.stop(); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/access_control.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/access_control.test.ts index cab2d394475f..50ac4a7f36be 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/access_control.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/access_control.test.ts @@ -18,17 +18,19 @@ describe('e2e_token_contract access control', () => { it('Set admin', async () => { await t.asset.methods.set_admin(t.account1Address).send({ from: t.adminAddress }); - expect(await t.asset.methods.get_admin().simulate({ from: t.adminAddress })).toBe(t.account1Address.toBigInt()); + expect((await t.asset.methods.get_admin().simulate({ from: t.adminAddress })).result).toBe( + t.account1Address.toBigInt(), + ); }); it('Add minter as admin', async () => { await t.asset.methods.set_minter(t.account1Address, true).send({ from: t.account1Address }); - expect(await t.asset.methods.is_minter(t.account1Address).simulate({ from: t.adminAddress })).toBe(true); + expect((await t.asset.methods.is_minter(t.account1Address).simulate({ from: t.adminAddress })).result).toBe(true); }); it('Revoke minter as admin', async () => { await t.asset.methods.set_minter(t.account1Address, false).send({ from: t.account1Address }); - expect(await t.asset.methods.is_minter(t.account1Address).simulate({ from: t.adminAddress })).toBe(false); + expect((await t.asset.methods.is_minter(t.account1Address).simulate({ from: t.adminAddress })).result).toBe(false); }); describe('failure cases', () => { diff --git a/yarn-project/end-to-end/src/e2e_token_contract/burn.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/burn.test.ts index 1c9b670771ca..b9760a983627 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/burn.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/burn.test.ts @@ -27,7 +27,7 @@ describe('e2e_token_contract burn', () => { describe('public', () => { it('burn less than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.burn_public(adminAddress, amount, 0).send({ from: adminAddress }); @@ -36,7 +36,7 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); @@ -61,7 +61,9 @@ describe('e2e_token_contract burn', () => { describe('failure cases', () => { it('burn more than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = 0; await expect( @@ -70,7 +72,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); const authwitNonce = 1; @@ -82,7 +86,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of other without "approval"', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); await expect( @@ -91,7 +97,9 @@ describe('e2e_token_contract burn', () => { }); it('burn more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -109,7 +117,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -132,7 +142,9 @@ describe('e2e_token_contract burn', () => { describe('private', () => { it('burn less than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.burn_private(adminAddress, amount, 0).send({ from: adminAddress }); @@ -140,7 +152,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -160,7 +174,9 @@ describe('e2e_token_contract burn', () => { describe('failure cases', () => { it('burn more than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; expect(amount).toBeGreaterThan(0n); await expect( @@ -169,7 +185,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); await expect( @@ -180,7 +198,9 @@ describe('e2e_token_contract burn', () => { }); it('burn more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -195,7 +215,9 @@ describe('e2e_token_contract burn', () => { }); it('burn on behalf of other without approval', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -214,7 +236,9 @@ describe('e2e_token_contract burn', () => { }); it('on behalf of other (invalid designated caller)', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts index bc6a1251a833..e7479801a3a6 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/minting.test.ts @@ -25,10 +25,12 @@ describe('e2e_token_contract minting', () => { await asset.methods.mint_to_public(adminAddress, amount).send({ from: adminAddress }); tokenSim.mintPublic(adminAddress, amount); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual( + expect((await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).result).toEqual( tokenSim.balanceOfPublic(adminAddress), ); - expect(await asset.methods.total_supply().simulate({ from: adminAddress })).toEqual(tokenSim.totalSupply); + expect((await asset.methods.total_supply().simulate({ from: adminAddress })).result).toEqual( + tokenSim.totalSupply, + ); }); describe('failure cases', () => { @@ -61,10 +63,12 @@ describe('e2e_token_contract minting', () => { await asset.methods.mint_to_private(adminAddress, amount).send({ from: adminAddress }); tokenSim.mintPrivate(adminAddress, amount); - expect(await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).toEqual( + expect((await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).result).toEqual( tokenSim.balanceOfPrivate(adminAddress), ); - expect(await asset.methods.total_supply().simulate({ from: adminAddress })).toEqual(tokenSim.totalSupply); + expect((await asset.methods.total_supply().simulate({ from: adminAddress })).result).toEqual( + tokenSim.totalSupply, + ); }); describe('failure cases', () => { diff --git a/yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts index a986ab6799ba..ffa5688df3b5 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts @@ -23,7 +23,9 @@ describe('e2e_token_contract private transfer recursion', () => { // itself to consume them all (since it retrieves 2 notes on the first pass and 8 in each subsequent pass). const totalNotes = 16; const totalBalance = await mintNotes(wallet, adminAddress, adminAddress, asset, Array(totalNotes).fill(10n)); - const txReceipt = await asset.methods.transfer(account1Address, totalBalance).send({ from: adminAddress }); + const { receipt: txReceipt } = await asset.methods + .transfer(account1Address, totalBalance) + .send({ from: adminAddress }); const txEffects = await node.getTxEffect(txReceipt.txHash); // We should have nullified all notes, plus an extra nullifier for the transaction and one for the event commitment. @@ -59,7 +61,7 @@ describe('e2e_token_contract private transfer recursion', () => { const totalBalance = await mintNotes(wallet, adminAddress, adminAddress, asset, noteAmounts); const toSend = totalBalance - expectedChange; - const txReceipt = await asset.methods.transfer(account1Address, toSend).send({ from: adminAddress }); + const { receipt: txReceipt } = await asset.methods.transfer(account1Address, toSend).send({ from: adminAddress }); const txEffects = await node.getTxEffect(txReceipt.txHash); // We should have nullified all notes, plus an extra nullifier for the transaction and one for the event commitment. @@ -67,7 +69,9 @@ describe('e2e_token_contract private transfer recursion', () => { // We should have created two new notes, one for the recipient and one for the sender (with the change) expect(txEffects!.data.noteHashes.length).toBe(2); - const senderBalance = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: senderBalance } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); expect(senderBalance).toEqual(expectedChange); const events = await wallet.getPrivateEvents(TokenContract.events.Transfer, { @@ -93,7 +97,9 @@ describe('e2e_token_contract private transfer recursion', () => { describe('failure cases', () => { it('transfer more than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/reading_constants.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/reading_constants.test.ts index a564a5610fed..185ac4231e8e 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/reading_constants.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/reading_constants.test.ts @@ -22,34 +22,40 @@ describe('e2e_token_contract reading constants', () => { }); it('check name private', async () => { - const name = readFieldCompressedString(await t.asset.methods.private_get_name().simulate({ from: t.adminAddress })); + const name = readFieldCompressedString( + (await t.asset.methods.private_get_name().simulate({ from: t.adminAddress })).result, + ); expect(name).toBe(TOKEN_NAME); }); it('check name public', async () => { - const name = readFieldCompressedString(await t.asset.methods.public_get_name().simulate({ from: t.adminAddress })); + const name = readFieldCompressedString( + (await t.asset.methods.public_get_name().simulate({ from: t.adminAddress })).result, + ); expect(name).toBe(TOKEN_NAME); }); it('check symbol private', async () => { const sym = readFieldCompressedString( - await t.asset.methods.private_get_symbol().simulate({ from: t.adminAddress }), + (await t.asset.methods.private_get_symbol().simulate({ from: t.adminAddress })).result, ); expect(sym).toBe(TOKEN_SYMBOL); }); it('check symbol public', async () => { - const sym = readFieldCompressedString(await t.asset.methods.public_get_symbol().simulate({ from: t.adminAddress })); + const sym = readFieldCompressedString( + (await t.asset.methods.public_get_symbol().simulate({ from: t.adminAddress })).result, + ); expect(sym).toBe(TOKEN_SYMBOL); }); it('check decimals private', async () => { - const dec = await t.asset.methods.private_get_decimals().simulate({ from: t.adminAddress }); + const { result: dec } = await t.asset.methods.private_get_decimals().simulate({ from: t.adminAddress }); expect(dec).toBe(TOKEN_DECIMALS); }); it('check decimals public', async () => { - const dec = await t.asset.methods.public_get_decimals().simulate({ from: t.adminAddress }); + const { result: dec } = await t.asset.methods.public_get_decimals().simulate({ from: t.adminAddress }); expect(dec).toBe(TOKEN_DECIMALS); }); }); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/token_contract_test.ts b/yarn-project/end-to-end/src/e2e_token_contract/token_contract_test.ts index ebfde8461643..bbc7f024fd19 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/token_contract_test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/token_contract_test.ts @@ -81,24 +81,28 @@ export class TokenContractTest { await publicDeployAccounts(this.wallet, [this.adminAddress, this.account1Address]); this.logger.verbose(`Deploying TokenContract...`); - this.asset = await TokenContract.deploy( + ({ contract: this.asset } = await TokenContract.deploy( this.wallet, this.adminAddress, TokenContractTest.TOKEN_NAME, TokenContractTest.TOKEN_SYMBOL, TokenContractTest.TOKEN_DECIMALS, - ).send({ from: this.adminAddress }); + ).send({ from: this.adminAddress })); this.logger.verbose(`Token deployed to ${this.asset.address}`); this.logger.verbose(`Deploying bad account...`); - this.badAccount = await InvalidAccountContract.deploy(this.wallet).send({ from: this.adminAddress }); + ({ contract: this.badAccount } = await InvalidAccountContract.deploy(this.wallet).send({ + from: this.adminAddress, + })); this.logger.verbose(`Deployed to ${this.badAccount.address}.`); // Deploy a proxy contract for "on behalf of other" tests. The note owner must be the tx sender // (so their notes are in scope), but msg_sender in the target must differ from the note owner // to trigger authwit validation. The proxy forwards calls so that msg_sender != tx sender. this.logger.verbose(`Deploying generic proxy...`); - this.authwitProxy = await GenericProxyContract.deploy(this.wallet).send({ from: this.adminAddress }); + ({ contract: this.authwitProxy } = await GenericProxyContract.deploy(this.wallet).send({ + from: this.adminAddress, + })); this.logger.verbose(`Deployed to ${this.authwitProxy.address}.`); this.tokenSim = new TokenSimulator(this.asset, this.wallet, this.adminAddress, this.logger, [ @@ -106,7 +110,7 @@ export class TokenContractTest { this.account1Address, ]); - expect(await this.asset.methods.get_admin().simulate({ from: this.adminAddress })).toBe( + expect((await this.asset.methods.get_admin().simulate({ from: this.adminAddress })).result).toBe( this.adminAddress.toBigInt(), ); } @@ -140,7 +144,9 @@ export class TokenContractTest { await asset.methods.mint_to_public(adminAddress, amount).send({ from: adminAddress }); tokenSim.mintPublic(adminAddress, amount); - const publicBalance = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: publicBalance } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); this.logger.verbose(`Public balance of wallet 0: ${publicBalance}`); expect(publicBalance).toEqual(this.tokenSim.balanceOfPublic(adminAddress)); @@ -148,11 +154,13 @@ export class TokenContractTest { await mintTokensToPrivate(asset, adminAddress, adminAddress, amount); tokenSim.mintPrivate(adminAddress, amount); - const privateBalance = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: privateBalance } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); this.logger.verbose(`Private balance of wallet 0: ${privateBalance}`); expect(privateBalance).toEqual(tokenSim.balanceOfPrivate(adminAddress)); - const totalSupply = await asset.methods.total_supply().simulate({ from: adminAddress }); + const { result: totalSupply } = await asset.methods.total_supply().simulate({ from: adminAddress }); this.logger.verbose(`Total supply: ${totalSupply}`); expect(totalSupply).toEqual(tokenSim.totalSupply); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/transfer.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/transfer.test.ts index d801532f8478..564707a74c77 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/transfer.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/transfer.test.ts @@ -24,11 +24,11 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer less than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); - const txReceipt = await asset.methods.transfer(account1Address, amount).send({ from: adminAddress }); + const { receipt: txReceipt } = await asset.methods.transfer(account1Address, amount).send({ from: adminAddress }); tokenSim.transferPrivate(adminAddress, account1Address, amount); const events = await wallet.getPrivateEvents(TokenContract.events.Transfer, { @@ -53,7 +53,7 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer less than balance to non-deployed account', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); @@ -68,7 +68,7 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer to self', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.transfer(adminAddress, amount).send({ from: adminAddress }); @@ -77,7 +77,9 @@ describe('e2e_token_contract transfer private', () => { describe('failure cases', () => { it('transfer more than balance', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 + 1n; expect(amount).toBeGreaterThan(0n); await expect(asset.methods.transfer(account1Address, amount).simulate({ from: adminAddress })).rejects.toThrow( diff --git a/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts index 6177d2845832..385c912cec06 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts @@ -25,7 +25,7 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -45,7 +45,9 @@ describe('e2e_token_contract transfer private', () => { describe('failure cases', () => { it('transfer on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 - 1n; expect(amount).toBeGreaterThan(0n); await expect( @@ -61,8 +63,12 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_private(account1Address).simulate({ from: account1Address }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); + const { result: balance1 } = await asset.methods + .balance_of_private(account1Address) + .simulate({ from: account1Address }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -74,10 +80,12 @@ describe('e2e_token_contract transfer private', () => { await expect( simulateThroughAuthwitProxy(t.authwitProxy, action, { from: adminAddress, authWitnesses: [witness] }), ).rejects.toThrow('Assertion failed: Balance too low'); - expect(await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_private(account1Address).simulate({ from: account1Address })).toEqual( - balance1, + expect((await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).result).toEqual( + balance0, ); + expect( + (await asset.methods.balance_of_private(account1Address).simulate({ from: account1Address })).result, + ).toEqual(balance1); }); it.skip('transfer into account to overflow', () => { @@ -88,7 +96,9 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer on behalf of other without approval', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -107,7 +117,9 @@ describe('e2e_token_contract transfer private', () => { }); it('transfer on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -125,11 +137,15 @@ describe('e2e_token_contract transfer private', () => { await expect( simulateThroughAuthwitProxy(t.authwitProxy, action, { from: adminAddress, authWitnesses: [witness] }), ).rejects.toThrow(`Unknown auth witness for message hash ${expectedMessageHash.toString()}`); - expect(await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); + expect((await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress })).result).toEqual( + balance0, + ); }); it('transfer on behalf of other, cancelled authwit', async () => { - const balance0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balance0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts index 689a99d61bc9..f50c89d80b5a 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts @@ -43,7 +43,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer less than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.transfer_in_public(adminAddress, account1Address, amount, 0).send({ from: adminAddress }); @@ -52,7 +52,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer to self', async () => { - const balance = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance / 2n; expect(amount).toBeGreaterThan(0n); await asset.methods.transfer_in_public(adminAddress, adminAddress, amount, 0).send({ from: adminAddress }); @@ -61,7 +61,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); @@ -90,7 +90,7 @@ describe('e2e_token_contract transfer public', () => { describe('failure cases', () => { it('transfer more than balance', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = 0; await expect( @@ -101,7 +101,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer on behalf of self with non-zero nonce', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 - 1n; const authwitNonce = 1; await expect( @@ -114,7 +114,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer on behalf of other without "approval"', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); await expect( @@ -125,8 +125,10 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer more than balance on behalf of other', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance1 } = await asset.methods + .balance_of_public(account1Address) + .simulate({ from: account1Address }); const amount = balance0 + 1n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -145,15 +147,19 @@ describe('e2e_token_contract transfer public', () => { U128_UNDERFLOW_ERROR, ); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).toEqual( - balance1, + expect((await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).result).toEqual( + balance0, ); + expect( + (await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).result, + ).toEqual(balance1); }); it('transfer on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance1 } = await asset.methods + .balance_of_public(account1Address) + .simulate({ from: account1Address }); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -171,15 +177,19 @@ describe('e2e_token_contract transfer public', () => { // Perform the transfer await expect(action.simulate({ from: account1Address })).rejects.toThrow(/unauthorized/); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).toEqual( - balance1, + expect((await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).result).toEqual( + balance0, ); + expect( + (await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).result, + ).toEqual(balance1); }); it('transfer on behalf of other, wrong designated caller', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); - const balance1 = await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance1 } = await asset.methods + .balance_of_public(account1Address) + .simulate({ from: account1Address }); const amount = balance0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -196,14 +206,16 @@ describe('e2e_token_contract transfer public', () => { // Perform the transfer await expect(action.simulate({ from: account1Address })).rejects.toThrow(/unauthorized/); - expect(await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).toEqual(balance0); - expect(await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).toEqual( - balance1, + expect((await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress })).result).toEqual( + balance0, ); + expect( + (await asset.methods.balance_of_public(account1Address).simulate({ from: account1Address })).result, + ).toEqual(balance1); }); it('transfer on behalf of other, cancelled authwit', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); @@ -232,7 +244,7 @@ describe('e2e_token_contract transfer public', () => { }); it('transfer on behalf of other, cancelled authwit, flow 2', async () => { - const balance0 = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balance0 } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balance0 / 2n; expect(amount).toBeGreaterThan(0n); const authwitNonce = Fr.random(); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_private.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_private.test.ts index 051ba9370fce..2688fea57172 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_private.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_private.test.ts @@ -22,7 +22,7 @@ describe('e2e_token_contract transfer_to_private', () => { }); it('to self', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balancePub } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balancePub / 2n; expect(amount).toBeGreaterThan(0n); @@ -34,7 +34,7 @@ describe('e2e_token_contract transfer_to_private', () => { }); it('to someone else', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balancePub } = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); const amount = balancePub / 2n; expect(amount).toBeGreaterThan(0n); @@ -47,7 +47,9 @@ describe('e2e_token_contract transfer_to_private', () => { describe('failure cases', () => { it('to self (more than balance)', async () => { - const balancePub = await asset.methods.balance_of_public(adminAddress).simulate({ from: adminAddress }); + const { result: balancePub } = await asset.methods + .balance_of_public(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePub + 1n; expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_public.test.ts b/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_public.test.ts index 5394130c2429..1ff6f31ef53b 100644 --- a/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_public.test.ts +++ b/yarn-project/end-to-end/src/e2e_token_contract/transfer_to_public.test.ts @@ -26,7 +26,9 @@ describe('e2e_token_contract transfer_to_public', () => { }); it('on behalf of self', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv / 2n; expect(amount).toBeGreaterThan(0n); @@ -36,7 +38,9 @@ describe('e2e_token_contract transfer_to_public', () => { }); it('on behalf of other', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv0 / 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -56,7 +60,9 @@ describe('e2e_token_contract transfer_to_public', () => { describe('failure cases', () => { it('on behalf of self (more than balance)', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv + 1n; expect(amount).toBeGreaterThan(0n); @@ -66,7 +72,9 @@ describe('e2e_token_contract transfer_to_public', () => { }); it('on behalf of self (invalid authwit nonce)', async () => { - const balancePriv = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv + 1n; expect(amount).toBeGreaterThan(0n); @@ -78,7 +86,9 @@ describe('e2e_token_contract transfer_to_public', () => { }); it('on behalf of other (more than balance)', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); @@ -93,7 +103,9 @@ describe('e2e_token_contract transfer_to_public', () => { }); it('on behalf of other (invalid designated caller)', async () => { - const balancePriv0 = await asset.methods.balance_of_private(adminAddress).simulate({ from: adminAddress }); + const { result: balancePriv0 } = await asset.methods + .balance_of_private(adminAddress) + .simulate({ from: adminAddress }); const amount = balancePriv0 + 2n; const authwitNonce = Fr.random(); expect(amount).toBeGreaterThan(0n); diff --git a/yarn-project/end-to-end/src/fixtures/e2e_prover_test.ts b/yarn-project/end-to-end/src/fixtures/e2e_prover_test.ts index 6dad123c594a..59f38bfeedea 100644 --- a/yarn-project/end-to-end/src/fixtures/e2e_prover_test.ts +++ b/yarn-project/end-to-end/src/fixtures/e2e_prover_test.ts @@ -106,7 +106,9 @@ export class FullProverTest { await publicDeployAccounts(this.wallet, this.accounts.slice(0, 2)); this.logger.info('Applying base setup: deploying token contract'); - const { contract: asset, instance } = await TokenContract.deploy( + const { + receipt: { contract: asset, instance }, + } = await TokenContract.deploy( this.wallet, this.accounts[0], FullProverTest.TOKEN_NAME, @@ -121,7 +123,7 @@ export class FullProverTest { this.tokenSim = new TokenSimulator(this.fakeProofsAsset, this.wallet, this.accounts[0], this.logger, this.accounts); - expect(await this.fakeProofsAsset.methods.get_admin().simulate({ from: this.accounts[0] })).toBe( + expect((await this.fakeProofsAsset.methods.get_admin().simulate({ from: this.accounts[0] })).result).toBe( this.accounts[0].toBigInt(), ); } @@ -310,16 +312,20 @@ export class FullProverTest { } = this; tokenSim.mintPublic(address, publicAmount); - const publicBalance = await fakeProofsAsset.methods.balance_of_public(address).simulate({ from: address }); + const { result: publicBalance } = await fakeProofsAsset.methods + .balance_of_public(address) + .simulate({ from: address }); this.logger.verbose(`Public balance of wallet 0: ${publicBalance}`); expect(publicBalance).toEqual(this.tokenSim.balanceOfPublic(address)); tokenSim.mintPrivate(address, publicAmount); - const privateBalance = await fakeProofsAsset.methods.balance_of_private(address).simulate({ from: address }); + const { result: privateBalance } = await fakeProofsAsset.methods + .balance_of_private(address) + .simulate({ from: address }); this.logger.verbose(`Private balance of wallet 0: ${privateBalance}`); expect(privateBalance).toEqual(tokenSim.balanceOfPrivate(address)); - const totalSupply = await fakeProofsAsset.methods.total_supply().simulate({ from: address }); + const { result: totalSupply } = await fakeProofsAsset.methods.total_supply().simulate({ from: address }); this.logger.verbose(`Total supply: ${totalSupply}`); expect(totalSupply).toEqual(tokenSim.totalSupply); } diff --git a/yarn-project/end-to-end/src/fixtures/setup.ts b/yarn-project/end-to-end/src/fixtures/setup.ts index 517da8f7498e..acb06a638f73 100644 --- a/yarn-project/end-to-end/src/fixtures/setup.ts +++ b/yarn-project/end-to-end/src/fixtures/setup.ts @@ -753,7 +753,9 @@ export function getBalancesFn( ): (...addresses: (AztecAddress | { address: AztecAddress })[]) => Promise { const balances = async (...addressLikes: (AztecAddress | { address: AztecAddress })[]) => { const addresses = addressLikes.map(addressLike => ('address' in addressLike ? addressLike.address : addressLike)); - const b = await Promise.all(addresses.map(address => method(address).simulate({ from: address }))); + const b = await Promise.all( + addresses.map(async address => (await method(address).simulate({ from: address })).result), + ); const debugString = `${symbol} balances: ${addresses.map((address, i) => `${address}: ${b[i]}`).join(', ')}`; logger.verbose(debugString); return b; @@ -871,7 +873,7 @@ export async function publicDeployAccounts( const batch = new BatchCall(wallet, calls); - const txReceipt = await batch.send({ from: accountsToDeploy[0] }); + const { receipt: txReceipt } = await batch.send({ from: accountsToDeploy[0] }); if (waitUntilProven) { if (!node) { throw new Error('Need to provide an AztecNode to wait for proven.'); diff --git a/yarn-project/end-to-end/src/fixtures/token_utils.ts b/yarn-project/end-to-end/src/fixtures/token_utils.ts index aabcf5d6a215..a0d67993b7eb 100644 --- a/yarn-project/end-to-end/src/fixtures/token_utils.ts +++ b/yarn-project/end-to-end/src/fixtures/token_utils.ts @@ -6,7 +6,9 @@ import { TokenContract } from '@aztec/noir-contracts.js/Token'; export async function deployToken(wallet: Wallet, admin: AztecAddress, initialAdminBalance: bigint, logger: Logger) { logger.info(`Deploying Token contract...`); - const { contract, instance } = await TokenContract.deploy(wallet, admin, 'TokenName', 'TokenSymbol', 18).send({ + const { + receipt: { contract, instance }, + } = await TokenContract.deploy(wallet, admin, 'TokenName', 'TokenSymbol', 18).send({ from: admin, wait: { returnReceipt: true }, }); @@ -39,7 +41,7 @@ export async function expectTokenBalance( ) { // Then check the balance const contractWithWallet = TokenContract.at(token.address, wallet); - const balance = await contractWithWallet.methods.balance_of_private(owner).simulate({ from: owner }); + const { result: balance } = await contractWithWallet.methods.balance_of_private(owner).simulate({ from: owner }); logger.info(`Account ${owner} balance: ${balance}`); expect(balance).toBe(expectedBalance); } diff --git a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts index 9eaf2473b961..b9f1893bf500 100644 --- a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts +++ b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts @@ -73,7 +73,7 @@ describe('guides/writing_an_account_contract', () => { const address = account.address; logger.info(`Deployed account contract at ${address}`); - const token = await TokenContract.deploy(wallet, fundedAccount, 'TokenName', 'TokenSymbol', 18).send({ + const { contract: token } = await TokenContract.deploy(wallet, fundedAccount, 'TokenName', 'TokenSymbol', 18).send({ from: fundedAccount, }); logger.info(`Deployed token contract at ${token.address}`); @@ -81,7 +81,7 @@ describe('guides/writing_an_account_contract', () => { const mintAmount = 50n; await token.methods.mint_to_private(address, mintAmount).send({ from: fundedAccount }); - const balance = await token.methods.balance_of_private(address).simulate({ from: address }); + const { result: balance } = await token.methods.balance_of_private(address).simulate({ from: address }); logger.info(`Balance of wallet is now ${balance}`); expect(balance).toEqual(50n); diff --git a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts index be4564b2a67d..c1b2b39780eb 100644 --- a/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/cross_chain_test_harness.ts @@ -73,22 +73,26 @@ export async function deployAndInitializeTokenAndBridgeContracts( }); // deploy l2 token - const token = await TokenContract.deploy(wallet, owner, 'TokenName', 'TokenSymbol', 18).send({ from: owner }); + const { contract: token } = await TokenContract.deploy(wallet, owner, 'TokenName', 'TokenSymbol', 18).send({ + from: owner, + }); // deploy l2 token bridge and attach to the portal - const bridge = await TokenBridgeContract.deploy(wallet, token.address, tokenPortalAddress).send({ from: owner }); + const { contract: bridge } = await TokenBridgeContract.deploy(wallet, token.address, tokenPortalAddress).send({ + from: owner, + }); - if ((await token.methods.get_admin().simulate({ from: owner })) !== owner.toBigInt()) { + if ((await token.methods.get_admin().simulate({ from: owner })).result !== owner.toBigInt()) { throw new Error(`Token admin is not ${owner}`); } - if (!(await bridge.methods.get_config().simulate({ from: owner })).token.equals(token.address)) { + if (!(await bridge.methods.get_config().simulate({ from: owner })).result.token.equals(token.address)) { throw new Error(`Bridge token is not ${token.address}`); } // make the bridge a minter on the token: await token.methods.set_minter(bridge.address, true).send({ from: owner }); - if ((await token.methods.is_minter(bridge.address).simulate({ from: owner })) === 1n) { + if ((await token.methods.is_minter(bridge.address).simulate({ from: owner })).result === 1n) { throw new Error(`Bridge is not a minter`); } @@ -269,7 +273,7 @@ export class CrossChainTestHarness { authwitNonce: Fr = Fr.ZERO, authWitness: AuthWitness, ): Promise { - const withdrawReceipt = await this.l2Bridge.methods + const { receipt: withdrawReceipt } = await this.l2Bridge.methods .exit_to_l1_private(this.l2Token.address, this.ethAccount, withdrawAmount, EthAddress.ZERO, authwitNonce) .send({ authWitnesses: [authWitness], from: this.ownerAddress }); @@ -277,7 +281,7 @@ export class CrossChainTestHarness { } async withdrawPublicFromAztecToL1(withdrawAmount: bigint, authwitNonce: Fr = Fr.ZERO): Promise { - const withdrawReceipt = await this.l2Bridge.methods + const { receipt: withdrawReceipt } = await this.l2Bridge.methods .exit_to_l1_public(this.ethAccount, withdrawAmount, EthAddress.ZERO, authwitNonce) .send({ from: this.ownerAddress }); @@ -285,7 +289,7 @@ export class CrossChainTestHarness { } async getL2PrivateBalanceOf(owner: AztecAddress) { - return await this.l2Token.methods.balance_of_private(owner).simulate({ from: owner }); + return (await this.l2Token.methods.balance_of_private(owner).simulate({ from: owner })).result; } async expectPrivateBalanceOnL2(owner: AztecAddress, expectedBalance: bigint) { @@ -295,7 +299,7 @@ export class CrossChainTestHarness { } async getL2PublicBalanceOf(owner: AztecAddress) { - return await this.l2Token.methods.balance_of_public(owner).simulate({ from: this.ownerAddress }); + return (await this.l2Token.methods.balance_of_public(owner).simulate({ from: this.ownerAddress })).result; } async expectPublicBalanceOnL2(owner: AztecAddress, expectedBalance: bigint) { diff --git a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts index 4062e7def159..2e8426fa1351 100644 --- a/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts +++ b/yarn-project/end-to-end/src/shared/gas_portal_test_harness.ts @@ -131,7 +131,7 @@ export class GasBridgingTestHarness implements IGasBridgingTestHarness { } async getL2PublicBalanceOf(owner: AztecAddress) { - return await this.feeJuice.methods.balance_of_public(owner).simulate({ from: owner }); + return (await this.feeJuice.methods.balance_of_public(owner).simulate({ from: owner })).result; } async expectPublicBalanceOnL2(owner: AztecAddress, expectedBalance: bigint) { diff --git a/yarn-project/end-to-end/src/shared/submit-transactions.ts b/yarn-project/end-to-end/src/shared/submit-transactions.ts index c77fb97e8799..b8b6c5c1a11e 100644 --- a/yarn-project/end-to-end/src/shared/submit-transactions.ts +++ b/yarn-project/end-to-end/src/shared/submit-transactions.ts @@ -19,10 +19,7 @@ export const submitTxsTo = async ( times(numTxs, async () => { const accountManager = await wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()); const deployMethod = await accountManager.getDeployMethod(); - const txHash = await deployMethod.send({ - from: submitter, - wait: NO_WAIT, - }); + const { txHash } = await deployMethod.send({ from: submitter, wait: NO_WAIT }); logger.info(`Tx sent with hash ${txHash}`); const receipt: TxReceipt = await wallet.getTxReceipt(txHash); diff --git a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts index 7f25e1a2b4eb..6795cc1bf180 100644 --- a/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts +++ b/yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts @@ -130,7 +130,9 @@ export const uniswapL1L2TestSuite = ( client: l1Client, }); // deploy l2 uniswap contract and attach to portal - uniswapL2Contract = await UniswapContract.deploy(wallet, uniswapPortalAddress).send({ from: ownerAddress }); + ({ contract: uniswapL2Contract } = await UniswapContract.deploy(wallet, uniswapPortalAddress).send({ + from: ownerAddress, + })); const registryAddress = (await aztecNode.getNodeInfo()).l1ContractAddresses.registryAddress; @@ -195,7 +197,7 @@ export const uniswapL1L2TestSuite = ( logger.info('Withdrawing weth to L1 and sending message to swap to dai'); const [secretForDepositingSwappedDai, secretHashForDepositingSwappedDai] = await generateClaimSecret(); - const l2UniswapInteractionReceipt = await uniswapL2Contract.methods + const { receipt: l2UniswapInteractionReceipt } = await uniswapL2Contract.methods .swap_private( wethCrossChainHarness.l2Token.address, wethCrossChainHarness.l2Bridge.address, @@ -787,7 +789,7 @@ export const uniswapL1L2TestSuite = ( logger.info('Withdrawing weth to L1 and sending message to swap to dai'); const [, secretHashForDepositingSwappedDai] = await generateClaimSecret(); - const withdrawReceipt = await uniswapL2Contract.methods + const { receipt: withdrawReceipt } = await uniswapL2Contract.methods .swap_private( wethCrossChainHarness.l2Token.address, wethCrossChainHarness.l2Bridge.address, @@ -915,7 +917,7 @@ export const uniswapL1L2TestSuite = ( // Call swap_public on L2 const secretHashForDepositingSwappedDai = Fr.random(); - const withdrawReceipt = await uniswapL2Contract.methods + const { receipt: withdrawReceipt } = await uniswapL2Contract.methods .swap_public( ownerAddress, wethCrossChainHarness.l2Bridge.address, diff --git a/yarn-project/end-to-end/src/simulators/lending_simulator.ts b/yarn-project/end-to-end/src/simulators/lending_simulator.ts index fe10d7ed2276..404bb3d5ad8d 100644 --- a/yarn-project/end-to-end/src/simulators/lending_simulator.ts +++ b/yarn-project/end-to-end/src/simulators/lending_simulator.ts @@ -186,14 +186,16 @@ export class LendingSimulator { expect(this.borrowed).toEqual(this.stableCoin.totalSupply - this.mintedOutside); - const asset = await this.lendingContract.methods.get_asset(0).simulate({ from: this.account.address }); + const { result: asset } = await this.lendingContract.methods.get_asset(0).simulate({ from: this.account.address }); const interestAccumulator = asset['interest_accumulator']; expect(interestAccumulator).toEqual(this.accumulator); expect(asset['last_updated_ts']).toEqual(BigInt(this.time)); for (const key of [this.account.address, AztecAddress.fromField(await this.account.key())]) { - const privatePos = await this.lendingContract.methods.get_position(key).simulate({ from: this.account.address }); + const { result: privatePos } = await this.lendingContract.methods + .get_position(key) + .simulate({ from: this.account.address }); 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( diff --git a/yarn-project/end-to-end/src/simulators/token_simulator.ts b/yarn-project/end-to-end/src/simulators/token_simulator.ts index f29f6403a4d2..a2065beb4426 100644 --- a/yarn-project/end-to-end/src/simulators/token_simulator.ts +++ b/yarn-project/end-to-end/src/simulators/token_simulator.ts @@ -109,7 +109,9 @@ export class TokenSimulator { await Promise.all( chunk(calls, 5).map(batch => new BatchCall(this.defaultWallet, batch).simulate({ from: this.defaultAddress })), ) - ).flat(); + ) + .flat() + .map(r => r.result); expect(results[0]).toEqual(this.totalSupply); // Check that all our balances match @@ -123,7 +125,9 @@ export class TokenSimulator { const wallet = this.lookupProvider.get(address.toString()); const asset = wallet ? this.token.withWallet(wallet) : this.token; - const actualPrivateBalance = await asset.methods.balance_of_private(address).simulate({ from: address }); + const { result: actualPrivateBalance } = await asset.methods + .balance_of_private(address) + .simulate({ from: address }); expect(actualPrivateBalance).toEqual(this.balanceOfPrivate(address)); } } diff --git a/yarn-project/end-to-end/src/spartan/1tps.test.ts b/yarn-project/end-to-end/src/spartan/1tps.test.ts index b771d4621308..6d939deb5886 100644 --- a/yarn-project/end-to-end/src/spartan/1tps.test.ts +++ b/yarn-project/end-to-end/src/spartan/1tps.test.ts @@ -63,7 +63,8 @@ describe('token transfer test', () => { it('can get info', async () => { const name = readFieldCompressedString( - await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress }), + (await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress })) + .result, ); expect(name).toBe(testAccounts.tokenName); }); @@ -74,16 +75,20 @@ describe('token transfer test', () => { for (const acc of testAccounts.accounts) { expect(MINT_AMOUNT).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(acc) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(acc) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); } expect(0n).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(recipient) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(recipient) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); const defaultAccountAddress = testAccounts.accounts[0]; @@ -128,7 +133,7 @@ describe('token transfer test', () => { }), ); - const recipientBalance = await testAccounts.tokenContract.methods + const { result: recipientBalance } = await testAccounts.tokenContract.methods .balance_of_public(recipient) .simulate({ from: testAccounts.tokenAdminAddress }); logger.info(`recipientBalance: ${recipientBalance}`); diff --git a/yarn-project/end-to-end/src/spartan/4epochs.test.ts b/yarn-project/end-to-end/src/spartan/4epochs.test.ts index b2dcdd2ca987..a0d42328fb7a 100644 --- a/yarn-project/end-to-end/src/spartan/4epochs.test.ts +++ b/yarn-project/end-to-end/src/spartan/4epochs.test.ts @@ -68,7 +68,8 @@ describe('token transfer test', () => { it('can get info', async () => { const name = readFieldCompressedString( - await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress }), + (await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress })) + .result, ); expect(name).toBe(testAccounts.tokenName); logger.info(`Token name verified: ${name}`); @@ -85,18 +86,22 @@ describe('token transfer test', () => { for (const acc of testAccounts.accounts) { expect(MINT_AMOUNT).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(acc) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(acc) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); } logger.info('Minted tokens'); expect(0n).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(recipient) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(recipient) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); // For each round, make both private and public transfers @@ -132,16 +137,20 @@ describe('token transfer test', () => { for (const acc of testAccounts.accounts) { expect(MINT_AMOUNT - ROUNDS * transferAmount).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(acc) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(acc) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); } expect(ROUNDS * transferAmount * BigInt(testAccounts.accounts.length)).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(recipient) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(recipient) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); }); }); diff --git a/yarn-project/end-to-end/src/spartan/n_tps.test.ts b/yarn-project/end-to-end/src/spartan/n_tps.test.ts index d7a774b5fc3b..f2f452f20074 100644 --- a/yarn-project/end-to-end/src/spartan/n_tps.test.ts +++ b/yarn-project/end-to-end/src/spartan/n_tps.test.ts @@ -306,10 +306,10 @@ describe('sustained N TPS test', () => { logger.info('Deploying benchmark contract...'); const sponsor = new SponsoredFeePaymentMethod(await getSponsoredFPCAddress()); - benchmarkContract = await BenchmarkingContract.deploy(localTestAccounts[0].wallet).send({ + ({ contract: benchmarkContract } = await BenchmarkingContract.deploy(localTestAccounts[0].wallet).send({ from: localTestAccounts[0].recipientAddress, fee: { paymentMethod: sponsor }, - }); + })); logger.info('Benchmark contract deployed', { address: benchmarkContract.address.toString() }); logger.info(`Test setup complete`); diff --git a/yarn-project/end-to-end/src/spartan/n_tps_prove.test.ts b/yarn-project/end-to-end/src/spartan/n_tps_prove.test.ts index 5c1750c41b24..e5db55329823 100644 --- a/yarn-project/end-to-end/src/spartan/n_tps_prove.test.ts +++ b/yarn-project/end-to-end/src/spartan/n_tps_prove.test.ts @@ -304,10 +304,10 @@ describe(`prove ${TARGET_TPS}TPS test`, () => { } logger.info('Deploying benchmark contract...'); - benchmarkContract = await BenchmarkingContract.deploy(wallets[0]).send({ + ({ contract: benchmarkContract } = await BenchmarkingContract.deploy(wallets[0]).send({ from: accountAddresses[0], fee: { paymentMethod: sponsor }, - }); + })); logger.info('Test setup complete'); }); diff --git a/yarn-project/end-to-end/src/spartan/reorg.test.ts b/yarn-project/end-to-end/src/spartan/reorg.test.ts index 946f4f4a3b1a..e01d4ee06f20 100644 --- a/yarn-project/end-to-end/src/spartan/reorg.test.ts +++ b/yarn-project/end-to-end/src/spartan/reorg.test.ts @@ -32,16 +32,20 @@ const debugLogger = createLogger('e2e:spartan-test:reorg'); async function checkBalances(testAccounts: TestAccounts, mintAmount: bigint, totalAmountTransferred: bigint) { for (const acc of testAccounts.accounts) { expect( - await testAccounts.tokenContract.methods - .balance_of_public(acc) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(acc) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ).toBe(mintAmount - totalAmountTransferred); } expect( - await testAccounts.tokenContract.methods - .balance_of_public(testAccounts.recipientAddress) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(testAccounts.recipientAddress) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ).toBe(totalAmountTransferred * BigInt(testAccounts.accounts.length)); } diff --git a/yarn-project/end-to-end/src/spartan/reqresp_effectiveness.test.ts b/yarn-project/end-to-end/src/spartan/reqresp_effectiveness.test.ts index 3c740fdba873..435341a8b4af 100644 --- a/yarn-project/end-to-end/src/spartan/reqresp_effectiveness.test.ts +++ b/yarn-project/end-to-end/src/spartan/reqresp_effectiveness.test.ts @@ -71,7 +71,8 @@ describe('reqresp effectiveness under tx drop', () => { testAccounts = await deploySponsoredTestAccountsWithTokens(wallet, aztecNode, MINT_AMOUNT, logger); recipient = testAccounts.recipientAddress; const name = readFieldCompressedString( - await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress }), + (await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress })) + .result, ); expect(name).toBe(testAccounts.tokenName); }); diff --git a/yarn-project/end-to-end/src/spartan/setup_test_wallets.ts b/yarn-project/end-to-end/src/spartan/setup_test_wallets.ts index 8009d474e601..bb4d7328d90f 100644 --- a/yarn-project/end-to-end/src/spartan/setup_test_wallets.ts +++ b/yarn-project/end-to-end/src/spartan/setup_test_wallets.ts @@ -138,11 +138,8 @@ async function deployAccountWithDiagnostics( const deployMethod = await account.getDeployMethod(); let txHash; try { - txHash = await deployMethod.send({ - from: AztecAddress.ZERO, - fee: { paymentMethod }, - wait: NO_WAIT, - }); + const deployResult = await deployMethod.send({ from: AztecAddress.ZERO, fee: { paymentMethod }, wait: NO_WAIT }); + txHash = deployResult.txHash; await waitForTx(aztecNode, txHash, { timeout: 2400 }); logger.info(`${accountLabel} deployed at ${account.address}`); } catch (error) { @@ -310,13 +307,9 @@ async function deployTokenAndMint( logger: Logger, ) { logger.verbose(`Deploying TokenContract...`); - const { contract: tokenContract } = await TokenContract.deploy( - wallet, - admin, - TOKEN_NAME, - TOKEN_SYMBOL, - TOKEN_DECIMALS, - ).send({ + const { + receipt: { contract: tokenContract }, + } = await TokenContract.deploy(wallet, admin, TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS).send({ from: admin, fee: { paymentMethod, diff --git a/yarn-project/end-to-end/src/spartan/transfer.test.ts b/yarn-project/end-to-end/src/spartan/transfer.test.ts index b3fda8fb1186..7db4b2c0e2aa 100644 --- a/yarn-project/end-to-end/src/spartan/transfer.test.ts +++ b/yarn-project/end-to-end/src/spartan/transfer.test.ts @@ -52,7 +52,8 @@ describe('token transfer test', () => { it('can get info', async () => { const name = readFieldCompressedString( - await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress }), + (await testAccounts.tokenContract.methods.private_get_name().simulate({ from: testAccounts.tokenAdminAddress })) + .result, ); expect(name).toBe(testAccounts.tokenName); }); @@ -63,16 +64,20 @@ describe('token transfer test', () => { for (const a of testAccounts.accounts) { expect(MINT_AMOUNT).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(a) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(a) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); } expect(0n).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(recipient) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(recipient) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); // For each round, make both private and public transfers @@ -94,14 +99,16 @@ describe('token transfer test', () => { for (const a of testAccounts.accounts) { expect(MINT_AMOUNT - ROUNDS * transferAmount).toBe( - await testAccounts.tokenContract.methods.balance_of_public(a).simulate({ from: a }), + (await testAccounts.tokenContract.methods.balance_of_public(a).simulate({ from: a })).result, ); } expect(ROUNDS * transferAmount * BigInt(testAccounts.accounts.length)).toBe( - await testAccounts.tokenContract.methods - .balance_of_public(recipient) - .simulate({ from: testAccounts.tokenAdminAddress }), + ( + await testAccounts.tokenContract.methods + .balance_of_public(recipient) + .simulate({ from: testAccounts.tokenAdminAddress }) + ).result, ); }); }); diff --git a/yarn-project/stdlib/src/tx/simulated_tx.ts b/yarn-project/stdlib/src/tx/simulated_tx.ts index 3ad4e7b73c4e..5fb1ef4b8bd4 100644 --- a/yarn-project/stdlib/src/tx/simulated_tx.ts +++ b/yarn-project/stdlib/src/tx/simulated_tx.ts @@ -12,9 +12,11 @@ import { Gas } from '../gas/gas.js'; import type { GasUsed } from '../gas/gas_used.js'; import { PrivateKernelTailCircuitPublicInputs } from '../kernel/private_kernel_tail_circuit_public_inputs.js'; import { ChonkProof } from '../proofs/chonk_proof.js'; +import type { OffchainEffect } from './offchain_effect.js'; import { PrivateCallExecutionResult, PrivateExecutionResult, + collectOffchainEffects, collectSortedContractClassLogs, } from './private_execution_result.js'; import { type SimulationStats, SimulationStatsSchema } from './profiling.js'; @@ -84,6 +86,11 @@ export class TxSimulationResult { public stats?: SimulationStats, ) {} + /** Returns offchain effects collected from private execution. */ + get offchainEffects(): OffchainEffect[] { + return collectOffchainEffects(this.privateExecutionResult); + } + get gasUsed(): GasUsed { return ( this.publicOutput?.gasUsed ?? { @@ -106,7 +113,7 @@ export class TxSimulationResult { .transform(TxSimulationResult.from); } - static from(fields: Omit, 'gasUsed'>) { + static from(fields: Omit, 'gasUsed' | 'offchainEffects'>) { return new TxSimulationResult( fields.privateExecutionResult, fields.publicInputs, diff --git a/yarn-project/wallet-sdk/src/base-wallet/base_wallet.ts b/yarn-project/wallet-sdk/src/base-wallet/base_wallet.ts index f45118ed2773..484ed4b37edb 100644 --- a/yarn-project/wallet-sdk/src/base-wallet/base_wallet.ts +++ b/yarn-project/wallet-sdk/src/base-wallet/base_wallet.ts @@ -1,6 +1,11 @@ import type { Account } from '@aztec/aztec.js/account'; import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization'; -import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '@aztec/aztec.js/contracts'; +import { + type InteractionWaitOptions, + NO_WAIT, + type SendReturn, + extractOffchainOutput, +} from '@aztec/aztec.js/contracts'; import type { FeePaymentMethod } from '@aztec/aztec.js/fee'; import { waitForTx } from '@aztec/aztec.js/node'; import type { @@ -383,6 +388,7 @@ export abstract class BaseWallet implements Wallet { const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings); const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions); const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes)); + const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects()); const tx = await provenTx.toTx(); const txHash = tx.getTxHash(); if (await this.aztecNode.getTxEffect(txHash)) { @@ -396,7 +402,7 @@ export abstract class BaseWallet implements Wallet { // If wait is NO_WAIT, return txHash immediately if (opts.wait === NO_WAIT) { - return txHash as SendReturn; + return { txHash, ...offchainOutput } as SendReturn; } // Otherwise, wait for the full receipt (default behavior on wait: undefined) @@ -408,7 +414,7 @@ export abstract class BaseWallet implements Wallet { await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this)); } - return receipt as SendReturn; + return { receipt, ...offchainOutput } as SendReturn; } /** From f1c59a6cd777094eaf180a19382f97173247c292 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bene=C5=A1?= Date: Wed, 4 Mar 2026 23:33:36 +0700 Subject: [PATCH 07/12] chore: exclude auto-generated dirs from VS Code search (#20881) --- .vscode/settings.json | 44 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index ffdc7babdd20..a78bac933277 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -148,11 +148,53 @@ }, "solidity.formatter": "forge", "search.exclude": { + // Package managers / dependencies "**/.yarn": true, "**/.yalc": true, "**/node_modules": true, "**/.pnp.*": true, - "**/msgpack-c/**": true + "**/l1-contracts/lib/**": true, + "**/barretenberg/sol/lib/**": true, + "**/msgpack-c/**": true, + + // Build outputs + "**/dest/**": true, + "**/dist/**": true, + "**/target/**": true, + "**/build/**": true, + "**/out/**": true, + "**/artifacts/**": true, + "**/generated/**": true, + + // Caches + "**/.cache/**": true, + "**/.cache-loader/**": true, + "**/.docusaurus/**": true, + "**/.tsbuildinfo": true, + "**/tsconfig.tsbuildinfo": true, + "**/.eslintcache": true, + + // Docs: versioned/generated content + "**/docs/developer_versioned_docs/**": true, + "**/docs/network_versioned_docs/**": true, + "**/docs/network_versioned_sidebars/**": true, + "**/docs/processed-docs/**": true, + "**/docs/processed-docs-cache/**": true, + "**/docs/static/**": true, + "**/docs/build/**": true, + "**/barretenberg/docs/versioned_docs/**": true, + "**/barretenberg/docs/versioned_sidebars/**": true, + "**/barretenberg/docs/static/**": true, + "**/barretenberg/docs/build/**": true, + "**/noir/noir-repo/docs/versioned_docs/**": true, + "**/noir/noir-repo/docs/versioned_sidebars/**": true, + + // C++/Rust build + "**/barretenberg/cpp/build*/**": true, + "**/barretenberg/cpp/src/wasi-sdk*/**": true, + "**/cmake-build-*/**": true, + "**/bench-out/**": true, + "**/coverage/**": true }, "[terraform]": { "editor.defaultFormatter": "hashicorp.terraform" From 75ce5f954c9432615b78dc29fdc0240c316dece6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Venturo?= Date: Wed, 4 Mar 2026 15:47:19 -0300 Subject: [PATCH 08/12] feat: improve oracle name prefixes (#21101) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This adds the `aztec` namespace prefix to all oracles. We need this for https://github.com/noir-lang/noir/issues/10105, so that we can get proper error messages on `nargo` that link to aztec docs. It also shortens the current prefixes: - `utility` → `utl` - `private` → `prv` - `avmOpcode` → `avm` - `txe` unchanged The prefixes only exist as the actual oracle name in the nr <> ts communication layer, they are not present in the nr code nor ts code. I actually removed the current prefixes from oracle handler fn (e.g. `utilityGetBlockNumber` becomes `getBlockNumber`) to reduce verbosity and repetitiveness, given that those functions already exist in interfaces that scope the oracles that correspond to that execution mode. --------- Co-authored-by: Claude Opus 4.6 --- avm-transpiler/src/transpile.rs | 86 ++-- .../aztec-nr/aztec/src/capsules/mod.nr | 5 +- .../aztec/src/context/returns_hash.nr | 17 +- .../aztec-nr/aztec/src/keys/getters/mod.nr | 2 +- .../aztec/src/messages/encryption/aes128.nr | 8 +- .../aztec-nr/aztec/src/messages/logs/utils.nr | 10 +- .../processing/event_validation_request.nr | 2 +- .../processing/note_validation_request.nr | 2 +- .../aztec/src/oracle/aes128_decrypt.nr | 2 +- .../aztec-nr/aztec/src/oracle/auth_witness.nr | 2 +- .../aztec-nr/aztec/src/oracle/avm.nr | 58 +-- .../aztec-nr/aztec/src/oracle/block_header.nr | 2 +- .../aztec/src/oracle/call_private_function.nr | 2 +- .../aztec-nr/aztec/src/oracle/capsules.nr | 8 +- .../oracle/enqueue_public_function_call.nr | 8 +- .../aztec-nr/aztec/src/oracle/execution.nr | 2 +- .../aztec/src/oracle/execution_cache.nr | 4 +- .../aztec/src/oracle/get_contract_instance.nr | 8 +- .../oracle/get_l1_to_l2_membership_witness.nr | 2 +- .../src/oracle/get_membership_witness.nr | 4 +- .../get_nullifier_membership_witness.nr | 4 +- .../src/oracle/get_public_data_witness.nr | 2 +- .../src/oracle/key_validation_request.nr | 2 +- .../aztec-nr/aztec/src/oracle/keys.nr | 2 +- .../aztec-nr/aztec/src/oracle/logs.nr | 2 +- .../aztec/src/oracle/message_processing.nr | 6 +- .../aztec-nr/aztec/src/oracle/notes.nr | 12 +- .../aztec-nr/aztec/src/oracle/nullifiers.nr | 6 +- .../aztec/src/oracle/offchain_effect.nr | 2 +- .../aztec-nr/aztec/src/oracle/random.nr | 2 +- .../aztec/src/oracle/shared_secret.nr | 2 +- .../aztec-nr/aztec/src/oracle/storage.nr | 2 +- .../aztec-nr/aztec/src/oracle/version.nr | 7 +- .../helpers/test_environment/test/misc.nr | 2 +- .../aztec/src/test/helpers/txe_oracles.nr | 38 +- .../aztec-nr/aztec/src/utils/with_hash.nr | 2 +- .../aztec_sublib/src/history/storage.nr | 2 +- .../protocol/aztec_sublib/src/oracle/avm.nr | 58 +-- .../src/oracle/call_private_function.nr | 2 +- .../aztec_sublib/src/oracle/capsules.nr | 8 +- .../oracle/enqueue_public_function_call.nr | 8 +- .../aztec_sublib/src/oracle/execution.nr | 2 +- .../src/oracle/execution_cache.nr | 4 +- .../oracle/get_l1_to_l2_membership_witness.nr | 2 +- .../protocol/aztec_sublib/src/oracle/logs.nr | 2 +- .../aztec_sublib/src/oracle/nullifiers.nr | 6 +- .../aztec_sublib/src/oracle/storage.nr | 2 +- .../avm_test_contract/src/fake_avm_oracle.nr | 12 +- .../crates/types/src/logging.nr | 2 +- .../contract_function_simulator.ts | 2 +- .../oracle/interfaces.ts | 86 ++-- .../oracle/oracle.ts | 242 ++++++----- .../oracle/oracle_version_is_checked.test.ts | 19 +- .../oracle/private_execution.ts | 2 +- .../oracle/private_execution_oracle.ts | 56 +-- .../oracle/utility_execution.test.ts | 2 +- .../oracle/utility_execution_oracle.ts | 77 ++-- yarn-project/pxe/src/oracle_version.ts | 6 +- .../circuit_recording/circuit_recorder.ts | 4 +- yarn-project/txe/src/index.ts | 4 +- yarn-project/txe/src/oracle/interfaces.ts | 58 ++- .../src/oracle/txe_oracle_public_context.ts | 24 +- .../oracle/txe_oracle_top_level_context.ts | 48 +-- yarn-project/txe/src/rpc_translator.ts | 393 +++++++++++------- yarn-project/txe/src/txe_session.ts | 6 +- 65 files changed, 775 insertions(+), 691 deletions(-) diff --git a/avm-transpiler/src/transpile.rs b/avm-transpiler/src/transpile.rs index 9bed96b15386..40e3a6f0bb4f 100644 --- a/avm-transpiler/src/transpile.rs +++ b/avm-transpiler/src/transpile.rs @@ -538,38 +538,38 @@ fn handle_foreign_call( inputs: &[ValueOrArray], ) { match function { - "avmOpcodeCall" => handle_external_call(avm_instrs, destinations, inputs, AvmOpcode::CALL), - "avmOpcodeStaticCall" => { + "aztec_avm_call" => handle_external_call(avm_instrs, destinations, inputs, AvmOpcode::CALL), + "aztec_avm_staticCall" => { handle_external_call(avm_instrs, destinations, inputs, AvmOpcode::STATICCALL); } - "avmOpcodeEmitPublicLog" => { + "aztec_avm_emitPublicLog" => { handle_emit_public_log(avm_instrs, destinations, inputs); } - "avmOpcodeNoteHashExists" => handle_note_hash_exists(avm_instrs, destinations, inputs), - "avmOpcodeEmitNoteHash" | "avmOpcodeEmitNullifier" => handle_emit_note_hash_or_nullifier( - function == "avmOpcodeEmitNullifier", + "aztec_avm_noteHashExists" => handle_note_hash_exists(avm_instrs, destinations, inputs), + "aztec_avm_emitNoteHash" | "aztec_avm_emitNullifier" => handle_emit_note_hash_or_nullifier( + function == "aztec_avm_emitNullifier", avm_instrs, destinations, inputs, ), - "avmOpcodeNullifierExists" => handle_nullifier_exists(avm_instrs, destinations, inputs), - "avmOpcodeL1ToL2MsgExists" => handle_l1_to_l2_msg_exists(avm_instrs, destinations, inputs), - "avmOpcodeSendL2ToL1Msg" => handle_send_l2_to_l1_msg(avm_instrs, destinations, inputs), - "avmOpcodeCalldataCopy" => handle_calldata_copy(avm_instrs, destinations, inputs), - "avmOpcodeSuccessCopy" => handle_success_copy(avm_instrs, destinations, inputs), - "avmOpcodeReturndataSize" => handle_returndata_size(avm_instrs, destinations, inputs), - "avmOpcodeReturndataCopy" => handle_returndata_copy(avm_instrs, destinations, inputs), - "avmOpcodeReturn" => handle_return(avm_instrs, destinations, inputs), - "avmOpcodeRevert" => handle_revert(avm_instrs, destinations, inputs), - "avmOpcodeStorageRead" => handle_storage_read(avm_instrs, destinations, inputs), - "avmOpcodeStorageWrite" => handle_storage_write(avm_instrs, destinations, inputs), - "utilityLog" => handle_debug_log(avm_instrs, destinations, inputs), + "aztec_avm_nullifierExists" => handle_nullifier_exists(avm_instrs, destinations, inputs), + "aztec_avm_l1ToL2MsgExists" => handle_l1_to_l2_msg_exists(avm_instrs, destinations, inputs), + "aztec_avm_sendL2ToL1Msg" => handle_send_l2_to_l1_msg(avm_instrs, destinations, inputs), + "aztec_avm_calldataCopy" => handle_calldata_copy(avm_instrs, destinations, inputs), + "aztec_avm_successCopy" => handle_success_copy(avm_instrs, destinations, inputs), + "aztec_avm_returndataSize" => handle_returndata_size(avm_instrs, destinations, inputs), + "aztec_avm_returndataCopy" => handle_returndata_copy(avm_instrs, destinations, inputs), + "aztec_avm_return" => handle_return(avm_instrs, destinations, inputs), + "aztec_avm_revert" => handle_revert(avm_instrs, destinations, inputs), + "aztec_avm_storageRead" => handle_storage_read(avm_instrs, destinations, inputs), + "aztec_avm_storageWrite" => handle_storage_write(avm_instrs, destinations, inputs), + "aztec_utl_log" => handle_debug_log(avm_instrs, destinations, inputs), // Getters. _ if inputs.is_empty() && destinations.len() == 1 => { handle_getter_instruction(avm_instrs, function, destinations, inputs); } // Get contract instance variations. - _ if function.starts_with("avmOpcodeGetContractInstance") => { + _ if function.starts_with("aztec_avm_getContractInstance") => { handle_get_contract_instance(avm_instrs, function, destinations, inputs); } // Anything else. @@ -580,7 +580,7 @@ fn handle_foreign_call( /// Handle an AVM CALL /// (an external 'call' brillig foreign call was encountered) /// Adds the new instruction to the avm instructions list. -// #[oracle(avmOpcodeCall)] +// #[oracle(aztec_avm_call)] // unconstrained fn call_opcode( // l2_gas_allocation: u32, // da_gas_allocation: u32, @@ -947,18 +947,18 @@ fn handle_getter_instruction( }; let var_idx = match function { - "avmOpcodeAddress" => EnvironmentVariable::ADDRESS, - "avmOpcodeSender" => EnvironmentVariable::SENDER, - "avmOpcodeMinFeePerL2Gas" => EnvironmentVariable::MINFEEPERL2GAS, - "avmOpcodeMinFeePerDaGas" => EnvironmentVariable::MINFEEPERDAGAS, - "avmOpcodeTransactionFee" => EnvironmentVariable::TRANSACTIONFEE, - "avmOpcodeChainId" => EnvironmentVariable::CHAINID, - "avmOpcodeVersion" => EnvironmentVariable::VERSION, - "avmOpcodeBlockNumber" => EnvironmentVariable::BLOCKNUMBER, - "avmOpcodeTimestamp" => EnvironmentVariable::TIMESTAMP, - "avmOpcodeL2GasLeft" => EnvironmentVariable::L2GASLEFT, - "avmOpcodeDaGasLeft" => EnvironmentVariable::DAGASLEFT, - "avmOpcodeIsStaticCall" => EnvironmentVariable::ISSTATICCALL, + "aztec_avm_address" => EnvironmentVariable::ADDRESS, + "aztec_avm_sender" => EnvironmentVariable::SENDER, + "aztec_avm_minFeePerL2Gas" => EnvironmentVariable::MINFEEPERL2GAS, + "aztec_avm_minFeePerDaGas" => EnvironmentVariable::MINFEEPERDAGAS, + "aztec_avm_transactionFee" => EnvironmentVariable::TRANSACTIONFEE, + "aztec_avm_chainId" => EnvironmentVariable::CHAINID, + "aztec_avm_version" => EnvironmentVariable::VERSION, + "aztec_avm_blockNumber" => EnvironmentVariable::BLOCKNUMBER, + "aztec_avm_timestamp" => EnvironmentVariable::TIMESTAMP, + "aztec_avm_l2GasLeft" => EnvironmentVariable::L2GASLEFT, + "aztec_avm_daGasLeft" => EnvironmentVariable::DAGASLEFT, + "aztec_avm_isStaticCall" => EnvironmentVariable::ISSTATICCALL, _ => panic!("Transpiler doesn't know how to process getter {:?}", function), }; @@ -1348,7 +1348,7 @@ fn handle_debug_log( ) { // We need to handle two flavors here: // - // #[oracle(utilityLog)] + // #[oracle(aztec_utl_log)] // unconstrained fn log_oracle( // log_level: u8, // msg: str, @@ -1358,7 +1358,7 @@ fn handle_debug_log( // // and // - //#[oracle(utilityLog)] + //#[oracle(aztec_utl_log)] // unconstrained fn log_slice_oracle(log_level: u8, msg: str, args: [Field]) {} // // Luckily, these two flavors have both 4 arguments, since noir inserts a length field for slices before the slice. @@ -1420,7 +1420,7 @@ fn handle_debug_log( }); } -// #[oracle(avmOpcodeCalldataCopy)] +// #[oracle(aztec_avm_calldataCopy)] // unconstrained fn calldata_copy_opcode(cdoffset: Field) -> [Field; N] {} fn handle_calldata_copy( avm_instrs: &mut Vec, @@ -1463,7 +1463,7 @@ fn handle_calldata_copy( }); } -// #[oracle(avmOpcodeReturndataSize)] +// #[oracle(aztec_avm_returndataSize)] // unconstrained fn returndata_size_opcode() -> u32 {} fn handle_returndata_size( avm_instrs: &mut Vec, @@ -1488,7 +1488,7 @@ fn handle_returndata_size( }); } -// #[oracle(avmOpcodeReturndataCopy)] +// #[oracle(aztec_avm_returndataCopy)] // unconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {} fn handle_returndata_copy( avm_instrs: &mut Vec, @@ -1546,7 +1546,7 @@ fn handle_returndata_copy( ]); } -// #[oracle(avmOpcodeReturn)] +// #[oracle(aztec_avm_return)] // unconstrained fn return_opcode(returndata: [Field; N]) {} fn handle_return( avm_instrs: &mut Vec, @@ -1565,7 +1565,7 @@ fn handle_return( generate_return_instruction(avm_instrs, &return_data_offset, &return_data_size); } -// #[oracle(avmOpcodeRevert)] +// #[oracle(aztec_avm_revert)] // unconstrained fn revert_opcode(revertdata: [Field]) {} fn handle_revert( avm_instrs: &mut Vec, @@ -1640,9 +1640,9 @@ fn handle_get_contract_instance( assert_eq!(destinations.len(), 1); let member_idx = match function { - "avmOpcodeGetContractInstanceDeployer" => ContractInstanceMember::DEPLOYER, - "avmOpcodeGetContractInstanceClassId" => ContractInstanceMember::CLASS_ID, - "avmOpcodeGetContractInstanceInitializationHash" => ContractInstanceMember::INIT_HASH, + "aztec_avm_getContractInstanceDeployer" => ContractInstanceMember::DEPLOYER, + "aztec_avm_getContractInstanceClassId" => ContractInstanceMember::CLASS_ID, + "aztec_avm_getContractInstanceInitializationHash" => ContractInstanceMember::INIT_HASH, _ => panic!("Transpiler doesn't know how to process function {:?}", function), }; @@ -1767,7 +1767,7 @@ fn tag_from_bit_size(bit_size: BitSize) -> AvmTypeTag { } } -/// #[oracle(avmOpcodeSuccessCopy)] +/// #[oracle(aztec_avm_successCopy)] /// unconstrained fn success_copy_opcode() -> bool {} fn handle_success_copy( avm_instrs: &mut Vec, diff --git a/noir-projects/aztec-nr/aztec/src/capsules/mod.nr b/noir-projects/aztec-nr/aztec/src/capsules/mod.nr index 9921304dd71a..ec8af10da3b2 100644 --- a/noir-projects/aztec-nr/aztec/src/capsules/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/capsules/mod.nr @@ -312,8 +312,9 @@ mod test { array.push(5); array.push(6); - // We test that the utilityCopyCapsule was never called, which is the expensive operation we want to avoid. - let mock = std::test::OracleMock::mock("utilityCopyCapsule"); + // We test that the aztec_utl_copyCapsule was never called, which is the expensive operation we want to + // avoid. + let mock = std::test::OracleMock::mock("aztec_utl_copyCapsule"); array.for_each(|index, _| { array.remove(index); }); diff --git a/noir-projects/aztec-nr/aztec/src/context/returns_hash.nr b/noir-projects/aztec-nr/aztec/src/context/returns_hash.nr index 744a1cbf5d00..7226e9c4b092 100644 --- a/noir-projects/aztec-nr/aztec/src/context/returns_hash.nr +++ b/noir-projects/aztec-nr/aztec/src/context/returns_hash.nr @@ -1,8 +1,9 @@ use crate::{hash::hash_args, oracle::execution_cache}; use crate::protocol::traits::Deserialize; -/// A hash that represents a private contract function call's return value. Call `get_preimage` to get the underlying -/// value. +/// The hash of a private contract function call's return value. +/// +/// Use [`ReturnsHash::get_preimage`] to get the underlying value. /// /// The kernels don't process the actual return values but instead their hashes, so it is up to contracts to populate /// oracles with the preimages of these hashes on return to make them available to their callers. @@ -81,17 +82,7 @@ mod test { let hash = hash_args(serialized); - let _ = OracleMock::mock("privateLoadFromExecutionCache").returns(bad_serialized); + let _ = OracleMock::mock("aztec_prv_loadFromExecutionCache").returns(bad_serialized); assert_eq(ReturnsHash::new(hash).get_preimage(), value); } - - // This test passes due to a Noir bug. #[test(should_fail_with="Preimage mismatch")] unconstrained fn - // rejects_bad_empty_preimage() { - // let value = (); let serialized = []; - - // let hash = hash_args(serialized); - - // let _ = OracleMock::mock("privateLoadFromExecutionCache").returns([1]); - // assert_eq(ReturnsHash::new(hash).get_preimage(), value); - // } } diff --git a/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr b/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr index af2f31f4834c..6aa7f5bb52dc 100644 --- a/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr @@ -71,7 +71,7 @@ mod test { // partial address random_keys_and_partial_address[12] = 0x236703e2cb00a182e024e98e9f759231b556d25ff19f98896cebb69e9e678cc9; - let _ = OracleMock::mock("utilityTryGetPublicKeysAndPartialAddress").returns(Option::some( + let _ = OracleMock::mock("aztec_utl_tryGetPublicKeysAndPartialAddress").returns(Option::some( random_keys_and_partial_address, )); let _ = get_public_keys(account); diff --git a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr index e4b6a07b1a84..41997e71c00f 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr @@ -483,12 +483,12 @@ mod test { // Mock random values for deterministic test let eph_sk = 0x1358d15019d4639393d62b97e1588c095957ce74a1c32d6ec7d62fe6705d9538; - let _ = OracleMock::mock("utilityGetRandomField").returns(eph_sk).times(1); + let _ = OracleMock::mock("aztec_utl_getRandomField").returns(eph_sk).times(1); let randomness = 0x0101010101010101010101010101010101010101010101010101010101010101; - let _ = OracleMock::mock("utilityGetRandomField").returns(randomness).times(1000000); + let _ = OracleMock::mock("aztec_utl_getRandomField").returns(randomness).times(1000000); - let _ = OracleMock::mock("privateGetNextAppTagAsSender").returns(42); + let _ = OracleMock::mock("aztec_prv_getNextAppTagAsSender").returns(42); // Encrypt the message let encrypted_message = BoundedVec::from_array(AES128::encrypt(plaintext, recipient)); @@ -499,7 +499,7 @@ mod test { recipient.to_address_point().unwrap().inner, ); - let _ = OracleMock::mock("utilityGetSharedSecret").returns(shared_secret); + let _ = OracleMock::mock("aztec_utl_getSharedSecret").returns(shared_secret); // Decrypt the message let decrypted = AES128::decrypt(encrypted_message, recipient).unwrap(); diff --git a/noir-projects/aztec-nr/aztec/src/messages/logs/utils.nr b/noir-projects/aztec-nr/aztec/src/messages/logs/utils.nr index 1cae07e731f5..afd9ab550f49 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/logs/utils.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/logs/utils.nr @@ -34,9 +34,9 @@ mod test { let expected_tag = 42; - // Mock the tagging oracles - note privateGetSenderForTags returns none - let _ = OracleMock::mock("privateGetSenderForTags").returns(Option::::none()); - let _ = OracleMock::mock("privateGetNextAppTagAsSender").returns(expected_tag); + // Mock the tagging oracles - note aztec_prv_getSenderForTags returns none + let _ = OracleMock::mock("aztec_prv_getSenderForTags").returns(Option::::none()); + let _ = OracleMock::mock("aztec_prv_getNextAppTagAsSender").returns(expected_tag); let log_without_tag = [1, 2, 3]; let _ = prefix_with_tag(log_without_tag, recipient); @@ -50,8 +50,8 @@ mod test { let expected_tag = 42; // Mock the tagging oracles - let _ = OracleMock::mock("privateGetSenderForTags").returns(Option::some(sender)); - let _ = OracleMock::mock("privateGetNextAppTagAsSender").returns(expected_tag); + let _ = OracleMock::mock("aztec_prv_getSenderForTags").returns(Option::some(sender)); + let _ = OracleMock::mock("aztec_prv_getNextAppTagAsSender").returns(expected_tag); let log_without_tag = [1, 2, 3]; let log_with_tag = prefix_with_tag(log_without_tag, recipient); diff --git a/noir-projects/aztec-nr/aztec/src/messages/processing/event_validation_request.nr b/noir-projects/aztec-nr/aztec/src/messages/processing/event_validation_request.nr index 8e757e1fbf1c..b5337e61e507 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/processing/event_validation_request.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/processing/event_validation_request.nr @@ -2,7 +2,7 @@ use crate::{event::EventSelector, messages::logs::event::MAX_EVENT_SERIALIZED_LE use crate::protocol::{address::AztecAddress, traits::Serialize}; /// Intermediate struct used to perform batch event validation by PXE. The -/// `utilityValidateAndStoreEnqueuedNotesAndEvents` oracle expects for values of this type to be stored in a +/// `aztec_utl_validateAndStoreEnqueuedNotesAndEvents` oracle expects for values of this type to be stored in a /// `CapsuleArray` at the given `base_slot`. #[derive(Serialize)] pub(crate) struct EventValidationRequest { diff --git a/noir-projects/aztec-nr/aztec/src/messages/processing/note_validation_request.nr b/noir-projects/aztec-nr/aztec/src/messages/processing/note_validation_request.nr index 00d0e1ef4738..d845284f2f23 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/processing/note_validation_request.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/processing/note_validation_request.nr @@ -2,7 +2,7 @@ use crate::messages::logs::note::MAX_NOTE_PACKED_LEN; use crate::protocol::{address::AztecAddress, traits::Serialize}; /// Intermediate struct used to perform batch note validation by PXE. The -/// `utilityValidateAndStoreEnqueuedNotesAndEvents` oracle expects for values of this type to be stored in a +/// `aztec_utl_validateAndStoreEnqueuedNotesAndEvents` oracle expects for values of this type to be stored in a /// `CapsuleArray`. #[derive(Serialize)] pub(crate) struct NoteValidationRequest { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/aes128_decrypt.nr b/noir-projects/aztec-nr/aztec/src/oracle/aes128_decrypt.nr index 3798cfc58154..7874765a31f7 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/aes128_decrypt.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/aes128_decrypt.nr @@ -8,7 +8,7 @@ /// Note that we accept ciphertext as a BoundedVec, not as an array. This is because this function is typically used /// when processing logs and at that point we don't have a comptime information about the length of the ciphertext as /// the log is not specific to any individual note. -#[oracle(utilityAes128Decrypt)] +#[oracle(aztec_utl_aes128Decrypt)] pub unconstrained fn aes128_decrypt_oracle( ciphertext: BoundedVec, iv: [u8; 16], diff --git a/noir-projects/aztec-nr/aztec/src/oracle/auth_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/auth_witness.nr index 8880436b7661..57a54b5f7f35 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/auth_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/auth_witness.nr @@ -1,4 +1,4 @@ -#[oracle(utilityGetAuthWitness)] +#[oracle(aztec_utl_getAuthWitness)] unconstrained fn get_auth_witness_oracle(_message_hash: Field) -> [Field; N] {} /// Oracle wrapper to fetch an `auth_witness` for a given `message_hash` from the PXE. diff --git a/noir-projects/aztec-nr/aztec/src/oracle/avm.nr b/noir-projects/aztec-nr/aztec/src/oracle/avm.nr index 1d1d0c726815..8f8c3c669bc9 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/avm.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/avm.nr @@ -118,82 +118,82 @@ pub unconstrained fn storage_write(storage_slot: Field, value: Field) { storage_write_opcode(storage_slot, value); } -#[oracle(avmOpcodeAddress)] +#[oracle(aztec_avm_address)] unconstrained fn address_opcode() -> AztecAddress {} -#[oracle(avmOpcodeSender)] +#[oracle(aztec_avm_sender)] unconstrained fn sender_opcode() -> AztecAddress {} -#[oracle(avmOpcodeTransactionFee)] +#[oracle(aztec_avm_transactionFee)] unconstrained fn transaction_fee_opcode() -> Field {} -#[oracle(avmOpcodeChainId)] +#[oracle(aztec_avm_chainId)] unconstrained fn chain_id_opcode() -> Field {} -#[oracle(avmOpcodeVersion)] +#[oracle(aztec_avm_version)] unconstrained fn version_opcode() -> Field {} -#[oracle(avmOpcodeBlockNumber)] +#[oracle(aztec_avm_blockNumber)] unconstrained fn block_number_opcode() -> u32 {} -#[oracle(avmOpcodeTimestamp)] +#[oracle(aztec_avm_timestamp)] unconstrained fn timestamp_opcode() -> u64 {} -#[oracle(avmOpcodeMinFeePerL2Gas)] +#[oracle(aztec_avm_minFeePerL2Gas)] unconstrained fn min_fee_per_l2_gas_opcode() -> u128 {} -#[oracle(avmOpcodeMinFeePerDaGas)] +#[oracle(aztec_avm_minFeePerDaGas)] unconstrained fn min_fee_per_da_gas_opcode() -> u128 {} -#[oracle(avmOpcodeL2GasLeft)] +#[oracle(aztec_avm_l2GasLeft)] unconstrained fn l2_gas_left_opcode() -> u32 {} -#[oracle(avmOpcodeDaGasLeft)] +#[oracle(aztec_avm_daGasLeft)] unconstrained fn da_gas_left_opcode() -> u32 {} -#[oracle(avmOpcodeIsStaticCall)] +#[oracle(aztec_avm_isStaticCall)] unconstrained fn is_static_call_opcode() -> u1 {} -#[oracle(avmOpcodeNoteHashExists)] +#[oracle(aztec_avm_noteHashExists)] unconstrained fn note_hash_exists_opcode(note_hash: Field, leaf_index: u64) -> u1 {} -#[oracle(avmOpcodeEmitNoteHash)] +#[oracle(aztec_avm_emitNoteHash)] unconstrained fn emit_note_hash_opcode(note_hash: Field) {} -#[oracle(avmOpcodeNullifierExists)] +#[oracle(aztec_avm_nullifierExists)] unconstrained fn nullifier_exists_opcode(siloed_nullifier: Field) -> u1 {} -#[oracle(avmOpcodeEmitNullifier)] +#[oracle(aztec_avm_emitNullifier)] unconstrained fn emit_nullifier_opcode(nullifier: Field) {} -#[oracle(avmOpcodeEmitPublicLog)] +#[oracle(aztec_avm_emitPublicLog)] unconstrained fn emit_public_log_opcode(message: [Field]) {} -#[oracle(avmOpcodeL1ToL2MsgExists)] +#[oracle(aztec_avm_l1ToL2MsgExists)] unconstrained fn l1_to_l2_msg_exists_opcode(msg_hash: Field, msg_leaf_index: u64) -> u1 {} -#[oracle(avmOpcodeSendL2ToL1Msg)] +#[oracle(aztec_avm_sendL2ToL1Msg)] unconstrained fn send_l2_to_l1_msg_opcode(recipient: EthAddress, content: Field) {} -#[oracle(avmOpcodeCalldataCopy)] +#[oracle(aztec_avm_calldataCopy)] unconstrained fn calldata_copy_opcode(cdoffset: u32, copy_size: u32) -> [Field; N] {} -#[oracle(avmOpcodeReturndataSize)] +#[oracle(aztec_avm_returndataSize)] unconstrained fn returndata_size_opcode() -> u32 {} -#[oracle(avmOpcodeReturndataCopy)] +#[oracle(aztec_avm_returndataCopy)] unconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {} -#[oracle(avmOpcodeReturn)] +#[oracle(aztec_avm_return)] unconstrained fn return_opcode(returndata: [Field]) {} -#[oracle(avmOpcodeRevert)] +#[oracle(aztec_avm_revert)] unconstrained fn revert_opcode(revertdata: [Field]) {} // While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode // level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take // that route. -#[oracle(avmOpcodeCall)] +#[oracle(aztec_avm_call)] unconstrained fn call_opcode( l2_gas_allocation: u32, da_gas_allocation: u32, @@ -205,7 +205,7 @@ unconstrained fn call_opcode( // While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode // level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take // that route. -#[oracle(avmOpcodeStaticCall)] +#[oracle(aztec_avm_staticCall)] unconstrained fn call_static_opcode( l2_gas_allocation: u32, da_gas_allocation: u32, @@ -214,11 +214,11 @@ unconstrained fn call_static_opcode( args: [Field; N], ) {} -#[oracle(avmOpcodeSuccessCopy)] +#[oracle(aztec_avm_successCopy)] unconstrained fn success_copy_opcode() -> bool {} -#[oracle(avmOpcodeStorageRead)] +#[oracle(aztec_avm_storageRead)] unconstrained fn storage_read_opcode(storage_slot: Field, contract_address: Field) -> Field {} -#[oracle(avmOpcodeStorageWrite)] +#[oracle(aztec_avm_storageWrite)] unconstrained fn storage_write_opcode(storage_slot: Field, value: Field) {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/block_header.nr b/noir-projects/aztec-nr/aztec/src/oracle/block_header.nr index 99fd5edcbc77..ea2afd317baa 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/block_header.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/block_header.nr @@ -2,7 +2,7 @@ use crate::protocol::{abis::block_header::BlockHeader, merkle_tree::root::root_f use crate::{context::PrivateContext, oracle::get_membership_witness::get_block_hash_membership_witness}; -#[oracle(utilityGetBlockHeader)] +#[oracle(aztec_utl_getBlockHeader)] unconstrained fn get_block_header_at_oracle(_block_number: u32) -> BlockHeader {} unconstrained fn get_block_header_at_internal(block_number: u32) -> BlockHeader { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr b/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr index 95dae70c6710..8d7863306c13 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr @@ -1,6 +1,6 @@ use crate::protocol::{abis::function_selector::FunctionSelector, address::AztecAddress, utils::reader::Reader}; -#[oracle(privateCallPrivateFunction)] +#[oracle(aztec_prv_callPrivateFunction)] unconstrained fn call_private_function_oracle( _contract_address: AztecAddress, _function_selector: FunctionSelector, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/capsules.nr b/noir-projects/aztec-nr/aztec/src/oracle/capsules.nr index 8ac4f28848c6..93b3b07d67b5 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/capsules.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/capsules.nr @@ -33,7 +33,7 @@ pub unconstrained fn copy(contract_address: AztecAddress, src_slot: Field, dst_s copy_oracle(contract_address, src_slot, dst_slot, num_entries); } -#[oracle(utilityStoreCapsule)] +#[oracle(aztec_utl_storeCapsule)] unconstrained fn store_oracle(contract_address: AztecAddress, slot: Field, values: [Field; N]) {} /// We need to pass in `array_len` (the value of N) as a parameter to tell the oracle how many fields the response must @@ -43,17 +43,17 @@ unconstrained fn store_oracle(contract_address: AztecAddress, slot: /// require for the oracle resolver to know the shape of T (e.g. if T were a struct of 3 u32 values then the expected /// response shape would be 3 single items, whereas it were a struct containing `u32, [Field;10], u32` then the /// expected shape would be single, array, single.). Instead, we return the serialization and deserialize in Noir. -#[oracle(utilityLoadCapsule)] +#[oracle(aztec_utl_loadCapsule)] unconstrained fn load_oracle( contract_address: AztecAddress, slot: Field, array_len: u32, ) -> Option<[Field; N]> {} -#[oracle(utilityDeleteCapsule)] +#[oracle(aztec_utl_deleteCapsule)] unconstrained fn delete_oracle(contract_address: AztecAddress, slot: Field) {} -#[oracle(utilityCopyCapsule)] +#[oracle(aztec_utl_copyCapsule)] unconstrained fn copy_oracle(contract_address: AztecAddress, src_slot: Field, dst_slot: Field, num_entries: u32) {} mod test { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr b/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr index 3c4268b83f98..0ac1ab8d10bb 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr @@ -1,6 +1,6 @@ use crate::protocol::address::AztecAddress; -#[oracle(privateNotifyEnqueuedPublicFunctionCall)] +#[oracle(aztec_prv_notifyEnqueuedPublicFunctionCall)] unconstrained fn notify_enqueued_public_function_call_oracle( _contract_address: AztecAddress, _calldata_hash: Field, @@ -40,7 +40,7 @@ pub fn notify_enqueued_public_function_call( } } -#[oracle(privateNotifySetPublicTeardownFunctionCall)] +#[oracle(aztec_prv_notifySetPublicTeardownFunctionCall)] unconstrained fn notify_set_public_teardown_function_call_oracle( _contract_address: AztecAddress, _calldata_hash: Field, @@ -90,12 +90,12 @@ pub unconstrained fn notify_set_min_revertible_side_effect_counter_oracle_wrappe notify_set_min_revertible_side_effect_counter_oracle(counter); } -#[oracle(privateNotifySetMinRevertibleSideEffectCounter)] +#[oracle(aztec_prv_notifySetMinRevertibleSideEffectCounter)] unconstrained fn notify_set_min_revertible_side_effect_counter_oracle(_counter: u32) {} pub unconstrained fn is_side_effect_counter_revertible_oracle_wrapper(counter: u32) -> bool { is_side_effect_counter_revertible_oracle(counter) } -#[oracle(privateIsSideEffectCounterRevertible)] +#[oracle(aztec_prv_isSideEffectCounterRevertible)] unconstrained fn is_side_effect_counter_revertible_oracle(counter: u32) -> bool {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/execution.nr b/noir-projects/aztec-nr/aztec/src/oracle/execution.nr index a4621a048ad3..120d6da53b8e 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/execution.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/execution.nr @@ -1,6 +1,6 @@ use crate::context::UtilityContext; -#[oracle(utilityGetUtilityContext)] +#[oracle(aztec_utl_getUtilityContext)] unconstrained fn get_utility_context_oracle() -> UtilityContext {} /// Returns a utility context built from the global variables of anchor block and the contract address of the function diff --git a/noir-projects/aztec-nr/aztec/src/oracle/execution_cache.nr b/noir-projects/aztec-nr/aztec/src/oracle/execution_cache.nr index c7933b7e6203..1a56f7724fa5 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/execution_cache.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/execution_cache.nr @@ -13,8 +13,8 @@ pub unconstrained fn load(hash: Field) -> [Field; N] { load_from_execution_cache_oracle(hash) } -#[oracle(privateStoreInExecutionCache)] +#[oracle(aztec_prv_storeInExecutionCache)] unconstrained fn store_in_execution_cache_oracle(_values: [Field; N], _hash: Field) {} -#[oracle(privateLoadFromExecutionCache)] +#[oracle(aztec_prv_loadFromExecutionCache)] unconstrained fn load_from_execution_cache_oracle(_hash: Field) -> [Field; N] {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr index 7b4301e95d54..11eace998fa6 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr @@ -3,7 +3,7 @@ use crate::protocol::{ }; // NOTE: this is for use in private only -#[oracle(utilityGetContractInstance)] +#[oracle(aztec_utl_getContractInstance)] unconstrained fn get_contract_instance_oracle(_address: AztecAddress) -> ContractInstance {} // NOTE: this is for use in private only @@ -27,11 +27,11 @@ struct GetContractInstanceResult { } // These oracles each return a ContractInstance member plus a boolean indicating whether the instance was found. -#[oracle(avmOpcodeGetContractInstanceDeployer)] +#[oracle(aztec_avm_getContractInstanceDeployer)] unconstrained fn get_contract_instance_deployer_oracle_avm(_address: AztecAddress) -> [GetContractInstanceResult; 1] {} -#[oracle(avmOpcodeGetContractInstanceClassId)] +#[oracle(aztec_avm_getContractInstanceClassId)] unconstrained fn get_contract_instance_class_id_oracle_avm(_address: AztecAddress) -> [GetContractInstanceResult; 1] {} -#[oracle(avmOpcodeGetContractInstanceInitializationHash)] +#[oracle(aztec_avm_getContractInstanceInitializationHash)] unconstrained fn get_contract_instance_initialization_hash_oracle_avm( _address: AztecAddress, ) -> [GetContractInstanceResult; 1] {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr index 13f165bd3534..5e76304350a5 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr @@ -11,7 +11,7 @@ pub unconstrained fn get_l1_to_l2_membership_witness( } // Obtains membership witness (index and sibling path) for a message in the L1 to L2 message tree. -#[oracle(utilityGetL1ToL2MembershipWitness)] +#[oracle(aztec_utl_getL1ToL2MembershipWitness)] unconstrained fn get_l1_to_l2_membership_witness_oracle( _contract_address: AztecAddress, _message_hash: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr index 156524b07d7a..90f83ad6f9df 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr @@ -17,13 +17,13 @@ pub struct MembershipWitness { pub path: [Field; N], } -#[oracle(utilityGetNoteHashMembershipWitness)] +#[oracle(aztec_utl_getNoteHashMembershipWitness)] unconstrained fn get_note_hash_membership_witness_oracle( anchor_block_hash: Field, note_hash: Field, ) -> MembershipWitness {} -#[oracle(utilityGetBlockHashMembershipWitness)] +#[oracle(aztec_utl_getBlockHashMembershipWitness)] unconstrained fn get_block_hash_membership_witness_oracle( anchor_block_hash: Field, block_hash: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr index 71a2bb2b98b4..c6712ba82416 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr @@ -11,7 +11,7 @@ pub struct NullifierMembershipWitness { pub path: [Field; NULLIFIER_TREE_HEIGHT], } -#[oracle(utilityGetLowNullifierMembershipWitness)] +#[oracle(aztec_utl_getLowNullifierMembershipWitness)] unconstrained fn get_low_nullifier_membership_witness_oracle( _block_hash: Field, _nullifier: Field, @@ -27,7 +27,7 @@ pub unconstrained fn get_low_nullifier_membership_witness( get_low_nullifier_membership_witness_oracle(block_hash, nullifier) } -#[oracle(utilityGetNullifierMembershipWitness)] +#[oracle(aztec_utl_getNullifierMembershipWitness)] unconstrained fn get_nullifier_membership_witness_oracle( _block_hash: Field, _nullifier: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr index 250f7a31ee77..3e912bfde3ba 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr @@ -12,7 +12,7 @@ pub struct PublicDataWitness { pub path: [Field; PUBLIC_DATA_TREE_HEIGHT], } -#[oracle(utilityGetPublicDataWitness)] +#[oracle(aztec_utl_getPublicDataWitness)] unconstrained fn get_public_data_witness_oracle( _block_hash: Field, _public_data_tree_index: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr b/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr index 222d5959a897..2db9acde92bd 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr @@ -1,6 +1,6 @@ use crate::protocol::abis::validation_requests::KeyValidationRequest; -#[oracle(utilityGetKeyValidationRequest)] +#[oracle(aztec_utl_getKeyValidationRequest)] unconstrained fn get_key_validation_request_oracle(_pk_m_hash: Field, _key_index: Field) -> KeyValidationRequest {} pub unconstrained fn get_key_validation_request(pk_m_hash: Field, key_index: Field) -> KeyValidationRequest { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/keys.nr b/noir-projects/aztec-nr/aztec/src/oracle/keys.nr index b1d162f20816..3c234ca34524 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/keys.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/keys.nr @@ -8,7 +8,7 @@ pub unconstrained fn get_public_keys_and_partial_address(address: AztecAddress) try_get_public_keys_and_partial_address(address).expect(f"Public keys not registered for account {address}") } -#[oracle(utilityTryGetPublicKeysAndPartialAddress)] +#[oracle(aztec_utl_tryGetPublicKeysAndPartialAddress)] unconstrained fn try_get_public_keys_and_partial_address_oracle(_address: AztecAddress) -> Option<[Field; 13]> {} pub unconstrained fn try_get_public_keys_and_partial_address( diff --git a/noir-projects/aztec-nr/aztec/src/oracle/logs.nr b/noir-projects/aztec-nr/aztec/src/oracle/logs.nr index d203a7bf4d20..6d0d99c68f4f 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/logs.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/logs.nr @@ -10,7 +10,7 @@ pub unconstrained fn notify_created_contract_class_log( notify_created_contract_class_log_private_oracle(contract_address, message, length, counter) } -#[oracle(privateNotifyCreatedContractClassLog)] +#[oracle(aztec_prv_notifyCreatedContractClassLog)] unconstrained fn notify_created_contract_class_log_private_oracle( contract_address: AztecAddress, message: [Field; N], diff --git a/noir-projects/aztec-nr/aztec/src/oracle/message_processing.nr b/noir-projects/aztec-nr/aztec/src/oracle/message_processing.nr index d0582872b23d..76052860bffe 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/message_processing.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/message_processing.nr @@ -6,7 +6,7 @@ pub unconstrained fn fetch_tagged_logs(pending_tagged_log_array_base_slot: Field fetch_tagged_logs_oracle(pending_tagged_log_array_base_slot); } -#[oracle(utilityFetchTaggedLogs)] +#[oracle(aztec_utl_fetchTaggedLogs)] unconstrained fn fetch_tagged_logs_oracle(pending_tagged_log_array_base_slot: Field) {} // This must be a single oracle and not one for notes and one for events because the entire point is to validate all @@ -23,7 +23,7 @@ pub(crate) unconstrained fn validate_and_store_enqueued_notes_and_events( ); } -#[oracle(utilityValidateAndStoreEnqueuedNotesAndEvents)] +#[oracle(aztec_utl_validateAndStoreEnqueuedNotesAndEvents)] unconstrained fn validate_and_store_enqueued_notes_and_events_oracle( contract_address: AztecAddress, note_validation_requests_array_base_slot: Field, @@ -42,7 +42,7 @@ pub(crate) unconstrained fn bulk_retrieve_logs( ); } -#[oracle(utilityBulkRetrieveLogs)] +#[oracle(aztec_utl_bulkRetrieveLogs)] unconstrained fn bulk_retrieve_logs_oracle( contract_address: AztecAddress, log_retrieval_requests_array_base_slot: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/notes.nr b/noir-projects/aztec-nr/aztec/src/oracle/notes.nr index 710e77cb8573..1975fbabb999 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/notes.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/notes.nr @@ -57,7 +57,7 @@ unconstrained fn notify_created_note_oracle_wrapper( ); } -#[oracle(privateNotifyCreatedNote)] +#[oracle(aztec_prv_notifyCreatedNote)] unconstrained fn notify_created_note_oracle( _owner: AztecAddress, _storage_slot: Field, @@ -72,10 +72,10 @@ unconstrained fn notify_nullified_note_oracle_wrapper(nullifier: Field, note_has notify_nullified_note_oracle(nullifier, note_hash, counter); } -#[oracle(privateNotifyNullifiedNote)] +#[oracle(aztec_prv_notifyNullifiedNote)] unconstrained fn notify_nullified_note_oracle(_nullifier: Field, _note_hash: Field, _counter: u32) {} -#[oracle(utilityGetNotes)] +#[oracle(aztec_utl_getNotes)] unconstrained fn get_notes_oracle( _owner: Option, _storage_slot: Field, @@ -189,7 +189,7 @@ pub unconstrained fn get_next_app_tag_as_sender(sender: AztecAddress, recipient: get_next_app_tag_as_sender_oracle(sender, recipient) } -#[oracle(privateGetNextAppTagAsSender)] +#[oracle(aztec_prv_getNextAppTagAsSender)] unconstrained fn get_next_app_tag_as_sender_oracle(_sender: AztecAddress, _recipient: AztecAddress) -> Field {} /// Gets the sender for tags. @@ -204,7 +204,7 @@ pub unconstrained fn get_sender_for_tags() -> Option { get_sender_for_tags_oracle() } -#[oracle(privateGetSenderForTags)] +#[oracle(aztec_prv_getSenderForTags)] unconstrained fn get_sender_for_tags_oracle() -> Option {} /// Sets the sender for tags. @@ -220,5 +220,5 @@ pub unconstrained fn set_sender_for_tags(sender_for_tags: AztecAddress) { set_sender_for_tags_oracle(sender_for_tags); } -#[oracle(privateSetSenderForTags)] +#[oracle(aztec_prv_setSenderForTags)] unconstrained fn set_sender_for_tags_oracle(_sender_for_tags: AztecAddress) {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/nullifiers.nr b/noir-projects/aztec-nr/aztec/src/oracle/nullifiers.nr index 4ec567cbfe88..323028dac4db 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/nullifiers.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/nullifiers.nr @@ -11,7 +11,7 @@ pub fn notify_created_nullifier(inner_nullifier: Field) { unsafe { notify_created_nullifier_oracle(inner_nullifier) }; } -#[oracle(privateNotifyCreatedNullifier)] +#[oracle(aztec_prv_notifyCreatedNullifier)] unconstrained fn notify_created_nullifier_oracle(_inner_nullifier: Field) {} /// Returns true if the nullifier has been emitted in the same transaction, i.e. if [`notify_created_nullifier`] has @@ -26,7 +26,7 @@ pub unconstrained fn is_nullifier_pending(inner_nullifier: Field, contract_addre is_nullifier_pending_oracle(inner_nullifier, contract_address) } -#[oracle(privateIsNullifierPending)] +#[oracle(aztec_prv_isNullifierPending)] unconstrained fn is_nullifier_pending_oracle(_inner_nullifier: Field, _contract_address: AztecAddress) -> bool {} /// Returns true if the nullifier exists. Note that a `true` value can be constrained by proving existence of the @@ -37,5 +37,5 @@ pub unconstrained fn check_nullifier_exists(inner_nullifier: Field) -> bool { check_nullifier_exists_oracle(inner_nullifier) } -#[oracle(utilityCheckNullifierExists)] +#[oracle(aztec_utl_checkNullifierExists)] unconstrained fn check_nullifier_exists_oracle(_inner_nullifier: Field) -> bool {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/offchain_effect.nr b/noir-projects/aztec-nr/aztec/src/oracle/offchain_effect.nr index f9ebfe6daf58..c818270e8673 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/offchain_effect.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/offchain_effect.nr @@ -13,5 +13,5 @@ where emit_offchain_effect_oracle(data.serialize()); } -#[oracle(utilityEmitOffchainEffect)] +#[oracle(aztec_utl_emitOffchainEffect)] unconstrained fn emit_offchain_effect_oracle(data: [Field; N]) {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/random.nr b/noir-projects/aztec-nr/aztec/src/oracle/random.nr index 8e12ec0c1a51..827efadbbc15 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/random.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/random.nr @@ -6,5 +6,5 @@ pub unconstrained fn random() -> Field { rand_oracle() } -#[oracle(utilityGetRandomField)] +#[oracle(aztec_utl_getRandomField)] unconstrained fn rand_oracle() -> Field {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/shared_secret.nr b/noir-projects/aztec-nr/aztec/src/oracle/shared_secret.nr index 538aab40f55f..a040afdb98da 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/shared_secret.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/shared_secret.nr @@ -1,7 +1,7 @@ use crate::protocol::{address::aztec_address::AztecAddress, point::Point}; // TODO(#12656): return an app-siloed secret + document this -#[oracle(utilityGetSharedSecret)] +#[oracle(aztec_utl_getSharedSecret)] unconstrained fn get_shared_secret_oracle(address: AztecAddress, ephPk: Point) -> Point {} /// Returns an app-siloed shared secret between `address` and someone who knows the secret key behind an ephemeral diff --git a/noir-projects/aztec-nr/aztec/src/oracle/storage.nr b/noir-projects/aztec-nr/aztec/src/oracle/storage.nr index 09318aee2f66..fef8abe759c8 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/storage.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/storage.nr @@ -1,6 +1,6 @@ use crate::protocol::{abis::block_header::BlockHeader, address::AztecAddress, traits::{Hash, Packable, ToField}}; -#[oracle(utilityStorageRead)] +#[oracle(aztec_utl_storageRead)] unconstrained fn storage_read_oracle( block_hash: Field, address: Field, diff --git a/noir-projects/aztec-nr/aztec/src/oracle/version.nr b/noir-projects/aztec-nr/aztec/src/oracle/version.nr index b979532dc7dc..673822ce14a6 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/version.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/version.nr @@ -2,9 +2,10 @@ /// to version the oracle interface to ensure that developers get a reasonable error message if they use incompatible /// versions of Aztec.nr and PXE. The TypeScript counterpart is in `oracle_version.ts`. /// -/// @dev Whenever a contract function or Noir test is run, the `utilityAssertCompatibleOracleVersion` oracle is called +/// @dev Whenever a contract function or Noir test is run, the `aztec_utl_assertCompatibleOracleVersion` oracle is +/// called /// and if the oracle version is incompatible an error is thrown. -pub global ORACLE_VERSION: Field = 12; +pub global ORACLE_VERSION: Field = 13; /// Asserts that the version of the oracle is compatible with the version expected by the contract. pub fn assert_compatible_oracle_version() { @@ -19,7 +20,7 @@ unconstrained fn assert_compatible_oracle_version_wrapper() { assert_compatible_oracle_version_oracle(ORACLE_VERSION); } -#[oracle(utilityAssertCompatibleOracleVersion)] +#[oracle(aztec_utl_assertCompatibleOracleVersion)] unconstrained fn assert_compatible_oracle_version_oracle(version: Field) {} mod test { diff --git a/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment/test/misc.nr b/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment/test/misc.nr index de2fd4643622..09f4dd16f7ec 100644 --- a/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment/test/misc.nr +++ b/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment/test/misc.nr @@ -39,7 +39,7 @@ unconstrained fn private_public_and_utility_context_share_default_chain_id() { #[test] unconstrained fn oracle_version_is_checked_upon_env_creation() { - let mock = OracleMock::mock("utilityAssertCompatibleOracleVersion"); + let mock = OracleMock::mock("aztec_utl_assertCompatibleOracleVersion"); let _env = TestEnvironment::new(); diff --git a/noir-projects/aztec-nr/aztec/src/test/helpers/txe_oracles.nr b/noir-projects/aztec-nr/aztec/src/test/helpers/txe_oracles.nr index f1d61d82e8cc..608352e06d6b 100644 --- a/noir-projects/aztec-nr/aztec/src/test/helpers/txe_oracles.nr +++ b/noir-projects/aztec-nr/aztec/src/test/helpers/txe_oracles.nr @@ -63,19 +63,19 @@ pub unconstrained fn execute_utility_function( execute_utility_function_oracle(contract_address, function_selector, args) } -#[oracle(txeGetNextBlockNumber)] +#[oracle(aztec_txe_getNextBlockNumber)] pub unconstrained fn get_next_block_number() -> u32 {} -#[oracle(txeGetNextBlockTimestamp)] +#[oracle(aztec_txe_getNextBlockTimestamp)] pub unconstrained fn get_next_block_timestamp() -> u64 {} -#[oracle(txeGetLastBlockTimestamp)] +#[oracle(aztec_txe_getLastBlockTimestamp)] pub unconstrained fn get_last_block_timestamp() -> u64 {} -#[oracle(txeGetLastTxEffects)] +#[oracle(aztec_txe_getLastTxEffects)] pub unconstrained fn get_last_tx_effects() -> (Field, BoundedVec, BoundedVec) {} -#[oracle(txeGetDefaultAddress)] +#[oracle(aztec_txe_getDefaultAddress)] pub unconstrained fn get_default_address() -> AztecAddress {} // experimental @@ -97,20 +97,20 @@ pub(crate) unconstrained fn get_private_events( events } -#[oracle(txeGetPrivateEvents)] +#[oracle(aztec_txe_getPrivateEvents)] unconstrained fn get_private_events_oracle( selector: EventSelector, contract_address: AztecAddress, scope: AztecAddress, ) -> ([[Field; MAX_EVENT_SERIALIZATION_LENGTH]; MAX_PRIVATE_EVENTS_PER_TXE_QUERY], [u32; MAX_PRIVATE_EVENTS_PER_TXE_QUERY], u32) {} -#[oracle(txeAdvanceBlocksBy)] +#[oracle(aztec_txe_advanceBlocksBy)] pub unconstrained fn advance_blocks_by(blocks: u32) {} -#[oracle(txeAdvanceTimestampBy)] +#[oracle(aztec_txe_advanceTimestampBy)] pub unconstrained fn advance_timestamp_by(duration: u64) {} -#[oracle(txeDeploy)] +#[oracle(aztec_txe_deploy)] pub unconstrained fn deploy_oracle( path: str, initializer: str

, @@ -118,16 +118,16 @@ pub unconstrained fn deploy_oracle( secret: Field, ) -> [Field; CONTRACT_INSTANCE_LENGTH] {} -#[oracle(txeCreateAccount)] +#[oracle(aztec_txe_createAccount)] pub unconstrained fn create_account(secret: Field) -> TestAccount {} -#[oracle(txeAddAccount)] +#[oracle(aztec_txe_addAccount)] pub unconstrained fn add_account(secret: Field) -> TestAccount {} -#[oracle(txeAddAuthWitness)] +#[oracle(aztec_txe_addAuthWitness)] pub unconstrained fn add_authwit(address: AztecAddress, message_hash: Field) {} -#[oracle(txePrivateCallNewFlow)] +#[oracle(aztec_txe_privateCallNewFlow)] unconstrained fn private_call_new_flow_oracle( _from: AztecAddress, _contract_address: AztecAddress, @@ -137,7 +137,7 @@ unconstrained fn private_call_new_flow_oracle( _is_static_call: bool, ) -> [Field; N] {} -#[oracle(txePublicCallNewFlow)] +#[oracle(aztec_txe_publicCallNewFlow)] unconstrained fn public_call_new_flow_oracle( from: AztecAddress, contract_address: AztecAddress, @@ -145,24 +145,24 @@ unconstrained fn public_call_new_flow_oracle( is_static_call: bool, ) -> [Field; N] {} -#[oracle(txeExecuteUtilityFunction)] +#[oracle(aztec_txe_executeUtilityFunction)] unconstrained fn execute_utility_function_oracle( contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field; M], ) -> [Field; N] {} -#[oracle(txeSetTopLevelTXEContext)] +#[oracle(aztec_txe_setTopLevelTXEContext)] pub unconstrained fn set_top_level_txe_context() {} -#[oracle(txeSetPrivateTXEContext)] +#[oracle(aztec_txe_setPrivateTXEContext)] pub unconstrained fn set_private_txe_context( contract_address: Option, anchor_block_number: Option, ) -> PrivateContextInputs {} -#[oracle(txeSetPublicTXEContext)] +#[oracle(aztec_txe_setPublicTXEContext)] pub unconstrained fn set_public_txe_context(contract_address: Option) {} -#[oracle(txeSetUtilityTXEContext)] +#[oracle(aztec_txe_setUtilityTXEContext)] pub unconstrained fn set_utility_txe_context(contract_address: Option) {} diff --git a/noir-projects/aztec-nr/aztec/src/utils/with_hash.nr b/noir-projects/aztec-nr/aztec/src/utils/with_hash.nr index b2d465e7d0b2..14cc838857f1 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/with_hash.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/with_hash.nr @@ -173,7 +173,7 @@ mod test { // Mock the oracle to return a non-zero hint/packed value let value_packed = MockStruct { a: 1, b: 1 }.pack(); - let _ = OracleMock::mock("utilityStorageRead") + let _ = OracleMock::mock("aztec_utl_storageRead") .with_params((block_header.hash(), address.to_field(), STORAGE_SLOT, value_packed.len())) .returns(value_packed) .times(1); diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/history/storage.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/history/storage.nr index 957691e07fae..9a1edae258cd 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/history/storage.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/history/storage.nr @@ -17,7 +17,7 @@ pub struct PublicDataWitness { pub path: [Field; PUBLIC_DATA_TREE_HEIGHT], } -#[oracle(utilityGetPublicDataWitness)] +#[oracle(aztec_utl_getPublicDataWitness)] unconstrained fn get_public_data_witness_oracle( _block_hash: Field, _public_data_tree_index: Field, diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/avm.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/avm.nr index 1d1d0c726815..8f8c3c669bc9 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/avm.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/avm.nr @@ -118,82 +118,82 @@ pub unconstrained fn storage_write(storage_slot: Field, value: Field) { storage_write_opcode(storage_slot, value); } -#[oracle(avmOpcodeAddress)] +#[oracle(aztec_avm_address)] unconstrained fn address_opcode() -> AztecAddress {} -#[oracle(avmOpcodeSender)] +#[oracle(aztec_avm_sender)] unconstrained fn sender_opcode() -> AztecAddress {} -#[oracle(avmOpcodeTransactionFee)] +#[oracle(aztec_avm_transactionFee)] unconstrained fn transaction_fee_opcode() -> Field {} -#[oracle(avmOpcodeChainId)] +#[oracle(aztec_avm_chainId)] unconstrained fn chain_id_opcode() -> Field {} -#[oracle(avmOpcodeVersion)] +#[oracle(aztec_avm_version)] unconstrained fn version_opcode() -> Field {} -#[oracle(avmOpcodeBlockNumber)] +#[oracle(aztec_avm_blockNumber)] unconstrained fn block_number_opcode() -> u32 {} -#[oracle(avmOpcodeTimestamp)] +#[oracle(aztec_avm_timestamp)] unconstrained fn timestamp_opcode() -> u64 {} -#[oracle(avmOpcodeMinFeePerL2Gas)] +#[oracle(aztec_avm_minFeePerL2Gas)] unconstrained fn min_fee_per_l2_gas_opcode() -> u128 {} -#[oracle(avmOpcodeMinFeePerDaGas)] +#[oracle(aztec_avm_minFeePerDaGas)] unconstrained fn min_fee_per_da_gas_opcode() -> u128 {} -#[oracle(avmOpcodeL2GasLeft)] +#[oracle(aztec_avm_l2GasLeft)] unconstrained fn l2_gas_left_opcode() -> u32 {} -#[oracle(avmOpcodeDaGasLeft)] +#[oracle(aztec_avm_daGasLeft)] unconstrained fn da_gas_left_opcode() -> u32 {} -#[oracle(avmOpcodeIsStaticCall)] +#[oracle(aztec_avm_isStaticCall)] unconstrained fn is_static_call_opcode() -> u1 {} -#[oracle(avmOpcodeNoteHashExists)] +#[oracle(aztec_avm_noteHashExists)] unconstrained fn note_hash_exists_opcode(note_hash: Field, leaf_index: u64) -> u1 {} -#[oracle(avmOpcodeEmitNoteHash)] +#[oracle(aztec_avm_emitNoteHash)] unconstrained fn emit_note_hash_opcode(note_hash: Field) {} -#[oracle(avmOpcodeNullifierExists)] +#[oracle(aztec_avm_nullifierExists)] unconstrained fn nullifier_exists_opcode(siloed_nullifier: Field) -> u1 {} -#[oracle(avmOpcodeEmitNullifier)] +#[oracle(aztec_avm_emitNullifier)] unconstrained fn emit_nullifier_opcode(nullifier: Field) {} -#[oracle(avmOpcodeEmitPublicLog)] +#[oracle(aztec_avm_emitPublicLog)] unconstrained fn emit_public_log_opcode(message: [Field]) {} -#[oracle(avmOpcodeL1ToL2MsgExists)] +#[oracle(aztec_avm_l1ToL2MsgExists)] unconstrained fn l1_to_l2_msg_exists_opcode(msg_hash: Field, msg_leaf_index: u64) -> u1 {} -#[oracle(avmOpcodeSendL2ToL1Msg)] +#[oracle(aztec_avm_sendL2ToL1Msg)] unconstrained fn send_l2_to_l1_msg_opcode(recipient: EthAddress, content: Field) {} -#[oracle(avmOpcodeCalldataCopy)] +#[oracle(aztec_avm_calldataCopy)] unconstrained fn calldata_copy_opcode(cdoffset: u32, copy_size: u32) -> [Field; N] {} -#[oracle(avmOpcodeReturndataSize)] +#[oracle(aztec_avm_returndataSize)] unconstrained fn returndata_size_opcode() -> u32 {} -#[oracle(avmOpcodeReturndataCopy)] +#[oracle(aztec_avm_returndataCopy)] unconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {} -#[oracle(avmOpcodeReturn)] +#[oracle(aztec_avm_return)] unconstrained fn return_opcode(returndata: [Field]) {} -#[oracle(avmOpcodeRevert)] +#[oracle(aztec_avm_revert)] unconstrained fn revert_opcode(revertdata: [Field]) {} // While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode // level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take // that route. -#[oracle(avmOpcodeCall)] +#[oracle(aztec_avm_call)] unconstrained fn call_opcode( l2_gas_allocation: u32, da_gas_allocation: u32, @@ -205,7 +205,7 @@ unconstrained fn call_opcode( // While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode // level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take // that route. -#[oracle(avmOpcodeStaticCall)] +#[oracle(aztec_avm_staticCall)] unconstrained fn call_static_opcode( l2_gas_allocation: u32, da_gas_allocation: u32, @@ -214,11 +214,11 @@ unconstrained fn call_static_opcode( args: [Field; N], ) {} -#[oracle(avmOpcodeSuccessCopy)] +#[oracle(aztec_avm_successCopy)] unconstrained fn success_copy_opcode() -> bool {} -#[oracle(avmOpcodeStorageRead)] +#[oracle(aztec_avm_storageRead)] unconstrained fn storage_read_opcode(storage_slot: Field, contract_address: Field) -> Field {} -#[oracle(avmOpcodeStorageWrite)] +#[oracle(aztec_avm_storageWrite)] unconstrained fn storage_write_opcode(storage_slot: Field, value: Field) {} diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/call_private_function.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/call_private_function.nr index bb9e9373e1cc..8804801debb8 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/call_private_function.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/call_private_function.nr @@ -2,7 +2,7 @@ use crate::protocol::{ abis::function_selector::FunctionSelector, address::AztecAddress, utils::reader::Reader, }; -#[oracle(privateCallPrivateFunction)] +#[oracle(aztec_prv_callPrivateFunction)] unconstrained fn call_private_function_oracle( _contract_address: AztecAddress, _function_selector: FunctionSelector, diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/capsules.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/capsules.nr index e9c90557dbfb..762b984311b2 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/capsules.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/capsules.nr @@ -38,7 +38,7 @@ pub unconstrained fn copy( copy_oracle(contract_address, src_slot, dst_slot, num_entries); } -#[oracle(utilityStoreCapsule)] +#[oracle(aztec_utl_storeCapsule)] unconstrained fn store_oracle( contract_address: AztecAddress, slot: Field, @@ -52,17 +52,17 @@ unconstrained fn store_oracle( /// require for the oracle resolver to know the shape of T (e.g. if T were a struct of 3 u32 values then the expected /// response shape would be 3 single items, whereas it were a struct containing `u32, [Field;10], u32` then the /// expected shape would be single, array, single.). Instead, we return the serialization and deserialize in Noir. -#[oracle(utilityLoadCapsule)] +#[oracle(aztec_utl_loadCapsule)] unconstrained fn load_oracle( contract_address: AztecAddress, slot: Field, array_len: u32, ) -> Option<[Field; N]> {} -#[oracle(utilityDeleteCapsule)] +#[oracle(aztec_utl_deleteCapsule)] unconstrained fn delete_oracle(contract_address: AztecAddress, slot: Field) {} -#[oracle(utilityCopyCapsule)] +#[oracle(aztec_utl_copyCapsule)] unconstrained fn copy_oracle( contract_address: AztecAddress, src_slot: Field, diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/enqueue_public_function_call.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/enqueue_public_function_call.nr index 3c4268b83f98..0ac1ab8d10bb 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/enqueue_public_function_call.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/enqueue_public_function_call.nr @@ -1,6 +1,6 @@ use crate::protocol::address::AztecAddress; -#[oracle(privateNotifyEnqueuedPublicFunctionCall)] +#[oracle(aztec_prv_notifyEnqueuedPublicFunctionCall)] unconstrained fn notify_enqueued_public_function_call_oracle( _contract_address: AztecAddress, _calldata_hash: Field, @@ -40,7 +40,7 @@ pub fn notify_enqueued_public_function_call( } } -#[oracle(privateNotifySetPublicTeardownFunctionCall)] +#[oracle(aztec_prv_notifySetPublicTeardownFunctionCall)] unconstrained fn notify_set_public_teardown_function_call_oracle( _contract_address: AztecAddress, _calldata_hash: Field, @@ -90,12 +90,12 @@ pub unconstrained fn notify_set_min_revertible_side_effect_counter_oracle_wrappe notify_set_min_revertible_side_effect_counter_oracle(counter); } -#[oracle(privateNotifySetMinRevertibleSideEffectCounter)] +#[oracle(aztec_prv_notifySetMinRevertibleSideEffectCounter)] unconstrained fn notify_set_min_revertible_side_effect_counter_oracle(_counter: u32) {} pub unconstrained fn is_side_effect_counter_revertible_oracle_wrapper(counter: u32) -> bool { is_side_effect_counter_revertible_oracle(counter) } -#[oracle(privateIsSideEffectCounterRevertible)] +#[oracle(aztec_prv_isSideEffectCounterRevertible)] unconstrained fn is_side_effect_counter_revertible_oracle(counter: u32) -> bool {} diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution.nr index a4621a048ad3..120d6da53b8e 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution.nr @@ -1,6 +1,6 @@ use crate::context::UtilityContext; -#[oracle(utilityGetUtilityContext)] +#[oracle(aztec_utl_getUtilityContext)] unconstrained fn get_utility_context_oracle() -> UtilityContext {} /// Returns a utility context built from the global variables of anchor block and the contract address of the function diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution_cache.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution_cache.nr index b3bfe08fd0aa..5ba553baa659 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution_cache.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/execution_cache.nr @@ -16,8 +16,8 @@ pub unconstrained fn load(hash: Field) -> [Field; N] { load_from_execution_cache_oracle(hash) } -#[oracle(privateStoreInExecutionCache)] +#[oracle(aztec_prv_storeInExecutionCache)] unconstrained fn store_in_execution_cache_oracle(_values: [Field; N], _hash: Field) {} -#[oracle(privateLoadFromExecutionCache)] +#[oracle(aztec_prv_loadFromExecutionCache)] unconstrained fn load_from_execution_cache_oracle(_hash: Field) -> [Field; N] {} diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/get_l1_to_l2_membership_witness.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/get_l1_to_l2_membership_witness.nr index 13f165bd3534..5e76304350a5 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/get_l1_to_l2_membership_witness.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/get_l1_to_l2_membership_witness.nr @@ -11,7 +11,7 @@ pub unconstrained fn get_l1_to_l2_membership_witness( } // Obtains membership witness (index and sibling path) for a message in the L1 to L2 message tree. -#[oracle(utilityGetL1ToL2MembershipWitness)] +#[oracle(aztec_utl_getL1ToL2MembershipWitness)] unconstrained fn get_l1_to_l2_membership_witness_oracle( _contract_address: AztecAddress, _message_hash: Field, diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/logs.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/logs.nr index d203a7bf4d20..6d0d99c68f4f 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/logs.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/logs.nr @@ -10,7 +10,7 @@ pub unconstrained fn notify_created_contract_class_log( notify_created_contract_class_log_private_oracle(contract_address, message, length, counter) } -#[oracle(privateNotifyCreatedContractClassLog)] +#[oracle(aztec_prv_notifyCreatedContractClassLog)] unconstrained fn notify_created_contract_class_log_private_oracle( contract_address: AztecAddress, message: [Field; N], diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/nullifiers.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/nullifiers.nr index aea679990005..1f9f5de98a02 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/nullifiers.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/nullifiers.nr @@ -11,7 +11,7 @@ pub fn notify_created_nullifier(inner_nullifier: Field) { unsafe { notify_created_nullifier_oracle(inner_nullifier) }; } -#[oracle(privateNotifyCreatedNullifier)] +#[oracle(aztec_prv_notifyCreatedNullifier)] unconstrained fn notify_created_nullifier_oracle(_inner_nullifier: Field) {} /// Returns true if the nullifier has been emitted in the same transaction, i.e. if [notify_created_nullifier] has been @@ -28,7 +28,7 @@ pub unconstrained fn is_nullifier_pending( is_nullifier_pending_oracle(inner_nullifier, contract_address) } -#[oracle(privateIsNullifierPending)] +#[oracle(aztec_prv_isNullifierPending)] unconstrained fn is_nullifier_pending_oracle( _inner_nullifier: Field, _contract_address: AztecAddress, @@ -42,5 +42,5 @@ pub unconstrained fn check_nullifier_exists(inner_nullifier: Field) -> bool { check_nullifier_exists_oracle(inner_nullifier) } -#[oracle(utilityCheckNullifierExists)] +#[oracle(aztec_utl_checkNullifierExists)] unconstrained fn check_nullifier_exists_oracle(_inner_nullifier: Field) -> bool {} diff --git a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/storage.nr b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/storage.nr index f1181de8ab04..b91bf4c6866a 100644 --- a/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/storage.nr +++ b/noir-projects/noir-contracts/contracts/protocol/aztec_sublib/src/oracle/storage.nr @@ -4,7 +4,7 @@ use crate::protocol::{ traits::{Hash, Packable, ToField}, }; -#[oracle(utilityStorageRead)] +#[oracle(aztec_utl_storageRead)] unconstrained fn storage_read_oracle( block_hash: Field, address: Field, diff --git a/noir-projects/noir-contracts/contracts/test/avm_test_contract/src/fake_avm_oracle.nr b/noir-projects/noir-contracts/contracts/test/avm_test_contract/src/fake_avm_oracle.nr index ffaf9d504f1a..178d73414292 100644 --- a/noir-projects/noir-contracts/contracts/test/avm_test_contract/src/fake_avm_oracle.nr +++ b/noir-projects/noir-contracts/contracts/test/avm_test_contract/src/fake_avm_oracle.nr @@ -32,7 +32,7 @@ pub unconstrained fn revert(revertdata: [Field]) { // While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode // level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take that // route. -#[oracle(avmOpcodeCall)] +#[oracle(aztec_avm_call)] unconstrained fn call_opcode( l2_gas_allocation: u32, da_gas_allocation: u32, @@ -41,17 +41,17 @@ unconstrained fn call_opcode( args: [Field; N], ) {} -#[oracle(avmOpcodeSuccessCopy)] +#[oracle(aztec_avm_successCopy)] unconstrained fn success_copy_opcode() -> bool {} -#[oracle(avmOpcodeReturndataSize)] +#[oracle(aztec_avm_returndataSize)] unconstrained fn returndata_size_opcode() -> u32 {} -#[oracle(avmOpcodeReturndataCopy)] +#[oracle(aztec_avm_returndataCopy)] unconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {} -#[oracle(avmOpcodeReturn)] +#[oracle(aztec_avm_return)] unconstrained fn return_opcode(returndata: [Field]) {} -#[oracle(avmOpcodeRevert)] +#[oracle(aztec_avm_revert)] unconstrained fn revert_opcode(revertdata: [Field]) {} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/logging.nr b/noir-projects/noir-protocol-circuits/crates/types/src/logging.nr index 1fc74f3da220..30afa0713bb2 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/logging.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/logging.nr @@ -83,7 +83,7 @@ unconstrained fn log_oracle_wrapper( log_oracle(log_level, msg, N, args); } -#[oracle(utilityLog)] +#[oracle(aztec_utl_log)] unconstrained fn log_oracle( log_level: u8, msg: str, diff --git a/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts index b23535571a58..5fcb18aa42c8 100644 --- a/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts +++ b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts @@ -277,7 +277,7 @@ export class ContractFunctionSimulator { ); const publicFunctionsCalldata = await Promise.all( publicCallRequests.map(async r => { - const calldata = await privateExecutionOracle.privateLoadFromExecutionCache(r.calldataHash); + const calldata = await privateExecutionOracle.loadFromExecutionCache(r.calldataHash); return new HashedValues(calldata, r.calldataHash); }), ); diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/interfaces.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/interfaces.ts index 5d1e5a656cfb..3b6dba3494cf 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/interfaces.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/interfaces.ts @@ -52,9 +52,9 @@ export interface NoteData { export interface IMiscOracle { isMisc: true; - utilityGetRandomField(): Fr; - utilityAssertCompatibleOracleVersion(version: number): void; - utilityLog(level: number, message: string, fields: Fr[]): Promise; + getRandomField(): Fr; + assertCompatibleOracleVersion(version: number): void; + log(level: number, message: string, fields: Fr[]): Promise; } /** @@ -64,30 +64,30 @@ export interface IMiscOracle { export interface IUtilityExecutionOracle { isUtility: true; - utilityGetUtilityContext(): UtilityContext; - utilityGetKeyValidationRequest(pkMHash: Fr): Promise; - utilityGetContractInstance(address: AztecAddress): Promise; - utilityGetNoteHashMembershipWitness( + getUtilityContext(): UtilityContext; + getKeyValidationRequest(pkMHash: Fr): Promise; + getContractInstance(address: AztecAddress): Promise; + getNoteHashMembershipWitness( anchorBlockHash: BlockHash, noteHash: Fr, ): Promise | undefined>; - utilityGetBlockHashMembershipWitness( + getBlockHashMembershipWitness( anchorBlockHash: BlockHash, blockHash: BlockHash, ): Promise | undefined>; - utilityGetNullifierMembershipWitness( + getNullifierMembershipWitness( anchorBlockHash: BlockHash, nullifier: Fr, ): Promise; - utilityGetPublicDataWitness(anchorBlockHash: BlockHash, leafSlot: Fr): Promise; - utilityGetLowNullifierMembershipWitness( + getPublicDataWitness(anchorBlockHash: BlockHash, leafSlot: Fr): Promise; + getLowNullifierMembershipWitness( anchorBlockHash: BlockHash, nullifier: Fr, ): Promise; - utilityGetBlockHeader(blockNumber: BlockNumber): Promise; - utilityTryGetPublicKeysAndPartialAddress(account: AztecAddress): Promise; - utilityGetAuthWitness(messageHash: Fr): Promise; - utilityGetNotes( + getBlockHeader(blockNumber: BlockNumber): Promise; + tryGetPublicKeysAndPartialAddress(account: AztecAddress): Promise; + getAuthWitness(messageHash: Fr): Promise; + getNotes( owner: AztecAddress | undefined, storageSlot: Fr, numSelects: number, @@ -104,35 +104,35 @@ export interface IUtilityExecutionOracle { offset: number, status: NoteStatus, ): Promise; - utilityCheckNullifierExists(innerNullifier: Fr): Promise; - utilityGetL1ToL2MembershipWitness( + checkNullifierExists(innerNullifier: Fr): Promise; + getL1ToL2MembershipWitness( contractAddress: AztecAddress, messageHash: Fr, secret: Fr, ): Promise>; - utilityStorageRead( + storageRead( anchorBlockHash: BlockHash, contractAddress: AztecAddress, startStorageSlot: Fr, numberOfElements: number, ): Promise; - utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr): Promise; - utilityValidateAndStoreEnqueuedNotesAndEvents( + fetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr): Promise; + validateAndStoreEnqueuedNotesAndEvents( contractAddress: AztecAddress, noteValidationRequestsArrayBaseSlot: Fr, eventValidationRequestsArrayBaseSlot: Fr, ): Promise; - utilityBulkRetrieveLogs( + bulkRetrieveLogs( contractAddress: AztecAddress, logRetrievalRequestsArrayBaseSlot: Fr, logRetrievalResponsesArrayBaseSlot: Fr, ): Promise; - utilityStoreCapsule(contractAddress: AztecAddress, key: Fr, capsule: Fr[]): Promise; - utilityLoadCapsule(contractAddress: AztecAddress, key: Fr): Promise; - utilityDeleteCapsule(contractAddress: AztecAddress, key: Fr): Promise; - utilityCopyCapsule(contractAddress: AztecAddress, srcKey: Fr, dstKey: Fr, numEntries: number): Promise; - utilityAes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise; - utilityGetSharedSecret(address: AztecAddress, ephPk: Point): Promise; + storeCapsule(contractAddress: AztecAddress, key: Fr, capsule: Fr[]): Promise; + loadCapsule(contractAddress: AztecAddress, key: Fr): Promise; + deleteCapsule(contractAddress: AztecAddress, key: Fr): Promise; + copyCapsule(contractAddress: AztecAddress, srcKey: Fr, dstKey: Fr, numEntries: number): Promise; + aes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise; + getSharedSecret(address: AztecAddress, ephPk: Point): Promise; } /** @@ -142,9 +142,9 @@ export interface IUtilityExecutionOracle { export interface IPrivateExecutionOracle { isPrivate: true; - privateStoreInExecutionCache(values: Fr[], hash: Fr): void; - privateLoadFromExecutionCache(hash: Fr): Promise; - privateNotifyCreatedNote( + storeInExecutionCache(values: Fr[], hash: Fr): void; + loadFromExecutionCache(hash: Fr): Promise; + notifyCreatedNote( owner: AztecAddress, storageSlot: Fr, randomness: Fr, @@ -153,33 +153,33 @@ export interface IPrivateExecutionOracle { noteHash: Fr, counter: number, ): void; - privateNotifyNullifiedNote(innerNullifier: Fr, noteHash: Fr, counter: number): Promise; - privateNotifyCreatedNullifier(innerNullifier: Fr): Promise; - privateIsNullifierPending(innerNullifier: Fr, contractAddress: AztecAddress): Promise; - privateNotifyCreatedContractClassLog(log: ContractClassLog, counter: number): void; - privateCallPrivateFunction( + notifyNullifiedNote(innerNullifier: Fr, noteHash: Fr, counter: number): Promise; + notifyCreatedNullifier(innerNullifier: Fr): Promise; + isNullifierPending(innerNullifier: Fr, contractAddress: AztecAddress): Promise; + notifyCreatedContractClassLog(log: ContractClassLog, counter: number): void; + callPrivateFunction( targetContractAddress: AztecAddress, functionSelector: FunctionSelector, argsHash: Fr, sideEffectCounter: number, isStaticCall: boolean, ): Promise<{ endSideEffectCounter: Fr; returnsHash: Fr }>; - privateNotifyEnqueuedPublicFunctionCall( + notifyEnqueuedPublicFunctionCall( targetContractAddress: AztecAddress, calldataHash: Fr, sideEffectCounter: number, isStaticCall: boolean, ): Promise; - privateNotifySetPublicTeardownFunctionCall( + notifySetPublicTeardownFunctionCall( targetContractAddress: AztecAddress, calldataHash: Fr, sideEffectCounter: number, isStaticCall: boolean, ): Promise; - privateNotifySetMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter: number): Promise; - privateIsSideEffectCounterRevertible(sideEffectCounter: number): Promise; - privateGetSenderForTags(): Promise; - privateSetSenderForTags(senderForTags: AztecAddress): Promise; - privateGetNextAppTagAsSender(sender: AztecAddress, recipient: AztecAddress): Promise; - utilityEmitOffchainEffect(data: Fr[]): Promise; + notifySetMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter: number): Promise; + isSideEffectCounterRevertible(sideEffectCounter: number): Promise; + getSenderForTags(): Promise; + setSenderForTags(senderForTags: AztecAddress): Promise; + getNextAppTagAsSender(sender: AztecAddress, recipient: AztecAddress): Promise; + emitOffchainEffect(data: Fr[]): Promise; } diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts index ebfc888b4eab..81ca851245ee 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts @@ -69,12 +69,12 @@ export class Oracle { name => !excludedProps.includes(name as (typeof excludedProps)[number]), ); - // Validate oracle names - these must be prefixed with either "private" or "utility" to indicate their scope + // Validate oracle names - these must be prefixed with either "aztec_prv_" or "aztec_utl_" to indicate their scope // and must correspond to a function on the Oracle class. oracleNames.forEach(name => { - if (!name.startsWith('private') && !name.startsWith('utility')) { + if (!name.startsWith('aztec_prv_') && !name.startsWith('aztec_utl_')) { throw new Error( - `Oracle function "${name}" must be prefixed with either "private" or "utility" to indicate its scope`, + `Oracle function "${name}" must be prefixed with either "aztec_prv_" or "aztec_utl_" to indicate its scope`, ); } @@ -92,41 +92,46 @@ export class Oracle { }, {} as ACIRCallback); } - utilityAssertCompatibleOracleVersion([version]: ACVMField[]) { - this.handlerAsMisc().utilityAssertCompatibleOracleVersion(Fr.fromString(version).toNumber()); + // eslint-disable-next-line camelcase + aztec_utl_assertCompatibleOracleVersion([version]: ACVMField[]) { + this.handlerAsMisc().assertCompatibleOracleVersion(Fr.fromString(version).toNumber()); return Promise.resolve([]); } - utilityGetRandomField(): Promise { - const val = this.handlerAsMisc().utilityGetRandomField(); + // eslint-disable-next-line camelcase + aztec_utl_getRandomField(): Promise { + const val = this.handlerAsMisc().getRandomField(); return Promise.resolve([toACVMField(val)]); } - privateStoreInExecutionCache(values: ACVMField[], [hash]: ACVMField[]): Promise { - this.handlerAsPrivate().privateStoreInExecutionCache(values.map(Fr.fromString), Fr.fromString(hash)); + // eslint-disable-next-line camelcase + aztec_prv_storeInExecutionCache(values: ACVMField[], [hash]: ACVMField[]): Promise { + this.handlerAsPrivate().storeInExecutionCache(values.map(Fr.fromString), Fr.fromString(hash)); return Promise.resolve([]); } - async privateLoadFromExecutionCache([returnsHash]: ACVMField[]): Promise { - const values = await this.handlerAsPrivate().privateLoadFromExecutionCache(Fr.fromString(returnsHash)); + // eslint-disable-next-line camelcase + async aztec_prv_loadFromExecutionCache([returnsHash]: ACVMField[]): Promise { + const values = await this.handlerAsPrivate().loadFromExecutionCache(Fr.fromString(returnsHash)); return [values.map(toACVMField)]; } - utilityGetUtilityContext(): Promise<(ACVMField | ACVMField[])[]> { - const context = this.handlerAsUtility().utilityGetUtilityContext(); + // eslint-disable-next-line camelcase + aztec_utl_getUtilityContext(): Promise<(ACVMField | ACVMField[])[]> { + const context = this.handlerAsUtility().getUtilityContext(); return Promise.resolve(context.toNoirRepresentation()); } - async utilityGetKeyValidationRequest([pkMHash]: ACVMField[]): Promise { - const keyValidationRequest = await this.handlerAsUtility().utilityGetKeyValidationRequest(Fr.fromString(pkMHash)); + // eslint-disable-next-line camelcase + async aztec_utl_getKeyValidationRequest([pkMHash]: ACVMField[]): Promise { + const keyValidationRequest = await this.handlerAsUtility().getKeyValidationRequest(Fr.fromString(pkMHash)); return keyValidationRequest.toFields().map(toACVMField); } - async utilityGetContractInstance([address]: ACVMField[]): Promise { - const instance = await this.handlerAsUtility().utilityGetContractInstance( - AztecAddress.fromField(Fr.fromString(address)), - ); + // eslint-disable-next-line camelcase + async aztec_utl_getContractInstance([address]: ACVMField[]): Promise { + const instance = await this.handlerAsUtility().getContractInstance(AztecAddress.fromField(Fr.fromString(address))); return [ instance.salt, @@ -137,17 +142,15 @@ export class Oracle { ].map(toACVMField); } - async utilityGetNoteHashMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getNoteHashMembershipWitness( [anchorBlockHash]: ACVMField[], [noteHash]: ACVMField[], ): Promise<(ACVMField | ACVMField[])[]> { const parsedAnchorBlockHash = BlockHash.fromString(anchorBlockHash); const parsedNoteHash = Fr.fromString(noteHash); - const witness = await this.handlerAsUtility().utilityGetNoteHashMembershipWitness( - parsedAnchorBlockHash, - parsedNoteHash, - ); + const witness = await this.handlerAsUtility().getNoteHashMembershipWitness(parsedAnchorBlockHash, parsedNoteHash); if (!witness) { throw new Error( `Note hash ${noteHash} not found in the note hash tree at anchor block hash ${parsedAnchorBlockHash.toString()}.`, @@ -156,17 +159,15 @@ export class Oracle { return witness.toNoirRepresentation(); } - async utilityGetBlockHashMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getBlockHashMembershipWitness( [anchorBlockHash]: ACVMField[], [blockHash]: ACVMField[], ): Promise<(ACVMField | ACVMField[])[]> { const parsedAnchorBlockHash = BlockHash.fromString(anchorBlockHash); const parsedBlockHash = BlockHash.fromString(blockHash); - const witness = await this.handlerAsUtility().utilityGetBlockHashMembershipWitness( - parsedAnchorBlockHash, - parsedBlockHash, - ); + const witness = await this.handlerAsUtility().getBlockHashMembershipWitness(parsedAnchorBlockHash, parsedBlockHash); if (!witness) { throw new Error( `Block hash ${parsedBlockHash.toString()} not found in the archive tree at anchor block ${parsedAnchorBlockHash.toString()}.`, @@ -175,17 +176,15 @@ export class Oracle { return witness.toNoirRepresentation(); } - async utilityGetNullifierMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getNullifierMembershipWitness( [blockHash]: ACVMField[], [nullifier]: ACVMField[], // nullifier, we try to find the witness for (to prove inclusion) ): Promise<(ACVMField | ACVMField[])[]> { const parsedBlockHash = BlockHash.fromString(blockHash); const parsedNullifier = Fr.fromString(nullifier); - const witness = await this.handlerAsUtility().utilityGetNullifierMembershipWitness( - parsedBlockHash, - parsedNullifier, - ); + const witness = await this.handlerAsUtility().getNullifierMembershipWitness(parsedBlockHash, parsedNullifier); if (!witness) { throw new Error( `Nullifier witness not found for nullifier ${parsedNullifier} at block hash ${parsedBlockHash.toString()}.`, @@ -194,17 +193,15 @@ export class Oracle { return witness.toNoirRepresentation(); } - async utilityGetLowNullifierMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getLowNullifierMembershipWitness( [blockHash]: ACVMField[], [nullifier]: ACVMField[], // nullifier, we try to find the low nullifier witness for (to prove non-inclusion) ): Promise<(ACVMField | ACVMField[])[]> { const parsedBlockHash = BlockHash.fromString(blockHash); const parsedNullifier = Fr.fromString(nullifier); - const witness = await this.handlerAsUtility().utilityGetLowNullifierMembershipWitness( - parsedBlockHash, - parsedNullifier, - ); + const witness = await this.handlerAsUtility().getLowNullifierMembershipWitness(parsedBlockHash, parsedNullifier); if (!witness) { throw new Error( `Low nullifier witness not found for nullifier ${parsedNullifier} at block hash ${parsedBlockHash.toString()}.`, @@ -213,14 +210,15 @@ export class Oracle { return witness.toNoirRepresentation(); } - async utilityGetPublicDataWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getPublicDataWitness( [blockHash]: ACVMField[], [leafSlot]: ACVMField[], ): Promise<(ACVMField | ACVMField[])[]> { const parsedBlockHash = BlockHash.fromString(blockHash); const parsedLeafSlot = Fr.fromString(leafSlot); - const witness = await this.handlerAsUtility().utilityGetPublicDataWitness(parsedBlockHash, parsedLeafSlot); + const witness = await this.handlerAsUtility().getPublicDataWitness(parsedBlockHash, parsedLeafSlot); if (!witness) { throw new Error( `Public data witness not found for slot ${parsedLeafSlot} at block hash ${parsedBlockHash.toString()}.`, @@ -229,28 +227,31 @@ export class Oracle { return witness.toNoirRepresentation(); } - async utilityGetBlockHeader([blockNumber]: ACVMField[]): Promise { + // eslint-disable-next-line camelcase + async aztec_utl_getBlockHeader([blockNumber]: ACVMField[]): Promise { const parsedBlockNumber = Fr.fromString(blockNumber).toNumber(); - const header = await this.handlerAsUtility().utilityGetBlockHeader(BlockNumber(parsedBlockNumber)); + const header = await this.handlerAsUtility().getBlockHeader(BlockNumber(parsedBlockNumber)); if (!header) { throw new Error(`Block header not found for block ${parsedBlockNumber}.`); } return header.toFields().map(toACVMField); } - async utilityGetAuthWitness([messageHash]: ACVMField[]): Promise { + // eslint-disable-next-line camelcase + async aztec_utl_getAuthWitness([messageHash]: ACVMField[]): Promise { const messageHashField = Fr.fromString(messageHash); - const witness = await this.handlerAsUtility().utilityGetAuthWitness(messageHashField); + const witness = await this.handlerAsUtility().getAuthWitness(messageHashField); if (!witness) { throw new Error(`Unknown auth witness for message hash ${messageHashField}`); } return [witness.map(toACVMField)]; } - async utilityTryGetPublicKeysAndPartialAddress([address]: ACVMField[]): Promise<(ACVMField | ACVMField[])[]> { + // eslint-disable-next-line camelcase + async aztec_utl_tryGetPublicKeysAndPartialAddress([address]: ACVMField[]): Promise<(ACVMField | ACVMField[])[]> { const parsedAddress = AztecAddress.fromField(Fr.fromString(address)); - const result = await this.handlerAsUtility().utilityTryGetPublicKeysAndPartialAddress(parsedAddress); + const result = await this.handlerAsUtility().tryGetPublicKeysAndPartialAddress(parsedAddress); // We are going to return a Noir Option struct to represent the possibility of null values. Options are a struct // with two fields: `some` (a boolean) and `value` (a field array in this case). @@ -263,7 +264,8 @@ export class Oracle { } } - async utilityGetNotes( + // eslint-disable-next-line camelcase + async aztec_utl_getNotes( [ownerSome]: ACVMField[], [ownerValue]: ACVMField[], [storageSlot]: ACVMField[], @@ -285,7 +287,7 @@ export class Oracle { ): Promise<(ACVMField | ACVMField[])[]> { // Parse Option: ownerSome is 0 for None, 1 for Some const owner = Fr.fromString(ownerSome).toNumber() === 1 ? AztecAddress.fromString(ownerValue) : undefined; - const noteDatas = await this.handlerAsUtility().utilityGetNotes( + const noteDatas = await this.handlerAsUtility().getNotes( owner, Fr.fromString(storageSlot), +numSelects, @@ -324,7 +326,8 @@ export class Oracle { return arrayOfArraysToBoundedVecOfArrays(returnDataAsArrayOfACVMFieldArrays, +maxNotes, +packedHintedNoteLength); } - privateNotifyCreatedNote( + // eslint-disable-next-line camelcase + aztec_prv_notifyCreatedNote( [owner]: ACVMField[], [storageSlot]: ACVMField[], [randomness]: ACVMField[], @@ -333,7 +336,7 @@ export class Oracle { [noteHash]: ACVMField[], [counter]: ACVMField[], ): Promise { - this.handlerAsPrivate().privateNotifyCreatedNote( + this.handlerAsPrivate().notifyCreatedNote( AztecAddress.fromString(owner), Fr.fromString(storageSlot), Fr.fromString(randomness), @@ -345,43 +348,47 @@ export class Oracle { return Promise.resolve([]); } - async privateNotifyNullifiedNote( + // eslint-disable-next-line camelcase + async aztec_prv_notifyNullifiedNote( [innerNullifier]: ACVMField[], [noteHash]: ACVMField[], [counter]: ACVMField[], ): Promise { - await this.handlerAsPrivate().privateNotifyNullifiedNote( - Fr.fromString(innerNullifier), - Fr.fromString(noteHash), - +counter, - ); + await this.handlerAsPrivate().notifyNullifiedNote(Fr.fromString(innerNullifier), Fr.fromString(noteHash), +counter); return []; } - async privateNotifyCreatedNullifier([innerNullifier]: ACVMField[]): Promise { - await this.handlerAsPrivate().privateNotifyCreatedNullifier(Fr.fromString(innerNullifier)); + // eslint-disable-next-line camelcase + async aztec_prv_notifyCreatedNullifier([innerNullifier]: ACVMField[]): Promise { + await this.handlerAsPrivate().notifyCreatedNullifier(Fr.fromString(innerNullifier)); return []; } - async privateIsNullifierPending([innerNullifier]: ACVMField[], [contractAddress]: ACVMField[]): Promise { - const isPending = await this.handlerAsPrivate().privateIsNullifierPending( + // eslint-disable-next-line camelcase + async aztec_prv_isNullifierPending( + [innerNullifier]: ACVMField[], + [contractAddress]: ACVMField[], + ): Promise { + const isPending = await this.handlerAsPrivate().isNullifierPending( Fr.fromString(innerNullifier), AztecAddress.fromString(contractAddress), ); return [toACVMField(isPending)]; } - async utilityCheckNullifierExists([innerNullifier]: ACVMField[]): Promise { - const exists = await this.handlerAsUtility().utilityCheckNullifierExists(Fr.fromString(innerNullifier)); + // eslint-disable-next-line camelcase + async aztec_utl_checkNullifierExists([innerNullifier]: ACVMField[]): Promise { + const exists = await this.handlerAsUtility().checkNullifierExists(Fr.fromString(innerNullifier)); return [toACVMField(exists)]; } - async utilityGetL1ToL2MembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getL1ToL2MembershipWitness( [contractAddress]: ACVMField[], [messageHash]: ACVMField[], [secret]: ACVMField[], ): Promise<(ACVMField | ACVMField[])[]> { - const message = await this.handlerAsUtility().utilityGetL1ToL2MembershipWitness( + const message = await this.handlerAsUtility().getL1ToL2MembershipWitness( AztecAddress.fromString(contractAddress), Fr.fromString(messageHash), Fr.fromString(secret), @@ -389,13 +396,14 @@ export class Oracle { return message.toNoirRepresentation(); } - async utilityStorageRead( + // eslint-disable-next-line camelcase + async aztec_utl_storageRead( [blockHash]: ACVMField[], [contractAddress]: ACVMField[], [startStorageSlot]: ACVMField[], [numberOfElements]: ACVMField[], ): Promise { - const values = await this.handlerAsUtility().utilityStorageRead( + const values = await this.handlerAsUtility().storageRead( BlockHash.fromString(blockHash), new AztecAddress(Fr.fromString(contractAddress)), Fr.fromString(startStorageSlot), @@ -404,7 +412,8 @@ export class Oracle { return [values.map(toACVMField)]; } - privateNotifyCreatedContractClassLog( + // eslint-disable-next-line camelcase + aztec_prv_notifyCreatedContractClassLog( [contractAddress]: ACVMField[], message: ACVMField[], [length]: ACVMField[], @@ -413,11 +422,12 @@ export class Oracle { const logFields = new ContractClassLogFields(message.map(Fr.fromString)); const log = new ContractClassLog(new AztecAddress(Fr.fromString(contractAddress)), logFields, +length); - this.handlerAsPrivate().privateNotifyCreatedContractClassLog(log, +counter); + this.handlerAsPrivate().notifyCreatedContractClassLog(log, +counter); return Promise.resolve([]); } - async utilityLog( + // eslint-disable-next-line camelcase + async aztec_utl_log( level: ACVMField[], message: ACVMField[], _ignoredFieldsSize: ACVMField[], @@ -426,20 +436,21 @@ export class Oracle { const levelFr = Fr.fromString(level[0]); const messageStr = message.map(acvmField => String.fromCharCode(Fr.fromString(acvmField).toNumber())).join(''); const fieldsFr = fields.map(Fr.fromString); - await this.handlerAsMisc().utilityLog(levelFr.toNumber(), messageStr, fieldsFr); + await this.handlerAsMisc().log(levelFr.toNumber(), messageStr, fieldsFr); return []; } // This function's name is directly hardcoded in `circuit_recorder.ts`. Don't forget to update it there if you // change the name here. - async privateCallPrivateFunction( + // eslint-disable-next-line camelcase + async aztec_prv_callPrivateFunction( [contractAddress]: ACVMField[], [functionSelector]: ACVMField[], [argsHash]: ACVMField[], [sideEffectCounter]: ACVMField[], [isStaticCall]: ACVMField[], ): Promise { - const { endSideEffectCounter, returnsHash } = await this.handlerAsPrivate().privateCallPrivateFunction( + const { endSideEffectCounter, returnsHash } = await this.handlerAsPrivate().callPrivateFunction( AztecAddress.fromField(Fr.fromString(contractAddress)), FunctionSelector.fromField(Fr.fromString(functionSelector)), Fr.fromString(argsHash), @@ -449,13 +460,14 @@ export class Oracle { return [[endSideEffectCounter, returnsHash].map(toACVMField)]; } - async privateNotifyEnqueuedPublicFunctionCall( + // eslint-disable-next-line camelcase + async aztec_prv_notifyEnqueuedPublicFunctionCall( [contractAddress]: ACVMField[], [calldataHash]: ACVMField[], [sideEffectCounter]: ACVMField[], [isStaticCall]: ACVMField[], ): Promise { - await this.handlerAsPrivate().privateNotifyEnqueuedPublicFunctionCall( + await this.handlerAsPrivate().notifyEnqueuedPublicFunctionCall( AztecAddress.fromString(contractAddress), Fr.fromString(calldataHash), Fr.fromString(sideEffectCounter).toNumber(), @@ -464,13 +476,14 @@ export class Oracle { return []; } - async privateNotifySetPublicTeardownFunctionCall( + // eslint-disable-next-line camelcase + async aztec_prv_notifySetPublicTeardownFunctionCall( [contractAddress]: ACVMField[], [calldataHash]: ACVMField[], [sideEffectCounter]: ACVMField[], [isStaticCall]: ACVMField[], ): Promise { - await this.handlerAsPrivate().privateNotifySetPublicTeardownFunctionCall( + await this.handlerAsPrivate().notifySetPublicTeardownFunctionCall( AztecAddress.fromString(contractAddress), Fr.fromString(calldataHash), Fr.fromString(sideEffectCounter).toNumber(), @@ -479,41 +492,46 @@ export class Oracle { return []; } - async privateNotifySetMinRevertibleSideEffectCounter([minRevertibleSideEffectCounter]: ACVMField[]): Promise< + // eslint-disable-next-line camelcase + async aztec_prv_notifySetMinRevertibleSideEffectCounter([minRevertibleSideEffectCounter]: ACVMField[]): Promise< ACVMField[] > { - await this.handlerAsPrivate().privateNotifySetMinRevertibleSideEffectCounter( + await this.handlerAsPrivate().notifySetMinRevertibleSideEffectCounter( Fr.fromString(minRevertibleSideEffectCounter).toNumber(), ); return Promise.resolve([]); } - async privateIsSideEffectCounterRevertible([sideEffectCounter]: ACVMField[]): Promise { - const isRevertible = await this.handlerAsPrivate().privateIsSideEffectCounterRevertible( + // eslint-disable-next-line camelcase + async aztec_prv_isSideEffectCounterRevertible([sideEffectCounter]: ACVMField[]): Promise { + const isRevertible = await this.handlerAsPrivate().isSideEffectCounterRevertible( Fr.fromString(sideEffectCounter).toNumber(), ); return Promise.resolve([toACVMField(isRevertible)]); } - async privateGetNextAppTagAsSender([sender]: ACVMField[], [recipient]: ACVMField[]): Promise { - const tag = await this.handlerAsPrivate().privateGetNextAppTagAsSender( + // eslint-disable-next-line camelcase + async aztec_prv_getNextAppTagAsSender([sender]: ACVMField[], [recipient]: ACVMField[]): Promise { + const tag = await this.handlerAsPrivate().getNextAppTagAsSender( AztecAddress.fromString(sender), AztecAddress.fromString(recipient), ); return [toACVMField(tag.value)]; } - async utilityFetchTaggedLogs([pendingTaggedLogArrayBaseSlot]: ACVMField[]): Promise { - await this.handlerAsUtility().utilityFetchTaggedLogs(Fr.fromString(pendingTaggedLogArrayBaseSlot)); + // eslint-disable-next-line camelcase + async aztec_utl_fetchTaggedLogs([pendingTaggedLogArrayBaseSlot]: ACVMField[]): Promise { + await this.handlerAsUtility().fetchTaggedLogs(Fr.fromString(pendingTaggedLogArrayBaseSlot)); return []; } - async utilityValidateAndStoreEnqueuedNotesAndEvents( + // eslint-disable-next-line camelcase + async aztec_utl_validateAndStoreEnqueuedNotesAndEvents( [contractAddress]: ACVMField[], [noteValidationRequestsArrayBaseSlot]: ACVMField[], [eventValidationRequestsArrayBaseSlot]: ACVMField[], ): Promise { - await this.handlerAsUtility().utilityValidateAndStoreEnqueuedNotesAndEvents( + await this.handlerAsUtility().validateAndStoreEnqueuedNotesAndEvents( AztecAddress.fromString(contractAddress), Fr.fromString(noteValidationRequestsArrayBaseSlot), Fr.fromString(eventValidationRequestsArrayBaseSlot), @@ -522,12 +540,13 @@ export class Oracle { return []; } - async utilityBulkRetrieveLogs( + // eslint-disable-next-line camelcase + async aztec_utl_bulkRetrieveLogs( [contractAddress]: ACVMField[], [logRetrievalRequestsArrayBaseSlot]: ACVMField[], [logRetrievalResponsesArrayBaseSlot]: ACVMField[], ): Promise { - await this.handlerAsUtility().utilityBulkRetrieveLogs( + await this.handlerAsUtility().bulkRetrieveLogs( AztecAddress.fromString(contractAddress), Fr.fromString(logRetrievalRequestsArrayBaseSlot), Fr.fromString(logRetrievalResponsesArrayBaseSlot), @@ -535,12 +554,13 @@ export class Oracle { return []; } - async utilityStoreCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_storeCapsule( [contractAddress]: ACVMField[], [slot]: ACVMField[], capsule: ACVMField[], ): Promise { - await this.handlerAsUtility().utilityStoreCapsule( + await this.handlerAsUtility().storeCapsule( AztecAddress.fromField(Fr.fromString(contractAddress)), Fr.fromString(slot), capsule.map(Fr.fromString), @@ -548,12 +568,13 @@ export class Oracle { return []; } - async utilityLoadCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_loadCapsule( [contractAddress]: ACVMField[], [slot]: ACVMField[], [tSize]: ACVMField[], ): Promise<(ACVMField | ACVMField[])[]> { - const values = await this.handlerAsUtility().utilityLoadCapsule( + const values = await this.handlerAsUtility().loadCapsule( AztecAddress.fromField(Fr.fromString(contractAddress)), Fr.fromString(slot), ); @@ -569,21 +590,23 @@ export class Oracle { } } - async utilityDeleteCapsule([contractAddress]: ACVMField[], [slot]: ACVMField[]): Promise { - await this.handlerAsUtility().utilityDeleteCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_deleteCapsule([contractAddress]: ACVMField[], [slot]: ACVMField[]): Promise { + await this.handlerAsUtility().deleteCapsule( AztecAddress.fromField(Fr.fromString(contractAddress)), Fr.fromString(slot), ); return []; } - async utilityCopyCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_copyCapsule( [contractAddress]: ACVMField[], [srcSlot]: ACVMField[], [dstSlot]: ACVMField[], [numEntries]: ACVMField[], ): Promise { - await this.handlerAsUtility().utilityCopyCapsule( + await this.handlerAsUtility().copyCapsule( AztecAddress.fromField(Fr.fromString(contractAddress)), Fr.fromString(srcSlot), Fr.fromString(dstSlot), @@ -592,7 +615,8 @@ export class Oracle { return []; } - async utilityAes128Decrypt( + // eslint-disable-next-line camelcase + async aztec_utl_aes128Decrypt( ciphertextBVecStorage: ACVMField[], [ciphertextLength]: ACVMField[], iv: ACVMField[], @@ -602,36 +626,40 @@ export class Oracle { const ivBuffer = fromUintArray(iv, 8); const symKeyBuffer = fromUintArray(symKey, 8); - const plaintext = await this.handlerAsUtility().utilityAes128Decrypt(ciphertext, ivBuffer, symKeyBuffer); + const plaintext = await this.handlerAsUtility().aes128Decrypt(ciphertext, ivBuffer, symKeyBuffer); return bufferToBoundedVec(plaintext, ciphertextBVecStorage.length); } - async utilityGetSharedSecret( + // eslint-disable-next-line camelcase + async aztec_utl_getSharedSecret( [address]: ACVMField[], [ephPKField0]: ACVMField[], [ephPKField1]: ACVMField[], [ephPKField2]: ACVMField[], ): Promise { - const secret = await this.handlerAsUtility().utilityGetSharedSecret( + const secret = await this.handlerAsUtility().getSharedSecret( AztecAddress.fromField(Fr.fromString(address)), Point.fromFields([ephPKField0, ephPKField1, ephPKField2].map(Fr.fromString)), ); return secret.toFields().map(toACVMField); } - async utilityEmitOffchainEffect(data: ACVMField[]) { - await this.handlerAsPrivate().utilityEmitOffchainEffect(data.map(Fr.fromString)); + // eslint-disable-next-line camelcase + async aztec_utl_emitOffchainEffect(data: ACVMField[]) { + await this.handlerAsPrivate().emitOffchainEffect(data.map(Fr.fromString)); return []; } - async privateGetSenderForTags(): Promise { - const sender = await this.handlerAsPrivate().privateGetSenderForTags(); + // eslint-disable-next-line camelcase + async aztec_prv_getSenderForTags(): Promise { + const sender = await this.handlerAsPrivate().getSenderForTags(); // Return [1, address] for Some(address), [0, 0] for None return sender ? [toACVMField(1n), toACVMField(sender)] : [toACVMField(0n), toACVMField(0n)]; } - async privateSetSenderForTags([senderForTags]: ACVMField[]): Promise { - await this.handlerAsPrivate().privateSetSenderForTags(AztecAddress.fromField(Fr.fromString(senderForTags))); + // eslint-disable-next-line camelcase + async aztec_prv_setSenderForTags([senderForTags]: ACVMField[]): Promise { + await this.handlerAsPrivate().setSenderForTags(AztecAddress.fromField(Fr.fromString(senderForTags))); return []; } } diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/oracle_version_is_checked.test.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle_version_is_checked.test.ts index 9a6ce8b9bc36..92ee7252a4b7 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/oracle_version_is_checked.test.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle_version_is_checked.test.ts @@ -41,8 +41,8 @@ describe('Oracle Version Check test suite', () => { let acirSimulator: ContractFunctionSimulator; let contractAddress: AztecAddress; let anchorBlockHeader: BlockHeader; - let utilityAssertCompatibleOracleVersionSpy: jest.SpiedFunction< - typeof UtilityExecutionOracle.prototype.utilityAssertCompatibleOracleVersion + let assertCompatibleOracleVersionSpy: jest.SpiedFunction< + typeof UtilityExecutionOracle.prototype.assertCompatibleOracleVersion >; beforeEach(async () => { @@ -57,11 +57,8 @@ describe('Oracle Version Check test suite', () => { capsuleStore = mock(); privateEventStore = mock(); contractSyncService = mock(); - utilityAssertCompatibleOracleVersionSpy = jest.spyOn( - UtilityExecutionOracle.prototype, - 'utilityAssertCompatibleOracleVersion', - ); - utilityAssertCompatibleOracleVersionSpy.mockClear(); + assertCompatibleOracleVersionSpy = jest.spyOn(UtilityExecutionOracle.prototype, 'assertCompatibleOracleVersion'); + assertCompatibleOracleVersionSpy.mockClear(); aztecNode.getPublicStorageAt.mockResolvedValue(Fr.ZERO); anchorBlockHeader = BlockHeader.random(); @@ -107,7 +104,7 @@ describe('Oracle Version Check test suite', () => { }); describe('private function execution', () => { - it('should call utilityAssertCompatibleOracleVersion oracle when private function is called', async () => { + it('should call assertCompatibleOracleVersion oracle when private function is called', async () => { // Load the artifact of the OracleVersionCheck::private_function contract function and set up the relevant oracle handler const privateFunctionArtifact = { ...OracleVersionCheckContractArtifact.functions.find(f => f.name === 'private_function')!, @@ -149,12 +146,12 @@ describe('Oracle Version Check test suite', () => { scopes: 'ALL_SCOPES', }); - expect(utilityAssertCompatibleOracleVersionSpy).toHaveBeenCalledTimes(1); + expect(assertCompatibleOracleVersionSpy).toHaveBeenCalledTimes(1); }, 30_000); }); describe('utility function execution', () => { - it('should call utilityAssertCompatibleOracleVersion oracle when utility function is called', async () => { + it('should call assertCompatibleOracleVersion oracle when utility function is called', async () => { // Load the artifact of the OracleVersionCheck::utility_function contract function and set up the relevant oracle // handler const utilityFunctionArtifact = { @@ -178,7 +175,7 @@ describe('Oracle Version Check test suite', () => { // Call the utility function await acirSimulator.runUtility(execRequest, [], anchorBlockHeader, [], 'test'); - expect(utilityAssertCompatibleOracleVersionSpy).toHaveBeenCalledTimes(1); + expect(assertCompatibleOracleVersionSpy).toHaveBeenCalledTimes(1); }, 30_000); }); }); diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts index e25c99930f3f..5dbbd6509a9b 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts @@ -76,7 +76,7 @@ export async function executePrivateFunction( const contractClassLogs = privateExecutionOracle.getContractClassLogs(); - const rawReturnValues = await privateExecutionOracle.privateLoadFromExecutionCache(publicInputs.returnsHash); + const rawReturnValues = await privateExecutionOracle.loadFromExecutionCache(publicInputs.returnsHash); const newNotes = privateExecutionOracle.getNewNotes(); const noteHashNullifierCounterMap = privateExecutionOracle.getNoteHashNullifierCounterMap(); diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts index c6d33cc7244e..ea9a52d160bf 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts @@ -189,7 +189,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * The value persists through nested calls, meaning all calls down the stack will use the same * 'senderForTags' value (unless it is replaced). */ - public privateGetSenderForTags(): Promise { + public getSenderForTags(): Promise { return Promise.resolve(this.senderForTags); } @@ -204,7 +204,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * through nested calls, meaning all calls down the stack will use the same 'senderForTags' * value (unless it is replaced by another call to this setter). */ - public privateSetSenderForTags(senderForTags: AztecAddress): Promise { + public setSenderForTags(senderForTags: AztecAddress): Promise { this.senderForTags = senderForTags; return Promise.resolve(); } @@ -215,7 +215,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param recipient - The address receiving the log * @returns An app tag to be used in a log. */ - public async privateGetNextAppTagAsSender(sender: AztecAddress, recipient: AztecAddress): Promise { + public async getNextAppTagAsSender(sender: AztecAddress, recipient: AztecAddress): Promise { const extendedSecret = await this.#calculateExtendedDirectionalAppTaggingSecret( this.contractAddress, sender, @@ -223,7 +223,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP ); const index = await this.#getIndexToUseForSecret(extendedSecret); - this.log.debug( + this.logger.debug( `Incrementing tagging index for sender: ${sender}, recipient: ${recipient}, contract: ${this.contractAddress} to ${index}`, ); this.taggingIndexCache.setLastUsedIndex(extendedSecret, index); @@ -277,7 +277,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param values - Values to store. * @returns The hash of the values. */ - public privateStoreInExecutionCache(values: Fr[], hash: Fr) { + public storeInExecutionCache(values: Fr[], hash: Fr) { return this.executionCache.store(values, hash); } @@ -286,7 +286,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param hash - Hash of the values. * @returns The values. */ - public privateLoadFromExecutionCache(hash: Fr): Promise { + public loadFromExecutionCache(hash: Fr): Promise { const preimage = this.executionCache.getPreimage(hash); if (!preimage) { throw new Error(`Preimage for hash ${hash.toString()} not found in cache`); @@ -294,12 +294,12 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP return Promise.resolve(preimage); } - override async utilityCheckNullifierExists(innerNullifier: Fr): Promise { + override async checkNullifierExists(innerNullifier: Fr): Promise { // This oracle must be overridden because while utility execution can only meaningfully check if a nullifier exists // in the synched block, during private execution there's also the possibility of it being pending, i.e. created // in the current transaction. - this.log.debug(`Checking existence of inner nullifier ${innerNullifier}`, { + this.logger.debug(`Checking existence of inner nullifier ${innerNullifier}`, { contractAddress: this.contractAddress, }); @@ -307,7 +307,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP return ( this.noteCache.getNullifiers(this.contractAddress).has(nullifier) || - (await super.utilityCheckNullifierExists(innerNullifier)) + (await super.checkNullifierExists(innerNullifier)) ); } @@ -332,7 +332,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param status - The status of notes to fetch. * @returns Array of note data. */ - public override async utilityGetNotes( + public override async getNotes( owner: AztecAddress | undefined, storageSlot: Fr, numSelects: number, @@ -378,7 +378,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP offset, }); - this.log.debug( + this.logger.debug( `Returning ${notes.length} notes for ${this.callContext.contractAddress} at ${storageSlot}: ${notes .map(n => `${n.noteNonce.toString()}:[${n.note.items.map(i => i.toString()).join(',')}]`) .join(', ')}`, @@ -398,7 +398,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param noteHash - A hash of the new note. * @returns */ - public privateNotifyCreatedNote( + public notifyCreatedNote( owner: AztecAddress, storageSlot: Fr, randomness: Fr, @@ -407,7 +407,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP noteHash: Fr, counter: number, ) { - this.log.debug(`Notified of new note with inner hash ${noteHash}`, { + this.logger.debug(`Notified of new note with inner hash ${noteHash}`, { contractAddress: this.callContext.contractAddress, storageSlot, randomness, @@ -439,7 +439,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param innerNullifier - The pending nullifier to add in the list (not yet siloed by contract address). * @param noteHash - A hash of the new note. */ - public async privateNotifyNullifiedNote(innerNullifier: Fr, noteHash: Fr, counter: number) { + public async notifyNullifiedNote(innerNullifier: Fr, noteHash: Fr, counter: number) { const nullifiedNoteHashCounter = await this.noteCache.nullifyNote( this.callContext.contractAddress, innerNullifier, @@ -456,19 +456,19 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param innerNullifier - The pending nullifier to add in the list (not yet siloed by contract address). * @param noteHash - A hash of the new note. */ - public privateNotifyCreatedNullifier(innerNullifier: Fr) { - this.log.debug(`Notified of new inner nullifier ${innerNullifier}`, { contractAddress: this.contractAddress }); + public notifyCreatedNullifier(innerNullifier: Fr) { + this.logger.debug(`Notified of new inner nullifier ${innerNullifier}`, { contractAddress: this.contractAddress }); return this.noteCache.nullifierCreated(this.callContext.contractAddress, innerNullifier); } /** - * Check if a nullifier has been emitted in the same transaction, i.e. if privateNotifyCreatedNullifier has been + * Check if a nullifier has been emitted in the same transaction, i.e. if notifyCreatedNullifier has been * called for this inner nullifier from the contract with the specified address. * @param innerNullifier - The inner nullifier to check. * @param contractAddress - Address of the contract that emitted the nullifier. * @returns A boolean indicating whether the nullifier is pending or not. */ - public async privateIsNullifierPending(innerNullifier: Fr, contractAddress: AztecAddress): Promise { + public async isNullifierPending(innerNullifier: Fr, contractAddress: AztecAddress): Promise { const siloedNullifier = await siloNullifier(contractAddress, innerNullifier); const isNullifierPending = this.noteCache.getNullifiers(contractAddress).has(siloedNullifier.toBigInt()); return Promise.resolve(isNullifierPending); @@ -481,10 +481,10 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param log - The contract class log to be emitted. * @param counter - The contract class log's counter. */ - public privateNotifyCreatedContractClassLog(log: ContractClassLog, counter: number) { + public notifyCreatedContractClassLog(log: ContractClassLog, counter: number) { this.contractClassLogs.push(new CountedContractClassLog(log, counter)); const text = log.toBuffer().toString('hex'); - this.log.verbose( + this.logger.verbose( `Emitted log from ContractClassRegistry: "${text.length > 100 ? text.slice(0, 100) + '...' : text}"`, ); } @@ -510,7 +510,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param isStaticCall - Whether the call is a static call. * @returns The execution result. */ - async privateCallPrivateFunction( + async callPrivateFunction( targetContractAddress: AztecAddress, functionSelector: FunctionSelector, argsHash: Fr, @@ -524,7 +524,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP } const simulatorSetupTimer = new Timer(); - this.log.debug( + this.logger.debug( `Calling private function ${targetContractAddress}:${functionSelector} from ${this.callContext.contractAddress}`, ); @@ -573,7 +573,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP jobId: this.jobId, totalPublicCalldataCount: this.totalPublicCalldataCount, sideEffectCounter, - log: this.log, + log: this.logger, scopes: this.scopes, senderForTags: this.senderForTags, simulator: this.simulator!, @@ -627,7 +627,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param sideEffectCounter - The side effect counter at the start of the call. * @param isStaticCall - Whether the call is a static call. */ - public privateNotifyEnqueuedPublicFunctionCall( + public notifyEnqueuedPublicFunctionCall( _targetContractAddress: AztecAddress, calldataHash: Fr, _sideEffectCounter: number, @@ -644,7 +644,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP * @param sideEffectCounter - The side effect counter at the start of the call. * @param isStaticCall - Whether the call is a static call. */ - public privateNotifySetPublicTeardownFunctionCall( + public notifySetPublicTeardownFunctionCall( _targetContractAddress: AztecAddress, calldataHash: Fr, _sideEffectCounter: number, @@ -654,11 +654,11 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP return Promise.resolve(); } - public privateNotifySetMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter: number): Promise { + public notifySetMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter: number): Promise { return this.noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter); } - public privateIsSideEffectCounterRevertible(sideEffectCounter: number): Promise { + public isSideEffectCounterRevertible(sideEffectCounter: number): Promise { return Promise.resolve(this.noteCache.isSideEffectCounterRevertible(sideEffectCounter)); } @@ -686,7 +686,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP return this.contractStore.getDebugFunctionName(this.contractAddress, this.callContext.functionSelector); } - public utilityEmitOffchainEffect(data: Fr[]): Promise { + public emitOffchainEffect(data: Fr[]): Promise { this.offchainEffects.push({ data }); return Promise.resolve(); } diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts index fd6cb7ef4a2a..586b16df8ee0 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts @@ -226,7 +226,7 @@ describe('Utility Execution test suite', () => { describe('Respects synced block number', () => { it('throws when getting block for future block number', async () => { - await expect(utilityExecutionOracle.utilityGetBlockHeader(BlockNumber(syncedBlockNumber + 1))).rejects.toThrow( + await expect(utilityExecutionOracle.getBlockHeader(BlockNumber(syncedBlockNumber + 1))).rejects.toThrow( `Block number ${syncedBlockNumber + 1} is higher than current block ${syncedBlockNumber}`, ); }); diff --git a/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts index f957d44326a8..c52e4de97c9f 100644 --- a/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts @@ -86,7 +86,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra protected readonly capsuleStore: CapsuleStore; protected readonly privateEventStore: PrivateEventStore; protected readonly jobId: string; - protected log: ReturnType; + protected logger: ReturnType; protected readonly scopes: AccessScopes; constructor(args: UtilityExecutionOracleArgs) { @@ -104,21 +104,21 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra this.capsuleStore = args.capsuleStore; this.privateEventStore = args.privateEventStore; this.jobId = args.jobId; - this.log = args.log ?? createLogger('simulator:client_view_context'); + this.logger = args.log ?? createLogger('simulator:client_view_context'); this.scopes = args.scopes; } - public utilityAssertCompatibleOracleVersion(version: number): void { + public assertCompatibleOracleVersion(version: number): void { if (version !== ORACLE_VERSION) { throw new Error(`Incompatible oracle version. Expected version ${ORACLE_VERSION}, got ${version}.`); } } - public utilityGetRandomField(): Fr { + public getRandomField(): Fr { return Fr.random(); } - public utilityGetUtilityContext(): UtilityContext { + public getUtilityContext(): UtilityContext { return new UtilityContext(this.anchorBlockHeader, this.contractAddress); } @@ -129,7 +129,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @throws If the keys are not registered in the key store. * @throws If scopes are defined and the account is not in the scopes. */ - public async utilityGetKeyValidationRequest(pkMHash: Fr): Promise { + public async getKeyValidationRequest(pkMHash: Fr): Promise { // If scopes are defined, check that the key belongs to an account in the scopes. if (this.scopes !== 'ALL_SCOPES' && this.scopes.length > 0) { let hasAccess = false; @@ -152,7 +152,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param noteHash - The note hash to find in the note hash tree. * @returns The membership witness containing the leaf index and sibling path */ - public utilityGetNoteHashMembershipWitness( + public getNoteHashMembershipWitness( anchorBlockHash: BlockHash, noteHash: Fr, ): Promise | undefined> { @@ -170,7 +170,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param blockHash - The block hash to find in the archive tree. * @returns The membership witness containing the leaf index and sibling path */ - public utilityGetBlockHashMembershipWitness( + public getBlockHashMembershipWitness( anchorBlockHash: BlockHash, blockHash: BlockHash, ): Promise | undefined> { @@ -183,7 +183,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param nullifier - Nullifier we try to find witness for. * @returns The nullifier membership witness (if found). */ - public utilityGetNullifierMembershipWitness( + public getNullifierMembershipWitness( blockHash: BlockHash, nullifier: Fr, ): Promise { @@ -199,7 +199,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier * we are trying to prove non-inclusion for. */ - public utilityGetLowNullifierMembershipWitness( + public getLowNullifierMembershipWitness( blockHash: BlockHash, nullifier: Fr, ): Promise { @@ -212,7 +212,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param leafSlot - The slot of the public data tree to get the witness for. * @returns - The witness */ - public utilityGetPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise { + public getPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise { return this.aztecNode.getPublicDataWitness(blockHash, leafSlot); } @@ -221,7 +221,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param blockNumber - The number of a block of which to get the block header. * @returns Block extracted from a block with block number `blockNumber`. */ - public async utilityGetBlockHeader(blockNumber: BlockNumber): Promise { + public async getBlockHeader(blockNumber: BlockNumber): Promise { const anchorBlockNumber = this.anchorBlockHeader.getBlockNumber(); if (blockNumber > anchorBlockNumber) { throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`); @@ -236,7 +236,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param account - The account address. * @returns A complete address associated with the input address, or `undefined` if not registered. */ - public utilityTryGetPublicKeysAndPartialAddress(account: AztecAddress): Promise { + public tryGetPublicKeysAndPartialAddress(account: AztecAddress): Promise { return this.addressStore.getCompleteAddress(account); } @@ -256,11 +256,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param address - Address. * @returns A contract instance. */ - public utilityGetContractInstance(address: AztecAddress): Promise { - return this.getContractInstance(address); - } - - protected async getContractInstance(address: AztecAddress): Promise { + public async getContractInstance(address: AztecAddress): Promise { const instance = await this.contractStore.getContractInstance(address); if (!instance) { throw new Error(`No contract instance found for address ${address.toString()}`); @@ -274,7 +270,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param messageHash - Hash of the message to authenticate. * @returns Authentication witness for the requested message hash. */ - public utilityGetAuthWitness(messageHash: Fr): Promise { + public getAuthWitness(messageHash: Fr): Promise { return Promise.resolve(this.authWitnesses.find(w => w.requestHash.equals(messageHash))?.witness); } @@ -300,7 +296,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param status - The status of notes to fetch. * @returns Array of note data. */ - public async utilityGetNotes( + public async getNotes( owner: AztecAddress | undefined, storageSlot: Fr, numSelects: number, @@ -340,7 +336,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param innerNullifier - The inner nullifier. * @returns A boolean indicating whether the nullifier exists in the tree or not. */ - public async utilityCheckNullifierExists(innerNullifier: Fr) { + public async checkNullifierExists(innerNullifier: Fr) { const [nullifier, anchorBlockHash] = await Promise.all([ siloNullifier(this.contractAddress, innerNullifier!), this.anchorBlockHeader.hash(), @@ -359,7 +355,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @dev Contract address and secret are only used to compute the nullifier to get non-nullified messages * @returns The l1 to l2 membership witness (index of message in the tree and sibling path). */ - public async utilityGetL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) { + public async getL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) { const [messageIndex, siblingPath] = await getNonNullifiedL1ToL2MessageWitness( this.aztecNode, contractAddress, @@ -377,7 +373,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param startStorageSlot - The starting storage slot. * @param numberOfElements - Number of elements to read from the starting storage slot. */ - public async utilityStorageRead( + public async storageRead( blockHash: BlockHash, contractAddress: AztecAddress, startStorageSlot: Fr, @@ -391,7 +387,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)), ); - this.log.debug( + this.logger.debug( `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`, ); @@ -414,7 +410,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra return this.contractLogger; } - public async utilityLog(level: number, message: string, fields: Fr[]): Promise { + public async log(level: number, message: string, fields: Fr[]): Promise { if (!LogLevels[level]) { throw new Error(`Invalid log level: ${level}`); } @@ -422,7 +418,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra logContractMessage(logger, LogLevels[level], message, fields); } - public async utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) { + public async fetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) { const logService = new LogService( this.aztecNode, this.anchorBlockHeader, @@ -432,7 +428,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra this.senderAddressBookStore, this.addressStore, this.jobId, - this.log.getBindings(), + this.logger.getBindings(), ); await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, this.scopes); @@ -448,7 +444,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param noteValidationRequestsArrayBaseSlot - The base slot of capsule array containing note validation requests. * @param eventValidationRequestsArrayBaseSlot - The base slot of capsule array containing event validation requests. */ - public async utilityValidateAndStoreEnqueuedNotesAndEvents( + public async validateAndStoreEnqueuedNotesAndEvents( contractAddress: AztecAddress, noteValidationRequestsArrayBaseSlot: Fr, eventValidationRequestsArrayBaseSlot: Fr, @@ -504,7 +500,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra await this.capsuleStore.setCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, [], this.jobId); } - public async utilityBulkRetrieveLogs( + public async bulkRetrieveLogs( contractAddress: AztecAddress, logRetrievalRequestsArrayBaseSlot: Fr, logRetrievalResponsesArrayBaseSlot: Fr, @@ -529,7 +525,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra this.senderAddressBookStore, this.addressStore, this.jobId, - this.log.getBindings(), + this.logger.getBindings(), ); const maybeLogRetrievalResponses = await logService.bulkRetrieveLogs(logRetrievalRequests); @@ -546,7 +542,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra ); } - public utilityStoreCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise { + public storeCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise { if (!contractAddress.equals(this.contractAddress)) { // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`); @@ -555,7 +551,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra return Promise.resolve(); } - public async utilityLoadCapsule(contractAddress: AztecAddress, slot: Fr): Promise { + public async loadCapsule(contractAddress: AztecAddress, slot: Fr): Promise { if (!contractAddress.equals(this.contractAddress)) { // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`); @@ -567,7 +563,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra ); } - public utilityDeleteCapsule(contractAddress: AztecAddress, slot: Fr): Promise { + public deleteCapsule(contractAddress: AztecAddress, slot: Fr): Promise { if (!contractAddress.equals(this.contractAddress)) { // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`); @@ -576,12 +572,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra return Promise.resolve(); } - public utilityCopyCapsule( - contractAddress: AztecAddress, - srcSlot: Fr, - dstSlot: Fr, - numEntries: number, - ): Promise { + public copyCapsule(contractAddress: AztecAddress, srcSlot: Fr, dstSlot: Fr, numEntries: number): Promise { if (!contractAddress.equals(this.contractAddress)) { // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`); @@ -590,7 +581,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra } // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption. - public utilityAes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise { + public aes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise { const aes128 = new Aes128(); return aes128.decryptBufferCBC(ciphertext, iv, symKey); } @@ -601,11 +592,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra * @param ephPk - The ephemeral public key to get the secret for. * @returns The secret for the given address. */ - public utilityGetSharedSecret(address: AztecAddress, ephPk: Point): Promise { - return this.getSharedSecret(address, ephPk); - } - - protected async getSharedSecret(address: AztecAddress, ephPk: Point): Promise { + public async getSharedSecret(address: AztecAddress, ephPk: Point): Promise { // TODO(#12656): return an app-siloed secret const recipientCompleteAddress = await this.getCompleteAddressOrFail(address); const ivskM = await this.keyStore.getMasterSecretKey( diff --git a/yarn-project/pxe/src/oracle_version.ts b/yarn-project/pxe/src/oracle_version.ts index 5f6dd5abc335..898b3e631450 100644 --- a/yarn-project/pxe/src/oracle_version.ts +++ b/yarn-project/pxe/src/oracle_version.ts @@ -2,11 +2,11 @@ /// to version the oracle interface to ensure that developers get a reasonable error message if they use incompatible /// versions of Aztec.nr and PXE. The Noir counterpart is in `noir-projects/aztec-nr/aztec/src/oracle/version.nr`. /// -/// @dev Whenever a contract function or Noir test is run, the `utilityAssertCompatibleOracleVersion` oracle is called +/// @dev Whenever a contract function or Noir test is run, the `aztec_utl_assertCompatibleOracleVersion` oracle is called /// and if the oracle version is incompatible an error is thrown. -export const ORACLE_VERSION = 12; +export const ORACLE_VERSION = 13; /// This hash is computed as by hashing the Oracle interface and it is used to detect when the Oracle interface changes, /// which in turn implies that you need to update the ORACLE_VERSION constant in this file and in /// `noir-projects/aztec-nr/aztec/src/oracle/version.nr`. -export const ORACLE_INTERFACE_HASH = '666a8a7fc697f72b29dbf0ae7464db269cf5afa019acac8861f814543147dbb4'; +export const ORACLE_INTERFACE_HASH = '9fb918682455c164ce8dd3acb71c751e2b9b2fc48913604069c9ea885fa378ca'; diff --git a/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts b/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts index 871ae7f0bf4d..e30993fbbaf5 100644 --- a/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts +++ b/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts @@ -161,11 +161,11 @@ export class CircuitRecorder { throw new Error(`Oracle method ${name} not found when setting up recording callback`); } - const isExternalCall = (name as keyof ACIRCallback) === 'privateCallPrivateFunction'; + const isExternalCall = (name as keyof ACIRCallback) === 'aztec_prv_callPrivateFunction'; recordingCallback[name as keyof ACIRCallback] = (...args: ForeignCallInput[]): ReturnType => { const timer = new Timer(); - // If we're entering another circuit via `privateCallPrivateFunction`, we increase the stack depth and set the + // If we're entering another circuit via `aztec_prv_callPrivateFunction`, we increase the stack depth and set the // newCircuit variable to ensure we are creating a new recording object. if (isExternalCall) { this.stackDepth++; diff --git a/yarn-project/txe/src/index.ts b/yarn-project/txe/src/index.ts index 76c25b5a4751..182058ddf8ac 100644 --- a/yarn-project/txe/src/index.ts +++ b/yarn-project/txe/src/index.ts @@ -247,11 +247,11 @@ class TXEDispatcher { } switch (functionName) { - case 'txeDeploy': { + case 'aztec_txe_deploy': { await this.#processDeployInputs(callData); break; } - case 'txeAddAccount': { + case 'aztec_txe_addAccount': { await this.#processAddAccountInputs(callData); break; } diff --git a/yarn-project/txe/src/oracle/interfaces.ts b/yarn-project/txe/src/oracle/interfaces.ts index 98dd9f4c0086..c70fc0dbc4dd 100644 --- a/yarn-project/txe/src/oracle/interfaces.ts +++ b/yarn-project/txe/src/oracle/interfaces.ts @@ -24,18 +24,18 @@ import type { UInt64 } from '@aztec/stdlib/types'; export interface IAvmExecutionOracle { isAvm: true; - avmOpcodeAddress(): Promise; - avmOpcodeSender(): Promise; - avmOpcodeBlockNumber(): Promise; - avmOpcodeTimestamp(): Promise; - avmOpcodeIsStaticCall(): Promise; - avmOpcodeChainId(): Promise; - avmOpcodeVersion(): Promise; - avmOpcodeEmitNullifier(nullifier: Fr): Promise; - avmOpcodeEmitNoteHash(noteHash: Fr): Promise; - avmOpcodeNullifierExists(siloedNullifier: Fr): Promise; - avmOpcodeStorageWrite(slot: Fr, value: Fr): Promise; - avmOpcodeStorageRead(slot: Fr, contractAddress: AztecAddress): Promise; + address(): Promise; + sender(): Promise; + blockNumber(): Promise; + timestamp(): Promise; + isStaticCall(): Promise; + chainId(): Promise; + version(): Promise; + emitNullifier(nullifier: Fr): Promise; + emitNoteHash(noteHash: Fr): Promise; + nullifierExists(siloedNullifier: Fr): Promise; + storageWrite(slot: Fr, value: Fr): Promise; + storageRead(slot: Fr, contractAddress: AztecAddress): Promise; } /** @@ -44,27 +44,23 @@ export interface IAvmExecutionOracle { export interface ITxeExecutionOracle { isTxe: true; - txeGetDefaultAddress(): AztecAddress; - txeGetNextBlockNumber(): Promise; - txeGetNextBlockTimestamp(): Promise; - txeAdvanceBlocksBy(blocks: number): Promise; - txeAdvanceTimestampBy(duration: UInt64): void; - txeDeploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: Fr): Promise; - txeCreateAccount(secret: Fr): Promise; - txeAddAccount( - artifact: ContractArtifact, - instance: ContractInstanceWithAddress, - secret: Fr, - ): Promise; - txeAddAuthWitness(address: AztecAddress, messageHash: Fr): Promise; - txeGetLastBlockTimestamp(): Promise; - txeGetLastTxEffects(): Promise<{ + getDefaultAddress(): AztecAddress; + getNextBlockNumber(): Promise; + getNextBlockTimestamp(): Promise; + advanceBlocksBy(blocks: number): Promise; + advanceTimestampBy(duration: UInt64): void; + deploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: Fr): Promise; + createAccount(secret: Fr): Promise; + addAccount(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr): Promise; + addAuthWitness(address: AztecAddress, messageHash: Fr): Promise; + getLastBlockTimestamp(): Promise; + getLastTxEffects(): Promise<{ txHash: TxHash; noteHashes: Fr[]; nullifiers: Fr[]; }>; - txeGetPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise; - txePrivateCallNewFlow( + getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise; + privateCallNewFlow( from: AztecAddress, targetContractAddress: AztecAddress, functionSelector: FunctionSelector, @@ -73,13 +69,13 @@ export interface ITxeExecutionOracle { isStaticCall: boolean, jobId: string, ): Promise; - txeExecuteUtilityFunction( + executeUtilityFunction( targetContractAddress: AztecAddress, functionSelector: FunctionSelector, args: Fr[], jobId: string, ): Promise; - txePublicCallNewFlow( + publicCallNewFlow( from: AztecAddress, targetContractAddress: AztecAddress, calldata: Fr[], diff --git a/yarn-project/txe/src/oracle/txe_oracle_public_context.ts b/yarn-project/txe/src/oracle/txe_oracle_public_context.ts index fb9653b91d5f..3631cc067d69 100644 --- a/yarn-project/txe/src/oracle/txe_oracle_public_context.ts +++ b/yarn-project/txe/src/oracle/txe_oracle_public_context.ts @@ -39,46 +39,46 @@ export class TXEOraclePublicContext implements IAvmExecutionOracle { }); } - avmOpcodeAddress(): Promise { + address(): Promise { return Promise.resolve(this.contractAddress); } - avmOpcodeSender(): Promise { + sender(): Promise { return Promise.resolve(AztecAddress.ZERO); // todo: change? } - avmOpcodeBlockNumber(): Promise { + blockNumber(): Promise { return Promise.resolve(this.globalVariables.blockNumber); } - avmOpcodeTimestamp(): Promise { + timestamp(): Promise { return Promise.resolve(this.globalVariables.timestamp); } - avmOpcodeIsStaticCall(): Promise { + isStaticCall(): Promise { return Promise.resolve(false); } - avmOpcodeChainId(): Promise { + chainId(): Promise { return Promise.resolve(this.globalVariables.chainId); } - avmOpcodeVersion(): Promise { + version(): Promise { return Promise.resolve(this.globalVariables.version); } - async avmOpcodeEmitNullifier(nullifier: Fr) { + async emitNullifier(nullifier: Fr) { const siloedNullifier = await siloNullifier(this.contractAddress, nullifier); this.transientSiloedNullifiers.push(siloedNullifier); } - async avmOpcodeEmitNoteHash(noteHash: Fr) { + async emitNoteHash(noteHash: Fr) { const siloedNoteHash = await siloNoteHash(this.contractAddress, noteHash); // TODO: make the note hash unique - they are only siloed right now this.transientUniqueNoteHashes.push(siloedNoteHash); } - async avmOpcodeNullifierExists(siloedNullifier: Fr): Promise { + async nullifierExists(siloedNullifier: Fr): Promise { const treeIndex = ( await this.forkedWorldTrees.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, [siloedNullifier.toBuffer()]) )[0]; @@ -87,7 +87,7 @@ export class TXEOraclePublicContext implements IAvmExecutionOracle { return treeIndex !== undefined || transientIndex !== undefined; } - async avmOpcodeStorageWrite(slot: Fr, value: Fr) { + async storageWrite(slot: Fr, value: Fr) { this.logger.debug('AVM storage write', { slot, value }); const dataWrite = new PublicDataWrite(await computePublicDataTreeLeafSlot(this.contractAddress, slot), value); @@ -99,7 +99,7 @@ export class TXEOraclePublicContext implements IAvmExecutionOracle { ]); } - async avmOpcodeStorageRead(slot: Fr, contractAddress: AztecAddress): Promise { + async storageRead(slot: Fr, contractAddress: AztecAddress): Promise { const leafSlot = await computePublicDataTreeLeafSlot(contractAddress, slot); const lowLeafResult = await this.forkedWorldTrees.getPreviousValueIndex( diff --git a/yarn-project/txe/src/oracle/txe_oracle_top_level_context.ts b/yarn-project/txe/src/oracle/txe_oracle_top_level_context.ts index 45be8bbcf95c..1e604f94f1cd 100644 --- a/yarn-project/txe/src/oracle/txe_oracle_top_level_context.ts +++ b/yarn-project/txe/src/oracle/txe_oracle_top_level_context.ts @@ -116,7 +116,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl this.logger.debug('Entering Top Level Context'); } - utilityAssertCompatibleOracleVersion(version: number): void { + assertCompatibleOracleVersion(version: number): void { if (version !== ORACLE_VERSION) { throw new Error( `Incompatible oracle version. TXE is using version '${ORACLE_VERSION}', but got a request for '${version}'.`, @@ -126,12 +126,12 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl // This is typically only invoked in private contexts, but it is convenient to also have it in top-level for testing // setup. - utilityGetRandomField(): Fr { + getRandomField(): Fr { return Fr.random(); } // We instruct users to debug contracts via this oracle, so it makes sense that they'd expect it to also work in tests - utilityLog(level: number, message: string, fields: Fr[]): Promise { + log(level: number, message: string, fields: Fr[]): Promise { if (!LogLevels[level]) { throw new Error(`Invalid log level: ${level}`); } @@ -141,23 +141,23 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl return Promise.resolve(); } - txeGetDefaultAddress(): AztecAddress { + getDefaultAddress(): AztecAddress { return DEFAULT_ADDRESS; } - async txeGetNextBlockNumber(): Promise { + async getNextBlockNumber(): Promise { return BlockNumber((await this.getLastBlockNumber()) + 1); } - txeGetNextBlockTimestamp(): Promise { + getNextBlockTimestamp(): Promise { return Promise.resolve(this.nextBlockTimestamp); } - async txeGetLastBlockTimestamp() { + async getLastBlockTimestamp() { return (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.timestamp; } - async txeGetLastTxEffects() { + async getLastTxEffects() { const latestBlockNumber = await this.stateMachine.archiver.getBlockNumber(); const block = await this.stateMachine.archiver.getBlock(latestBlockNumber); @@ -173,7 +173,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl async syncContractNonOracleMethod(contractAddress: AztecAddress, scope: AztecAddress, jobId: string) { if (contractAddress.equals(DEFAULT_ADDRESS)) { - this.logger.debug(`Skipping sync in txeGetPrivateEvents because the events correspond to the default address.`); + this.logger.debug(`Skipping sync in getPrivateEvents because the events correspond to the default address.`); return; } @@ -190,7 +190,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl ); } - async txeGetPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress) { + async getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress) { return ( await this.privateEventStore.getPrivateEvents(selector, { contractAddress, @@ -201,7 +201,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl ).map(e => e.packedEvent); } - async txeAdvanceBlocksBy(blocks: number) { + async advanceBlocksBy(blocks: number) { this.logger.debug(`time traveling ${blocks} blocks`); for (let i = 0; i < blocks; i++) { @@ -209,12 +209,12 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl } } - txeAdvanceTimestampBy(duration: UInt64) { + advanceTimestampBy(duration: UInt64) { this.logger.debug(`time traveling ${duration} seconds`); this.nextBlockTimestamp += duration; } - async txeDeploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr) { + async deploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr) { // Emit deployment nullifier await this.mineBlock({ nullifiers: [ @@ -226,7 +226,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl }); if (!secret.equals(Fr.ZERO)) { - await this.txeAddAccount(artifact, instance, secret); + await this.addAccount(artifact, instance, secret); } else { await this.contractStore.addContractInstance(instance); await this.contractStore.addContractArtifact(artifact); @@ -234,7 +234,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl } } - async txeAddAccount(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr) { + async addAccount(artifact: ContractArtifact, instance: ContractInstanceWithAddress, secret: Fr) { const partialAddress = await computePartialAddress(instance); this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`); @@ -249,7 +249,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl return completeAddress; } - async txeCreateAccount(secret: Fr) { + async createAccount(secret: Fr) { // This is a foot gun ! const completeAddress = await this.keyStore.addAccount(secret, secret); await this.accountStore.setAccount(completeAddress.address, completeAddress); @@ -259,7 +259,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl return completeAddress; } - async txeAddAuthWitness(address: AztecAddress, messageHash: Fr) { + async addAuthWitness(address: AztecAddress, messageHash: Fr) { const account = await this.accountStore.getAccount(address); const privateKey = await this.keyStore.getMasterSecretKey(account.publicKeys.masterIncomingViewingPublicKey); @@ -272,7 +272,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl } async mineBlock(options: { nullifiers?: Fr[] } = {}) { - const blockNumber = await this.txeGetNextBlockNumber(); + const blockNumber = await this.getNextBlockNumber(); const txEffect = TxEffect.empty(); txEffect.nullifiers = [getSingleTxBlockRequestHash(blockNumber), ...(options.nullifiers ?? [])]; @@ -296,7 +296,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl await this.stateMachine.handleL2Block(block); } - async txePrivateCallNewFlow( + async privateCallNewFlow( from: AztecAddress, targetContractAddress: AztecAddress = AztecAddress.zero(), functionSelector: FunctionSelector = FunctionSelector.empty(), @@ -336,7 +336,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl effectiveScopes, ); - const blockNumber = await this.txeGetNextBlockNumber(); + const blockNumber = await this.getNextBlockNumber(); const callContext = new CallContext(from, targetContractAddress, functionSelector, isStaticCall); @@ -409,7 +409,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl ); const publicFunctionsCalldata = await Promise.all( publicCallRequests.map(async r => { - const calldata = await privateExecutionOracle.privateLoadFromExecutionCache(r.calldataHash); + const calldata = await privateExecutionOracle.loadFromExecutionCache(r.calldataHash); return new HashedValues(calldata, r.calldataHash); }), ); @@ -523,7 +523,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl return executionResult.returnValues ?? []; } - async txePublicCallNewFlow( + async publicCallNewFlow( from: AztecAddress, targetContractAddress: AztecAddress, calldata: Fr[], @@ -533,7 +533,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl `Executing public function ${await this.contractStore.getDebugFunctionName(targetContractAddress, FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`, ); - const blockNumber = await this.txeGetNextBlockNumber(); + const blockNumber = await this.getNextBlockNumber(); const gasLimits = new Gas(DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT); @@ -678,7 +678,7 @@ export class TXEOracleTopLevelContext implements IMiscOracle, ITxeExecutionOracl return returnValues ?? []; } - async txeExecuteUtilityFunction( + async executeUtilityFunction( targetContractAddress: AztecAddress, functionSelector: FunctionSelector, args: Fr[], diff --git a/yarn-project/txe/src/rpc_translator.ts b/yarn-project/txe/src/rpc_translator.ts index 55deeb05b91e..7ac755c2d501 100644 --- a/yarn-project/txe/src/rpc_translator.ts +++ b/yarn-project/txe/src/rpc_translator.ts @@ -104,13 +104,15 @@ export class RPCTranslator { // TXE session state transition functions - these get handled by the state handler - async txeSetTopLevelTXEContext() { + // eslint-disable-next-line camelcase + async aztec_txe_setTopLevelTXEContext() { await this.stateHandler.enterTopLevelState(); return toForeignCallResult([]); } - async txeSetPrivateTXEContext( + // eslint-disable-next-line camelcase + async aztec_txe_setPrivateTXEContext( foreignContractAddressIsSome: ForeignCallSingle, foreignContractAddressValue: ForeignCallSingle, foreignAnchorBlockNumberIsSome: ForeignCallSingle, @@ -129,7 +131,8 @@ export class RPCTranslator { return toForeignCallResult(privateContextInputs.toFields().map(toSingle)); } - async txeSetPublicTXEContext( + // eslint-disable-next-line camelcase + async aztec_txe_setPublicTXEContext( foreignContractAddressIsSome: ForeignCallSingle, foreignContractAddressValue: ForeignCallSingle, ) { @@ -142,7 +145,8 @@ export class RPCTranslator { return toForeignCallResult([]); } - async txeSetUtilityTXEContext( + // eslint-disable-next-line camelcase + async aztec_txe_setUtilityTXEContext( foreignContractAddressIsSome: ForeignCallSingle, foreignContractAddressValue: ForeignCallSingle, ) { @@ -159,44 +163,54 @@ export class RPCTranslator { // TXE-specific oracles - txeGetDefaultAddress() { - const defaultAddress = this.handlerAsTxe().txeGetDefaultAddress(); + // eslint-disable-next-line camelcase + aztec_txe_getDefaultAddress() { + const defaultAddress = this.handlerAsTxe().getDefaultAddress(); return toForeignCallResult([toSingle(defaultAddress)]); } - async txeGetNextBlockNumber() { - const nextBlockNumber = await this.handlerAsTxe().txeGetNextBlockNumber(); + // eslint-disable-next-line camelcase + async aztec_txe_getNextBlockNumber() { + const nextBlockNumber = await this.handlerAsTxe().getNextBlockNumber(); return toForeignCallResult([toSingle(nextBlockNumber)]); } - async txeGetNextBlockTimestamp() { - const nextBlockTimestamp = await this.handlerAsTxe().txeGetNextBlockTimestamp(); + // eslint-disable-next-line camelcase + async aztec_txe_getNextBlockTimestamp() { + const nextBlockTimestamp = await this.handlerAsTxe().getNextBlockTimestamp(); return toForeignCallResult([toSingle(nextBlockTimestamp)]); } - async txeAdvanceBlocksBy(foreignBlocks: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_txe_advanceBlocksBy(foreignBlocks: ForeignCallSingle) { const blocks = fromSingle(foreignBlocks).toNumber(); - await this.handlerAsTxe().txeAdvanceBlocksBy(blocks); + await this.handlerAsTxe().advanceBlocksBy(blocks); return toForeignCallResult([]); } - txeAdvanceTimestampBy(foreignDuration: ForeignCallSingle) { + // eslint-disable-next-line camelcase + aztec_txe_advanceTimestampBy(foreignDuration: ForeignCallSingle) { const duration = fromSingle(foreignDuration).toBigInt(); - this.handlerAsTxe().txeAdvanceTimestampBy(duration); + this.handlerAsTxe().advanceTimestampBy(duration); return toForeignCallResult([]); } - async txeDeploy(artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_txe_deploy( + artifact: ContractArtifact, + instance: ContractInstanceWithAddress, + foreignSecret: ForeignCallSingle, + ) { const secret = fromSingle(foreignSecret); - await this.handlerAsTxe().txeDeploy(artifact, instance, secret); + await this.handlerAsTxe().deploy(artifact, instance, secret); return toForeignCallResult([ toArray([ @@ -209,10 +223,11 @@ export class RPCTranslator { ]); } - async txeCreateAccount(foreignSecret: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_txe_createAccount(foreignSecret: ForeignCallSingle) { const secret = fromSingle(foreignSecret); - const completeAddress = await this.handlerAsTxe().txeCreateAccount(secret); + const completeAddress = await this.handlerAsTxe().createAccount(secret); return toForeignCallResult([ toSingle(completeAddress.address), @@ -220,14 +235,15 @@ export class RPCTranslator { ]); } - async txeAddAccount( + // eslint-disable-next-line camelcase + async aztec_txe_addAccount( artifact: ContractArtifact, instance: ContractInstanceWithAddress, foreignSecret: ForeignCallSingle, ) { const secret = fromSingle(foreignSecret); - const completeAddress = await this.handlerAsTxe().txeAddAccount(artifact, instance, secret); + const completeAddress = await this.handlerAsTxe().addAccount(artifact, instance, secret); return toForeignCallResult([ toSingle(completeAddress.address), @@ -235,39 +251,44 @@ export class RPCTranslator { ]); } - async txeAddAuthWitness(foreignAddress: ForeignCallSingle, foreignMessageHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_txe_addAuthWitness(foreignAddress: ForeignCallSingle, foreignMessageHash: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); const messageHash = fromSingle(foreignMessageHash); - await this.handlerAsTxe().txeAddAuthWitness(address, messageHash); + await this.handlerAsTxe().addAuthWitness(address, messageHash); return toForeignCallResult([]); } // PXE oracles - utilityAssertCompatibleOracleVersion(foreignVersion: ForeignCallSingle) { + // eslint-disable-next-line camelcase + aztec_utl_assertCompatibleOracleVersion(foreignVersion: ForeignCallSingle) { const version = fromSingle(foreignVersion).toNumber(); - this.handlerAsMisc().utilityAssertCompatibleOracleVersion(version); + this.handlerAsMisc().assertCompatibleOracleVersion(version); return toForeignCallResult([]); } - utilityGetRandomField() { - const randomField = this.handlerAsMisc().utilityGetRandomField(); + // eslint-disable-next-line camelcase + aztec_utl_getRandomField() { + const randomField = this.handlerAsMisc().getRandomField(); return toForeignCallResult([toSingle(randomField)]); } - async txeGetLastBlockTimestamp() { - const timestamp = await this.handlerAsTxe().txeGetLastBlockTimestamp(); + // eslint-disable-next-line camelcase + async aztec_txe_getLastBlockTimestamp() { + const timestamp = await this.handlerAsTxe().getLastBlockTimestamp(); return toForeignCallResult([toSingle(new Fr(timestamp))]); } - async txeGetLastTxEffects() { - const { txHash, noteHashes, nullifiers } = await this.handlerAsTxe().txeGetLastTxEffects(); + // eslint-disable-next-line camelcase + async aztec_txe_getLastTxEffects() { + const { txHash, noteHashes, nullifiers } = await this.handlerAsTxe().getLastTxEffects(); return toForeignCallResult([ toSingle(txHash.hash), @@ -276,7 +297,8 @@ export class RPCTranslator { ]); } - async txeGetPrivateEvents( + // eslint-disable-next-line camelcase + async aztec_txe_getPrivateEvents( foreignSelector: ForeignCallSingle, foreignContractAddress: ForeignCallSingle, foreignScope: ForeignCallSingle, @@ -292,7 +314,7 @@ export class RPCTranslator { await this.stateHandler.cycleJob(); } - const events = await this.handlerAsTxe().txeGetPrivateEvents(selector, contractAddress, scope); + const events = await this.handlerAsTxe().getPrivateEvents(selector, contractAddress, scope); if (events.length > MAX_PRIVATE_EVENTS_PER_TXE_QUERY) { throw new Error(`Array of length ${events.length} larger than maxLen ${MAX_PRIVATE_EVENTS_PER_TXE_QUERY}`); @@ -316,26 +338,29 @@ export class RPCTranslator { return toForeignCallResult([toArray(rawArrayStorage), toArray(eventLengths), toSingle(queryLength)]); } - privateStoreInExecutionCache(foreignValues: ForeignCallArray, foreignHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + aztec_prv_storeInExecutionCache(foreignValues: ForeignCallArray, foreignHash: ForeignCallSingle) { const values = fromArray(foreignValues); const hash = fromSingle(foreignHash); - this.handlerAsPrivate().privateStoreInExecutionCache(values, hash); + this.handlerAsPrivate().storeInExecutionCache(values, hash); return toForeignCallResult([]); } - async privateLoadFromExecutionCache(foreignHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_prv_loadFromExecutionCache(foreignHash: ForeignCallSingle) { const hash = fromSingle(foreignHash); - const returns = await this.handlerAsPrivate().privateLoadFromExecutionCache(hash); + const returns = await this.handlerAsPrivate().loadFromExecutionCache(hash); return toForeignCallResult([toArray(returns)]); } // When the argument is a slice, noir automatically adds a length field to oracle call. // When the argument is an array, we add the field length manually to the signature. - async utilityLog( + // eslint-disable-next-line camelcase + async aztec_utl_log( foreignLevel: ForeignCallSingle, foreignMessage: ForeignCallArray, _foreignLength: ForeignCallSingle, @@ -347,12 +372,13 @@ export class RPCTranslator { .join(''); const fields = fromArray(foreignFields); - await this.handlerAsMisc().utilityLog(level, message, fields); + await this.handlerAsMisc().log(level, message, fields); return toForeignCallResult([]); } - async utilityStorageRead( + // eslint-disable-next-line camelcase + async aztec_utl_storageRead( foreignBlockHash: ForeignCallSingle, foreignContractAddress: ForeignCallSingle, foreignStartStorageSlot: ForeignCallSingle, @@ -363,7 +389,7 @@ export class RPCTranslator { const startStorageSlot = fromSingle(foreignStartStorageSlot); const numberOfElements = fromSingle(foreignNumberOfElements).toNumber(); - const values = await this.handlerAsUtility().utilityStorageRead( + const values = await this.handlerAsUtility().storageRead( blockHash, contractAddress, startStorageSlot, @@ -373,11 +399,12 @@ export class RPCTranslator { return toForeignCallResult([toArray(values)]); } - async utilityGetPublicDataWitness(foreignBlockHash: ForeignCallSingle, foreignLeafSlot: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getPublicDataWitness(foreignBlockHash: ForeignCallSingle, foreignLeafSlot: ForeignCallSingle) { const blockHash = new BlockHash(fromSingle(foreignBlockHash)); const leafSlot = fromSingle(foreignLeafSlot); - const witness = await this.handlerAsUtility().utilityGetPublicDataWitness(blockHash, leafSlot); + const witness = await this.handlerAsUtility().getPublicDataWitness(blockHash, leafSlot); if (!witness) { throw new Error(`Public data witness not found for slot ${leafSlot} at block ${blockHash.toString()}.`); @@ -385,7 +412,8 @@ export class RPCTranslator { return toForeignCallResult(witness.toNoirRepresentation()); } - async utilityGetNotes( + // eslint-disable-next-line camelcase + async aztec_utl_getNotes( foreignOwnerIsSome: ForeignCallSingle, foreignOwnerValue: ForeignCallSingle, foreignStorageSlot: ForeignCallSingle, @@ -426,7 +454,7 @@ export class RPCTranslator { const maxNotes = fromSingle(foreignMaxNotes).toNumber(); const packedHintedNoteLength = fromSingle(foreignPackedHintedNoteLength).toNumber(); - const noteDatas = await this.handlerAsUtility().utilityGetNotes( + const noteDatas = await this.handlerAsUtility().getNotes( owner, storageSlot, numSelects, @@ -467,7 +495,8 @@ export class RPCTranslator { ); } - privateNotifyCreatedNote( + // eslint-disable-next-line camelcase + aztec_prv_notifyCreatedNote( foreignOwner: ForeignCallSingle, foreignStorageSlot: ForeignCallSingle, foreignRandomness: ForeignCallSingle, @@ -484,20 +513,13 @@ export class RPCTranslator { const noteHash = fromSingle(foreignNoteHash); const counter = fromSingle(foreignCounter).toNumber(); - this.handlerAsPrivate().privateNotifyCreatedNote( - owner, - storageSlot, - randomness, - noteTypeId, - note, - noteHash, - counter, - ); + this.handlerAsPrivate().notifyCreatedNote(owner, storageSlot, randomness, noteTypeId, note, noteHash, counter); return toForeignCallResult([]); } - async privateNotifyNullifiedNote( + // eslint-disable-next-line camelcase + async aztec_prv_notifyNullifiedNote( foreignInnerNullifier: ForeignCallSingle, foreignNoteHash: ForeignCallSingle, foreignCounter: ForeignCallSingle, @@ -506,40 +528,47 @@ export class RPCTranslator { const noteHash = fromSingle(foreignNoteHash); const counter = fromSingle(foreignCounter).toNumber(); - await this.handlerAsPrivate().privateNotifyNullifiedNote(innerNullifier, noteHash, counter); + await this.handlerAsPrivate().notifyNullifiedNote(innerNullifier, noteHash, counter); return toForeignCallResult([]); } - async privateNotifyCreatedNullifier(foreignInnerNullifier: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_prv_notifyCreatedNullifier(foreignInnerNullifier: ForeignCallSingle) { const innerNullifier = fromSingle(foreignInnerNullifier); - await this.handlerAsPrivate().privateNotifyCreatedNullifier(innerNullifier); + await this.handlerAsPrivate().notifyCreatedNullifier(innerNullifier); return toForeignCallResult([]); } - async privateIsNullifierPending(foreignInnerNullifier: ForeignCallSingle, foreignContractAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_prv_isNullifierPending( + foreignInnerNullifier: ForeignCallSingle, + foreignContractAddress: ForeignCallSingle, + ) { const innerNullifier = fromSingle(foreignInnerNullifier); const contractAddress = addressFromSingle(foreignContractAddress); - const isPending = await this.handlerAsPrivate().privateIsNullifierPending(innerNullifier, contractAddress); + const isPending = await this.handlerAsPrivate().isNullifierPending(innerNullifier, contractAddress); return toForeignCallResult([toSingle(new Fr(isPending))]); } - async utilityCheckNullifierExists(foreignInnerNullifier: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_checkNullifierExists(foreignInnerNullifier: ForeignCallSingle) { const innerNullifier = fromSingle(foreignInnerNullifier); - const exists = await this.handlerAsUtility().utilityCheckNullifierExists(innerNullifier); + const exists = await this.handlerAsUtility().checkNullifierExists(innerNullifier); return toForeignCallResult([toSingle(new Fr(exists))]); } - async utilityGetContractInstance(foreignAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getContractInstance(foreignAddress: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); - const instance = await this.handlerAsUtility().utilityGetContractInstance(address); + const instance = await this.handlerAsUtility().getContractInstance(address); return toForeignCallResult( [ @@ -552,10 +581,11 @@ export class RPCTranslator { ); } - async utilityTryGetPublicKeysAndPartialAddress(foreignAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_tryGetPublicKeysAndPartialAddress(foreignAddress: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); - const result = await this.handlerAsUtility().utilityTryGetPublicKeysAndPartialAddress(address); + const result = await this.handlerAsUtility().tryGetPublicKeysAndPartialAddress(address); // We are going to return a Noir Option struct to represent the possibility of null values. Options are a struct // with two fields: `some` (a boolean) and `value` (a field array in this case). @@ -571,15 +601,17 @@ export class RPCTranslator { } } - async utilityGetKeyValidationRequest(foreignPkMHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getKeyValidationRequest(foreignPkMHash: ForeignCallSingle) { const pkMHash = fromSingle(foreignPkMHash); - const keyValidationRequest = await this.handlerAsUtility().utilityGetKeyValidationRequest(pkMHash); + const keyValidationRequest = await this.handlerAsUtility().getKeyValidationRequest(pkMHash); return toForeignCallResult(keyValidationRequest.toFields().map(toSingle)); } - privateCallPrivateFunction( + // eslint-disable-next-line camelcase + aztec_prv_callPrivateFunction( _foreignTargetContractAddress: ForeignCallSingle, _foreignFunctionSelector: ForeignCallSingle, _foreignArgsHash: ForeignCallSingle, @@ -591,11 +623,15 @@ export class RPCTranslator { ); } - async utilityGetNullifierMembershipWitness(foreignBlockHash: ForeignCallSingle, foreignNullifier: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getNullifierMembershipWitness( + foreignBlockHash: ForeignCallSingle, + foreignNullifier: ForeignCallSingle, + ) { const blockHash = new BlockHash(fromSingle(foreignBlockHash)); const nullifier = fromSingle(foreignNullifier); - const witness = await this.handlerAsUtility().utilityGetNullifierMembershipWitness(blockHash, nullifier); + const witness = await this.handlerAsUtility().getNullifierMembershipWitness(blockHash, nullifier); if (!witness) { throw new Error(`Nullifier membership witness not found at block ${blockHash}.`); @@ -603,10 +639,11 @@ export class RPCTranslator { return toForeignCallResult(witness.toNoirRepresentation()); } - async utilityGetAuthWitness(foreignMessageHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getAuthWitness(foreignMessageHash: ForeignCallSingle) { const messageHash = fromSingle(foreignMessageHash); - const authWitness = await this.handlerAsUtility().utilityGetAuthWitness(messageHash); + const authWitness = await this.handlerAsUtility().getAuthWitness(messageHash); if (!authWitness) { throw new Error(`Auth witness not found for message hash ${messageHash}.`); @@ -614,7 +651,8 @@ export class RPCTranslator { return toForeignCallResult([toArray(authWitness)]); } - public privateNotifyEnqueuedPublicFunctionCall( + // eslint-disable-next-line camelcase + public aztec_prv_notifyEnqueuedPublicFunctionCall( _foreignTargetContractAddress: ForeignCallSingle, _foreignCalldataHash: ForeignCallSingle, _foreignSideEffectCounter: ForeignCallSingle, @@ -623,7 +661,8 @@ export class RPCTranslator { throw new Error('Enqueueing public calls is not supported in TestEnvironment::private_context'); } - public privateNotifySetPublicTeardownFunctionCall( + // eslint-disable-next-line camelcase + public aztec_prv_notifySetPublicTeardownFunctionCall( _foreignTargetContractAddress: ForeignCallSingle, _foreignCalldataHash: ForeignCallSingle, _foreignSideEffectCounter: ForeignCallSingle, @@ -632,26 +671,30 @@ export class RPCTranslator { throw new Error('Enqueueing public calls is not supported in TestEnvironment::private_context'); } - public privateNotifySetMinRevertibleSideEffectCounter(_foreignMinRevertibleSideEffectCounter: ForeignCallSingle) { + // eslint-disable-next-line camelcase + public aztec_prv_notifySetMinRevertibleSideEffectCounter(_foreignMinRevertibleSideEffectCounter: ForeignCallSingle) { throw new Error('Enqueueing public calls is not supported in TestEnvironment::private_context'); } - public async privateIsSideEffectCounterRevertible(foreignSideEffectCounter: ForeignCallSingle) { + // eslint-disable-next-line camelcase + public async aztec_prv_isSideEffectCounterRevertible(foreignSideEffectCounter: ForeignCallSingle) { const sideEffectCounter = fromSingle(foreignSideEffectCounter).toNumber(); - const isRevertible = await this.handlerAsPrivate().privateIsSideEffectCounterRevertible(sideEffectCounter); + const isRevertible = await this.handlerAsPrivate().isSideEffectCounterRevertible(sideEffectCounter); return toForeignCallResult([toSingle(new Fr(isRevertible))]); } - utilityGetUtilityContext() { - const context = this.handlerAsUtility().utilityGetUtilityContext(); + // eslint-disable-next-line camelcase + aztec_utl_getUtilityContext() { + const context = this.handlerAsUtility().getUtilityContext(); return toForeignCallResult(context.toNoirRepresentation()); } - async utilityGetBlockHeader(foreignBlockNumber: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_getBlockHeader(foreignBlockNumber: ForeignCallSingle) { const blockNumber = BlockNumber(fromSingle(foreignBlockNumber).toNumber()); - const header = await this.handlerAsUtility().utilityGetBlockHeader(blockNumber); + const header = await this.handlerAsUtility().getBlockHeader(blockNumber); if (!header) { throw new Error(`Block header not found for block ${blockNumber}.`); @@ -659,14 +702,15 @@ export class RPCTranslator { return toForeignCallResult(header.toFields().map(toSingle)); } - async utilityGetNoteHashMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getNoteHashMembershipWitness( foreignAnchorBlockHash: ForeignCallSingle, foreignNoteHash: ForeignCallSingle, ) { const blockHash = new BlockHash(fromSingle(foreignAnchorBlockHash)); const noteHash = fromSingle(foreignNoteHash); - const witness = await this.handlerAsUtility().utilityGetNoteHashMembershipWitness(blockHash, noteHash); + const witness = await this.handlerAsUtility().getNoteHashMembershipWitness(blockHash, noteHash); if (!witness) { throw new Error(`Note hash ${noteHash} not found in the note hash tree at block ${blockHash.toString()}.`); @@ -674,14 +718,15 @@ export class RPCTranslator { return toForeignCallResult(witness.toNoirRepresentation()); } - async utilityGetBlockHashMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getBlockHashMembershipWitness( foreignAnchorBlockHash: ForeignCallSingle, foreignBlockHash: ForeignCallSingle, ) { const anchorBlockHash = new BlockHash(fromSingle(foreignAnchorBlockHash)); const blockHash = new BlockHash(fromSingle(foreignBlockHash)); - const witness = await this.handlerAsUtility().utilityGetBlockHashMembershipWitness(anchorBlockHash, blockHash); + const witness = await this.handlerAsUtility().getBlockHashMembershipWitness(anchorBlockHash, blockHash); if (!witness) { throw new Error( @@ -691,14 +736,15 @@ export class RPCTranslator { return toForeignCallResult(witness.toNoirRepresentation()); } - async utilityGetLowNullifierMembershipWitness( + // eslint-disable-next-line camelcase + async aztec_utl_getLowNullifierMembershipWitness( foreignBlockHash: ForeignCallSingle, foreignNullifier: ForeignCallSingle, ) { const blockHash = new BlockHash(fromSingle(foreignBlockHash)); const nullifier = fromSingle(foreignNullifier); - const witness = await this.handlerAsUtility().utilityGetLowNullifierMembershipWitness(blockHash, nullifier); + const witness = await this.handlerAsUtility().getLowNullifierMembershipWitness(blockHash, nullifier); if (!witness) { throw new Error(`Low nullifier witness not found for nullifier ${nullifier} at block ${blockHash}.`); @@ -706,15 +752,17 @@ export class RPCTranslator { return toForeignCallResult(witness.toNoirRepresentation()); } - async utilityFetchTaggedLogs(foreignPendingTaggedLogArrayBaseSlot: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_fetchTaggedLogs(foreignPendingTaggedLogArrayBaseSlot: ForeignCallSingle) { const pendingTaggedLogArrayBaseSlot = fromSingle(foreignPendingTaggedLogArrayBaseSlot); - await this.handlerAsUtility().utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot); + await this.handlerAsUtility().fetchTaggedLogs(pendingTaggedLogArrayBaseSlot); return toForeignCallResult([]); } - public async utilityValidateAndStoreEnqueuedNotesAndEvents( + // eslint-disable-next-line camelcase + public async aztec_utl_validateAndStoreEnqueuedNotesAndEvents( foreignContractAddress: ForeignCallSingle, foreignNoteValidationRequestsArrayBaseSlot: ForeignCallSingle, foreignEventValidationRequestsArrayBaseSlot: ForeignCallSingle, @@ -723,7 +771,7 @@ export class RPCTranslator { const noteValidationRequestsArrayBaseSlot = fromSingle(foreignNoteValidationRequestsArrayBaseSlot); const eventValidationRequestsArrayBaseSlot = fromSingle(foreignEventValidationRequestsArrayBaseSlot); - await this.handlerAsUtility().utilityValidateAndStoreEnqueuedNotesAndEvents( + await this.handlerAsUtility().validateAndStoreEnqueuedNotesAndEvents( contractAddress, noteValidationRequestsArrayBaseSlot, eventValidationRequestsArrayBaseSlot, @@ -732,7 +780,8 @@ export class RPCTranslator { return toForeignCallResult([]); } - public async utilityBulkRetrieveLogs( + // eslint-disable-next-line camelcase + public async aztec_utl_bulkRetrieveLogs( foreignContractAddress: ForeignCallSingle, foreignLogRetrievalRequestsArrayBaseSlot: ForeignCallSingle, foreignLogRetrievalResponsesArrayBaseSlot: ForeignCallSingle, @@ -741,7 +790,7 @@ export class RPCTranslator { const logRetrievalRequestsArrayBaseSlot = fromSingle(foreignLogRetrievalRequestsArrayBaseSlot); const logRetrievalResponsesArrayBaseSlot = fromSingle(foreignLogRetrievalResponsesArrayBaseSlot); - await this.handlerAsUtility().utilityBulkRetrieveLogs( + await this.handlerAsUtility().bulkRetrieveLogs( contractAddress, logRetrievalRequestsArrayBaseSlot, logRetrievalResponsesArrayBaseSlot, @@ -750,7 +799,8 @@ export class RPCTranslator { return toForeignCallResult([]); } - async utilityStoreCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_storeCapsule( foreignContractAddress: ForeignCallSingle, foreignSlot: ForeignCallSingle, foreignCapsule: ForeignCallArray, @@ -759,12 +809,13 @@ export class RPCTranslator { const slot = fromSingle(foreignSlot); const capsule = fromArray(foreignCapsule); - await this.handlerAsUtility().utilityStoreCapsule(contractAddress, slot, capsule); + await this.handlerAsUtility().storeCapsule(contractAddress, slot, capsule); return toForeignCallResult([]); } - async utilityLoadCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_loadCapsule( foreignContractAddress: ForeignCallSingle, foreignSlot: ForeignCallSingle, foreignTSize: ForeignCallSingle, @@ -773,7 +824,7 @@ export class RPCTranslator { const slot = fromSingle(foreignSlot); const tSize = fromSingle(foreignTSize).toNumber(); - const values = await this.handlerAsUtility().utilityLoadCapsule(contractAddress, slot); + const values = await this.handlerAsUtility().loadCapsule(contractAddress, slot); // We are going to return a Noir Option struct to represent the possibility of null values. Options are a struct // with two fields: `some` (a boolean) and `value` (a field array in this case). @@ -786,16 +837,18 @@ export class RPCTranslator { } } - async utilityDeleteCapsule(foreignContractAddress: ForeignCallSingle, foreignSlot: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_utl_deleteCapsule(foreignContractAddress: ForeignCallSingle, foreignSlot: ForeignCallSingle) { const contractAddress = AztecAddress.fromField(fromSingle(foreignContractAddress)); const slot = fromSingle(foreignSlot); - await this.handlerAsUtility().utilityDeleteCapsule(contractAddress, slot); + await this.handlerAsUtility().deleteCapsule(contractAddress, slot); return toForeignCallResult([]); } - async utilityCopyCapsule( + // eslint-disable-next-line camelcase + async aztec_utl_copyCapsule( foreignContractAddress: ForeignCallSingle, foreignSrcSlot: ForeignCallSingle, foreignDstSlot: ForeignCallSingle, @@ -806,7 +859,7 @@ export class RPCTranslator { const dstSlot = fromSingle(foreignDstSlot); const numEntries = fromSingle(foreignNumEntries).toNumber(); - await this.handlerAsUtility().utilityCopyCapsule(contractAddress, srcSlot, dstSlot, numEntries); + await this.handlerAsUtility().copyCapsule(contractAddress, srcSlot, dstSlot, numEntries); return toForeignCallResult([]); } @@ -815,7 +868,8 @@ export class RPCTranslator { // The compiler didn't throw an error, so it took me a while to learn of the existence of this file, and that I need // to implement this function here. Isn't there a way to programmatically identify that this is missing, given the // existence of a txe_oracle method? - async utilityAes128Decrypt( + // eslint-disable-next-line camelcase + async aztec_utl_aes128Decrypt( foreignCiphertextBVecStorage: ForeignCallArray, foreignCiphertextLength: ForeignCallSingle, foreignIv: ForeignCallArray, @@ -825,14 +879,15 @@ export class RPCTranslator { const iv = fromUintArray(foreignIv, 8); const symKey = fromUintArray(foreignSymKey, 8); - const plaintextBuffer = await this.handlerAsUtility().utilityAes128Decrypt(ciphertext, iv, symKey); + const plaintextBuffer = await this.handlerAsUtility().aes128Decrypt(ciphertext, iv, symKey); return toForeignCallResult( arrayToBoundedVec(bufferToU8Array(plaintextBuffer), foreignCiphertextBVecStorage.length), ); } - async utilityGetSharedSecret( + // eslint-disable-next-line camelcase + async aztec_utl_getSharedSecret( foreignAddress: ForeignCallSingle, foreignEphPKField0: ForeignCallSingle, foreignEphPKField1: ForeignCallSingle, @@ -845,44 +900,49 @@ export class RPCTranslator { fromSingle(foreignEphPKField2), ]); - const secret = await this.handlerAsUtility().utilityGetSharedSecret(address, ephPK); + const secret = await this.handlerAsUtility().getSharedSecret(address, ephPK); return toForeignCallResult(secret.toFields().map(toSingle)); } - emitOffchainEffect(_foreignData: ForeignCallArray) { + // eslint-disable-next-line camelcase + aztec_utl_emitOffchainEffect(_foreignData: ForeignCallArray) { throw new Error('Offchain effects are not yet supported in the TestEnvironment'); } // AVM opcodes - avmOpcodeEmitPublicLog(_foreignMessage: ForeignCallArray) { + // eslint-disable-next-line camelcase + aztec_avm_emitPublicLog(_foreignMessage: ForeignCallArray) { // TODO(#8811): Implement return toForeignCallResult([]); } - async avmOpcodeStorageRead(foreignSlot: ForeignCallSingle, foreignContractAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_storageRead(foreignSlot: ForeignCallSingle, foreignContractAddress: ForeignCallSingle) { const slot = fromSingle(foreignSlot); const contractAddress = AztecAddress.fromField(fromSingle(foreignContractAddress)); - const value = (await this.handlerAsAvm().avmOpcodeStorageRead(slot, contractAddress)).value; + const value = (await this.handlerAsAvm().storageRead(slot, contractAddress)).value; return toForeignCallResult([toSingle(new Fr(value))]); } - async avmOpcodeStorageWrite(foreignSlot: ForeignCallSingle, foreignValue: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_storageWrite(foreignSlot: ForeignCallSingle, foreignValue: ForeignCallSingle) { const slot = fromSingle(foreignSlot); const value = fromSingle(foreignValue); - await this.handlerAsAvm().avmOpcodeStorageWrite(slot, value); + await this.handlerAsAvm().storageWrite(slot, value); return toForeignCallResult([]); } - async avmOpcodeGetContractInstanceDeployer(foreignAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_getContractInstanceDeployer(foreignAddress: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); - const instance = await this.handlerAsUtility().utilityGetContractInstance(address); + const instance = await this.handlerAsUtility().getContractInstance(address); return toForeignCallResult([ toSingle(instance.deployer), @@ -891,10 +951,11 @@ export class RPCTranslator { ]); } - async avmOpcodeGetContractInstanceClassId(foreignAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_getContractInstanceClassId(foreignAddress: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); - const instance = await this.handlerAsUtility().utilityGetContractInstance(address); + const instance = await this.handlerAsUtility().getContractInstance(address); return toForeignCallResult([ toSingle(instance.currentContractClassId), @@ -903,10 +964,11 @@ export class RPCTranslator { ]); } - async avmOpcodeGetContractInstanceInitializationHash(foreignAddress: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_getContractInstanceInitializationHash(foreignAddress: ForeignCallSingle) { const address = addressFromSingle(foreignAddress); - const instance = await this.handlerAsUtility().utilityGetContractInstance(address); + const instance = await this.handlerAsUtility().getContractInstance(address); return toForeignCallResult([ toSingle(instance.initializationHash), @@ -915,85 +977,98 @@ export class RPCTranslator { ]); } - async avmOpcodeSender() { - const sender = await this.handlerAsAvm().avmOpcodeSender(); + // eslint-disable-next-line camelcase + async aztec_avm_sender() { + const sender = await this.handlerAsAvm().sender(); return toForeignCallResult([toSingle(sender)]); } - async avmOpcodeEmitNullifier(foreignNullifier: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_emitNullifier(foreignNullifier: ForeignCallSingle) { const nullifier = fromSingle(foreignNullifier); - await this.handlerAsAvm().avmOpcodeEmitNullifier(nullifier); + await this.handlerAsAvm().emitNullifier(nullifier); return toForeignCallResult([]); } - async avmOpcodeEmitNoteHash(foreignNoteHash: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_emitNoteHash(foreignNoteHash: ForeignCallSingle) { const noteHash = fromSingle(foreignNoteHash); - await this.handlerAsAvm().avmOpcodeEmitNoteHash(noteHash); + await this.handlerAsAvm().emitNoteHash(noteHash); return toForeignCallResult([]); } - async avmOpcodeNullifierExists(foreignSiloedNullifier: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_avm_nullifierExists(foreignSiloedNullifier: ForeignCallSingle) { const siloedNullifier = fromSingle(foreignSiloedNullifier); - const exists = await this.handlerAsAvm().avmOpcodeNullifierExists(siloedNullifier); + const exists = await this.handlerAsAvm().nullifierExists(siloedNullifier); return toForeignCallResult([toSingle(new Fr(exists))]); } - async avmOpcodeAddress() { - const contractAddress = await this.handlerAsAvm().avmOpcodeAddress(); + // eslint-disable-next-line camelcase + async aztec_avm_address() { + const contractAddress = await this.handlerAsAvm().address(); return toForeignCallResult([toSingle(contractAddress.toField())]); } - async avmOpcodeBlockNumber() { - const blockNumber = await this.handlerAsAvm().avmOpcodeBlockNumber(); + // eslint-disable-next-line camelcase + async aztec_avm_blockNumber() { + const blockNumber = await this.handlerAsAvm().blockNumber(); return toForeignCallResult([toSingle(new Fr(blockNumber))]); } - async avmOpcodeTimestamp() { - const timestamp = await this.handlerAsAvm().avmOpcodeTimestamp(); + // eslint-disable-next-line camelcase + async aztec_avm_timestamp() { + const timestamp = await this.handlerAsAvm().timestamp(); return toForeignCallResult([toSingle(new Fr(timestamp))]); } - async avmOpcodeIsStaticCall() { - const isStaticCall = await this.handlerAsAvm().avmOpcodeIsStaticCall(); + // eslint-disable-next-line camelcase + async aztec_avm_isStaticCall() { + const isStaticCall = await this.handlerAsAvm().isStaticCall(); return toForeignCallResult([toSingle(new Fr(isStaticCall ? 1 : 0))]); } - async avmOpcodeChainId() { - const chainId = await this.handlerAsAvm().avmOpcodeChainId(); + // eslint-disable-next-line camelcase + async aztec_avm_chainId() { + const chainId = await this.handlerAsAvm().chainId(); return toForeignCallResult([toSingle(chainId)]); } - async avmOpcodeVersion() { - const version = await this.handlerAsAvm().avmOpcodeVersion(); + // eslint-disable-next-line camelcase + async aztec_avm_version() { + const version = await this.handlerAsAvm().version(); return toForeignCallResult([toSingle(version)]); } - avmOpcodeReturndataSize() { + // eslint-disable-next-line camelcase + aztec_avm_returndataSize() { throw new Error( 'Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead', ); } - avmOpcodeReturndataCopy(_foreignRdOffset: ForeignCallSingle, _foreignCopySize: ForeignCallSingle) { + // eslint-disable-next-line camelcase + aztec_avm_returndataCopy(_foreignRdOffset: ForeignCallSingle, _foreignCopySize: ForeignCallSingle) { throw new Error( 'Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead', ); } - avmOpcodeCall( + // eslint-disable-next-line camelcase + aztec_avm_call( _foreignL2Gas: ForeignCallSingle, _foreignDaGas: ForeignCallSingle, _foreignAddress: ForeignCallSingle, @@ -1005,7 +1080,8 @@ export class RPCTranslator { ); } - avmOpcodeStaticCall( + // eslint-disable-next-line camelcase + aztec_avm_staticCall( _foreignL2Gas: ForeignCallSingle, _foreignDaGas: ForeignCallSingle, _foreignAddress: ForeignCallSingle, @@ -1017,13 +1093,15 @@ export class RPCTranslator { ); } - avmOpcodeSuccessCopy() { + // eslint-disable-next-line camelcase + aztec_avm_successCopy() { throw new Error( 'Contract calls are forbidden inside a `TestEnvironment::public_context`, use `public_call` instead', ); } - async txePrivateCallNewFlow( + // eslint-disable-next-line camelcase + async aztec_txe_privateCallNewFlow( foreignFrom: ForeignCallSingle, foreignTargetContractAddress: ForeignCallSingle, foreignFunctionSelector: ForeignCallSingle, @@ -1038,7 +1116,7 @@ export class RPCTranslator { const argsHash = fromSingle(foreignArgsHash); const isStaticCall = fromSingle(foreignIsStaticCall).toBool(); - const returnValues = await this.handlerAsTxe().txePrivateCallNewFlow( + const returnValues = await this.handlerAsTxe().privateCallNewFlow( from, targetContractAddress, functionSelector, @@ -1053,7 +1131,8 @@ export class RPCTranslator { return toForeignCallResult([toArray(returnValues)]); } - async txeExecuteUtilityFunction( + // eslint-disable-next-line camelcase + async aztec_txe_executeUtilityFunction( foreignTargetContractAddress: ForeignCallSingle, foreignFunctionSelector: ForeignCallSingle, foreignArgs: ForeignCallArray, @@ -1062,7 +1141,7 @@ export class RPCTranslator { const functionSelector = FunctionSelector.fromField(fromSingle(foreignFunctionSelector)); const args = fromArray(foreignArgs); - const returnValues = await this.handlerAsTxe().txeExecuteUtilityFunction( + const returnValues = await this.handlerAsTxe().executeUtilityFunction( targetContractAddress, functionSelector, args, @@ -1074,7 +1153,8 @@ export class RPCTranslator { return toForeignCallResult([toArray(returnValues)]); } - async txePublicCallNewFlow( + // eslint-disable-next-line camelcase + async aztec_txe_publicCallNewFlow( foreignFrom: ForeignCallSingle, foreignAddress: ForeignCallSingle, foreignCalldata: ForeignCallArray, @@ -1085,15 +1165,16 @@ export class RPCTranslator { const calldata = fromArray(foreignCalldata); const isStaticCall = fromSingle(foreignIsStaticCall).toBool(); - const returnValues = await this.handlerAsTxe().txePublicCallNewFlow(from, address, calldata, isStaticCall); + const returnValues = await this.handlerAsTxe().publicCallNewFlow(from, address, calldata, isStaticCall); // TODO(F-335): Avoid doing the following call here. await this.stateHandler.cycleJob(); return toForeignCallResult([toArray(returnValues)]); } - async privateGetSenderForTags() { - const sender = await this.handlerAsPrivate().privateGetSenderForTags(); + // eslint-disable-next-line camelcase + async aztec_prv_getSenderForTags() { + const sender = await this.handlerAsPrivate().getSenderForTags(); // Return a Noir Option struct with `some` and `value` fields if (sender === undefined) { @@ -1105,19 +1186,21 @@ export class RPCTranslator { } } - async privateSetSenderForTags(foreignSenderForTags: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_prv_setSenderForTags(foreignSenderForTags: ForeignCallSingle) { const senderForTags = AztecAddress.fromField(fromSingle(foreignSenderForTags)); - await this.handlerAsPrivate().privateSetSenderForTags(senderForTags); + await this.handlerAsPrivate().setSenderForTags(senderForTags); return toForeignCallResult([]); } - async privateGetNextAppTagAsSender(foreignSender: ForeignCallSingle, foreignRecipient: ForeignCallSingle) { + // eslint-disable-next-line camelcase + async aztec_prv_getNextAppTagAsSender(foreignSender: ForeignCallSingle, foreignRecipient: ForeignCallSingle) { const sender = AztecAddress.fromField(fromSingle(foreignSender)); const recipient = AztecAddress.fromField(fromSingle(foreignRecipient)); - const nextAppTag = await this.handlerAsPrivate().privateGetNextAppTagAsSender(sender, recipient); + const nextAppTag = await this.handlerAsPrivate().getNextAppTagAsSender(sender, recipient); return toForeignCallResult([toSingle(nextAppTag.value)]); } diff --git a/yarn-project/txe/src/txe_session.ts b/yarn-project/txe/src/txe_session.ts index 5c7b87ea4feb..d98b6761601b 100644 --- a/yarn-project/txe/src/txe_session.ts +++ b/yarn-project/txe/src/txe_session.ts @@ -202,7 +202,7 @@ export class TXESession implements TXESessionStateHandler { chainId, new Map(), ); - await topLevelOracleHandler.txeAdvanceBlocksBy(1); + await topLevelOracleHandler.advanceBlocksBy(1); return new TXESession( createLogger('txe:session'), @@ -452,8 +452,8 @@ export class TXESession implements TXESessionStateHandler { // Note that while all public and private contexts do is build a single block that we then process when exiting // those, the top level context performs a large number of actions not captured in the following 'close' call. Among - // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via - // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a + // others, it will create empty blocks (via `advanceBlocksBy` and `deploy`), create blocks with transactions via + // `privateCallNewFlow` and `publicCallNewFlow`, add accounts to PXE via `addAccount`, etc. This is a // slight inconsistency in the working model of this class, but is not too bad. // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset From a4ef9267ae526ad598c79ad13eab5804bca14025 Mon Sep 17 00:00:00 2001 From: Santiago Palladino Date: Wed, 4 Mar 2026 16:06:39 -0300 Subject: [PATCH 09/12] fix(pxe): correct contract class log DA gas metering from +2 to +1 (#21102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Fixes contract class log DA gas metering in the PXE contract function simulator - Changed `+ 2` to `+ 1` for the additional fields per contract class log, matching the circuits (gas_meter.nr, tx_blob_data.nr, sponge_blob.nr) and the TS blob encoder which all use `+ 1` - Contract class logs only emit the contract address as an extra field (unlike private logs which also emit a length field), so the old `+ 2` was overcharging by 1 DA field (32 DA gas) per log Fixes F-377 ## Test plan - Existing tests pass — this is a gas metering correction, not a logic change - Contract class log blob encoding is unchanged; only the gas estimation in the PXE was wrong 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 --- .../contract_function_simulator.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts index 5fcb18aa42c8..55d8c1900f07 100644 --- a/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts +++ b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts @@ -809,9 +809,9 @@ function meterGasUsed(data: PrivateToRollupAccumulatedData | PrivateToPublicAccu meteredL2Gas += numPrivatelogs * L2_GAS_PER_PRIVATE_LOG; const numContractClassLogs = arrayNonEmptyLength(data.contractClassLogsHashes, log => log.isEmpty()); - // Every contract class log emits its length and contract address as additional fields + // Every contract class log emits its contract address as an additional field meteredDAFields += data.contractClassLogsHashes.reduce( - (acc, log) => (!log.isEmpty() ? acc + log.logHash.length + 2 : acc), + (acc, log) => (!log.isEmpty() ? acc + log.logHash.length + 1 : acc), 0, ); meteredL2Gas += numContractClassLogs * L2_GAS_PER_CONTRACT_CLASS_LOG; From b451dc543d8ba9a73412e7c58d9a8ef6f77ade87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Venturo?= Date: Wed, 4 Mar 2026 16:33:26 -0300 Subject: [PATCH 10/12] chore: remove stale aes comments (#21133) What the title says. --- .../aztec-nr/aztec/src/messages/encryption/aes128.nr | 4 ---- 1 file changed, 4 deletions(-) diff --git a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr index 41997e71c00f..d74e5db6fc64 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr @@ -247,9 +247,6 @@ impl MessageEncryption for AES128 { // Derive ECDH shared secret with recipient using a fresh ephemeral keypair. let (eph_sk, eph_pk) = generate_positive_ephemeral_key_pair(); - // (not to be confused with the tagging shared secret) TODO (#17158): Currently we unwrap the Option returned - // by derive_ecdh_shared_secret. We need to handle the case where the ephemeral public key is invalid to - // prevent potential DoS vectors. let ciphertext_shared_secret = derive_ecdh_shared_secret( eph_sk, recipient @@ -269,7 +266,6 @@ impl MessageEncryption for AES128 { ) .inner, ); - // TODO: also use this shared secret for deriving note randomness. // AES128-CBC encrypt the plaintext bytes. // It is safe to call the `unsafe` function here, because we know the `shared_secret` was derived using an From d7d0149f37fb9309edacf3787f3db919d5809af5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Venturo?= Date: Wed, 4 Mar 2026 16:43:01 -0300 Subject: [PATCH 11/12] chore: add warning on invalid recipients (#21134) What the title says. --- .../aztec/src/messages/encryption/aes128.nr | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr index d74e5db6fc64..38490c0416a8 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr @@ -4,10 +4,12 @@ use crate::protocol::{ hash::poseidon2_hash_with_separator, point::Point, public_keys::AddressPoint, + traits::ToField, }; use crate::{ keys::{ecdh_shared_secret::derive_ecdh_shared_secret, ephemeral::generate_positive_ephemeral_key_pair}, + logging::aztecnr_warn_log_format, messages::{ encoding::{ EPH_PK_X_SIZE_IN_FIELDS, HEADER_CIPHERTEXT_SIZE_IN_BYTES, MESSAGE_CIPHERTEXT_LEN, MESSAGE_PLAINTEXT_LEN, @@ -251,7 +253,13 @@ impl MessageEncryption for AES128 { eph_sk, recipient .to_address_point() - .unwrap_or( + .unwrap_or_else(|| { + aztecnr_warn_log_format!( + "Attempted to encrypt message for an invalid recipient ({0})", + )( + [recipient.to_field()], + ); + // Safety: if the recipient is an invalid address, then it is not possible to encrypt a message for // them because we cannot establish a shared secret. This is never expected to occur during normal // operation. However, it is technically possible for us to receive an invalid address, and we must @@ -262,8 +270,10 @@ impl MessageEncryption for AES128 { // random valid address. The sender is free to choose this address and hence shared secret, but // this has no security implications as they already know not only the full plaintext but also the // ephemeral private key anyway. - unsafe { random_address_point() }, - ) + unsafe { + random_address_point() + } + }) .inner, ); From 80ecd983042b58fec713e8b2a9f5997c9b3f16b2 Mon Sep 17 00:00:00 2001 From: Nicolas Chamo Date: Wed, 4 Mar 2026 21:08:04 +0000 Subject: [PATCH 12/12] feat: mask ciphertext fields with Poseidon2-derived values (#21009) --- .../docs/resources/migration_notes.md | 4 + .../aztec/src/messages/encryption/aes128.nr | 87 ++++++++++++------- noir-projects/aztec-nr/aztec/src/utils/mod.nr | 1 - .../aztec-nr/aztec/src/utils/random.nr | 17 ---- .../crates/types/src/constants.nr | 1 + .../crates/types/src/constants_tests.nr | 29 ++++--- yarn-project/constants/src/constants.gen.ts | 1 + 7 files changed, 77 insertions(+), 63 deletions(-) delete mode 100644 noir-projects/aztec-nr/aztec/src/utils/random.nr diff --git a/docs/docs-developers/docs/resources/migration_notes.md b/docs/docs-developers/docs/resources/migration_notes.md index c6ced5fa03ff..cfc21d84d7a2 100644 --- a/docs/docs-developers/docs/resources/migration_notes.md +++ b/docs/docs-developers/docs/resources/migration_notes.md @@ -9,6 +9,10 @@ Aztec is in active development. Each version may introduce breaking changes that ## TBD +### [Aztec.nr] Removed `get_random_bytes` + +The `get_random_bytes` unconstrained function has been removed from `aztec::utils::random`. If you were using it, you can replace it with direct calls to the `random` oracle from `aztec::oracle::random` and convert to bytes yourself. + ### [Aztec.js] `simulate()`, `send()`, and deploy return types changed to always return objects All SDK interaction methods now return structured objects that include offchain output alongside the primary result. This affects `.simulate()`, `.send()`, deploy `.send()`, and `Wallet.sendTx()`. diff --git a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr index 38490c0416a8..fdcddf10fcd4 100644 --- a/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr +++ b/noir-projects/aztec-nr/aztec/src/messages/encryption/aes128.nr @@ -1,6 +1,6 @@ use crate::protocol::{ address::AztecAddress, - constants::{DOM_SEP__SYMMETRIC_KEY, DOM_SEP__SYMMETRIC_KEY_2}, + constants::{DOM_SEP__CIPHERTEXT_FIELD_MASK, DOM_SEP__SYMMETRIC_KEY, DOM_SEP__SYMMETRIC_KEY_2}, hash::poseidon2_hash_with_separator, point::Point, public_keys::AddressPoint, @@ -28,7 +28,6 @@ use crate::{ fields_to_bytes::{fields_from_bytes, fields_to_bytes}, }, point::point_from_x_coord_and_sign, - random::get_random_bytes, }, }; @@ -158,8 +157,9 @@ impl MessageEncryption for AES128 { /// ## Overview /// /// The plaintext is an array of up to `MESSAGE_PLAINTEXT_LEN` (12) fields. The output is always exactly - /// `MESSAGE_CIPHERTEXT_LEN` (15) fields, regardless of plaintext size. Unused trailing fields are filled with - /// random data so that all encrypted messages are indistinguishable by size. + /// `MESSAGE_CIPHERTEXT_LEN` (15) fields, regardless of plaintext size. All output fields except the + /// ephemeral public key are uniformly random `Field` values to any observer without knowledge of the + /// shared secret, making all encrypted messages indistinguishable by size or content. /// /// ## PKCS#7 Padding /// @@ -206,27 +206,31 @@ impl MessageEncryption for AES128 { /// Messages are transmitted as fields, not bytes. A field is ~254 bits and can safely store 31 whole bytes, so /// we need to pack our byte data into 31-byte chunks. This packing drives the wire format. /// - /// **Step 1 -- Assemble bytes.** The ciphertexts are laid out in a byte array, padded with random bytes to a + /// **Step 1 -- Assemble bytes.** The ciphertexts are laid out in a byte array, padded with zero bytes to a /// multiple of 31 so it divides evenly into fields: /// /// ```text /// +------------+-------------------------+---------+ /// | header ct | body ct | byte pad| - /// | 16 B | PlaintextLen*32 + 16 B | (random)| + /// | 16 B | PlaintextLen*32 + 16 B | (zeros) | /// +------------+-------------------------+---------+ /// |<-------- padded to a multiple of 31 B -------->| /// ``` /// - /// **Step 2 -- Pack into fields.** The byte array is split into 31-byte chunks, each stored in one field. The - /// ephemeral public key x-coordinate is prepended as its own field. Any remaining fields (up to 15 total) are - /// filled with random data so that all messages are the same size: + /// **Step 2 -- Pack and mask.** The byte array is split into 31-byte chunks, each stored in one field. A + /// Poseidon2-derived mask (see `derive_field_mask`) is added to each so that the resulting fields appear as + /// uniformly random `Field` values to any observer without knowledge of the shared secret, hiding the fact + /// that the underlying ciphertext consists of 128-bit AES blocks. + /// + /// **Step 3 -- Assemble ciphertext.** The ephemeral public key x-coordinate is prepended and random field padding + /// is appended to fill to 15 fields: /// /// ```text /// +----------+-------------------------+-------------------+ - /// | eph_pk.x | message-byte fields | random field pad | - /// | | (packed 31 B per field) | (fills to 15) | + /// | eph_pk.x | masked message fields | random field pad | + /// | | (packed 31 B per field) | (fills to 15) | /// +----------+-------------------------+-------------------+ - /// |<---------- MESSAGE_CIPHERTEXT_LEN = 15 fields ------->| + /// |<---------- MESSAGE_CIPHERTEXT_LEN = 15 fields -------->| /// ``` /// /// ## Key Derivation @@ -314,11 +318,7 @@ impl MessageEncryption for AES128 { // Assemble the message byte array: // [header_ct (16B)] [body_ct] [padding to mult of 31] - let mut message_bytes_padding_to_mult_31 = - get_arr_of_size__message_bytes_padding__from_PT::(); - // Safety: this randomness won't be constrained to be random. It's in the interest of the executor of this fn - // to encrypt with random bytes. - message_bytes_padding_to_mult_31 = unsafe { get_random_bytes() }; + let message_bytes_padding_to_mult_31 = get_arr_of_size__message_bytes_padding__from_PT::(); let mut message_bytes = get_arr_of_size__message_bytes__from_PT::(); @@ -356,30 +356,26 @@ impl MessageEncryption for AES128 { assert(offset == message_bytes.len(), "unexpected encrypted message length"); // Pack message bytes into fields (31 bytes per field) and prepend eph_pk.x. - // TODO(#12749): As Mike pointed out, we need to make messages produced by different encryption schemes - // indistinguishable from each other and for this reason the output here and in the last for-loop of this - // function should cover a full field. let message_bytes_as_fields = bytes_to_fields(message_bytes); let mut ciphertext: [Field; MESSAGE_CIPHERTEXT_LEN] = [0; MESSAGE_CIPHERTEXT_LEN]; ciphertext[0] = eph_pk.x; + // Mask each content field with a Poseidon2-derived value, so that they appear as uniformly random `Field` + // values let mut offset = 1; for i in 0..message_bytes_as_fields.len() { - ciphertext[offset + i] = message_bytes_as_fields[i]; + let mask = derive_field_mask(ciphertext_shared_secret, i as u32); + ciphertext[offset + i] = message_bytes_as_fields[i] + mask; } offset += message_bytes_as_fields.len(); + // Pad with random fields so that padding is indistinguishable from masked data fields. for i in offset..MESSAGE_CIPHERTEXT_LEN { - // We need to get a random value that fits in 31 bytes to not leak information about the size of the - // message (all the "real" message fields contain at most 31 bytes because of the way we convert the bytes - // to fields). TODO(#12749): Long term, this is not a good solution. - // Safety: we assume that the sender wants for the message to be private - a malicious one could simply // reveal its contents publicly. It is therefore fine to trust the sender to provide random padding. - let field_bytes = unsafe { get_random_bytes::<31>() }; - ciphertext[i] = Field::from_be_bytes::<31>(field_bytes); + ciphertext[i] = unsafe { random() }; } ciphertext @@ -391,14 +387,11 @@ impl MessageEncryption for AES128 { ) -> Option> { let eph_pk_x = ciphertext.get(0); - let ciphertext_without_eph_pk_x_fields = array::subbvec::( + let masked_fields = array::subbvec::( ciphertext, EPH_PK_X_SIZE_IN_FIELDS, ); - // Convert the ciphertext represented as fields to a byte representation (its original format) - let ciphertext_without_eph_pk_x = bytes_from_fields(ciphertext_without_eph_pk_x_fields); - // With the x-coordinate of the ephemeral public key we can reconstruct the point as we know that the // y-coordinate must be positive. This may fail however, as not all x-coordinates are on the curve. In that // case, we simply return `Option::none`. @@ -406,6 +399,14 @@ impl MessageEncryption for AES128 { // Derive shared secret let ciphertext_shared_secret = get_shared_secret(recipient, eph_pk); + let unmasked_fields = masked_fields.mapi(|i, field| { + let unmasked = unmask_field(ciphertext_shared_secret, i, field); + // If we failed to unmask the field, we are dealing with the random padding. We'll ignore it later, + // so we can simply set it to 0 + unmasked.unwrap_or(0) + }); + let ciphertext_without_eph_pk_x = bytes_from_fields(unmasked_fields); + // Derive symmetric keys: let pairs = derive_aes_symmetric_key_and_iv_from_ecdh_shared_secret_using_poseidon2_unsafe::<2>( ciphertext_shared_secret, @@ -446,6 +447,30 @@ impl MessageEncryption for AES128 { } } +/// 2^248: upper bound for values that fit in 31 bytes +global TWO_POW_248: Field = 2.pow_32(248); + +/// Removes the Poseidon2-derived mask from a ciphertext field. Returns the unmasked value if it fits in 31 bytes +/// (a content field), or `None` if it doesn't (random padding). Unconstrained to prevent accidental use in +/// constrained context. +unconstrained fn unmask_field(shared_secret: Point, index: u32, masked: Field) -> Option { + let unmasked = masked - derive_field_mask(shared_secret, index); + if unmasked.lt(TWO_POW_248) { + Option::some(unmasked) + } else { + Option::none() + } +} + +/// Derives a field mask from an ECDH shared secret and field index. Applied only to data fields (those carrying +/// packed message bytes). Padding fields use `random()` instead. +fn derive_field_mask(shared_secret: Point, index: u32) -> Field { + poseidon2_hash_with_separator( + [shared_secret.x, shared_secret.y], + DOM_SEP__CIPHERTEXT_FIELD_MASK + index, + ) +} + /// Produces a random valid address point, i.e. one that is on the curve. This is equivalent to calling /// [`AztecAddress::to_address_point`] on a random valid address. unconstrained fn random_address_point() -> AddressPoint { diff --git a/noir-projects/aztec-nr/aztec/src/utils/mod.nr b/noir-projects/aztec-nr/aztec/src/utils/mod.nr index 0e1b8653a442..f708bd7ad09c 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/mod.nr @@ -4,7 +4,6 @@ pub mod array; pub mod comparison; pub mod conversion; pub mod point; -pub mod random; mod with_hash; pub use with_hash::WithHash; pub mod remove_constraints; diff --git a/noir-projects/aztec-nr/aztec/src/utils/random.nr b/noir-projects/aztec-nr/aztec/src/utils/random.nr deleted file mode 100644 index 6cb65f361058..000000000000 --- a/noir-projects/aztec-nr/aztec/src/utils/random.nr +++ /dev/null @@ -1,17 +0,0 @@ -use crate::oracle::random::random; - -/// Returns as many random bytes as specified through N. -pub unconstrained fn get_random_bytes() -> [u8; N] { - let mut bytes = [0; N]; - let mut idx = 32; - let mut randomness = [0; 32]; - for i in 0..N { - if idx == 32 { - randomness = random().to_be_bytes(); - idx = 1; // Skip the first byte as it's always 0. - } - bytes[i] = randomness[idx]; - idx += 1; - } - bytes -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr b/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr index 98dbda352970..5ab1d49109e4 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr @@ -705,6 +705,7 @@ pub global DOM_SEP__AUTHWIT_NULLIFIER: u32 = 1239150694; pub global DOM_SEP__SYMMETRIC_KEY: u32 = 3882206064; pub global DOM_SEP__SYMMETRIC_KEY_2: u32 = 4129434989; +pub global DOM_SEP__CIPHERTEXT_FIELD_MASK: u32 = 1870492847; pub global DOM_SEP__PARTIAL_NOTE_VALIDITY_COMMITMENT: u32 = 623934423; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/constants_tests.nr b/noir-projects/noir-protocol-circuits/crates/types/src/constants_tests.nr index 699edf5b8b84..6f7c9dee1cc1 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/constants_tests.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/constants_tests.nr @@ -7,19 +7,19 @@ use crate::{ CONTRACT_CLASS_REGISTRY_UTILITY_FUNCTION_BROADCASTED_MAGIC_VALUE, CONTRACT_INSTANCE_PUBLISHED_MAGIC_VALUE, CONTRACT_INSTANCE_UPDATED_MAGIC_VALUE, DOM_SEP__AUTHWIT_INNER, DOM_SEP__AUTHWIT_NULLIFIER, DOM_SEP__AUTHWIT_OUTER, - DOM_SEP__BLOCK_HEADER_HASH, DOM_SEP__CONTRACT_ADDRESS_V1, DOM_SEP__CONTRACT_CLASS_ID, - DOM_SEP__EVENT_COMMITMENT, DOM_SEP__FUNCTION_ARGS, DOM_SEP__INITIALIZATION_NULLIFIER, - DOM_SEP__INITIALIZER, DOM_SEP__IVSK_M, DOM_SEP__MESSAGE_NULLIFIER, DOM_SEP__NHK_M, - DOM_SEP__NOTE_HASH, DOM_SEP__NOTE_HASH_NONCE, DOM_SEP__NOTE_NULLIFIER, DOM_SEP__OVSK_M, - DOM_SEP__PARTIAL_ADDRESS, DOM_SEP__PARTIAL_NOTE_VALIDITY_COMMITMENT, - DOM_SEP__PRIVATE_FUNCTION_LEAF, DOM_SEP__PRIVATE_LOG_FIRST_FIELD, DOM_SEP__PRIVATE_TX_HASH, - DOM_SEP__PROTOCOL_CONTRACTS, DOM_SEP__PUBLIC_BYTECODE, DOM_SEP__PUBLIC_CALLDATA, - DOM_SEP__PUBLIC_KEYS_HASH, DOM_SEP__PUBLIC_LEAF_SLOT, DOM_SEP__PUBLIC_STORAGE_MAP_SLOT, - DOM_SEP__PUBLIC_TX_HASH, DOM_SEP__SECRET_HASH, DOM_SEP__SIGNATURE_PAYLOAD, - DOM_SEP__SILOED_NOTE_HASH, DOM_SEP__SILOED_NULLIFIER, DOM_SEP__SYMMETRIC_KEY, - DOM_SEP__SYMMETRIC_KEY_2, DOM_SEP__TSK_M, DOM_SEP__TX_NULLIFIER, DOM_SEP__TX_REQUEST, - DOM_SEP__UNIQUE_NOTE_HASH, NULL_MSG_SENDER_CONTRACT_ADDRESS, SIDE_EFFECT_MASKING_ADDRESS, - TX_START_PREFIX, + DOM_SEP__BLOCK_HEADER_HASH, DOM_SEP__CIPHERTEXT_FIELD_MASK, DOM_SEP__CONTRACT_ADDRESS_V1, + DOM_SEP__CONTRACT_CLASS_ID, DOM_SEP__EVENT_COMMITMENT, DOM_SEP__FUNCTION_ARGS, + DOM_SEP__INITIALIZATION_NULLIFIER, DOM_SEP__INITIALIZER, DOM_SEP__IVSK_M, + DOM_SEP__MESSAGE_NULLIFIER, DOM_SEP__NHK_M, DOM_SEP__NOTE_HASH, DOM_SEP__NOTE_HASH_NONCE, + DOM_SEP__NOTE_NULLIFIER, DOM_SEP__OVSK_M, DOM_SEP__PARTIAL_ADDRESS, + DOM_SEP__PARTIAL_NOTE_VALIDITY_COMMITMENT, DOM_SEP__PRIVATE_FUNCTION_LEAF, + DOM_SEP__PRIVATE_LOG_FIRST_FIELD, DOM_SEP__PRIVATE_TX_HASH, DOM_SEP__PROTOCOL_CONTRACTS, + DOM_SEP__PUBLIC_BYTECODE, DOM_SEP__PUBLIC_CALLDATA, DOM_SEP__PUBLIC_KEYS_HASH, + DOM_SEP__PUBLIC_LEAF_SLOT, DOM_SEP__PUBLIC_STORAGE_MAP_SLOT, DOM_SEP__PUBLIC_TX_HASH, + DOM_SEP__SECRET_HASH, DOM_SEP__SIGNATURE_PAYLOAD, DOM_SEP__SILOED_NOTE_HASH, + DOM_SEP__SILOED_NULLIFIER, DOM_SEP__SYMMETRIC_KEY, DOM_SEP__SYMMETRIC_KEY_2, DOM_SEP__TSK_M, + DOM_SEP__TX_NULLIFIER, DOM_SEP__TX_REQUEST, DOM_SEP__UNIQUE_NOTE_HASH, + NULL_MSG_SENDER_CONTRACT_ADDRESS, SIDE_EFFECT_MASKING_ADDRESS, TX_START_PREFIX, }, hash::poseidon2_hash_bytes, traits::{FromField, ToField}, @@ -129,7 +129,7 @@ impl HashedValueTester::new(); + let mut tester = HashedValueTester::<50, 43>::new(); // ----------------- // Domain separators @@ -174,6 +174,7 @@ fn hashed_values_match_derived() { tester.assert_dom_sep_matches_derived(DOM_SEP__AUTHWIT_NULLIFIER, "authwit_nullifier"); tester.assert_dom_sep_matches_derived(DOM_SEP__SYMMETRIC_KEY, "symmetric_key"); tester.assert_dom_sep_matches_derived(DOM_SEP__SYMMETRIC_KEY_2, "symmetric_key_2"); + tester.assert_dom_sep_matches_derived(DOM_SEP__CIPHERTEXT_FIELD_MASK, "ciphertext_field_mask"); tester.assert_dom_sep_matches_derived( DOM_SEP__PARTIAL_NOTE_VALIDITY_COMMITMENT, "partial_note_validity_commitment", diff --git a/yarn-project/constants/src/constants.gen.ts b/yarn-project/constants/src/constants.gen.ts index 53bb162c97d7..568bd3723c9f 100644 --- a/yarn-project/constants/src/constants.gen.ts +++ b/yarn-project/constants/src/constants.gen.ts @@ -538,6 +538,7 @@ export enum DomainSeparator { AUTHWIT_NULLIFIER = 1239150694, SYMMETRIC_KEY = 3882206064, SYMMETRIC_KEY_2 = 4129434989, + CIPHERTEXT_FIELD_MASK = 1870492847, PARTIAL_NOTE_VALIDITY_COMMITMENT = 623934423, INITIALIZATION_NULLIFIER = 1653084894, SECRET_HASH = 4199652938,