From d22c7b1f69ea936c532fac68d19c6362f8a34be5 Mon Sep 17 00:00:00 2001 From: Tom French <15848336+TomAFrench@users.noreply.github.com> Date: Thu, 21 Sep 2023 19:12:19 +0100 Subject: [PATCH 01/12] feat(bb): avoid initializing CRS for `bb info` command (#2425) This PR executes the `bb info` command before we initialize the CRS as it doesn't require it. This avoids having to read a large amount of data from file / download from AWS when it is unnecessary. --- barretenberg/cpp/src/barretenberg/bb/main.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/barretenberg/cpp/src/barretenberg/bb/main.cpp b/barretenberg/cpp/src/barretenberg/bb/main.cpp index 2eae122b471f..72f0a95990c7 100644 --- a/barretenberg/cpp/src/barretenberg/bb/main.cpp +++ b/barretenberg/cpp/src/barretenberg/bb/main.cpp @@ -332,6 +332,14 @@ int main(int argc, char* argv[]) std::string vk_path = getOption(args, "-k", "./target/vk"); CRS_PATH = getOption(args, "-c", "./crs"); bool recursive = flagPresent(args, "-r") || flagPresent(args, "--recursive"); + + // Skip CRS initialization for any command which doesn't require the CRS. + if (command == "info") { + std::string output_path = getOption(args, "-o", "info.json"); + acvmInfo(output_path); + return 0; + } + init(); if (command == "prove_and_verify") { @@ -355,9 +363,6 @@ int main(int argc, char* argv[]) } else if (command == "vk_as_fields") { std::string output_path = getOption(args, "-o", vk_path + "_fields.json"); vkAsFields(vk_path, output_path); - } else if (command == "info") { - std::string output_path = getOption(args, "-o", "info.json"); - acvmInfo(output_path); } else { std::cerr << "Unknown command: " << command << "\n"; return 1; From 7d315cdb32a8cef809e7622718f2ea72456cec97 Mon Sep 17 00:00:00 2001 From: Santiago Palladino Date: Thu, 21 Sep 2023 15:56:14 -0300 Subject: [PATCH 02/12] feat(docs): Use preprocessor syntax for including versions (#2462) Introduces a new `#include_aztec_version` and `#include_noir_version` preprocessor macros that can be used to insert versions. Do not require escaping the triple-backtick code block, which is annoying in parsing. --- docs/README.md | 29 +- docs/docs/dev_docs/contracts/syntax/main.md | 17 +- .../dapps/tutorials/contract_deployment.md | 13 +- .../getting_started/noir_contracts.md | 9 +- .../token_contract_tutorial.md | 15 +- docs/src/preprocess/include_code.js | 324 +++++++++++++++++ docs/src/preprocess/include_version.js | 52 +++ docs/src/preprocess/index.js | 339 +----------------- 8 files changed, 444 insertions(+), 354 deletions(-) create mode 100644 docs/src/preprocess/include_code.js create mode 100644 docs/src/preprocess/include_version.js diff --git a/docs/README.md b/docs/README.md index 625823e2be1c..d07cc7f39814 100644 --- a/docs/README.md +++ b/docs/README.md @@ -56,10 +56,12 @@ Most changes are reflected live without having to restart the server. $ yarn build ``` -This command generates static content into the `build` directory and can be served using any static contents hosting service. +This command generates static content into the `build` directory and can be served using any static contents hosting service. When run on Netlify, it will also build the typescript projects needed for extracting type information via typedoc. -## #include_code macro +## Macros + +### `#include_code` You can embed code snippets into a `.md`/`.mdx` file from code which lives elsewhere in the repo. - In your markdown file: @@ -119,7 +121,26 @@ You can embed code snippets into a `.md`/`.mdx` file from code which lives elsew - `#include_code hello path/from/repo/root/to/file.ts typescript noTitle,noLineNumbers,noSourceLink` - Ironically, we can't show you a rendering of these examples, because this README.md file doesn't support the `#include_code` macro! +> See [here](./src/components/GithubCode/index.js) for another way to include code, although this approach is flakier, so the above `#include_code` macro is preferred. + +### `#include_aztec_version` + +This macros will be replaced inline with the current aztec packages tag, which is `aztec-packages-v0.7.10` at the time of these writing. This value is sourced from `.release-please-manifest.json` on the project root. -### Another way to include code. +Alternatively, you can also use the `AztecPackagesVersion()` js function, which you need to import explicitly: + +``` +import { AztecPackagesVersion } from "@site/src/components/Version"; +<>{AztecPackagesVersion()} +``` -See [here](./src/components/GithubCode/index.js), although this approach is flakier, so the above `#include_code` macro is preferred. \ No newline at end of file + ### `#include_noir_version` + +This macros will be replaced inline with the required nargo version, which is `0.11.1-aztec.0` at the time of these writing. This value is sourced from `yarn-project/noir-compiler/src/noir-version.json`. + +Alternatively, you can also use the `NoirVersion()` js function, which you need to import explicitly: + +``` +import { NoirVersion } from "@site/src/components/Version"; +<>{NoirVersion()} +``` diff --git a/docs/docs/dev_docs/contracts/syntax/main.md b/docs/docs/dev_docs/contracts/syntax/main.md index c89e97a1a2db..124e271e7eea 100644 --- a/docs/docs/dev_docs/contracts/syntax/main.md +++ b/docs/docs/dev_docs/contracts/syntax/main.md @@ -18,22 +18,21 @@ Aztec.nr contains abstractions which remove the need to understand the low-level To import Aztec.nr into your Aztec contract project, simply include it as a dependency. For example: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] +```toml +[package] name = "token_contract" authors = [""] compiler_version = "0.1" type = "contract" - + [dependencies] # Framework import -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } - +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } + # Utility dependencies -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` :::info Note: currently the dependency name ***MUST*** be `aztec`. The framework expects this namespace to be available when compiling into contracts. This limitation may be removed in the future. diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md b/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md index d677b403f771..36972b19fc7b 100644 --- a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md +++ b/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md @@ -17,13 +17,12 @@ nargo new --contract token Then, open the `contracts/token/Nargo.toml` configuration file, and add the `aztec.nr` and `value_note` libraries as dependencies: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} +```toml +[dependencies] +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` Last, copy-paste the code from the `Token` contract into `contracts/token/main.nr`: diff --git a/docs/docs/dev_docs/getting_started/noir_contracts.md b/docs/docs/dev_docs/getting_started/noir_contracts.md index 65adc75609fd..d05a4cafbb4a 100644 --- a/docs/docs/dev_docs/getting_started/noir_contracts.md +++ b/docs/docs/dev_docs/getting_started/noir_contracts.md @@ -59,17 +59,16 @@ Before writing the contracts, we must add the aztec.nr library. This adds smart 3. Add aztec.nr library as a dependency to your noir project. Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] +```toml +[package] name = "example_contract" authors = [""] compiler_version = "0.1" type = "contract" [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="master", directory="yarn-project/aztec-nr/aztec" } -`} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +``` :::note You may need to update your dependencies depending on the contract that you are writing. For example, the token contract [imports more](../getting_started/token_contract_tutorial#project-setup). diff --git a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md b/docs/docs/dev_docs/getting_started/token_contract_tutorial.md index d53e63c161db..64a61a5faae5 100644 --- a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md +++ b/docs/docs/dev_docs/getting_started/token_contract_tutorial.md @@ -80,19 +80,18 @@ Your project should look like this: Add the following dependencies to your Nargo.toml file, below the package information: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] +```toml +[package] name = "token_contract" authors = [""] compiler_version = "0.1" type = "contract" - + [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` ## Contract Interface diff --git a/docs/src/preprocess/include_code.js b/docs/src/preprocess/include_code.js new file mode 100644 index 000000000000..1e87b9aa3513 --- /dev/null +++ b/docs/src/preprocess/include_code.js @@ -0,0 +1,324 @@ +const fs = require("fs"); +const path = require("path"); +const childProcess = require("child_process"); + +const getLineNumberFromIndex = (fileContent, index) => { + return fileContent.substring(0, index).split("\n").length; +}; + +/** + * Search for lines of the form + */ +function processHighlighting(codeSnippet, identifier) { + const lines = codeSnippet.split("\n"); + /** + * For an identifier = bar: + * + * Matches of the form: `highlight-next-line:foo:bar:baz` will be replaced with "highlight-next-line". + * Matches of the form: `highlight-next-line:foo:baz` will be replaced with "". + */ + const regex1 = /highlight-next-line:([a-zA-Z0-9-._:]+)/; + const replacement1 = "highlight-next-line"; + const regex2 = /highlight-start:([a-zA-Z0-9-._:]+)/; + const replacement2 = "highlight-start"; + const regex3 = /highlight-end:([a-zA-Z0-9-._:]+)/; + const replacement3 = "highlight-end"; + const regex4 = /this-will-error:([a-zA-Z0-9-._:]+)/; + const replacement4 = "this-will-error"; + + let result = ""; + let mutated = false; + + const processLine = (line, regex, replacement) => { + const match = line.match(regex); + if (match) { + mutated = true; + + const identifiers = match[1].split(":"); + if (identifiers.includes(identifier)) { + line = line.replace(match[0], replacement); + } else { + // Remove matched text completely + line = line.replace(match[0], ""); + } + } else { + // No match: it's an ordinary line of code. + } + return line.trim() == "//" || line.trim() == "#" ? "" : line; + }; + + for (let line of lines) { + mutated = false; + line = processLine(line, regex1, replacement1); + line = processLine(line, regex2, replacement2); + line = processLine(line, regex3, replacement3); + line = processLine(line, regex4, replacement4); + result += line === "" && mutated ? "" : line + "\n"; + } + + return result.trim(); +} + +let lastReleasedVersion; + +/** Returns the last released tag */ +function getLatestTag() { + if (!lastReleasedVersion) { + const manifest = path.resolve( + __dirname, + "../../../.release-please-manifest.json" + ); + lastReleasedVersion = JSON.parse(fs.readFileSync(manifest).toString())["."]; + } + return lastReleasedVersion + ? `aztec-packages-v${lastReleasedVersion}` + : undefined; +} + +/** Returns whether to use the latest release or the current version of stuff. */ +function useLastRelease() { + return process.env.NETLIFY || process.env.INCLUDE_RELEASED_CODE; +} + +/** + * Returns the contents of a file. If the build is running for publishing, it will load the contents + * of the file in the last released version. + */ +function readFile(filePath, tag) { + if (tag && tag !== "master") { + try { + const tag = getLatestTag(); + const root = path.resolve(__dirname, "../../../"); + const relPath = path.relative(root, filePath); + return childProcess.execSync(`git show ${tag}:${relPath}`).toString(); + } catch (err) { + console.error( + `Error reading file ${relPath} from latest version. Falling back to current content.` + ); + } + } + return fs.readFileSync(filePath, "utf-8"); +} + +/** Extracts a code snippet, trying with the last release if applicable, and falling back to current content. */ +function extractCodeSnippet(filePath, identifier) { + if (useLastRelease()) { + try { + return doExtractCodeSnippet(filePath, identifier, false); + } catch (err) { + console.error( + `Error extracting code snippet ${identifier} for ${filePath}: ${err}. Falling back to current content.` + ); + } + } + + return doExtractCodeSnippet(filePath, identifier, true); +} + +/** + * Parse a code file, looking for identifiers of the form: + * `docs:start:${identifier}` and `docs:end:{identifier}`. + * Extract that section of code. + * + * It's complicated if code snippet identifiers overlap (i.e. the 'start' of one code snippet is in the + * middle of another code snippet). The extra logic in this function searches for all identifiers, and + * removes any which fall within the bounds of the code snippet for this particular `identifier` param. + * @returns the code snippet, and start and end line numbers which can later be used for creating a link to github source code. + */ +function doExtractCodeSnippet(filePath, identifier, useCurrent) { + const tag = useCurrent ? "master" : getLatestTag(); + let fileContent = readFile(filePath, tag); + let lineRemovalCount = 0; + let linesToRemove = []; + + const startRegex = /(?:\/\/|#)\s+docs:start:([a-zA-Z0-9-._:]+)/g; // `g` will iterate through the regex.exec loop + const endRegex = /(?:\/\/|#)\s+docs:end:([a-zA-Z0-9-._:]+)/g; + + /** + * Search for one of the regex statements in the code file. If it's found, return the line as a string and the line number. + */ + const lookForMatch = (regex) => { + let match; + let matchFound = false; + let matchedLineNum = null; + let actualMatch = null; + let lines = fileContent.split("\n"); + while ((match = regex.exec(fileContent))) { + if (match !== null) { + const identifiers = match[1].split(":"); + let tempMatch = identifiers.includes(identifier) ? match : null; + + if (tempMatch === null) { + // If it's not a match, we'll make a note that we should remove the matched text, because it's from some other identifier and should not appear in the snippet for this identifier. + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + if (line.trim() == match[0].trim()) { + linesToRemove.push(i + 1); // lines are indexed from 1 + ++lineRemovalCount; + } + } + } else { + if (matchFound === true) { + throw new Error( + `Duplicate for regex ${regex} and identifier ${identifier}` + ); + } + matchFound = true; + matchedLineNum = getLineNumberFromIndex(fileContent, tempMatch.index); + actualMatch = tempMatch; + } + } + } + + return [actualMatch, matchedLineNum]; + }; + + let [startMatch, startLineNum] = lookForMatch(startRegex); + let [endMatch, endLineNum] = lookForMatch(endRegex); + + // Double-check that the extracted line actually contains the required start and end identifier. + if (startMatch !== null) { + const startIdentifiers = startMatch[1].split(":"); + startMatch = startIdentifiers.includes(identifier) ? startMatch : null; + } + if (endMatch !== null) { + const endIdentifiers = endMatch[1].split(":"); + endMatch = endIdentifiers.includes(identifier) ? endMatch : null; + } + + if (startMatch === null || endMatch === null) { + if (startMatch === null && endMatch === null) { + throw new Error( + `Identifier "${identifier}" not found in file "${filePath}"` + ); + } else if (startMatch === null) { + throw new Error( + `Start line "docs:start:${identifier}" not found in file "${filePath}"` + ); + } else { + throw new Error( + `End line "docs:end:${identifier}" not found in file "${filePath}"` + ); + } + } + + let lines = fileContent.split("\n"); + + // We only want to remove lines which actually fall within the bounds of our code snippet, so narrow down the list of lines that we actually want to remove. + linesToRemove = linesToRemove.filter((lineNum) => { + const removal_in_bounds = lineNum >= startLineNum && lineNum <= endLineNum; + return removal_in_bounds; + }); + + // Remove lines which contain `docs:` comments for unrelated identifiers: + lines = lines.filter((l, i) => { + return !linesToRemove.includes(i + 1); // lines are indexed from 1 + }); + + // Remove lines from the snippet which fall outside the `docs:start` and `docs:end` values. + lines = lines.filter((l, i) => { + return i + 1 > startLineNum && i + 1 < endLineNum - linesToRemove.length; // lines are indexed from 1 + }); + + // We have our code snippet! + let codeSnippet = lines.join("\n"); + + // The code snippet might contain some docusaurus highlighting comments for other identifiers. We should remove those. + codeSnippet = processHighlighting(codeSnippet, identifier); + + return [codeSnippet, startLineNum, endLineNum, tag]; +} + +/** + * Explaining this regex: + * + * E.g. `#include_code snippet_identifier /circuits/my_code.cpp cpp` + * + * #include_code\s+(\S+)\s+(\S+)\s+(\S+) + * - This is the main regex to match the above format. + * - \s+: one or more whitespace characters (space or tab) after `include_code` command. + * - (\S+): one or more non-whitespaced characters. Captures this as the first argument, which is a human-readable identifier for the code block. + * - etc. + * + * Lookaheads are needed to allow us to ignore commented-out lines: + * + * ^(?! + +## Set up for aztec.nr contracts + +1. Inside the yarn project you created from the [Sanbox page](../getting_started/sandbox.md), create a sub-folder where the contracts will reside. + +```bash +mkdir contracts +``` + +All contract projects will reside within this folder. Note that contracts don't actually have to live here and this is just a style choice. + +2. Next, create a noir project using nargo by running the following in the terminal from the `contracts` folder + +```bash +cd contracts +nargo new --contract example_contract +``` + +This creates `example_contract` directory within contracts which is a noir project with: + +- a Nargo.toml (which is the manifest file of the project) at `example_contract/Nargo.toml`. +- a main.nr file (the file where our contract will reside) at `example_contract/src/main.nr`. + +Your folder should look like: + +```tree +. +|-contracts +| |--example_contract +| | |--src +| | | |--main.nr +| | |--Nargo.toml +|-src +| |--index.ts +``` + +Before writing the contracts, we must add the aztec.nr library. This adds smart contract utility functions for interacting with the Aztec network. + +3. Finally, add relevant aztec-nr dependencies that you might use such as `aztec.nr`, `value_note` and `safe_math` libraries. + +Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows + +```toml +[package] +name = "example_contract" +authors = [""] +compiler_version = "0.1" +type = "contract" + +[dependencies] +# Framework import +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } + +# Utility dependencies +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` + +:::info +Note: currently the dependency name **_MUST_** be `aztec`. The framework expects this namespace to be available when compiling into contracts. This limitation may be removed in the future. +::: + +You are now ready to write your own contracts! + +## Next Steps + +- Read up about how to [write a contract](./syntax/main.md) OR +- Follow a [tutorial](../tutorials/main.md) diff --git a/docs/docs/dev_docs/contracts/syntax/main.md b/docs/docs/dev_docs/contracts/syntax/main.md index 124e271e7eea..59c7d8a7f7ba 100644 --- a/docs/docs/dev_docs/contracts/syntax/main.md +++ b/docs/docs/dev_docs/contracts/syntax/main.md @@ -1,4 +1,5 @@ import DocCardList from '@theme/DocCardList'; +import { AztecPackagesVersion } from "@site/src/components/Version"; # Aztec.nr Syntax @@ -16,26 +17,6 @@ Aztec.nr contains abstractions which remove the need to understand the low-level - secrets - Functions for communicating with [Ethereum L1](../portals/main.md) -To import Aztec.nr into your Aztec contract project, simply include it as a dependency. For example: - -```toml -[package] -name = "token_contract" -authors = [""] -compiler_version = "0.1" -type = "contract" - -[dependencies] -# Framework import -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } - -# Utility dependencies -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} -``` - -:::info -Note: currently the dependency name ***MUST*** be `aztec`. The framework expects this namespace to be available when compiling into contracts. This limitation may be removed in the future. -::: +To setup a aztec-nr project, follow the [setup instructions](../setup.md) diff --git a/docs/docs/dev_docs/contracts/workflow.md b/docs/docs/dev_docs/contracts/workflow.md index eb4641cbc8d1..f0d9bbe1b9d1 100644 --- a/docs/docs/dev_docs/contracts/workflow.md +++ b/docs/docs/dev_docs/contracts/workflow.md @@ -2,6 +2,9 @@ title: Contract Workflow --- +## Setup +[Set up your project](./setup.md) + ## Write [Write a contract](./syntax/main.md). diff --git a/docs/docs/dev_docs/getting_started/noir_contracts.md b/docs/docs/dev_docs/getting_started/noir_contracts.md deleted file mode 100644 index d05a4cafbb4a..000000000000 --- a/docs/docs/dev_docs/getting_started/noir_contracts.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Aztec.nr Contracts Quickstart ---- - -## Introduction - -This guide explains the set up required to write a contract using the Aztec.nr library; then deploy it to the sandbox. Aztec.nr is a library on top of [Noir](https://noir-lang.org/) that can be used to write smart contracts for Aztec. Since Noir files use the `.nr` extension, we are calling this library "Aztec.nr". - -:::info Prerequisite reading -If you haven't read [Aztec Sandbox](./sandbox.md), we recommend going there first. -::: - -### Dependencies - -#### `nargo` - -Nargo is Noir's build tool. On your terminal, run: - - - -#### Aztec Sandbox - -You need to setup the [Aztec sandbox](./sandbox.md). - - - -## Set up for aztec.nr contracts - -1. Inside the yarn project you created from the [Aztec.js](./sandbox.md) page, create a sub-folder where the contracts will reside. - -```bash -mkdir contracts -``` - -All contract projects will reside within this folder. Note that contracts don't actually have to live here and this is just a style choice. - -2. Next, create a noir project using nargo by running the following in the terminal from the `contracts` folder - -```bash -cd contracts -nargo new example_contract -``` - -This creates a noir project with a Nargo.toml (which is the manifest file of the project). This file is found at `example_contract/src/main.nr`, where we will write our contract. - -Your folder should look like: - -``` -. -|-contracts -| |--example_contract -| | |--src -| | | |--main.nr -|-src -| |--index.ts -``` - -Before writing the contracts, we must add the aztec.nr library. This adds smart contract utility functions for interacting with the Aztec network. - -3. Add aztec.nr library as a dependency to your noir project. Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows: - -```toml -[package] -name = "example_contract" -authors = [""] -compiler_version = "0.1" -type = "contract" - -[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } -``` - -:::note -You may need to update your dependencies depending on the contract that you are writing. For example, the token contract [imports more](../getting_started/token_contract_tutorial#project-setup). -::: - -You are now ready to write your own contracts! - -You can replace the content of the generated file `example_contract/src/main.nr` with your contract code. - -## Next Steps - -- You can learn more about writing contracts from the [Contracts section](../contracts/main.md). -- You can find more example Aztec contracts [here](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts). -- Consider going through the [token contract tutorial](./token_contract_tutorial.md) for a deep dive on writing more advanced Aztec contracts and an introduction to some of the concepts that underpin the Aztec network architecture. -- After writing the contract, you have to compile it. Details can be found [here](../contracts/compiling.md). -- After compiling, you can deploy your contract to the Aztec network. Relevant instructions and explanations can be found [here](../contracts/deploying.md). -- Thereafter, you can interact with the contracts similar to how it was shown in the the [Creating and submitting transactions section on the Sandbox page](./sandbox.md#creating-and-submitting-transactions). diff --git a/docs/docs/dev_docs/getting_started/quickstart.md b/docs/docs/dev_docs/getting_started/quickstart.md index f75879a0a74e..51e0233b0d5f 100644 --- a/docs/docs/dev_docs/getting_started/quickstart.md +++ b/docs/docs/dev_docs/getting_started/quickstart.md @@ -87,7 +87,7 @@ The default accounts that come with sandbox will likely change over time. Save t #include_code declare-accounts yarn-project/end-to-end/src/guides/up_quick_start.sh bash -Start by deploying a token contract. After it is deployed, we check that the deployment succeeded, export the deployment address to use in future commands and then call the `_initialize` function. For more detail on how the token contract works, see the [token contract tutorial](./token_contract_tutorial). +Start by deploying a token contract. After it is deployed, we check that the deployment succeeded, export the deployment address to use in future commands and then call the `_initialize` function. For more detail on how the token contract works, see the [token contract tutorial](../tutorials/writing_token_contract.md). #include_code deploy yarn-project/end-to-end/src/guides/up_quick_start.sh bash @@ -97,7 +97,7 @@ Note that the deployed contract address is exported, so we can use it as `$CONTR Alice is set up as the contract admin and token minter in the `_initialize` function. Let's get Alice some private tokens. -We need to export the `SECRET` and `SECRET_HASH` values in order to privately mint tokens. Private tokens are claimable by anyone with the pre-image to a provided hash, see more about how the token contract works in the [token contract tutorial](./token_contract_tutorial.md). Once the tokens have been minted, Alice can claim them with the `redeem_shield` function. After this, Alice should have 1000 tokens in their private balance. +We need to export the `SECRET` and `SECRET_HASH` values in order to privately mint tokens. Private tokens are claimable by anyone with the pre-image to a provided hash, see more about how the token contract works in the [token contract tutorial](../tutorials/writing_token_contract.md). Once the tokens have been minted, Alice can claim them with the `redeem_shield` function. After this, Alice should have 1000 tokens in their private balance. #include_code mint-private yarn-project/end-to-end/src/guides/up_quick_start.sh bash @@ -116,4 +116,5 @@ Aztec's Layer 2 network is a fully programmable combined private/public ZK rollu - Aztec Node - Aggregates all of the 'backend' services necessary for the building and publishing of rollups. - Aztec RPC Server - Normally residing with the end client, this decrypts and stores a client's private state, executes simulations and submits transactions to the Aztec Node. - [Aztec.js](./sandbox) - Aztec's client library for interacting with the Aztec RPC Server (think Ethers.js). -- [Write your own contracts](./noir_contracts.md) +- [Aztec.nr](../contracts/main.md) - Aztec's smart contract framework + diff --git a/docs/docs/dev_docs/getting_started/sandbox.md b/docs/docs/dev_docs/getting_started/sandbox.md index 32a663537474..b61591004006 100644 --- a/docs/docs/dev_docs/getting_started/sandbox.md +++ b/docs/docs/dev_docs/getting_started/sandbox.md @@ -8,18 +8,24 @@ import Image from "@theme/IdealImage"; The Aztec Sandbox aims to provide a local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. +:::info +For a quickstart checkout [the Quickstart section](./quickstart.md) +::: + Here we will walkthrough the process of retrieving the Sandbox, installing the client libraries and using it to deploy and use a fully private token contract on the Aztec network using Aztec.js. -## What do you need? +You can find the [complete tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token). + +## Prerequisites - Node.js >= v18 - Docker and Docker Compose (Docker Desktop under WSL2 on windows) That's it... -## Ok, so how do I try it out? +## Install the Sandbox -You can just curl the site like this: +In your terminal: ```sh /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" @@ -36,17 +42,15 @@ Within a few seconds the Sandbox should be up and running! -## I have the Sandbox running, show me how to use it - -We will deploy a token contract, and send tokens privately, using the Sandbox. You can see the final result of the [tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token), if you don't want to follow along, copy and pasting the example code. +## Project setup -Writing the contract itself is out of scope for this tutorial, so we will use a Token Contract which has been pre-supplied as an example. See [here](../contracts/main.md) for more information on how to write contracts for Aztec. +We will deploy a pre-compiled token contract, and send tokens privately, using the Sandbox. -The following should work for MacOS, Linux or even WSL2 Ubuntu under Windows. +:::info +If you don't want to follow along and copy pasting step-by-step, the full code repository is available [here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token) +::: -Let's create an empty project called `token`. If you are familiar with setting up Typescript projects then you can skip to step 6. - -Although both `yarn` and `npm` would work, this example uses `yarn`. Open the terminal and do the following +We will create a `yarn` project called `token` (although npm works fine too). If you are familiar with setting up Javascript/Typescript projects then you can skip to step 6. 1. Ensure node version is 18 or higher by running @@ -59,22 +63,22 @@ node -v ```sh mkdir token cd token -yarn init +yarn init -yp ``` -1. Create a `src` folder inside your new `token` directory: +3. Create a `src` folder inside your new `token` directory: ```sh mkdir src ``` -4. Add typescript to the yarn project +4. Add necessary yarn packages (and optionally add typescript too) ```sh -yarn add typescript @types/node --dev +yarn add @aztec/aztec.js @aztec/noir-contracts typescript @types/node ``` -Add a `tsconfig.json` file into the project root, here is an example: +5. [Optional] If creating a typescript file, add a `tsconfig.json` file into the project root, here is an example: ```json { @@ -102,7 +106,7 @@ Add a `tsconfig.json` file into the project root, here is an example: } ``` -5. Add a `scripts` section to `package.json` and set `"type": "module"`: +6. Update `package.json` - Add a `scripts` section to `package.json` and set `"type": "module"`: ```json { @@ -119,20 +123,22 @@ Add a `tsconfig.json` file into the project root, here is an example: "clean": "rm -rf ./dest tsconfig.tsbuildinfo", "start": "yarn build && DEBUG='token' node ./dest/index.js" }, - "devDependencies": { - "@types/node": "^20.4.9", - "typescript": "^5.1.6" + "dependencies": { + "@aztec/aztec.js": "^0.7.10", + "@aztec/noir-contracts": "^0.7.10", + "@types/node": "^20.6.3", + "typescript": "^5.2.2" } } ``` -6. Next, install Aztec related dependencies +7. Next, install Aztec related dependencies ```sh yarn add @aztec/aztec.js @aztec/noir-contracts ``` -7. Create an `index.ts` file in the `src` directory with the following sandbox connection setup: +8. Create an `index.ts` file in the `src` directory with the following sandbox connection setup: ```ts #include_code imports /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts raw @@ -144,7 +150,9 @@ async function main() { main(); ``` -8. Finally, run the package: +9. Finally, run the package: + +In the project root, run ```sh yarn start @@ -166,48 +174,21 @@ A successful run should show: Great! The Sandbox is running and we are able to interact with it. -## Account Creation/Deployment - -The next step is to create some accounts. An in-depth explaining about accounts on aztec can be found [here](../../concepts/foundation/accounts/main.md). But creating an account on the Sandbox does 2 things: +## Accounts -1. Deploys an account contract -- representing you -- allowing you to perform actions on the network (deploy contracts, call functions etc). -2. Adds your encryption keys to the RPC Server allowing it to decrypt and manage your private state. +The sandbox is preloaded with multiple accounts so you don't have to sit and create them. Let's load these accounts -Continue with adding the following to the `index.ts` file in our example: +#include_code load_accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript -#include_code Accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript +An explanation on accounts on Aztec can be found [here](../../concepts/foundation/accounts/main.md). -Running `yarn start` should now output: - -``` - token Aztec Sandbox Info { - version: 1, - chainId: 31337, - rollupAddress: EthAddress { - buffer: - }, - client: 'aztec-rpc@0.1.0', - compatibleNargoVersion: '0.11.1-aztec.0' - } - token Creating accounts using schnorr signers... +3ms - token Created Alice's account at 0x1509b252...0027 +10s - token Created Bob's account at 0x031862e8...e7a3 +0ms -``` - -That might seem like a lot to digest but it can be broken down into the following steps: - -1. We create 2 `Account` objects in Typescript. This object heavily abstracts away the mechanics of configuring and deploying an account contract and setting up a 'wallet' for signing transactions. If you aren't interested in building new types of account contracts or wallets then you don't need to be too concerned with it. In this example we have constructed account contracts and corresponding wallets that sign/verify transactions using schnorr signatures. -2. We wait for the deployment of the 2 account contracts to complete. -3. We retrieve the expected account addresses from the `Account` objects and ensure that they are present in the set of account addresses registered on the Sandbox. - -Note, we use the `getRegisteredAccounts` API to verify that the addresses computed as part of the -account contract deployment have been successfully added to the Sandbox. - -If you were looking at your terminal that is running the Sandbox you should have seen a lot of activity. This is because the Sandbox will have simulated the deployment of both contracts, executed the private kernel circuit for each before submitted 2 transactions to the pool. The sequencer will have picked them up and inserted them into a rollup and executed the recursive rollup circuits before publishing the rollup to Anvil. Once this has completed, the rollup is retrieved and pulled down to the internal RPC Server so that any new account state can be decrypted. +If you want more accounts, you can find instructions in the [Account creation section](../wallets/creating_schnorr_accounts.md). ## Token Contract Deployment -Now that we have our accounts setup, let's move on to deploy our private token contract. Add this to `index.ts` below the code you added earlier: +Writing a contract from scratch is beyond the scope of this page. Feel free to look at the [Token contract tutorial](../tutorials/writing_token_contract.md) or the section on aztec-noir contracts [here](../contracts/main.md) + +Now that we have our accounts loaded, let's move on to deploy our pre-compiled token contract. Add this to `index.ts` below the code you added earlier: #include_code Deployment /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript @@ -369,4 +350,4 @@ You can find the [complete tutorial code here](https://github.com/AztecProtocol/ Here we showed how to interact with the sandbox, but didn't go into details on how to write your own contract or any relevant setup needed for it. -You can find more information about writing Aztec contracts [here](./noir_contracts.md) and refer to the [Contracts section](../contracts/main.md) on syntax, compiling, deploying and interacting with how to start writing contracts. +You can find more information about writing Aztec contracts [here](../contracts/main.md) on syntax, compiling, deploying and interacting with how to start writing contracts. diff --git a/docs/docs/dev_docs/sandbox/main.md b/docs/docs/dev_docs/sandbox/main.md deleted file mode 100644 index 66d4e60c755e..000000000000 --- a/docs/docs/dev_docs/sandbox/main.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Aztec Sandbox ---- - -## What is the Aztec Sandbox? - -The Aztec Sandbox is local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. - -For a complete walk-through deploying and using a private contract with the Sandbox and CLI, see our [quickstart](../getting_started/quickstart). diff --git a/docs/docs/dev_docs/sandbox/common_errors.md b/docs/docs/dev_docs/sandbox_errors/main.md similarity index 100% rename from docs/docs/dev_docs/sandbox/common_errors.md rename to docs/docs/dev_docs/sandbox_errors/main.md diff --git a/docs/docs/dev_docs/testing/testing.md b/docs/docs/dev_docs/testing/testing.md index d8bdf31adbe7..8ae02751cdb6 100644 --- a/docs/docs/dev_docs/testing/testing.md +++ b/docs/docs/dev_docs/testing/testing.md @@ -8,7 +8,7 @@ We will be using typescript to write our tests, and rely on the [`aztec.js`](htt ## A simple example -Let's start with a simple example for a test using the [Sandbox](../sandbox/main.md). We will create two accounts and deploy a token contract in a setup step, and then issue a transfer from one user to another. +Let's start with a simple example for a test using the [Sandbox](../getting_started/sandbox.md#install-the-sandbox). We will create two accounts and deploy a token contract in a setup step, and then issue a transfer from one user to another. #include_code sandbox-example /yarn-project/end-to-end/src/guides/dapp_testing.test.ts typescript diff --git a/docs/docs/dev_docs/tutorials/main.md b/docs/docs/dev_docs/tutorials/main.md new file mode 100644 index 000000000000..da6889b6fc80 --- /dev/null +++ b/docs/docs/dev_docs/tutorials/main.md @@ -0,0 +1,3 @@ +import DocCardList from '@theme/DocCardList'; + + diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md similarity index 97% rename from docs/docs/dev_docs/dapps/tutorials/contract_deployment.md rename to docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md index 36972b19fc7b..033f155ccfd2 100644 --- a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md @@ -3,7 +3,7 @@ To add contracts to your application, we'll start by creating a new `nargo` project. We'll then compile the contracts, and write a simple script to deploy them to our Sandbox. :::info -Follow the instructions [here](../../getting_started/noir_contracts.md) to install `nargo` if you haven't done so already. +Follow the instructions [here](../../contracts/setup.md) to install `nargo` if you haven't done so already. ::: ## Initialise nargo project diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_interaction.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md similarity index 100% rename from docs/docs/dev_docs/dapps/tutorials/contract_interaction.md rename to docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md diff --git a/docs/docs/dev_docs/dapps/tutorials/main.md b/docs/docs/dev_docs/tutorials/writing_dapp/main.md similarity index 92% rename from docs/docs/dev_docs/dapps/tutorials/main.md rename to docs/docs/dev_docs/tutorials/writing_dapp/main.md index 0685ab032a30..e62d47301272 100644 --- a/docs/docs/dev_docs/dapps/tutorials/main.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/main.md @@ -13,8 +13,8 @@ The full code for this tutorial is [available on the `aztec-packages` repository - Linux or OSX environment - [NodeJS](https://nodejs.org/) 18 or higher - [Aztec Sandbox](../../getting_started/sandbox.md) -- [Aztec CLI](../../cli/cli.md) -- [Nargo](../../getting_started/noir_contracts.md) for building contracts +- [Aztec CLI](../../cli/main.md) +- [Nargo](../../contracts/setup.md) for building contracts ## Prerequisites diff --git a/docs/docs/dev_docs/dapps/tutorials/project_setup.md b/docs/docs/dev_docs/tutorials/writing_dapp/project_setup.md similarity index 100% rename from docs/docs/dev_docs/dapps/tutorials/project_setup.md rename to docs/docs/dev_docs/tutorials/writing_dapp/project_setup.md diff --git a/docs/docs/dev_docs/dapps/tutorials/rpc_server.md b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md similarity index 87% rename from docs/docs/dev_docs/dapps/tutorials/rpc_server.md rename to docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md index 4df09e27b9e7..23767890cb91 100644 --- a/docs/docs/dev_docs/dapps/tutorials/rpc_server.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md @@ -2,7 +2,7 @@ As an app developer, the [Aztec RPC Server](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec-rpc) interface provides you with access to the user's accounts and their private state, as well as a connection to the network for accessing public global state. -During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../sandbox/main.md), which runs a local RPC Server and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialised accounts that you can use from your app. +During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../getting_started/sandbox.md), which runs a local RPC Server and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialised accounts that you can use from your app. In this section, we'll connect to the Sandbox from our project. diff --git a/docs/docs/dev_docs/dapps/tutorials/testing.md b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md similarity index 96% rename from docs/docs/dev_docs/dapps/tutorials/testing.md rename to docs/docs/dev_docs/tutorials/writing_dapp/testing.md index 24da56dbf84d..7083e22a6582 100644 --- a/docs/docs/dev_docs/dapps/tutorials/testing.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md @@ -56,4 +56,4 @@ yarn node --experimental-vm-modules $(yarn bin jest) --testRegex '.*\.test\.mjs$ ## Next steps -Now that you have finished the tutorial, you can learn more about [writing contracts with Noir](../../contracts/main.md), check out the [Sandbox's architecture](../../sandbox/main.md), or read about the [fundamental concepts behind Aztec Network](../../../concepts/foundation/main.md). +Now that you have finished the tutorial, you can learn more about [writing contracts with Noir](../../contracts/main.md) or read about the [fundamental concepts behind Aztec Network](../../../concepts/foundation/main.md). diff --git a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md b/docs/docs/dev_docs/tutorials/writing_token_contract.md similarity index 97% rename from docs/docs/dev_docs/getting_started/token_contract_tutorial.md rename to docs/docs/dev_docs/tutorials/writing_token_contract.md index 64a61a5faae5..018592b978fe 100644 --- a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md +++ b/docs/docs/dev_docs/tutorials/writing_token_contract.md @@ -1,7 +1,7 @@ -# Token Contract Tutorial +# Writing a Standard token contract in Aztec.nr In this tutorial we will go through writing a standard L2 native token contract -for the Aztec Network, using the Aztec.nr contract libraries. It is recommended that you go through the [the introduction to contracts](./noir_contracts) section before this tutorial to gain some familiarity with writing Aztec smart contracts. +for the Aztec Network, using the Aztec.nr contract libraries. It is recommended that you go through the [the introduction to contracts](../contracts/main.md) and [setup instructions](../contracts/setup.md) section before this tutorial to gain some familiarity with writing Aztec smart contracts. This tutorial is intended to help you get familiar with the Aztec.nr library, Aztec contract syntax and some of the underlying structure of the Aztec network. @@ -14,7 +14,7 @@ In this tutorial you will learn how to: - Handle different private note types - Pass data between private and public state -We are going to start with a blank project and fill in the code defined [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr), and explain what is being added as we go. +We are going to start with a blank project and fill in the token contract source code defined [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr), and explain what is being added as we go. ## Requirements @@ -22,7 +22,7 @@ You will need to install nargo, the Noir build too. if you are familiar with Rus -If you've already installed the `aztec-cli`, as described in the quickstart [here](./quickstart#cli), you can check which version of Noir is compatible with your version of the CLI and sandbox by running: +If you've already installed the `aztec-cli`, as described in the quickstart [here](../getting_started/quickstart.md#cli), you can check which version of Noir is compatible with your version of the CLI and sandbox by running: ```bash aztec-cli get-node-info @@ -65,7 +65,7 @@ cd token_contract_tutorial && mkdir contracts && cd contracts Create a new Noir project using nargo. ```bash -nargo init --name token_contract +nargo new --contract token_contract ``` Your project should look like this: @@ -486,7 +486,7 @@ This must be included in every contract because it depends on the storage slots, ## Compiling -Now that the contract is complete, you should be able to compile it with the `aztec-cli`. See the [CLI page](../cli/cli.md) for instructions on setting it up. +Now that the contract is complete, you should be able to compile it with the `aztec-cli`. See the [CLI page](../cli/main.md) for instructions on setting it up. ```bash aztec-cli compile /path/to/token_contracts_folder diff --git a/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md new file mode 100644 index 000000000000..ea9e1cda5f5a --- /dev/null +++ b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md @@ -0,0 +1,60 @@ +--- +title: Creating Schnorr Accounts +--- + +## Introduction + +This section shows how to create schnorr account wallets on the Aztec Sandbox. + +An in-depth explaining about accounts on aztec can be found [here](../../concepts/foundation/accounts/main.md). But creating an account on the Sandbox does 2 things: + +1. Deploys an account contract -- representing you -- allowing you to perform actions on the network (deploy contracts, call functions etc). +2. Adds your encryption keys to the RPC Server allowing it to decrypt and manage your private state. + +## Pre-requisites + +Have a running Sandbox and a repository that interacts with it as explained [here](../getting_started/sandbox.md). + +Let's assume you have a file `src/index.ts` from the example used in the Sandbox page. + +## Create accounts on the sandbox + +1. Import relevant modules: + +#include_code imports /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript + +2. Code to create an account. You must run this inside of a function: + +#include_code create_accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript + +3. Running `yarn start` should now output: + +``` + token Aztec Sandbox Info { + version: 1, + chainId: 31337, + rollupAddress: EthAddress { + buffer: + }, + client: 'aztec-rpc@0.1.0', + compatibleNargoVersion: '0.11.1-aztec.0' + } + token Creating accounts using schnorr signers... +3ms + token Created Alice's account at 0x1509b252...0027 +10s + token Created Bob's account at 0x031862e8...e7a3 +0ms +``` + +That might seem like a lot to digest but it can be broken down into the following steps: + +1. We create 2 `Account` objects in Typescript. This object heavily abstracts away the mechanics of configuring and deploying an account contract and setting up a 'wallet' for signing transactions. If you aren't interested in building new types of account contracts or wallets then you don't need to be too concerned with it. In this example we have constructed account contracts and corresponding wallets that sign/verify transactions using schnorr signatures. +2. We wait for the deployment of the 2 account contracts to complete. +3. We retrieve the expected account addresses from the `Account` objects and ensure that they are present in the set of account addresses registered on the Sandbox. + +Note, we use the `getRegisteredAccounts` API to verify that the addresses computed as part of the +account contract deployment have been successfully added to the Sandbox. + +If you were looking at your terminal that is running the Sandbox you should have seen a lot of activity. This is because the Sandbox will have simulated the deployment of both contracts, executed the private kernel circuit for each before submitted 2 transactions to the pool. The sequencer will have picked them up and inserted them into a rollup and executed the recursive rollup circuits before publishing the rollup to Anvil. Once this has completed, the rollup is retrieved and pulled down to the internal RPC Server so that any new account state can be decrypted. + +## Next Steps + +Check out our section on [Writing your own Account Contract](./writing_an_account_contract.md) leveraging our account abstraction diff --git a/docs/netlify.toml b/docs/netlify.toml index 478b38843c9e..96e8a4fbc882 100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@ -56,7 +56,43 @@ [[redirects]] from = "/dev_docs/getting_started/cli" - to = "/dev_docs/cli" + to = "/dev_docs/cli/main" + +[[redirects]] + from = "/dev_docs/getting_started/noir_contracts" + to = "/dev_docs/contracts/main" + +[[redirects]] + from = "/dev_docs/getting_started/token_contract_tutorial" + to = "/dev_docs/tutorials/writing_token_contract" + +[[redirects]] + from = "/dev_docs/sandbox/main" + to = "/dev_docs/getting_started/sandbox" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/main" + to = "/dev_docs/tutorials/writing_dapp/main" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/project_setup" + to = "/dev_docs/tutorials/writing_dapp/project_setup" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/contract_deployment" + to = "/dev_docs/tutorials/writing_dapp/contract_deployment" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/contract_interaction" + to = "/dev_docs/tutorials/writing_dapp/contract_interaction" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/rpc_server" + to = "/dev_docs/tutorials/writing_dapp/rpc_server" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/testing" + to = "/dev_docs/tutorials/writing_dapp/testing" [[redirects]] from = "/aztec/cryptography/cryptography-roadmap" diff --git a/docs/sidebars.js b/docs/sidebars.js index 9b4ac8d3111b..230c1a5b0ff4 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -196,8 +196,33 @@ const sidebars = { items: [ "dev_docs/getting_started/quickstart", "dev_docs/getting_started/sandbox", - "dev_docs/getting_started/noir_contracts", - "dev_docs/getting_started/token_contract_tutorial", + ], + }, + + { + label: "Tutorials", + type: "category", + link: { + type: "doc", + id: "dev_docs/tutorials/main", + }, + items: [ + "dev_docs/tutorials/writing_token_contract", + { + label: "Writing a DApp", + type: "category", + link: { + type: "doc", + id: "dev_docs/tutorials/writing_dapp/main", + }, + items: [ + "dev_docs/tutorials/writing_dapp/project_setup", + "dev_docs/tutorials/writing_dapp/rpc_server", + "dev_docs/tutorials/writing_dapp/contract_deployment", + "dev_docs/tutorials/writing_dapp/contract_interaction", + "dev_docs/tutorials/writing_dapp/testing", + ], + }, ], }, @@ -210,6 +235,7 @@ const sidebars = { }, items: [ "dev_docs/contracts/workflow", + "dev_docs/contracts/setup", "dev_docs/contracts/layout", { label: "Syntax", @@ -227,6 +253,9 @@ const sidebars = { "dev_docs/contracts/syntax/globals", ], }, + "dev_docs/contracts/compiling", + "dev_docs/contracts/deploying", + "dev_docs/contracts/artifacts", { label: "Portals", type: "category", @@ -241,9 +270,6 @@ const sidebars = { "dev_docs/contracts/portals/outbox", ], }, - "dev_docs/contracts/compiling", - "dev_docs/contracts/deploying", - "dev_docs/contracts/artifacts", // { // label: "Resources", // type: "category", @@ -283,58 +309,7 @@ const sidebars = { ], }, - { - label: "Sandbox", - type: "category", - link: { - type: "doc", - id: "dev_docs/sandbox/main", - }, - items: ["dev_docs/sandbox/common_errors"], - }, - - { - label: "CLI", - type: "category", - link: { - type: "doc", - id: "dev_docs/cli/main", - }, - items: ["dev_docs/cli/cli"], - }, - { - label: "DApp Development", - type: "category", - items: [ - // { - // label: "API", - // type: "category", - // link: { - // type: "doc", - // id: "dev_docs/dapps/api/main", - // }, - // items: [ - // "dev_docs/dapps/api/aztec_rpc", - // "dev_docs/dapps/api/contract_interaction", - // ], - // }, - { - label: "Tutorials", - type: "category", - link: { - type: "doc", - id: "dev_docs/dapps/tutorials/main", - }, - items: [ - "dev_docs/dapps/tutorials/project_setup", - "dev_docs/dapps/tutorials/rpc_server", - "dev_docs/dapps/tutorials/contract_deployment", - "dev_docs/dapps/tutorials/contract_interaction", - "dev_docs/dapps/tutorials/testing", - ], - }, - ], - }, + "dev_docs/cli/main", { label: "Testing", @@ -356,6 +331,7 @@ const sidebars = { items: [ "dev_docs/wallets/architecture", "dev_docs/wallets/writing_an_account_contract", + "dev_docs/wallets/creating_schnorr_accounts", ], }, @@ -364,6 +340,7 @@ const sidebars = { type: "category", items: [], },*/ + "dev_docs/sandbox_errors/main", "dev_docs/privacy/main", "dev_docs/limitations/main", diff --git a/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts b/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts index eddee6de9d67..0cf0115d8b8d 100644 --- a/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts +++ b/yarn-project/end-to-end/src/e2e_sandbox_example.test.ts @@ -6,6 +6,7 @@ import { createAztecRpcClient, createDebugLogger, getSchnorrAccount, + getSandboxAccountsWallets, waitForSandbox, } from '@aztec/aztec.js'; import { GrumpkinScalar } from '@aztec/circuits.js'; @@ -34,54 +35,19 @@ describe('e2e_sandbox_example', () => { expect(typeof nodeInfo.chainId).toBe('number'); expect(typeof nodeInfo.rollupAddress).toBe('object'); - // docs:start:Accounts - ////////////// CREATE SOME ACCOUNTS WITH SCHNORR SIGNERS ////////////// - // Creates new accounts using an account contract that verifies schnorr signatures - // Returns once the deployment transactions have settled - const createSchnorrAccounts = async (numAccounts: number, aztecRpc: AztecRPC) => { - const accountManagers = Array(numAccounts) - .fill(0) - .map(() => - getSchnorrAccount( - aztecRpc, - GrumpkinScalar.random(), // encryption private key - GrumpkinScalar.random(), // signing private key - ), - ); - return await Promise.all( - accountManagers.map(async x => { - await x.waitDeploy({}); - return x; - }), - ); - }; - - // Create 2 accounts and wallets to go with each - logger(`Creating accounts using schnorr signers...`); - const accounts = await createSchnorrAccounts(2, aztecRpc); - - ////////////// VERIFY THE ACCOUNTS WERE CREATED SUCCESSFULLY ////////////// - - const [alice, bob] = (await Promise.all(accounts.map(x => x.getCompleteAddress()))).map(x => x.address); - - // Verify that the accounts were deployed - const registeredAccounts = (await aztecRpc.getRegisteredAccounts()).map(x => x.address); - for (const [account, name] of [ - [alice, 'Alice'], - [bob, 'Bob'], - ] as const) { - if (registeredAccounts.find(acc => acc.equals(account))) { - logger(`Created ${name}'s account at ${account.toShortString()}`); - continue; - } - logger(`Failed to create account for ${name}!`); - } - // docs:end:Accounts - - // check that alice and bob are in registeredAccounts - expect(registeredAccounts.find(acc => acc.equals(alice))).toBeTruthy(); - expect(registeredAccounts.find(acc => acc.equals(bob))).toBeTruthy(); - + // For the sandbox quickstart we just want to show them preloaded accounts (since it is a quickstart) + // We show creation of accounts in a later test + + // docs:start:load_accounts + ////////////// LOAD SOME ACCOUNTS FROM THE SANDBOX ////////////// + // The sandbox comes with a set of created accounts. Load them + const accounts = await getSandboxAccountsWallets(aztecRpc); + const alice = accounts[0].getAddress(); + const bob = accounts[1].getAddress(); + logger(`Loaded alice's account at ${alice.toShortString()}`); + logger(`Loaded bob's account at ${bob.toShortString()}`); + // docs:end:load_accounts + // docs:start:Deployment ////////////// DEPLOY OUR TOKEN CONTRACT ////////////// @@ -92,7 +58,7 @@ describe('e2e_sandbox_example', () => { const contract = await TokenContract.deploy(aztecRpc).send().deployed(); // Create the contract abstraction and link to Alice's wallet for future signing - const tokenContractAlice = await TokenContract.at(contract.address, await accounts[0].getWallet()); + const tokenContractAlice = await TokenContract.at(contract.address, accounts[0]); // Initialize the contract and add Bob as a minter await tokenContractAlice.methods._initialize(alice).send().wait(); @@ -116,7 +82,7 @@ describe('e2e_sandbox_example', () => { // Bob wants to mint some funds, the contract is already deployed, create an abstraction and link it his wallet // Since we already have a token link, we can simply create a new instance of the contract linked to Bob's wallet - const tokenContractBob = tokenContractAlice.withWallet(await accounts[1].getWallet()); + const tokenContractBob = tokenContractAlice.withWallet(accounts[1]); let aliceBalance = await tokenContractAlice.methods.balance_of_private(alice).view(); logger(`Alice's balance ${aliceBalance}`); @@ -168,4 +134,60 @@ describe('e2e_sandbox_example', () => { expect(aliceBalance).toBe(initialSupply - transferQuantity); expect(bobBalance).toBe(transferQuantity + mintQuantity); }, 120_000); + + it('can create accounts on the sandbox', async () => { + const logger = createDebugLogger('token'); + // We create AztecRPC client connected to the sandbox URL + const aztecRpc = createAztecRpcClient(SANDBOX_URL); + // Wait for sandbox to be ready + await waitForSandbox(aztecRpc); + + // docs:start:create_accounts + ////////////// CREATE SOME ACCOUNTS WITH SCHNORR SIGNERS ////////////// + // Creates new accounts using an account contract that verifies schnorr signatures + // Returns once the deployment transactions have settled + const createSchnorrAccounts = async (numAccounts: number, aztecRpc: AztecRPC) => { + const accountManagers = Array(numAccounts) + .fill(0) + .map(() => + getSchnorrAccount( + aztecRpc, + GrumpkinScalar.random(), // encryption private key + GrumpkinScalar.random(), // signing private key + ), + ); + return await Promise.all( + accountManagers.map(async x => { + await x.waitDeploy({}); + return x; + }), + ); + }; + + // Create 2 accounts and wallets to go with each + logger(`Creating accounts using schnorr signers...`); + const accounts = await createSchnorrAccounts(2, aztecRpc); + + ////////////// VERIFY THE ACCOUNTS WERE CREATED SUCCESSFULLY ////////////// + + const [alice, bob] = (await Promise.all(accounts.map(x => x.getCompleteAddress()))).map(x => x.address); + + // Verify that the accounts were deployed + const registeredAccounts = (await aztecRpc.getRegisteredAccounts()).map(x => x.address); + for (const [account, name] of [ + [alice, 'Alice'], + [bob, 'Bob'], + ] as const) { + if (registeredAccounts.find(acc => acc.equals(account))) { + logger(`Created ${name}'s account at ${account.toShortString()}`); + continue; + } + logger(`Failed to create account for ${name}!`); + } + // docs:end:create_accounts + + // check that alice and bob are in registeredAccounts + expect(registeredAccounts.find(acc => acc.equals(alice))).toBeTruthy(); + expect(registeredAccounts.find(acc => acc.equals(bob))).toBeTruthy(); + }); }); diff --git a/yarn-project/noir-contracts/README.md b/yarn-project/noir-contracts/README.md index 0b2fb8e44c48..2ad77cb638fe 100644 --- a/yarn-project/noir-contracts/README.md +++ b/yarn-project/noir-contracts/README.md @@ -119,7 +119,7 @@ It has prebuilt binaries and is super easy to install using `noirup` 1. Go to `src/contracts` folder. 2. Create a new package whose name has to end with **\_contract**. E.g.: ``` - nargo new example_contract + nargo new --contract example_contract ``` 3. Add the aztec dependency to `nargo.toml`: From ab612dff85aa2dec28aefd680764a8477efd86e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bene=C5=A1?= Date: Fri, 22 Sep 2023 09:26:32 +0200 Subject: [PATCH 04/12] docs: update instructions (#2297) Fixes #1827 --- .../docs/dev_docs/getting_started/updating.md | 91 +++++++++++++++++++ docs/sidebars.js | 1 + docs/src/preprocess/include_version.js | 3 +- yarn-project/aztec-sandbox/package.json | 1 + yarn-project/aztec-sandbox/src/bin/index.ts | 7 +- yarn-project/aztec-sandbox/tsconfig.json | 3 + .../end-to-end/src/cli_docs_sandbox.test.ts | 16 +++- yarn-project/yarn.lock | 1 + 8 files changed, 119 insertions(+), 4 deletions(-) create mode 100644 docs/docs/dev_docs/getting_started/updating.md diff --git a/docs/docs/dev_docs/getting_started/updating.md b/docs/docs/dev_docs/getting_started/updating.md new file mode 100644 index 000000000000..cb0662ca63ca --- /dev/null +++ b/docs/docs/dev_docs/getting_started/updating.md @@ -0,0 +1,91 @@ +--- +title: Updating +--- + +There are 4 components whose versions need to be kept compatible: +1. Aztec Sandbox, +2. Aztec CLI, +3. Noir compiler `nargo`, +4. Noir framework for Aztec contracts `aztec.nr`. + +Aztec Sandbox, Aztec CLI and `aztec.nr` are using the same versioning scheme and their versions must match. +The Noir compiler `nargo` has its own versioning scheme and its version must match the compatible nargo version specified in Sandbox. + +## Updating Aztec Sandbox +To update the sandbox to the latest version, simply run the curl command we used for installation again: +```shell +/bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" +``` + +It will download and start the latest version of sandbox. + +If you would like to use a fixed version of the sandbox, you can export the `SANDBOX_VERSION` environmental variable. +If you are unsure what version to use go to [aztec-packages repository](https://github.com/AztecProtocol/aztec-packages/releases) and choose the `aztec-packages` release based on the changelog. + +Then set the `SANDBOX_VERSION` environmental variable to the version you want to use. E.g.: +```shell +export SANDBOX_VERSION=#include_aztec_short_version +``` + +Now when you run the curl command it will use the version you specified. +To verify that it's the case check the console output of the curl command. +You should see the following line: +``` +Setting up Aztec Sandbox v#include_aztec_short_version (nargo #include_noir_version), please stand by... +``` + +Alternatively you can open a new terminal and use aztec-cli to get the version. + +#include_code node-info yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +The sandbox version should be the same as the one we chose by setting the `SANDBOX_VERSION` environmental variable. + +## Updating Aztec CLI +If the latest version was used when updating the sandbox then we can simply run the following command to update the CLI: +```shell +npm install -g @aztec/cli +``` + +If a specific version was set for the sandbox then we need to install the CLI with the same version: +```shell +npm install -g @aztec/cli@$SANDBOX_VERSION +``` + +E.g.: +```shell +npm install -g @aztec/cli@#include_aztec_short_version +``` + +## Updating Noir compiler +Now we need to update the Noir compiler `nargo` to the version compatible with the sandbox. +Use `aztec-cli` to get it: +#include_code node-info yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +Then we install the `Compatible Nargo Version` with (replace `COMPATIBLE_NARGO_VERSION` with the version from the previous command): +```shell +noirup -v COMPATIBLE_NARGO_VERSION +``` + +## Updating Noir framework +Finally we need to update the Noir framework for Aztec contracts. +We need to install a version compatible with our `nargo` and Sandbox. + +To update the framework we will update a tag of the `aztec.nr` dependency in the `Nargo.toml` file to the `SANDBOX_VERSION` from above. +Find all the dependencies pointing to the directory within `aztec.nr` framework and update the corresponding tag. +E.g.: + +```diff +[dependencies] +-aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="aztec-packages-v0.7.5", directory="yarn-project/aztec-nr/aztec" } ++aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +-value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="aztec-packages-v0.7.5", directory="yarn-project/aztec-nr/value-note" } ++value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note" } +``` + +Go to the project directory and try compiling it with `aztec-cli`` to verify that the update was successful: +```shell +cd /your/project/root +aztec-cli compile ./ +``` + +If the dependencies fail to resolve ensure that the tag matches a tag in the [aztec-packages repository](https://github.com/AztecProtocol/aztec-packages/tags). diff --git a/docs/sidebars.js b/docs/sidebars.js index 230c1a5b0ff4..7bc4f2b58b3d 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -196,6 +196,7 @@ const sidebars = { items: [ "dev_docs/getting_started/quickstart", "dev_docs/getting_started/sandbox", + "dev_docs/getting_started/updating", ], }, diff --git a/docs/src/preprocess/include_version.js b/docs/src/preprocess/include_version.js index 296b06158c82..afa372e0a047 100644 --- a/docs/src/preprocess/include_version.js +++ b/docs/src/preprocess/include_version.js @@ -1,7 +1,7 @@ const path = require("path"); const fs = require("fs"); -const VERSION_IDENTIFIERS = ["noir", "aztec"]; +const VERSION_IDENTIFIERS = ["noir", "aztec", "aztec_short"]; let versions; async function getVersions() { @@ -24,6 +24,7 @@ async function getVersions() { versions = { noir: noirVersion, aztec: `aztec-packages-v${aztecVersion}`, + aztec_short: aztecVersion, }; } catch (err) { throw new Error( diff --git a/yarn-project/aztec-sandbox/package.json b/yarn-project/aztec-sandbox/package.json index d176756f835f..134de4da8b90 100644 --- a/yarn-project/aztec-sandbox/package.json +++ b/yarn-project/aztec-sandbox/package.json @@ -35,6 +35,7 @@ "@aztec/ethereum": "workspace:^", "@aztec/foundation": "workspace:^", "@aztec/l1-artifacts": "workspace:^", + "@aztec/noir-compiler": "workspace:^", "@aztec/noir-contracts": "workspace:^", "@aztec/types": "workspace:^", "abitype": "^0.8.11", diff --git a/yarn-project/aztec-sandbox/src/bin/index.ts b/yarn-project/aztec-sandbox/src/bin/index.ts index 6588ed051430..8f906cf874da 100644 --- a/yarn-project/aztec-sandbox/src/bin/index.ts +++ b/yarn-project/aztec-sandbox/src/bin/index.ts @@ -2,6 +2,7 @@ import { deployInitialSandboxAccounts } from '@aztec/aztec.js'; import { createDebugLogger } from '@aztec/foundation/log'; import { fileURLToPath } from '@aztec/foundation/url'; +import NoirVersion from '@aztec/noir-compiler/noir-version'; import { readFileSync } from 'fs'; import { dirname, resolve } from 'path'; @@ -23,7 +24,7 @@ async function main() { const packageJsonPath = resolve(dirname(fileURLToPath(import.meta.url)), '../../package.json'); const version = JSON.parse(readFileSync(packageJsonPath).toString()).version; - logger.info(`Setting up Aztec Sandbox v${version}, please stand by...`); + logger.info(`Setting up Aztec Sandbox v${version} (nargo ${NoirVersion.tag}), please stand by...`); const { l1Contracts, rpcServer, stop } = await createSandbox(); @@ -55,7 +56,9 @@ async function main() { } } logger.info( - `${splash}\n${github}\n\n`.concat(...accountStrings).concat(`Aztec Sandbox v${version} is now ready for use!`), + `${splash}\n${github}\n\n` + .concat(...accountStrings) + .concat(`Aztec Sandbox v${version} (nargo ${NoirVersion.tag}) is now ready for use!`), ); } diff --git a/yarn-project/aztec-sandbox/tsconfig.json b/yarn-project/aztec-sandbox/tsconfig.json index fcd42f67eb95..897517cdef65 100644 --- a/yarn-project/aztec-sandbox/tsconfig.json +++ b/yarn-project/aztec-sandbox/tsconfig.json @@ -27,6 +27,9 @@ { "path": "../l1-artifacts" }, + { + "path": "../noir-compiler" + }, { "path": "../noir-contracts" }, diff --git a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts index 0f0eff61eb3f..bedab689aef2 100644 --- a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts +++ b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts @@ -26,10 +26,24 @@ describe('CLI docs sandbox', () => { }, 60_000); const waitForSandboxWithCli = async () => { + const docs = ` +// docs:start:node-info +% aztec-cli get-node-info +Node Info: + +Sandbox Version: #include_aztec_short_version +Compatible Nargo Version: #include_noir_version +Chain Id: 31337 +Protocol Version: 1 +Rollup Address: 0x0dcd1bf9a1b36ce34237eeafef220932846bcd82 +// docs:end:node-info +`; + + const command = docs.split('\n')[2].split('aztec-cli ')[1]; while (true) { resetCli(); try { - await run('get-node-info'); + await run(command); break; } catch (err) { await sleep(1000); diff --git a/yarn-project/yarn.lock b/yarn-project/yarn.lock index da65105c613c..3853bf9f7a8c 100644 --- a/yarn-project/yarn.lock +++ b/yarn-project/yarn.lock @@ -183,6 +183,7 @@ __metadata: "@aztec/ethereum": "workspace:^" "@aztec/foundation": "workspace:^" "@aztec/l1-artifacts": "workspace:^" + "@aztec/noir-compiler": "workspace:^" "@aztec/noir-contracts": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 From a779d114584742e41e5489ce36821d8554772ea0 Mon Sep 17 00:00:00 2001 From: Lasse Herskind <16536249+LHerskind@users.noreply.github.com> Date: Fri, 22 Sep 2023 09:45:10 +0100 Subject: [PATCH 05/12] docs: update sidebar + embed youtube video (#2470) Moves the testing with typescript tutorials to tutorials and embed recording from Privacy + Scaling Explorations into the indexed merkle tree section. --- .../advanced/data_structures/indexed_merkle_tree.md | 4 ++++ docs/docs/dev_docs/{testing => tutorials}/testing.md | 4 ++-- docs/docs/dev_docs/tutorials/writing_dapp/testing.md | 6 +++--- docs/sidebars.js | 3 ++- 4 files changed, 11 insertions(+), 6 deletions(-) rename docs/docs/dev_docs/{testing => tutorials}/testing.md (97%) diff --git a/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md b/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md index 5e61e570052c..927a4e6a3876 100644 --- a/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md +++ b/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md @@ -9,6 +9,10 @@ import Disclaimer from "../../../misc/common/\_disclaimer.mdx"; ## Indexed Merkle Trees +This article will introduce the concept of an indexed merkle tree, and how it can be used to improve the performance of nullifier trees in circuits. The content was also covered in a presentation for the [Privacy + Scaling Explorations team at the Ethereum Foundation](https://pse.dev/). + + + #### Primer on Nullifier Trees Currently the only feasible way to get privacy in public blockchains is via a UTXO model. In this model, state is stored in encrypted UTXO's in merkle trees. However, to maintain privacy, state can not be updated. The very act of performing an update leaks information. In order to simulate "updating" the state, we "destroy" old UTXO's and create new ones for each state update. Resulting in a merkle tree that is append-only. diff --git a/docs/docs/dev_docs/testing/testing.md b/docs/docs/dev_docs/tutorials/testing.md similarity index 97% rename from docs/docs/dev_docs/testing/testing.md rename to docs/docs/dev_docs/tutorials/testing.md index 8ae02751cdb6..e00bccd1a81f 100644 --- a/docs/docs/dev_docs/testing/testing.md +++ b/docs/docs/dev_docs/tutorials/testing.md @@ -127,7 +127,7 @@ In the near future, transactions where a public function call fails will get min We can check private or public state directly rather than going through view-only methods, as we did in the initial example by calling `token.methods.balance().view()`. Bear in mind that directly accessing contract storage will break any kind of encapsulation. -To query storage directly, you'll need to know the slot you want to access. This can be checked in the [contract's `Storage` definition](../contracts/syntax/storage.md) directly for most data types. However, when it comes to mapping types, as in most EVM languages, we'll need to calculate the slot for a given key. To do this, we'll use the `CheatCodes` utility class: +To query storage directly, you'll need to know the slot you want to access. This can be checked in the [contract's `Storage` definition](../contracts/syntax/storage.md) directly for most data types. However, when it comes to mapping types, as in most EVM languages, we'll need to calculate the slot for a given key. To do this, we'll use the [`CheatCodes`](./../testing/cheat_codes.md) utility class: #include_code calc-slot /yarn-project/end-to-end/src/guides/dapp_testing.test.ts typescript @@ -163,7 +163,7 @@ We can query the RPC server for the unencrypted logs emitted in the block where ## Cheats -The `CheatCodes` class, which we used for [calculating the storage slot above](#state), also includes a set of cheat methods for modifying the chain state that can be handy for testing. +The [`CheatCodes`](./../testing/cheat_codes.md) class, which we used for [calculating the storage slot above](#state), also includes a set of cheat methods for modifying the chain state that can be handy for testing. ### Set next block timestamp diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/testing.md b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md index 7083e22a6582..ff9732be801f 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/testing.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md @@ -4,7 +4,7 @@ title: Testing To wrap up this tutorial, we'll set up a simple automated test for our dapp contracts. We will be using [jest](https://jestjs.io/), but any nodejs test runner works fine. -Here we'll only test the happy path for a `transfer` on our private token contract, but in a real application you should be testing both happy and unhappy paths, as well as both your contracts and application logic. Refer to the full [testing guide](../../testing/testing.md) for more info on testing and assertions. +Here we'll only test the happy path for a `transfer` on our private token contract, but in a real application you should be testing both happy and unhappy paths, as well as both your contracts and application logic. Refer to the full [testing guide](../testing.md) for more info on testing and assertions. ## Dependencies @@ -32,7 +32,7 @@ import TokenContractAbi from "../contracts/token/target/Token.json" assert { typ describe("token", () => {}); ``` -Let's set up our test suite. We'll start [a new Sandbox instance within the test](../../testing/testing.md#running-sandbox-in-the-nodejs-process), create two fresh accounts to test with, and deploy an instance of our contract. The `aztec-sandbox` and `aztec.js` provide the helper functions we need to do this: +Let's set up our test suite. We'll start [a new Sandbox instance within the test](../testing.md#running-sandbox-in-the-nodejs-process), create two fresh accounts to test with, and deploy an instance of our contract. The `aztec-sandbox` and `aztec.js` provide the helper functions we need to do this: #include_code setup yarn-project/end-to-end/src/sample-dapp/index.test.mjs javascript @@ -44,7 +44,7 @@ Now that we have a working test environment, we can write our first test for exe #include_code test yarn-project/end-to-end/src/sample-dapp/index.test.mjs javascript -In this example, we assert that the `recipient`'s balance is increased by the amount transferred. We could also test that the `owner`'s funds are decremented by the same amount, or that a transaction that attempts to send more funds than those available would fail. Check out the [testing guide](../../testing/testing.md) for more ideas. +In this example, we assert that the `recipient`'s balance is increased by the amount transferred. We could also test that the `owner`'s funds are decremented by the same amount, or that a transaction that attempts to send more funds than those available would fail. Check out the [testing guide](../testing.md) for more ideas. ## Running our tests diff --git a/docs/sidebars.js b/docs/sidebars.js index 7bc4f2b58b3d..d9362ebe4817 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -224,6 +224,7 @@ const sidebars = { "dev_docs/tutorials/writing_dapp/testing", ], }, + "dev_docs/tutorials/testing", ], }, @@ -319,7 +320,7 @@ const sidebars = { type: "doc", id: "dev_docs/testing/main", }, - items: ["dev_docs/testing/testing", "dev_docs/testing/cheat_codes"], + items: ["dev_docs/testing/cheat_codes"], }, { From 85e504c95953cc8ebbb32e2c4ea2f66c7da7a889 Mon Sep 17 00:00:00 2001 From: Santiago Palladino Date: Fri, 22 Sep 2023 06:47:53 -0300 Subject: [PATCH 06/12] feat(docs): Reenable typedoc for aztec-rpc and aztec.js (#2452) Attempts another shot at https://github.com/AztecProtocol/aztec-packages/pull/2255, but this time including a build script specific to Netlify. Includes aztec.js contract and account modules, and expands some inline docs. ![image](https://github.com/AztecProtocol/aztec-packages/assets/429604/9bc9af0b-9d4c-44e3-ab9f-69b491a687c8) Fixes #2044 Fixes #2045 Fixes #2046 Fixes #2415 --- .circleci/config.yml | 5 +- docs/Dockerfile | 10 +- docs/docs/.gitignore | 1 + docs/docusaurus.config.js | 26 +++ docs/package.json | 18 +- docs/scripts/build.sh | 48 +++++ docs/sidebars.js | 17 ++ docs/src/preprocess/include_code.js | 2 +- docs/yarn.lock | 98 +++++++++ yarn-project/aztec.js/README.md | 48 +++-- yarn-project/aztec.js/package.json | 1 + yarn-project/aztec.js/package.local.json | 5 +- yarn-project/aztec.js/src/account/index.ts | 22 ++ .../{utils/account.ts => account/utils.ts} | 2 +- .../src/contract/base_contract_interaction.ts | 4 +- .../contract/contract_function_interaction.ts | 4 +- yarn-project/aztec.js/src/contract/index.ts | 37 ++++ .../src/contract_deployer/deploy_method.ts | 4 +- yarn-project/aztec.js/src/utils/index.ts | 1 - yarn-project/types/src/contract_data.ts | 2 +- .../types/src/interfaces/aztec_rpc.ts | 203 ++++++++---------- .../types/src/interfaces/deployed-contract.ts | 22 ++ yarn-project/types/src/interfaces/index.ts | 3 + .../types/src/interfaces/node-info.ts | 27 +++ .../types/src/interfaces/sync-status.ts | 7 + 25 files changed, 458 insertions(+), 159 deletions(-) create mode 100644 docs/docs/.gitignore create mode 100755 docs/scripts/build.sh rename yarn-project/aztec.js/src/{utils/account.ts => account/utils.ts} (96%) create mode 100644 yarn-project/types/src/interfaces/deployed-contract.ts create mode 100644 yarn-project/types/src/interfaces/node-info.ts create mode 100644 yarn-project/types/src/interfaces/sync-status.ts diff --git a/.circleci/config.yml b/.circleci/config.yml index ae14946c3d81..67896e61472f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1315,8 +1315,6 @@ workflows: when: equal: [system, << pipeline.parameters.workflow >>] jobs: - - build-docs: *defaults - # Barretenberg - barretenberg-x86_64-linux-gcc: *defaults - barretenberg-x86_64-linux-clang: *defaults @@ -1409,7 +1407,8 @@ workflows: - l1-contracts - noir-contracts-build <<: *defaults - + + - build-docs: *yarn_project - aztec-js: *yarn_project - end-to-end: *yarn_project - ethereum: *yarn_project diff --git a/docs/Dockerfile b/docs/Dockerfile index 572658476eb6..eb5071dc4f22 100644 --- a/docs/Dockerfile +++ b/docs/Dockerfile @@ -1,10 +1,14 @@ -FROM node:18-alpine -RUN apk update +FROM 278380418400.dkr.ecr.eu-west-2.amazonaws.com/yarn-project-base AS builder WORKDIR /usr/src COPY . . +WORKDIR /usr/src/yarn-project + +RUN yarn build + WORKDIR /usr/src/docs -RUN yarn && yarn build \ No newline at end of file +RUN yarn && yarn build + diff --git a/docs/docs/.gitignore b/docs/docs/.gitignore new file mode 100644 index 000000000000..6fa7731468dd --- /dev/null +++ b/docs/docs/.gitignore @@ -0,0 +1 @@ +/apis diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 7354306c98f9..54f750d2e396 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -122,6 +122,32 @@ const config = { disableInDev: false, }, ], + [ + "@spalladino/docusaurus-plugin-typedoc", + { + id: "apis/aztec-rpc", + entryPoints: ["../yarn-project/types/src/interfaces/aztec_rpc.ts"], + tsconfig: "../yarn-project/types/tsconfig.json", + entryPointStrategy: "expand", + out: "apis/aztec-rpc", + disableSources: true, + frontmatter: { sidebar_label: "Aztec RPC Server" }, + }, + ], + [ + "@spalladino/docusaurus-plugin-typedoc", + { + id: "apis/aztec-js", + entryPoints: [ + "../yarn-project/aztec.js/src/contract/index.ts", + "../yarn-project/aztec.js/src/account/index.ts", + ], + tsconfig: "../yarn-project/aztec.js/tsconfig.json", + entryPointStrategy: "resolve", + out: "apis/aztec-js", + disableSources: true, + }, + ], // ["./src/plugins/plugin-embed-code", {}], ], themeConfig: diff --git a/docs/package.json b/docs/package.json index b3017e9b2b22..594416233534 100644 --- a/docs/package.json +++ b/docs/package.json @@ -4,19 +4,20 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "docusaurus start", - "start:dev": "concurrently \"yarn preprocess:dev\" \"docusaurus start --host 0.0.0.0\"", - "start:dev:local": "concurrently \"yarn preprocess:dev\" \"docusaurus start\"", - "build": "yarn preprocess && docusaurus build", + "start": "yarn preprocess && yarn typedoc && docusaurus start", + "start:dev": "concurrently \"yarn preprocess:dev\" \"yarn typedoc:dev\" \"sleep 2 && docusaurus start --host 0.0.0.0\"", + "start:dev:local": "concurrently \"yarn preprocess:dev\" \"yarn typedoc:dev\" \"sleep 2 && docusaurus start\"", + "build": "./scripts/build.sh", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", - "clear": "rm -rf 'processed-docs' 'processed-docs-cache' && docusaurus clear", + "clear": "rm -rf 'processed-docs' 'processed-docs-cache' docs/apis && docusaurus clear", "serve": "docusaurus serve", "preprocess": "yarn node ./src/preprocess/index.js", "preprocess:dev": "nodemon --config nodemon.json ./src/preprocess/index.js", + "typedoc": "rm -rf docs/apis && docusaurus generate-typedoc && cp -a docs/apis processed-docs/", + "typedoc:dev": "nodemon -w ../yarn-project -e '*.js,*.ts,*.nr,*.md' --exec \"rm -rf docs/apis && yarn docusaurus generate-typedoc && cp -a docs/apis processed-docs/\"", "write-translations": "docusaurus write-translations", - "write-heading-ids": "docusaurus write-heading-ids", - "update-specs": "./scripts/update_specs.sh" + "write-heading-ids": "docusaurus write-heading-ids" }, "dependencies": { "@docusaurus/core": "^2.4.1", @@ -36,9 +37,12 @@ }, "devDependencies": { "@docusaurus/module-type-aliases": "^2.4.1", + "@spalladino/docusaurus-plugin-typedoc": "^0.20.3", "@tsconfig/docusaurus": "^1.0.5", "concurrently": "^8.0.1", "nodemon": "^3.0.1", + "typedoc": "^0.25.1", + "typedoc-plugin-markdown": "^3.16.0", "typescript": "^4.7.2" }, "browserslist": { diff --git a/docs/scripts/build.sh b/docs/scripts/build.sh new file mode 100755 index 000000000000..d1c4aaab1d4d --- /dev/null +++ b/docs/scripts/build.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -eo pipefail + +# Helper function for building packages in yarn project +build_package() { + local package_name="$1" + local build_command="${2:-yarn build}" + + echo "Building $package_name..." + (cd "yarn-project/$package_name" && $build_command) +} + +# Build script. If run on Netlify, first it needs to compile all yarn-projects +# that are involved in typedoc in order to generate their type information. +if [ -n "$NETLIFY" ]; then + # Move to project root + cd .. + echo Working dir $(pwd) + + # Make sure the latest tag is available for loading code snippets from it + LAST_TAG="aztec-packages-v$(jq -r '.["."]' .release-please-manifest.json)" + echo Fetching latest released tag $LAST_TAG... + git fetch origin refs/tags/$LAST_TAG:refs/tags/$LAST_TAG + + # Tweak global tsconfig so we skip tests in all projects + echo Removing test files from tsconfig... + jq '. + { "exclude": ["**/*test.ts"] }' yarn-project/tsconfig.json > yarn-project/tsconfig.tmp.json + mv yarn-project/tsconfig.tmp.json yarn-project/tsconfig.json + + # Install deps (maybe we can have netlify download these automatically so they get cached..?) + echo Installing yarn-project dependencies... + (cd yarn-project && yarn) + + # Build the required projects for typedoc + build_package "aztec-rpc" + build_package "aztec.js" "yarn build:ts" + + # Back to docs site + cd docs + + # Install deps + echo Install docs deps... + yarn +fi + +# Now build the docsite +echo Building docsite... +yarn preprocess && yarn typedoc && yarn docusaurus build diff --git a/docs/sidebars.js b/docs/sidebars.js index d9362ebe4817..94ec83570ede 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -346,6 +346,23 @@ const sidebars = { "dev_docs/privacy/main", "dev_docs/limitations/main", + { + label: "API Reference", + type: "category", + items: [ + { + label: "Aztec RPC Server", + type: "doc", + id: "apis/aztec-rpc/interfaces/AztecRPC", + }, + { + label: "Aztec.js", + type: "category", + items: [{ dirName: "apis/aztec-js", type: "autogenerated" }], + }, + ], + }, + { type: "html", value: '', diff --git a/docs/src/preprocess/include_code.js b/docs/src/preprocess/include_code.js index 1e87b9aa3513..9991780e2cc0 100644 --- a/docs/src/preprocess/include_code.js +++ b/docs/src/preprocess/include_code.js @@ -93,7 +93,7 @@ function readFile(filePath, tag) { return childProcess.execSync(`git show ${tag}:${relPath}`).toString(); } catch (err) { console.error( - `Error reading file ${relPath} from latest version. Falling back to current content.` + `Error reading file ${filePath} from latest version. Falling back to current content.` ); } } diff --git a/docs/yarn.lock b/docs/yarn.lock index 6b47a0365228..3057a40b1e83 100644 --- a/docs/yarn.lock +++ b/docs/yarn.lock @@ -1875,6 +1875,11 @@ p-map "^4.0.0" webpack-sources "^3.2.2" +"@spalladino/docusaurus-plugin-typedoc@^0.20.3": + version "0.20.3" + resolved "https://registry.yarnpkg.com/@spalladino/docusaurus-plugin-typedoc/-/docusaurus-plugin-typedoc-0.20.3.tgz#04e0f8db61b8328ab0b8d6d4bd43a59fb0cdbbdd" + integrity sha512-LufWGbOUbyztOgJY42UDeQ0bnpTqZBtdIL1duTaIMpNj1MM2N9F3QqQhmQY3J9SnqCnkMjZu13RnK/ninWbLLg== + "@svgr/babel-plugin-add-jsx-attribute@^6.5.1": version "6.5.1" resolved "https://registry.yarnpkg.com/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-6.5.1.tgz#74a5d648bd0347bda99d82409d87b8ca80b9a1ba" @@ -2531,6 +2536,11 @@ ansi-regex@^6.0.1: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== +ansi-sequence-parser@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/ansi-sequence-parser/-/ansi-sequence-parser-1.1.1.tgz#e0aa1cdcbc8f8bb0b5bca625aac41f5f056973cf" + integrity sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg== + ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -2802,6 +2812,13 @@ brace-expansion@^1.1.7: balanced-match "^1.0.0" concat-map "0.0.1" +brace-expansion@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" + integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== + dependencies: + balanced-match "^1.0.0" + braces@^3.0.2, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" @@ -4693,6 +4710,18 @@ handle-thing@^2.0.0: resolved "https://registry.yarnpkg.com/handle-thing/-/handle-thing-2.0.1.tgz#857f79ce359580c340d43081cc648970d0bb234e" integrity sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg== +handlebars@^4.7.7: + version "4.7.8" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.7.8.tgz#41c42c18b1be2365439188c77c6afae71c0cd9e9" + integrity sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ== + dependencies: + minimist "^1.2.5" + neo-async "^2.6.2" + source-map "^0.6.1" + wordwrap "^1.0.0" + optionalDependencies: + uglify-js "^3.1.4" + has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" @@ -5402,6 +5431,11 @@ json5@^2.1.2, json5@^2.2.2: resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== +jsonc-parser@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" + integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== + jsonfile@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" @@ -5596,6 +5630,11 @@ lru-cache@^6.0.0: dependencies: yallist "^4.0.0" +lunr@^2.3.9: + version "2.3.9" + resolved "https://registry.yarnpkg.com/lunr/-/lunr-2.3.9.tgz#18b123142832337dd6e964df1a5a7707b25d35e1" + integrity sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow== + make-dir@^3.0.0, make-dir@^3.0.2, make-dir@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f" @@ -5608,6 +5647,11 @@ markdown-escapes@^1.0.0: resolved "https://registry.yarnpkg.com/markdown-escapes/-/markdown-escapes-1.0.4.tgz#c95415ef451499d7602b91095f3c8e8975f78535" integrity sha512-8z4efJYk43E0upd0NbVXwgSTQs6cT3T06etieCMEg7dRbzCbxUCK/GHlX8mhHRDcp+OLlHkPKsvqQTCvsRl2cg== +marked@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/marked/-/marked-4.3.0.tgz#796362821b019f734054582038b116481b456cf3" + integrity sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A== + mdast-squeeze-paragraphs@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/mdast-squeeze-paragraphs/-/mdast-squeeze-paragraphs-4.0.0.tgz#7c4c114679c3bee27ef10b58e2e015be79f1ef97" @@ -5781,6 +5825,13 @@ minimatch@3.1.2, minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch dependencies: brace-expansion "^1.1.7" +minimatch@^9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.3.tgz#a6e00c3de44c3a542bfaae70abfc22420a6da825" + integrity sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg== + dependencies: + brace-expansion "^2.0.1" + minimist@^1.2.0, minimist@^1.2.5: version "1.2.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" @@ -7474,6 +7525,16 @@ shelljs@^0.8.5: interpret "^1.0.0" rechoir "^0.6.2" +shiki@^0.14.1: + version "0.14.4" + resolved "https://registry.yarnpkg.com/shiki/-/shiki-0.14.4.tgz#2454969b466a5f75067d0f2fa0d7426d32881b20" + integrity sha512-IXCRip2IQzKwxArNNq1S+On4KPML3Yyn8Zzs/xRgcgOWIr8ntIK3IKzjFPfjy/7kt9ZMjc+FItfqHRBg8b6tNQ== + dependencies: + ansi-sequence-parser "^1.1.0" + jsonc-parser "^3.2.0" + vscode-oniguruma "^1.7.0" + vscode-textmate "^8.0.0" + side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" @@ -7962,6 +8023,23 @@ typedarray-to-buffer@^3.1.5: dependencies: is-typedarray "^1.0.0" +typedoc-plugin-markdown@^3.16.0: + version "3.16.0" + resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-3.16.0.tgz#98da250271aafade8b6740a8116a97cd3941abcd" + integrity sha512-eeiC78fDNGFwemPIHiwRC+mEC7W5jwt3fceUev2gJ2nFnXpVHo8eRrpC9BLWZDee6ehnz/sPmNjizbXwpfaTBw== + dependencies: + handlebars "^4.7.7" + +typedoc@^0.25.1: + version "0.25.1" + resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.25.1.tgz#50de2d8fb93623fbfb59e2fa6407ff40e3d3f438" + integrity sha512-c2ye3YUtGIadxN2O6YwPEXgrZcvhlZ6HlhWZ8jQRNzwLPn2ylhdGqdR8HbyDRyALP8J6lmSANILCkkIdNPFxqA== + dependencies: + lunr "^2.3.9" + marked "^4.3.0" + minimatch "^9.0.3" + shiki "^0.14.1" + typescript@^4.7.2: version "4.9.4" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.4.tgz#a2a3d2756c079abda241d75f149df9d561091e78" @@ -7972,6 +8050,11 @@ ua-parser-js@^0.7.30: resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.32.tgz#cd8c639cdca949e30fa68c44b7813ef13e36d211" integrity sha512-f9BESNVhzlhEFf2CHMSj40NWOjYPl1YKYbrvIr/hFTDEmLq7SRbWvm7FcdcpCYT95zrOhC7gZSxjdnnTpBcwVw== +uglify-js@^3.1.4: + version "3.17.4" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.17.4.tgz#61678cf5fa3f5b7eb789bb345df29afb8257c22c" + integrity sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g== + undefsafe@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c" @@ -8250,6 +8333,16 @@ vfile@^4.0.0: unist-util-stringify-position "^2.0.0" vfile-message "^2.0.0" +vscode-oniguruma@^1.7.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz#439bfad8fe71abd7798338d1cd3dc53a8beea94b" + integrity sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA== + +vscode-textmate@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/vscode-textmate/-/vscode-textmate-8.0.0.tgz#2c7a3b1163ef0441097e0b5d6389cd5504b59e5d" + integrity sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg== + wait-on@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/wait-on/-/wait-on-6.0.1.tgz#16bbc4d1e4ebdd41c5b4e63a2e16dbd1f4e5601e" @@ -8461,6 +8554,11 @@ wildcard@^2.0.0: resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== +wordwrap@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + integrity sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q== + wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" diff --git a/yarn-project/aztec.js/README.md b/yarn-project/aztec.js/README.md index efaeb621cd84..1c92ea26ede1 100644 --- a/yarn-project/aztec.js/README.md +++ b/yarn-project/aztec.js/README.md @@ -1,44 +1,46 @@ # Aztec.js -Aztec.js is a tool that provides APIs for interacting with contracts on the Aztec network. It communicates with the [AztecRPCServer](../aztec-rpc/) through an AztecRPCClient implementation, allowing developers to easily deploy contracts, view functions, and send transactions. +Aztec.js is a library that provides APIs for managing accounts and interacting with contracts on the Aztec network. It communicates with the [Aztec RPC Server](https://docs.aztec.network/apis/aztec-rpc/interfaces/AztecRPC) through an `AztecRPCClient` implementation, allowing developers to easily register new accounts, deploy contracts, view functions, and send transactions. -### Usage +## Usage -#### Deploy a contract +### Create a new account ```typescript -import { ContractDeployer } from '@aztec/aztec.js'; +import { getSchnorrAccount } from '@aztec/aztec.js'; +import { GrumpkinPrivateKey } from '@aztec/types'; -const deployer = new ContractDeployer(contractAbi, aztecRpcServer); -const tx = deployer.deploy(constructorArgs[0], constructorArgs[1]).send(); -// wait for tx to be mined -const receipt = await tx.wait(); -console.log(`Contract deployed at ${receipt.contractAddress}`); +const encryptionPrivateKey = GrumpkinPrivateKey.random(); +const signingPrivateKey = GrumpkinPrivateKey.random(); +const wallet = getSchnorrAccount(rpc, encryptionPrivateKey, signingPrivateKey).waitDeploy(); +console.log(`New account deployed at ${wallet.getAddress()}`); ``` -#### Send a transaction +### Deploy a contract ```typescript import { Contract } from '@aztec/aztec.js'; -const contract = await Contract.at(contractAddress, contractAbi, aztecRpcServer); -const tx = contract.methods - .transfer(amount, recipientAddress) - .send({ origin: senderAddress }); +const contract = await Contract.deploy(wallet, MyContractAbi, [...constructorArgs]).send().deployed(); +console.log(`Contract deployed at ${contract.address}`); +``` + +### Send a transaction + +```typescript +import { Contract } from '@aztec/aztec.js'; -// wait for tx to be mined -await tx.wait(); -console.log(`Transferred ${amount} to ${recipientAddress}!`); +const contract = await Contract.at(contractAddress, MyContractAbi, wallet); +const tx = await contract.methods.transfer(amount, recipientAddress).send().wait(); +console.log(`Transferred ${amount} to ${recipientAddress} on block ${tx.blockNumber}`); ``` -#### Call a view function +### Call a view function ```typescript import { Contract } from '@aztec/aztec.js'; -const contract = await Contract.at(contractAddress, contractAbi, aztecRpcServer); -const balance = contract.methods - .getBalance(accountPublicKey)) - .view({ from: accountAddress }); -console.log(`Account balance: ${balance}.`); +const contract = await Contract.at(contractAddress, MyContractAbi, wallet); +const balance = await contract.methods.getBalance(wallet.getAddress()).view(); +console.log(`Account balance is ${balance}`); ``` diff --git a/yarn-project/aztec.js/package.json b/yarn-project/aztec.js/package.json index 87846f730cb9..12d26f8484b6 100644 --- a/yarn-project/aztec.js/package.json +++ b/yarn-project/aztec.js/package.json @@ -19,6 +19,7 @@ "build": "yarn clean && tsc -b && webpack", "build:web": "webpack", "build:dev": "tsc -b --watch", + "build:ts": "tsc -b", "clean": "rm -rf ./dest .tsbuildinfo", "formatting": "run -T prettier --check ./src && run -T eslint ./src", "formatting:fix": "run -T prettier -w ./src", diff --git a/yarn-project/aztec.js/package.local.json b/yarn-project/aztec.js/package.local.json index ae44d5384f7f..bdabc013c57a 100644 --- a/yarn-project/aztec.js/package.local.json +++ b/yarn-project/aztec.js/package.local.json @@ -1,5 +1,8 @@ { "scripts": { - "build": "yarn clean && tsc -b && webpack" + "build": "yarn clean && tsc -b && webpack", + "build:web": "webpack", + "build:dev": "tsc -b --watch", + "build:ts": "tsc -b" } } diff --git a/yarn-project/aztec.js/src/account/index.ts b/yarn-project/aztec.js/src/account/index.ts index eee5ce8e1e6b..4db12237ee81 100644 --- a/yarn-project/aztec.js/src/account/index.ts +++ b/yarn-project/aztec.js/src/account/index.ts @@ -1,3 +1,24 @@ +/** + * The `account` module provides utilities for managing accounts. The most common methods to use + * are {@link getEcdsaAccount} and {@link getSchnorrAccount}, which return {@link AccountManager} instances + * using the default ECDSA or Schnorr account implementation respectively. The {@link AccountManager} class then + * allows to deploy and register a fresh account, or to obtain a `Wallet` instance out of an account already deployed. + * + * ```ts + * const encryptionPrivateKey = GrumpkinScalar.random(); + * const signingPrivateKey = GrumpkinScalar.random(); + * const wallet = getSchnorrAccount(rpc, encryptionPrivateKey, signingPrivateKey).waitDeploy(); + * ``` + * + * For testing purposes, consider using the {@link createAccount} and {@link createAccounts} methods, + * which create, register, and deploy random accounts, and return their associated `Wallet`s. + * + * For implementing your own account contract, the recommended way is to extend from the base + * {@link BaseAccountContract} class. + * Read more in {@link https://docs.aztec.network/dev_docs/wallets/writing_an_account_contract | Writing an account contract}. + * + * @packageDocumentation + */ import { AztecRPC, CompleteAddress, GrumpkinPrivateKey } from '@aztec/types'; import { AccountContract, AccountWallet, AztecAddress, Fr } from '../index.js'; @@ -8,6 +29,7 @@ import { AccountManager } from './manager/index.js'; export * from './contract/index.js'; export * from './defaults/index.js'; +export * from './utils.js'; export { AccountInterface, AuthWitnessProvider } from './interface.js'; export { AccountManager, CompleteAddress }; diff --git a/yarn-project/aztec.js/src/utils/account.ts b/yarn-project/aztec.js/src/account/utils.ts similarity index 96% rename from yarn-project/aztec.js/src/utils/account.ts rename to yarn-project/aztec.js/src/account/utils.ts index 8bf9bda47981..fcf63096b3a6 100644 --- a/yarn-project/aztec.js/src/utils/account.ts +++ b/yarn-project/aztec.js/src/account/utils.ts @@ -5,7 +5,7 @@ import { getSchnorrAccount } from '../index.js'; import { AccountWallet } from '../wallet/account_wallet.js'; /** - * Deploys and registers a new account using random private keys and returns the associated wallet. Useful for testing. + * Deploys and registers a new account using random private keys and returns the associated Schnorr account wallet. Useful for testing. * @param rpc - RPC client. * @returns - A wallet for a fresh account. */ 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 df444dff0628..6a9458f27c5d 100644 --- a/yarn-project/aztec.js/src/contract/base_contract_interaction.ts +++ b/yarn-project/aztec.js/src/contract/base_contract_interaction.ts @@ -6,12 +6,12 @@ import { SentTx } from './sent_tx.js'; * Represents options for calling a (constrained) function in a contract. * Allows the user to specify the sender address and nonce for a transaction. */ -export interface SendMethodOptions { +export type SendMethodOptions = { /** * Wether to skip the simulation of the public part of the transaction. */ skipPublicSimulation?: boolean; -} +}; /** * Base class for an interaction with a contract, be it a deployment, a function call, or a batch. 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 23753d6eb887..e8a58728fe4c 100644 --- a/yarn-project/aztec.js/src/contract/contract_function_interaction.ts +++ b/yarn-project/aztec.js/src/contract/contract_function_interaction.ts @@ -11,12 +11,12 @@ export { SendMethodOptions }; * Represents the options for a view method in a contract function interaction. * Allows specifying the address from which the view method should be called. */ -export interface ViewMethodOptions { +export type ViewMethodOptions = { /** * The sender's Aztec address. */ from?: AztecAddress; -} +}; /** * This is the class that is returned when calling e.g. `contract.methods.myMethod(arg0, arg1)`. diff --git a/yarn-project/aztec.js/src/contract/index.ts b/yarn-project/aztec.js/src/contract/index.ts index 0079784c7d78..9ef6df450499 100644 --- a/yarn-project/aztec.js/src/contract/index.ts +++ b/yarn-project/aztec.js/src/contract/index.ts @@ -1,3 +1,40 @@ +/** + * The `contract` module provides utilities for deploying and interacting with contracts, based on a + * `Wallet` instance and a compiled artifact. Refer to the {@link account} module for how to obtain a valid + * `Wallet` instance, and to the {@link https://docs.aztec.network/dev_docs/contracts/compiling | Compiling contracts} + * section of the documentation for how to generate an artifact out of your Noir source code. + * + * The {@link Contract} class is the main class in this module, and provides static methods for deploying + * a contract or interacting with an already deployed one. The `methods` property of the contract instance + * provides access to private, public, and view methods, that can be invoked in a transaction via `send()`, + * or can be queried via `view()`. + * + * ```ts + * const contract = await Contract.deploy(wallet, MyContractAbi, [...constructorArgs]).send().deployed(); + * console.log(`Contract deployed at ${contract.address}`); + * ``` + * + * ```ts + * const contract = await Contract.at(address, MyContractAbi, wallet); + * await contract.methods.mint(1000, owner).send().wait(); + * console.log(`Total supply is now ${await contract.methods.totalSupply().view()}`); + * ``` + * + * The result of calling a method in a contract instance, such as `contract.methods.mint(1000, owner)` + * in the example, is a {@link ContractFunctionInteraction} instance. Usually this will be just sent as + * a transaction to the network via the `send` method, but you can also `simulate` it without sending, + * or obtaining the `request` for aggregating into a {@link BatchCall}. + * + * The result of `send`ing a transaction is a {@link SentTx} object, from which you can get the + * transaction hash, or simply `wait` until the transaction is mined and the local RPC server + * has synchronised its changes. + * + * @remarks If you are using typescript, consider using the + * {@link https://docs.aztec.network/dev_docs/contracts/compiling#typescript-interfaces | autogenerated type-safe interfaces} + * for interacting with your contracts. + * + * @packageDocumentation + */ export * from './contract.js'; export * from './contract_function_interaction.js'; export * from './sent_tx.js'; diff --git a/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts b/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts index 9e80b8d45a02..b10c6df43fc2 100644 --- a/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts +++ b/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts @@ -18,7 +18,7 @@ import { DeploySentTx } from './deploy_sent_tx.js'; * Options for deploying a contract on the Aztec network. * Allows specifying a portal contract, contract address salt, and additional send method options. */ -export interface DeployOptions extends SendMethodOptions { +export type DeployOptions = { /** * The Ethereum address of the Portal contract. */ @@ -27,7 +27,7 @@ export interface DeployOptions extends SendMethodOptions { * An optional salt value used to deterministically calculate the contract address. */ contractAddressSalt?: Fr; -} +} & SendMethodOptions; /** * Creates a TxRequest from a contract ABI, for contract deployment. diff --git a/yarn-project/aztec.js/src/utils/index.ts b/yarn-project/aztec.js/src/utils/index.ts index cddef692554e..a2df1771c57a 100644 --- a/yarn-project/aztec.js/src/utils/index.ts +++ b/yarn-project/aztec.js/src/utils/index.ts @@ -1,5 +1,4 @@ export * from './secrets.js'; -export * from './account.js'; export * from './pub_key.js'; export * from './l1_contracts.js'; export * from './l2_contracts.js'; diff --git a/yarn-project/types/src/contract_data.ts b/yarn-project/types/src/contract_data.ts index 56b5d5f0bc79..933b8322b990 100644 --- a/yarn-project/types/src/contract_data.ts +++ b/yarn-project/types/src/contract_data.ts @@ -120,7 +120,7 @@ export class ExtendedContractData { private publicFunctions: EncodedContractFunction[], /** Partial addresses of the contract. */ public readonly partialAddress: PartialAddress, - /** Public keys of the contract. */ + /** Public key of the contract. */ public readonly publicKey: PublicKey, ) { this.bytecode = serializeBufferArrayToVector(publicFunctions.map(fn => fn.toBuffer())); diff --git a/yarn-project/types/src/interfaces/aztec_rpc.ts b/yarn-project/types/src/interfaces/aztec_rpc.ts index 775ad61c6e09..0a5d1fdddd96 100644 --- a/yarn-project/types/src/interfaces/aztec_rpc.ts +++ b/yarn-project/types/src/interfaces/aztec_rpc.ts @@ -1,5 +1,4 @@ -import { AztecAddress, EthAddress, Fr, GrumpkinPrivateKey, PartialAddress } from '@aztec/circuits.js'; -import { ContractAbi } from '@aztec/foundation/abi'; +import { AztecAddress, Fr, GrumpkinPrivateKey, PartialAddress } from '@aztec/circuits.js'; import { AuthWitness, CompleteAddress, @@ -13,191 +12,163 @@ import { TxReceipt, } from '@aztec/types'; -/** - * Represents a deployed contract on the Aztec network. - * Contains the contract ABI, address, and associated portal contract address. - */ -export interface DeployedContract { - /** - * The Application Binary Interface of the deployed contract. - */ - abi: ContractAbi; - /** - * The complete address representing the contract on L2. - */ - completeAddress: CompleteAddress; - /** - * The Ethereum address of the L1 portal contract. - */ - portalContract: EthAddress; -} - -/** - * Provides basic information about the running node. - */ -export type NodeInfo = { - /** - * Version as tracked in the aztec-packages repository. - */ - sandboxVersion: string; - /** - * The nargo version compatible with this sandbox version - */ - compatibleNargoVersion: string; - /** - * L1 chain id. - */ - chainId: number; - /** - * Protocol version. - */ - protocolVersion: number; - /** - * The rollup contract address - */ - rollupAddress: EthAddress; -}; - -/** Provides up to which block has been synced by different components. */ -export type SyncStatus = { - /** Up to which block has been synched for blocks and txs. */ - blocks: number; - /** Up to which block has been synched for notes, indexed by each public key being monitored. */ - notes: Record; -}; +import { DeployedContract } from './deployed-contract.js'; +import { NodeInfo } from './node-info.js'; +import { SyncStatus } from './sync-status.js'; // docs:start:rpc-interface /** - * Represents an Aztec RPC implementation. - * Provides functionality for all the operations needed to interact with the Aztec network, - * including account management, contract deployment, transaction creation, and execution, - * as well as storage and view functions for smart contracts. + * The Aztec RPC Server runs locally for each user, providing functionality for all the operations + * needed to interact with the Aztec network, including account management, private data management, + * transaction local simulation, and access to an Aztec node. This interface, as part of a Wallet, + * is exposed to dapps for interacting with the network on behalf of the user. */ export interface AztecRPC { /** - * Insert a witness for a given message hash. - * @param authWitness - The auth witness to insert. + * Insert an auth witness for a given message hash. Auth witnesses are used to authorise actions on + * behalf of a user. For instance, a token transfer initiated by a different address may request + * authorisation from the user to move their tokens. This authorisation is granted by the user + * account contract by verifying an auth witness requested to the execution oracle. Witnesses are + * usually a signature over a hash of the action to be authorised, but their actual contents depend + * on the account contract that consumes them. + * + * @param authWitness - The auth witness to insert. Composed of an identifier, which is the hash of + * the action to be authorised, and the actual witness as an array of fields, which are to be + * deserialised and processed by the account contract. */ addAuthWitness(authWitness: AuthWitness): Promise; /** - * Registers an account in the Aztec RPC server. + * Registers a user account in the Aztec RPC server given its master encryption private key. + * Once a new account is registered, the RPC server will trial-decrypt all published notes on + * the chain and store those that correspond to the registered account. * * @param privKey - Private key of the corresponding user master public key. - * @param partialAddress - A partial address of the account contract corresponding to the account being registered. - * @returns Empty promise. + * @param partialAddress - The partial address of the account contract corresponding to the account being registered. * @throws If the account is already registered. */ registerAccount(privKey: GrumpkinPrivateKey, partialAddress: PartialAddress): Promise; /** - * Registers recipient in the Aztec RPC server. - * @param recipient - A complete address of the recipient - * @returns Empty promise. + * Registers a recipient in the Aztec RPC server. This is required when sending encrypted notes to + * a user who hasn't deployed their account contract yet. Since their account is not deployed, their + * encryption public key has not been broadcasted, so we need to manually register it on the RPC server + * in order to be able to encrypt data for this recipient. + * + * @param recipient - The complete address of the recipient * @remarks Called recipient because we can only send notes to this account and not receive them via this RPC server. - * This is because we don't have the associated private key and for this reason we can't decrypt - * the recipient's notes. We can send notes to this account because we can encrypt them with the recipient's - * public key. + * This is because we don't have the associated private key and for this reason we can't decrypt + * the recipient's notes. We can send notes to this account because we can encrypt them with the recipient's + * public key. */ registerRecipient(recipient: CompleteAddress): Promise; /** - * Retrieves the list of accounts added to this rpc server. - * The addresses are returned as a promise that resolves to an array of CompleteAddress objects. - * - * @returns A promise that resolves to an array of the accounts registered on this RPC server. + * Retrieves the user accounts registered on this rpc server. + * @returns An array of the accounts registered on this RPC server. */ getRegisteredAccounts(): Promise; /** * Retrieves the complete address of the account corresponding to the provided aztec address. - * @param address - The aztec address of the account contract. - * @returns A promise that resolves to the complete address of the requested account. + * Complete addresses include the address, the partial address, and the encryption public key. + * + * @param address - The address of account. + * @returns The complete address of the requested account if found. */ getRegisteredAccount(address: AztecAddress): Promise; /** - * Retrieves the list of recipients added to this rpc server. - * The addresses are returned as a promise that resolves to an array of CompleteAddress objects. - * - * @returns A promise that resolves to an array registered recipients on this RPC server. + * Retrieves the recipients added to this rpc server. + * @returns An array of recipients registered on this RPC server. */ getRecipients(): Promise; /** * Retrieves the complete address of the recipient corresponding to the provided aztec address. + * Complete addresses include the address, the partial address, and the encryption public key. + * * @param address - The aztec address of the recipient. - * @returns A promise that resolves to the complete address of the requested recipient. + * @returns The complete address of the requested recipient. */ getRecipient(address: AztecAddress): Promise; /** - * Add an array of deployed contracts to the database. - * Each contract should contain ABI, address, and portalContract information. + * Adds deployed contracts to the RPC server. Deployed contract information is used to access the + * contract code when simulating local transactions. This is automatically called by aztec.js when + * deploying a contract. Dapps that wish to interact with contracts already deployed should register + * these contracts in their users' RPC server through this method. * - * @param contracts - An array of DeployedContract objects containing contract ABI, address, and portalContract. - * @returns A Promise that resolves once all the contracts have been added to the database. + * @param contracts - An array of DeployedContract objects containing contract ABI, address, and portal contract. */ addContracts(contracts: DeployedContract[]): Promise; /** - * Retrieves the list of addresses of contracts added to this rpc server. - * @returns A promise that resolves to an array of contracts addresses registered on this RPC server. + * Retrieves the addresses of contracts added to this rpc server. + * @returns An array of contracts addresses registered on this RPC server. */ getContracts(): Promise; /** - * Create a transaction for a contract function call with the provided arguments. - * Throws an error if the contract or function is unknown. + * Creates a transaction based on the provided preauthenticated execution request. This will + * run a local simulation of the private execution (and optionally of public as well), assemble + * the zero-knowledge proof for the private execution, and return the transaction object. * * @param txRequest - An authenticated tx request ready for simulation * @param simulatePublic - Whether to simulate the public part of the transaction. - * @returns A Tx ready to send to the p2p pool for execution. + * @returns A transaction ready to be sent to the network for excution. + * @throws If the code for the functions executed in this transaction has not been made available via `addContracts`. */ simulateTx(txRequest: TxExecutionRequest, simulatePublic: boolean): Promise; /** - * Send a transaction. - * @param tx - The transaction. + * Sends a transaction to an Aztec node to be broadcasted to the network and mined. + * @param tx - The transaction as created via `simulateTx`. * @returns A hash of the transaction, used to identify it. */ sendTx(tx: Tx): Promise; /** - * Fetches a transaction receipt for a tx. + * Fetches a transaction receipt for a given transaction hash. Returns a mined receipt if it was added + * to the chain, a pending receipt if it's still in the mempool of the connected Aztec node, or a dropped + * receipt if not found in the connected Aztec node. + * * @param txHash - The transaction hash. * @returns A receipt of the transaction. */ getTxReceipt(txHash: TxHash): Promise; /** - * Retrieves the private storage data at a specified contract address and storage slot. - * The returned data is data at the storage slot or throws an error if the contract is not deployed. + * Retrieves the private storage data at a specified contract address and storage slot. Returns only data + * encrypted for the specified owner that has been already decrypted by the RPC server. Note that there + * may be multiple notes for a user in a single slot. * * @param owner - The address for whom the private data is encrypted. * @param contract - The AztecAddress of the target contract. - * @param storageSlot - The Fr representing the storage slot to be fetched. + * @param storageSlot - The storage slot to be fetched. * @returns A set of note preimages for the owner in that contract and slot. + * @throws If the contract is not deployed. */ getPrivateStorageAt(owner: AztecAddress, contract: AztecAddress, storageSlot: Fr): Promise; /** * Retrieves the public storage data at a specified contract address and storage slot. - * The returned data is data at the storage slot or throws an error if the contract is not deployed. * * @param contract - The AztecAddress of the target contract. * @param storageSlot - The Fr representing the storage slot to be fetched. * @returns A buffer containing the public storage data at the storage slot. + * @throws If the contract is not deployed. */ getPublicStorageAt(contract: AztecAddress, storageSlot: Fr): Promise; /** - * Find the nonce(s) for a note in a tx with given preimage at a specified contract address and storage slot. + * Finds the nonce(s) for a note in a tx with given preimage at a specified contract address and storage slot. * @param contract - The contract address of the note. * @param storageSlot - The storage slot of the note. * @param preimage - The note preimage. * @param txHash - The tx hash of the tx containing the note. - * @returns The nonces of the note. It's an array because there might be more than one note with the same preimage. + * @returns The nonces of the note. + * @remarks More than single nonce may be returned since there might be more than one note with the same preimage. */ getNoteNonces(contract: AztecAddress, storageSlot: Fr, preimage: NotePreimage, txHash: TxHash): Promise; @@ -210,28 +181,32 @@ export interface AztecRPC { * @param functionName - The name of the function to be called in the contract. * @param args - The arguments to be provided to the function. * @param to - The address of the contract to be called. - * @param from - (Optional) The caller of the transaction. + * @param from - (Optional) The msg sender to set for the call. * @returns The result of the view function call, structured based on the function ABI. */ viewTx(functionName: string, args: any[], to: AztecAddress, from?: AztecAddress): Promise; /** - * Get the extended contract data for this contract. - * @param contractAddress - The contract data address. - * @returns The extended contract data or undefined if not found. + * Gets the extended contract data for this contract. Extended contract data includes the address, + * portal contract address on L1, public functions, partial address, and encryption public key. + * + * @param contractAddress - The contract's address. + * @returns The extended contract data if found. */ getExtendedContractData(contractAddress: AztecAddress): Promise; /** - * Lookup the L2 contract data for this contract. - * Contains the ethereum portal address . - * @param contractAddress - The contract data address. - * @returns The contract's address & portal address. + * Gets the portal contract address on L1 for the given contract. + * + * @param contractAddress - The contract's address. + * @returns The contract's portal address if found. */ getContractData(contractAddress: AztecAddress): Promise; /** - * Gets L2 block unencrypted logs. + * Gets unencrypted public logs from the specified block range. Logs are grouped by block and then by + * transaction. Use the `L2BlockL2Logs.unrollLogs` helper function to get an flattened array of logs instead. + * * @param from - Number of the L2 block to which corresponds the first unencrypted logs to be returned. * @param limit - The maximum number of unencrypted logs to return. * @returns The requested unencrypted logs. @@ -245,7 +220,8 @@ export interface AztecRPC { getBlockNumber(): Promise; /** - * Returns the information about the server's node + * Returns the information about the server's node. Includes current Sandbox version, compatible Noir version, + * L1 chain identifier, protocol version, and L1 address of the rollup contract. * @returns - The node information. */ getNodeInfo(): Promise; @@ -253,8 +229,8 @@ export interface AztecRPC { /** * Checks whether all the blocks were processed (tree roots updated, txs updated with block info, etc.). * @returns True if there are no outstanding blocks to be synched. - * @remarks This indicates that blocks and transactions are synched even if notes are not. - * @remarks Compares local block number with the block number from aztec node. + * @remarks This indicates that blocks and transactions are synched even if notes are not. Compares local block number with the block number from aztec node. + * @deprecated Use `getSyncStatus` instead. */ isGlobalStateSynchronised(): Promise; @@ -262,13 +238,16 @@ export interface AztecRPC { * Checks if the specified account is synchronised. * @param account - The aztec address for which to query the sync status. * @returns True if the account is fully synched, false otherwise. + * @deprecated Use `getSyncStatus` instead. * @remarks Checks whether all the notes from all the blocks have been processed. If it is not the case, the - * retrieved information from contracts might be old/stale (e.g. old token balance). + * retrieved information from contracts might be old/stale (e.g. old token balance). */ isAccountStateSynchronised(account: AztecAddress): Promise; /** - * Returns the latest block that has been synchronised by the synchronizer and each account. + * Returns the latest block that has been synchronised globally and for each account. The global block number + * indicates whether global state has been updated up to that block, whereas each address indicates up to which + * block the private state has been synced for that account. * @returns The latest block synchronised for blocks, and the latest block synched for notes for each public key being tracked. */ getSyncStatus(): Promise; diff --git a/yarn-project/types/src/interfaces/deployed-contract.ts b/yarn-project/types/src/interfaces/deployed-contract.ts new file mode 100644 index 000000000000..6afa2d285e4b --- /dev/null +++ b/yarn-project/types/src/interfaces/deployed-contract.ts @@ -0,0 +1,22 @@ +import { EthAddress } from '@aztec/circuits.js'; +import { ContractAbi } from '@aztec/foundation/abi'; +import { CompleteAddress } from '@aztec/types'; + +/** + * Represents a deployed contract on the Aztec network. + * Contains the contract ABI, address, and associated portal contract address. + */ +export interface DeployedContract { + /** + * The Application Binary Interface of the deployed contract. + */ + abi: ContractAbi; + /** + * The complete address representing the contract on L2. + */ + completeAddress: CompleteAddress; + /** + * The Ethereum address of the L1 portal contract. + */ + portalContract: EthAddress; +} diff --git a/yarn-project/types/src/interfaces/index.ts b/yarn-project/types/src/interfaces/index.ts index bc3101ac1169..d53098ad94ca 100644 --- a/yarn-project/types/src/interfaces/index.ts +++ b/yarn-project/types/src/interfaces/index.ts @@ -4,3 +4,6 @@ export * from './data_commitment_provider.js'; export * from './l1_l2_message_provider.js'; export * from './aztec-node.js'; export * from './aztec_rpc.js'; +export * from './deployed-contract.js'; +export * from './node-info.js'; +export * from './sync-status.js'; diff --git a/yarn-project/types/src/interfaces/node-info.ts b/yarn-project/types/src/interfaces/node-info.ts new file mode 100644 index 000000000000..4037d4917ed8 --- /dev/null +++ b/yarn-project/types/src/interfaces/node-info.ts @@ -0,0 +1,27 @@ +import { EthAddress } from '@aztec/circuits.js'; + +/** + * Provides basic information about the running node. + */ +export type NodeInfo = { + /** + * Version as tracked in the aztec-packages repository. + */ + sandboxVersion: string; + /** + * The nargo version compatible with this sandbox version + */ + compatibleNargoVersion: string; + /** + * L1 chain id. + */ + chainId: number; + /** + * Protocol version. + */ + protocolVersion: number; + /** + * The rollup contract address + */ + rollupAddress: EthAddress; +}; diff --git a/yarn-project/types/src/interfaces/sync-status.ts b/yarn-project/types/src/interfaces/sync-status.ts new file mode 100644 index 000000000000..75770ffe14b6 --- /dev/null +++ b/yarn-project/types/src/interfaces/sync-status.ts @@ -0,0 +1,7 @@ +/** Provides up to which block has been synced by different components. */ +export type SyncStatus = { + /** Up to which block has been synched for blocks and txs. */ + blocks: number; + /** Up to which block has been synched for notes, indexed by each public key being monitored. */ + notes: Record; +}; From 3995de91ebfed185714b0b2045c1e1243386e778 Mon Sep 17 00:00:00 2001 From: Dan Lee <142251406+dan-aztec@users.noreply.github.com> Date: Fri, 22 Sep 2023 06:06:53 -0700 Subject: [PATCH 07/12] chore: run formatting:fix for box lint (#2479) landed without formatting previously... # Checklist: Remove the checklist to signal you've completed it. Enable auto-merge if the PR is ready to merge. - [ ] If the pull request requires a cryptography review (e.g. cryptographic algorithm implementations) I have added the 'crypto' tag. - [ ] I have reviewed my diff in github, line by line and removed unexpected formatting changes, testing logs, or commented-out code. - [ ] Every change is related to the PR description. - [ ] I have [linked](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) this pull request to relevant issues (if any exist). --- .../contract_function_form.module.scss | 99 +++++++++---------- .../app/components/contract_function_form.tsx | 9 +- .../src/app/components/copy.module.scss | 10 +- .../src/app/components/dropdown.module.scss | 74 +++++++------- .../src/app/components/popup.module.scss | 40 ++++---- .../src/app/components/select.module.scss | 72 +++++++------- .../components/wallet_dropdown.module.scss | 16 +-- .../blank-react/src/app/contract.module.scss | 68 ++++++------- .../blank-react/src/app/home.module.scss | 42 ++++---- yarn-project/boxes/blank/src/index.html | 18 ++-- .../contract_function_form.module.scss | 99 +++++++++---------- .../app/components/contract_function_form.tsx | 9 +- .../src/app/components/copy.module.scss | 10 +- .../src/app/components/dropdown.module.scss | 74 +++++++------- .../src/app/components/popup.module.scss | 40 ++++---- .../src/app/components/select.module.scss | 72 +++++++------- .../components/wallet_dropdown.module.scss | 16 +-- .../src/app/contract.module.scss | 68 ++++++------- .../private-token/src/app/home.module.scss | 42 ++++---- 19 files changed, 444 insertions(+), 434 deletions(-) diff --git a/yarn-project/boxes/blank-react/src/app/components/contract_function_form.module.scss b/yarn-project/boxes/blank-react/src/app/components/contract_function_form.module.scss index f28047b581ab..056dcc719ff6 100644 --- a/yarn-project/boxes/blank-react/src/app/components/contract_function_form.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/contract_function_form.module.scss @@ -1,67 +1,66 @@ .input { - border: none; - outline-width: 0; - outline-color: rgba(0, 0, 0, 0); - padding: 2px 20px 0 20px; - width: 100%; - height: 45px; - color: #000; - border: 1px solid rgba(0, 0, 0, 0); - font-size: 16px; - text-align: left; - font-weight: 400; - border-radius: 10px; - text-align: left; - text-overflow: ellipsis; - transition: box-shadow .2s; - box-shadow: 0px 4px 10px rgba(0, 0, 0, .1); - background-color: white; - -webkit-appearance: none; + border: none; + outline-width: 0; + outline-color: rgba(0, 0, 0, 0); + padding: 2px 20px 0 20px; + width: 100%; + height: 45px; + color: #000; + border: 1px solid rgba(0, 0, 0, 0); + font-size: 16px; + text-align: left; + font-weight: 400; + border-radius: 10px; + text-align: left; + text-overflow: ellipsis; + transition: box-shadow 0.2s; + box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); + background-color: white; + -webkit-appearance: none; - - &:disabled { - color: #4a4a4a; - background-color: rgba(239, 239, 239, 0.3); - background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); - -webkit-text-fill-color: #4a4a4a; - cursor: not-allowed; - } + &:disabled { + color: #4a4a4a; + background-color: rgba(239, 239, 239, 0.3); + background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); + -webkit-text-fill-color: #4a4a4a; + cursor: not-allowed; + } } .label { - font-weight: 450; - font-size: 18px; - display: flex; - width: 100%; - flex-direction: column; - text-align: left; - margin-bottom: 15px; - justify-content: space-between; + font-weight: 450; + font-size: 18px; + display: flex; + width: 100%; + flex-direction: column; + text-align: left; + margin-bottom: 15px; + justify-content: space-between; } .inputWrapper { - width: 100%; - display: flex; - gap: 15px; + width: 100%; + display: flex; + gap: 15px; } .field { - display: flex; - justify-content: start; - flex-direction: column; - align-items: flex-start; + display: flex; + justify-content: start; + flex-direction: column; + align-items: flex-start; } .content { - display: flex; - justify-content: space-between; - flex-direction: column; - margin: 30px; - width: 450px; - gap: 30px; + display: flex; + justify-content: space-between; + flex-direction: column; + margin: 30px; + width: 450px; + gap: 30px; } .actionButton { - width: 100%; - align-self: center; -} \ No newline at end of file + width: 100%; + align-self: center; +} diff --git a/yarn-project/boxes/blank-react/src/app/components/contract_function_form.tsx b/yarn-project/boxes/blank-react/src/app/components/contract_function_form.tsx index e31c940a927f..69916e7061ee 100644 --- a/yarn-project/boxes/blank-react/src/app/components/contract_function_form.tsx +++ b/yarn-project/boxes/blank-react/src/app/components/contract_function_form.tsx @@ -86,7 +86,14 @@ async function handleFunctionCall( if (functionAbi.functionType === 'unconstrained') { return await viewContractFunction(contractAddress!, contractAbi, functionName, typedArgs, rpcClient, wallet); } else { - const txnReceipt = await callContractFunction(contractAddress!, contractAbi, functionName, typedArgs, rpcClient, wallet); + const txnReceipt = await callContractFunction( + contractAddress!, + contractAbi, + functionName, + typedArgs, + rpcClient, + wallet, + ); return `Transaction ${txnReceipt.status} on block number ${txnReceipt.blockNumber}`; } } diff --git a/yarn-project/boxes/blank-react/src/app/components/copy.module.scss b/yarn-project/boxes/blank-react/src/app/components/copy.module.scss index 6b4a52bf549c..26b2360c58a0 100644 --- a/yarn-project/boxes/blank-react/src/app/components/copy.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/copy.module.scss @@ -1,6 +1,6 @@ .copy { - cursor: pointer; - width: 35px; - height: 25px; - padding: 2px 8px; -} \ No newline at end of file + cursor: pointer; + width: 35px; + height: 25px; + padding: 2px 8px; +} diff --git a/yarn-project/boxes/blank-react/src/app/components/dropdown.module.scss b/yarn-project/boxes/blank-react/src/app/components/dropdown.module.scss index 8041aff4bc8f..18bd40b356bd 100644 --- a/yarn-project/boxes/blank-react/src/app/components/dropdown.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/dropdown.module.scss @@ -1,68 +1,68 @@ .dropdownWrapper { - position: absolute; - top: 60px; - right: 0px; - border-radius: 10px; - display: flex; - overflow: hidden; - flex-direction: column; - gap: 1px; - border: 1px solid #ebeaea; - background-color: #ebeaea; - z-index: 1; + position: absolute; + top: 60px; + right: 0px; + border-radius: 10px; + display: flex; + overflow: hidden; + flex-direction: column; + gap: 1px; + border: 1px solid #ebeaea; + background-color: #ebeaea; + z-index: 1; } .dropdownOptionBackground { - background-color: white; + background-color: white; } .dropdownOption { - font-size: 14px; - padding: 10px 25px; - white-space: nowrap; - cursor: pointer; - font-weight: 600; - justify-content: space-between; - letter-spacing: 0.5px; - display: flex; + font-size: 14px; + padding: 10px 25px; + white-space: nowrap; + cursor: pointer; + font-weight: 600; + justify-content: space-between; + letter-spacing: 0.5px; + display: flex; } .singleOption { - text-align: center; - align-items: center; - justify-content: center; + text-align: center; + align-items: center; + justify-content: center; } .dropdownOption.disabled { - background-image: initial; - cursor: default; - background-color: #c4c4c4; + background-image: initial; + cursor: default; + background-color: #c4c4c4; } .dropdownOptionBackground:hover { - background-color: #ebeaea; + background-color: #ebeaea; } .dropdownOptionBackground.disabled:hover { - background-color: white; + background-color: white; } .sublabel { - text-align: right; + text-align: right; } .sublabels { - display: flex; - flex-direction: row; - font-weight: 450; + display: flex; + flex-direction: row; + font-weight: 450; } .feeOption { - gap: 5px; - display: flex; - flex-direction: column; + gap: 5px; + display: flex; + flex-direction: column; } .label { - color: #2f1f49; -} \ No newline at end of file + color: #2f1f49; +} diff --git a/yarn-project/boxes/blank-react/src/app/components/popup.module.scss b/yarn-project/boxes/blank-react/src/app/components/popup.module.scss index ecaab4c22fb1..0917ca93f413 100644 --- a/yarn-project/boxes/blank-react/src/app/components/popup.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/popup.module.scss @@ -1,27 +1,27 @@ .popup { - width: 66vw; - position: absolute; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - background-color: white; - border-radius: 20px; - justify-content: space-around; - box-shadow: 0px 4px 10px rgba(0, 0, 0, .1); - border: 3px solid rgb(47, 31, 73); - align-items: center; - gap: 30px; - padding: 30px; - overflow: scroll; - min-width: 600px; - z-index: 100; + width: 66vw; + position: absolute; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: white; + border-radius: 20px; + justify-content: space-around; + box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); + border: 3px solid rgb(47, 31, 73); + align-items: center; + gap: 30px; + padding: 30px; + overflow: scroll; + min-width: 600px; + z-index: 100; } .alert { - width: 20px; + width: 20px; } .content { - width: 100%; -} \ No newline at end of file + width: 100%; +} diff --git a/yarn-project/boxes/blank-react/src/app/components/select.module.scss b/yarn-project/boxes/blank-react/src/app/components/select.module.scss index 71ecf95ab7f1..d639c52f47d7 100644 --- a/yarn-project/boxes/blank-react/src/app/components/select.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/select.module.scss @@ -1,65 +1,65 @@ .selectBox { - border-radius: 10px; - background-color: white; - position: relative; - font-family: Sohne; - font-size: 16px; - height: 45px; - cursor: pointer; - font-weight: 450; + border-radius: 10px; + background-color: white; + position: relative; + font-family: Sohne; + font-size: 16px; + height: 45px; + cursor: pointer; + font-weight: 450; - @media (max-width: 480px) { - margin: 0; - } + @media (max-width: 480px) { + margin: 0; + } } .icon { - min-width: 12px; + min-width: 12px; } .border { - box-shadow: 0px 4px 14px rgba(0, 0, 0, 0.1); + box-shadow: 0px 4px 14px rgba(0, 0, 0, 0.1); } .innerFrame { - height: 45px; - padding: 0 15px; - display: flex; - align-items: center; - justify-content: space-between; - overflow: hidden; - gap: 10px; + height: 45px; + padding: 0 15px; + display: flex; + align-items: center; + justify-content: space-between; + overflow: hidden; + gap: 10px; } .innerFrameWithButton { - padding-right: 0px; + padding-right: 0px; } .value { - white-space: nowrap; + white-space: nowrap; } .dropdown { - top: 45px; - left: 0%; - min-width: 130px; - width: 100%; + top: 45px; + left: 0%; + min-width: 130px; + width: 100%; } .closeButton { - height: 30px; - padding: 15px 15px 15px 5px; - display: flex; - justify-content: flex-end; - align-items: center; + height: 30px; + padding: 15px 15px 15px 5px; + display: flex; + justify-content: flex-end; + align-items: center; } .disabled { - background-color: rgba(239, 239, 239, 0.3); - color: #4a4a4a; - cursor: not-allowed; + background-color: rgba(239, 239, 239, 0.3); + color: #4a4a4a; + cursor: not-allowed; } .placeholder { - color: #757575; -} \ No newline at end of file + color: #757575; +} diff --git a/yarn-project/boxes/blank-react/src/app/components/wallet_dropdown.module.scss b/yarn-project/boxes/blank-react/src/app/components/wallet_dropdown.module.scss index 8ad6aae3cf6c..27fdfc4f7f72 100644 --- a/yarn-project/boxes/blank-react/src/app/components/wallet_dropdown.module.scss +++ b/yarn-project/boxes/blank-react/src/app/components/wallet_dropdown.module.scss @@ -1,9 +1,9 @@ .walletSelector { - position: fixed; - top: 30px; - right: 30px; - display: flex; - gap: 10px; - flex-direction: row; - align-items: center; -} \ No newline at end of file + position: fixed; + top: 30px; + right: 30px; + display: flex; + gap: 10px; + flex-direction: row; + align-items: center; +} diff --git a/yarn-project/boxes/blank-react/src/app/contract.module.scss b/yarn-project/boxes/blank-react/src/app/contract.module.scss index bd16d1959046..d5404d250357 100644 --- a/yarn-project/boxes/blank-react/src/app/contract.module.scss +++ b/yarn-project/boxes/blank-react/src/app/contract.module.scss @@ -1,53 +1,53 @@ .tos { - position: fixed; - bottom: 30px; - right: 30px; - cursor: pointer; - font-size: 14px; + position: fixed; + bottom: 30px; + right: 30px; + cursor: pointer; + font-size: 14px; } .selectorWrapper { - display: flex; - flex-direction: column; - margin: 30px; - gap: 20px; + display: flex; + flex-direction: column; + margin: 30px; + gap: 20px; } .functions { - display: flex; - flex-direction: row; - gap: 20px; + display: flex; + flex-direction: row; + gap: 20px; } .tag { - font-weight: 450; - display: flex; - position: relative; - flex-direction: column; - font-size: 16px; - gap: 5px; - background-color: #fff; - text-align: right; - padding: 14px 18px; - text-align: center; - background-color: #f9f9f9; - align-self: center; - border-radius: 10px; + font-weight: 450; + display: flex; + position: relative; + flex-direction: column; + font-size: 16px; + gap: 5px; + background-color: #fff; + text-align: right; + padding: 14px 18px; + text-align: center; + background-color: #f9f9f9; + align-self: center; + border-radius: 10px; } .back { - top: 15px; - width: 20px; - left: 30px; - margin-bottom: 15px; + top: 15px; + width: 20px; + left: 30px; + margin-bottom: 15px; } .address { - display: flex; - justify-content: center; - align-items: center; + display: flex; + justify-content: center; + align-items: center; } .title { - font-weight: 500; -} \ No newline at end of file + font-weight: 500; +} diff --git a/yarn-project/boxes/blank-react/src/app/home.module.scss b/yarn-project/boxes/blank-react/src/app/home.module.scss index 12cce21ad73e..44ff7f764465 100644 --- a/yarn-project/boxes/blank-react/src/app/home.module.scss +++ b/yarn-project/boxes/blank-react/src/app/home.module.scss @@ -1,28 +1,28 @@ .main { - display: flex; - gap: 20px; - flex-direction: column; - justify-content: center; - align-items: center; + display: flex; + gap: 20px; + flex-direction: column; + justify-content: center; + align-items: center; } .logo { - position: fixed; - cursor: pointer; - top: 35px; - left: 30px; - height: 35px; + position: fixed; + cursor: pointer; + top: 35px; + left: 30px; + height: 35px; } .privateBackground { - transform: rotate(-20deg); - width: 150vw; - height: 150vh; - font-weight: 500; - opacity: 0.3; - font-size: 14px; - pointer-events: none; - position: absolute; - font-size: 14px; - z-index: 0; -} \ No newline at end of file + transform: rotate(-20deg); + width: 150vw; + height: 150vh; + font-weight: 500; + opacity: 0.3; + font-size: 14px; + pointer-events: none; + position: absolute; + font-size: 14px; + z-index: 0; +} diff --git a/yarn-project/boxes/blank/src/index.html b/yarn-project/boxes/blank/src/index.html index b5a876be4e82..84f225fe8a91 100644 --- a/yarn-project/boxes/blank/src/index.html +++ b/yarn-project/boxes/blank/src/index.html @@ -1,16 +1,14 @@ - + - - - - + + + Minimal Noir Contract Webpack - + - + - - - \ No newline at end of file + + diff --git a/yarn-project/boxes/private-token/src/app/components/contract_function_form.module.scss b/yarn-project/boxes/private-token/src/app/components/contract_function_form.module.scss index f28047b581ab..056dcc719ff6 100644 --- a/yarn-project/boxes/private-token/src/app/components/contract_function_form.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/contract_function_form.module.scss @@ -1,67 +1,66 @@ .input { - border: none; - outline-width: 0; - outline-color: rgba(0, 0, 0, 0); - padding: 2px 20px 0 20px; - width: 100%; - height: 45px; - color: #000; - border: 1px solid rgba(0, 0, 0, 0); - font-size: 16px; - text-align: left; - font-weight: 400; - border-radius: 10px; - text-align: left; - text-overflow: ellipsis; - transition: box-shadow .2s; - box-shadow: 0px 4px 10px rgba(0, 0, 0, .1); - background-color: white; - -webkit-appearance: none; + border: none; + outline-width: 0; + outline-color: rgba(0, 0, 0, 0); + padding: 2px 20px 0 20px; + width: 100%; + height: 45px; + color: #000; + border: 1px solid rgba(0, 0, 0, 0); + font-size: 16px; + text-align: left; + font-weight: 400; + border-radius: 10px; + text-align: left; + text-overflow: ellipsis; + transition: box-shadow 0.2s; + box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); + background-color: white; + -webkit-appearance: none; - - &:disabled { - color: #4a4a4a; - background-color: rgba(239, 239, 239, 0.3); - background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); - -webkit-text-fill-color: #4a4a4a; - cursor: not-allowed; - } + &:disabled { + color: #4a4a4a; + background-color: rgba(239, 239, 239, 0.3); + background: radial-gradient(rgba(239, 239, 239, 0.3), rgba(239, 239, 239, 0.3)); + -webkit-text-fill-color: #4a4a4a; + cursor: not-allowed; + } } .label { - font-weight: 450; - font-size: 18px; - display: flex; - width: 100%; - flex-direction: column; - text-align: left; - margin-bottom: 15px; - justify-content: space-between; + font-weight: 450; + font-size: 18px; + display: flex; + width: 100%; + flex-direction: column; + text-align: left; + margin-bottom: 15px; + justify-content: space-between; } .inputWrapper { - width: 100%; - display: flex; - gap: 15px; + width: 100%; + display: flex; + gap: 15px; } .field { - display: flex; - justify-content: start; - flex-direction: column; - align-items: flex-start; + display: flex; + justify-content: start; + flex-direction: column; + align-items: flex-start; } .content { - display: flex; - justify-content: space-between; - flex-direction: column; - margin: 30px; - width: 450px; - gap: 30px; + display: flex; + justify-content: space-between; + flex-direction: column; + margin: 30px; + width: 450px; + gap: 30px; } .actionButton { - width: 100%; - align-self: center; -} \ No newline at end of file + width: 100%; + align-self: center; +} diff --git a/yarn-project/boxes/private-token/src/app/components/contract_function_form.tsx b/yarn-project/boxes/private-token/src/app/components/contract_function_form.tsx index c8c672f06768..ac19e8f9fc03 100644 --- a/yarn-project/boxes/private-token/src/app/components/contract_function_form.tsx +++ b/yarn-project/boxes/private-token/src/app/components/contract_function_form.tsx @@ -86,7 +86,14 @@ async function handleFunctionCall( if (functionAbi.functionType === 'unconstrained') { return await viewContractFunction(contractAddress!, contractAbi, functionName, typedArgs, rpcClient, wallet); } else { - const txnReceipt = await callContractFunction(contractAddress!, contractAbi, functionName, typedArgs, rpcClient, wallet); + const txnReceipt = await callContractFunction( + contractAddress!, + contractAbi, + functionName, + typedArgs, + rpcClient, + wallet, + ); return `Transaction ${txnReceipt.status} on block number ${txnReceipt.blockNumber}`; } } diff --git a/yarn-project/boxes/private-token/src/app/components/copy.module.scss b/yarn-project/boxes/private-token/src/app/components/copy.module.scss index 6b4a52bf549c..26b2360c58a0 100644 --- a/yarn-project/boxes/private-token/src/app/components/copy.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/copy.module.scss @@ -1,6 +1,6 @@ .copy { - cursor: pointer; - width: 35px; - height: 25px; - padding: 2px 8px; -} \ No newline at end of file + cursor: pointer; + width: 35px; + height: 25px; + padding: 2px 8px; +} diff --git a/yarn-project/boxes/private-token/src/app/components/dropdown.module.scss b/yarn-project/boxes/private-token/src/app/components/dropdown.module.scss index 8041aff4bc8f..18bd40b356bd 100644 --- a/yarn-project/boxes/private-token/src/app/components/dropdown.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/dropdown.module.scss @@ -1,68 +1,68 @@ .dropdownWrapper { - position: absolute; - top: 60px; - right: 0px; - border-radius: 10px; - display: flex; - overflow: hidden; - flex-direction: column; - gap: 1px; - border: 1px solid #ebeaea; - background-color: #ebeaea; - z-index: 1; + position: absolute; + top: 60px; + right: 0px; + border-radius: 10px; + display: flex; + overflow: hidden; + flex-direction: column; + gap: 1px; + border: 1px solid #ebeaea; + background-color: #ebeaea; + z-index: 1; } .dropdownOptionBackground { - background-color: white; + background-color: white; } .dropdownOption { - font-size: 14px; - padding: 10px 25px; - white-space: nowrap; - cursor: pointer; - font-weight: 600; - justify-content: space-between; - letter-spacing: 0.5px; - display: flex; + font-size: 14px; + padding: 10px 25px; + white-space: nowrap; + cursor: pointer; + font-weight: 600; + justify-content: space-between; + letter-spacing: 0.5px; + display: flex; } .singleOption { - text-align: center; - align-items: center; - justify-content: center; + text-align: center; + align-items: center; + justify-content: center; } .dropdownOption.disabled { - background-image: initial; - cursor: default; - background-color: #c4c4c4; + background-image: initial; + cursor: default; + background-color: #c4c4c4; } .dropdownOptionBackground:hover { - background-color: #ebeaea; + background-color: #ebeaea; } .dropdownOptionBackground.disabled:hover { - background-color: white; + background-color: white; } .sublabel { - text-align: right; + text-align: right; } .sublabels { - display: flex; - flex-direction: row; - font-weight: 450; + display: flex; + flex-direction: row; + font-weight: 450; } .feeOption { - gap: 5px; - display: flex; - flex-direction: column; + gap: 5px; + display: flex; + flex-direction: column; } .label { - color: #2f1f49; -} \ No newline at end of file + color: #2f1f49; +} diff --git a/yarn-project/boxes/private-token/src/app/components/popup.module.scss b/yarn-project/boxes/private-token/src/app/components/popup.module.scss index ecaab4c22fb1..0917ca93f413 100644 --- a/yarn-project/boxes/private-token/src/app/components/popup.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/popup.module.scss @@ -1,27 +1,27 @@ .popup { - width: 66vw; - position: absolute; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - background-color: white; - border-radius: 20px; - justify-content: space-around; - box-shadow: 0px 4px 10px rgba(0, 0, 0, .1); - border: 3px solid rgb(47, 31, 73); - align-items: center; - gap: 30px; - padding: 30px; - overflow: scroll; - min-width: 600px; - z-index: 100; + width: 66vw; + position: absolute; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: white; + border-radius: 20px; + justify-content: space-around; + box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); + border: 3px solid rgb(47, 31, 73); + align-items: center; + gap: 30px; + padding: 30px; + overflow: scroll; + min-width: 600px; + z-index: 100; } .alert { - width: 20px; + width: 20px; } .content { - width: 100%; -} \ No newline at end of file + width: 100%; +} diff --git a/yarn-project/boxes/private-token/src/app/components/select.module.scss b/yarn-project/boxes/private-token/src/app/components/select.module.scss index 71ecf95ab7f1..d639c52f47d7 100644 --- a/yarn-project/boxes/private-token/src/app/components/select.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/select.module.scss @@ -1,65 +1,65 @@ .selectBox { - border-radius: 10px; - background-color: white; - position: relative; - font-family: Sohne; - font-size: 16px; - height: 45px; - cursor: pointer; - font-weight: 450; + border-radius: 10px; + background-color: white; + position: relative; + font-family: Sohne; + font-size: 16px; + height: 45px; + cursor: pointer; + font-weight: 450; - @media (max-width: 480px) { - margin: 0; - } + @media (max-width: 480px) { + margin: 0; + } } .icon { - min-width: 12px; + min-width: 12px; } .border { - box-shadow: 0px 4px 14px rgba(0, 0, 0, 0.1); + box-shadow: 0px 4px 14px rgba(0, 0, 0, 0.1); } .innerFrame { - height: 45px; - padding: 0 15px; - display: flex; - align-items: center; - justify-content: space-between; - overflow: hidden; - gap: 10px; + height: 45px; + padding: 0 15px; + display: flex; + align-items: center; + justify-content: space-between; + overflow: hidden; + gap: 10px; } .innerFrameWithButton { - padding-right: 0px; + padding-right: 0px; } .value { - white-space: nowrap; + white-space: nowrap; } .dropdown { - top: 45px; - left: 0%; - min-width: 130px; - width: 100%; + top: 45px; + left: 0%; + min-width: 130px; + width: 100%; } .closeButton { - height: 30px; - padding: 15px 15px 15px 5px; - display: flex; - justify-content: flex-end; - align-items: center; + height: 30px; + padding: 15px 15px 15px 5px; + display: flex; + justify-content: flex-end; + align-items: center; } .disabled { - background-color: rgba(239, 239, 239, 0.3); - color: #4a4a4a; - cursor: not-allowed; + background-color: rgba(239, 239, 239, 0.3); + color: #4a4a4a; + cursor: not-allowed; } .placeholder { - color: #757575; -} \ No newline at end of file + color: #757575; +} diff --git a/yarn-project/boxes/private-token/src/app/components/wallet_dropdown.module.scss b/yarn-project/boxes/private-token/src/app/components/wallet_dropdown.module.scss index 8ad6aae3cf6c..27fdfc4f7f72 100644 --- a/yarn-project/boxes/private-token/src/app/components/wallet_dropdown.module.scss +++ b/yarn-project/boxes/private-token/src/app/components/wallet_dropdown.module.scss @@ -1,9 +1,9 @@ .walletSelector { - position: fixed; - top: 30px; - right: 30px; - display: flex; - gap: 10px; - flex-direction: row; - align-items: center; -} \ No newline at end of file + position: fixed; + top: 30px; + right: 30px; + display: flex; + gap: 10px; + flex-direction: row; + align-items: center; +} diff --git a/yarn-project/boxes/private-token/src/app/contract.module.scss b/yarn-project/boxes/private-token/src/app/contract.module.scss index bd16d1959046..d5404d250357 100644 --- a/yarn-project/boxes/private-token/src/app/contract.module.scss +++ b/yarn-project/boxes/private-token/src/app/contract.module.scss @@ -1,53 +1,53 @@ .tos { - position: fixed; - bottom: 30px; - right: 30px; - cursor: pointer; - font-size: 14px; + position: fixed; + bottom: 30px; + right: 30px; + cursor: pointer; + font-size: 14px; } .selectorWrapper { - display: flex; - flex-direction: column; - margin: 30px; - gap: 20px; + display: flex; + flex-direction: column; + margin: 30px; + gap: 20px; } .functions { - display: flex; - flex-direction: row; - gap: 20px; + display: flex; + flex-direction: row; + gap: 20px; } .tag { - font-weight: 450; - display: flex; - position: relative; - flex-direction: column; - font-size: 16px; - gap: 5px; - background-color: #fff; - text-align: right; - padding: 14px 18px; - text-align: center; - background-color: #f9f9f9; - align-self: center; - border-radius: 10px; + font-weight: 450; + display: flex; + position: relative; + flex-direction: column; + font-size: 16px; + gap: 5px; + background-color: #fff; + text-align: right; + padding: 14px 18px; + text-align: center; + background-color: #f9f9f9; + align-self: center; + border-radius: 10px; } .back { - top: 15px; - width: 20px; - left: 30px; - margin-bottom: 15px; + top: 15px; + width: 20px; + left: 30px; + margin-bottom: 15px; } .address { - display: flex; - justify-content: center; - align-items: center; + display: flex; + justify-content: center; + align-items: center; } .title { - font-weight: 500; -} \ No newline at end of file + font-weight: 500; +} diff --git a/yarn-project/boxes/private-token/src/app/home.module.scss b/yarn-project/boxes/private-token/src/app/home.module.scss index 12cce21ad73e..44ff7f764465 100644 --- a/yarn-project/boxes/private-token/src/app/home.module.scss +++ b/yarn-project/boxes/private-token/src/app/home.module.scss @@ -1,28 +1,28 @@ .main { - display: flex; - gap: 20px; - flex-direction: column; - justify-content: center; - align-items: center; + display: flex; + gap: 20px; + flex-direction: column; + justify-content: center; + align-items: center; } .logo { - position: fixed; - cursor: pointer; - top: 35px; - left: 30px; - height: 35px; + position: fixed; + cursor: pointer; + top: 35px; + left: 30px; + height: 35px; } .privateBackground { - transform: rotate(-20deg); - width: 150vw; - height: 150vh; - font-weight: 500; - opacity: 0.3; - font-size: 14px; - pointer-events: none; - position: absolute; - font-size: 14px; - z-index: 0; -} \ No newline at end of file + transform: rotate(-20deg); + width: 150vw; + height: 150vh; + font-weight: 500; + opacity: 0.3; + font-size: 14px; + pointer-events: none; + position: absolute; + font-size: 14px; + z-index: 0; +} From 6366be596f659e1ca4364bc3f0f95c104c8f5717 Mon Sep 17 00:00:00 2001 From: spypsy Date: Fri, 22 Sep 2023 14:35:19 +0100 Subject: [PATCH 08/12] fix: canary image build (#2480) Fix docker image build for Canary testing # Checklist: Remove the checklist to signal you've completed it. Enable auto-merge if the PR is ready to merge. - [ ] If the pull request requires a cryptography review (e.g. cryptographic algorithm implementations) I have added the 'crypto' tag. - [ ] I have reviewed my diff in github, line by line and removed unexpected formatting changes, testing logs, or commented-out code. - [ ] Every change is related to the PR description. - [ ] I have [linked](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) this pull request to relevant issues (if any exist). --- yarn-project/canary/Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn-project/canary/Dockerfile b/yarn-project/canary/Dockerfile index 8e2455ef174d..4e77cd834b75 100644 --- a/yarn-project/canary/Dockerfile +++ b/yarn-project/canary/Dockerfile @@ -1,8 +1,5 @@ FROM 278380418400.dkr.ecr.eu-west-2.amazonaws.com/yarn-project-base AS builder -RUN apk update && apk add --no-cache udev ttf-freefont chromium curl jq bash -ENV CHROME_BIN="/usr/bin/chromium-browser" PUPPETEER_SKIP_CHROMIUM_DOWNLOAD="true" - ARG COMMIT_TAG="." COPY . . @@ -23,6 +20,9 @@ RUN ./scripts/update_packages.sh $COMMIT_TAG RUN yarn && yarn build FROM node:18-alpine +RUN apk update && apk add --no-cache udev ttf-freefont chromium curl jq bash +ENV CHROME_BIN="/usr/bin/chromium-browser" PUPPETEER_SKIP_CHROMIUM_DOWNLOAD="true" + COPY --from=builder /usr/src/ /usr/src/ WORKDIR /usr/src/yarn-project/canary From a8aec70dac829c42874b89119767e4eb5689d4aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bene=C5=A1?= Date: Fri, 22 Sep 2023 15:37:18 +0200 Subject: [PATCH 09/12] docs: common contract errors (#2471) Fixes #2468 --- docs/docs/dev_docs/contracts/common_errors.md | 54 +++++++++++++++++-- docs/sidebars.js | 1 + 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/docs/docs/dev_docs/contracts/common_errors.md b/docs/docs/dev_docs/contracts/common_errors.md index ce96e27ed09d..cefaa8535fbe 100644 --- a/docs/docs/dev_docs/contracts/common_errors.md +++ b/docs/docs/dev_docs/contracts/common_errors.md @@ -1,9 +1,53 @@ -# Errors - -List common errors. +# Common Errors There are two kinds of errors: errors in an Aztec.nr contract, and errors spat out by an Aztec Sandbox node! +This section will provide an overview of the errors you might encounter, and how to fix them. + +### Assertion Error + +This error is thrown when a condition is not met. + +This is what the error typically looks like: +``` +Simulation error: Assertion failed: Balance too low 'sum == amount' +``` + +To address the error. find the line in the contract that is throwing the error and investigate why the condition is not met. + +### Unknown Contract Error +This error occurs when you are trying to interact with a smart contract via an Aztec RPC Server that does not have the necessary information to execute a transaction. + +This is what the error typically looks like: +``` +Unknown contract 0x1d206be10b873b78b875259e1a8c39e2212e2f181d2fd0b0407446487deba522: add it to Aztec RPC server by calling server.addContracts(...) +``` + +To execute a transaction, the Aztec RPC Server needs to know the complete address of a contract, portal address (if portal is used) and contract artifacts. + +To address the error, add the contract to the Aztec RPC Server by calling `server.addContracts(...)`. + +### Unknown Complete Address Error +This error occurs when your contract is trying to get a public key via the `get_public_key` oracle call, but the Aztec RPC Server does not have the Complete Address (Complete Address contains the public key). + +This is what the error typically looks like: +``` +Simulation error: Unknown complete address for address 0x0d179a5f9bd4505f7dfb8ca37d64e0bd0cd31b5cb018e252fd647bdf88959b95. Add the information to Aztec RPC server by calling server.registerRecipient(...) or server.registerAccount(...) +``` + +Your contract typically needs a public key when it wants to send a note to a recipient because the public key is used to encrypt notes. + +:::info +Manually adding the recipient to the Aztec RPC Server should not be required in case the recipient contract has already been deployed and the Aztec RPC Server is fully synced. +This is because this information is submitted on-chain when the recipient contract is deployed. +::: + +### Unknown account +This error occurs when your contract is trying to get a secret via the `get_secret` oracle call, but the Aztec RPC Server does not have the secret for the public key. -Maybe even auto-generate error docs, based on error codes in our codebase. +This is what the error typically looks like: +``` +Could not process note because of "Error: Unknown account.". Skipping note... +``` -Make sure descriptions of errors relate to the end user experience. An error like 'SegFault' is useless to a contract developer! \ No newline at end of file +This error might occurr when you register an account only as a recipient and not as an account. +To address the error, register the account by calling `server.registerAccount(...)`. \ No newline at end of file diff --git a/docs/sidebars.js b/docs/sidebars.js index 94ec83570ede..1ec97eda8ea5 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -272,6 +272,7 @@ const sidebars = { "dev_docs/contracts/portals/outbox", ], }, + "dev_docs/contracts/common_errors", // { // label: "Resources", // type: "category", From 04efee1f5db83eebe5e4e9139ad8fc1a16a74c40 Mon Sep 17 00:00:00 2001 From: Alex Gherghisan Date: Fri, 22 Sep 2023 16:33:27 +0100 Subject: [PATCH 10/12] refactor: aztec-node json-rpc (#2444) This PR replaces the HTTP rest API exposed by `rollup-provider` with a JSON-RPC server for `AztecNode`. ATM the `@aztec/aztec-node` package exports both the server and client implementation but it might make sense to move the JSON-RPC client to its own package. Along the way I had to update some of the models to make them serialisable to/from strings. I have added tests as needed. I have also removed `rollup-provider` since that seemed to no longer used and it was a just thin wrapper around an `AztecNode` and its REST API. See also #2358 # Checklist: Remove the checklist to signal you've completed it. Enable auto-merge if the PR is ready to merge. - [ ] If the pull request requires a cryptography review (e.g. cryptographic algorithm implementations) I have added the 'crypto' tag. - [x] I have reviewed my diff in github, line by line and removed unexpected formatting changes, testing logs, or commented-out code. - [x] Every change is related to the PR description. - [x] I have [linked](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) this pull request to relevant issues (if any exist). --- .circleci/config.yml | 13 - build_manifest.json | 6 +- .../src/aztec-node/http-node.test.ts | 519 ------------------ .../aztec-node/src/aztec-node/http-node.ts | 388 ------------- .../aztec-node/src/aztec-node/server.ts | 24 +- yarn-project/aztec-node/src/index.ts | 3 +- .../aztec-node/src/rpc/http_rpc_client.ts | 23 + .../aztec-node/src/rpc/http_rpc_server.ts | 31 ++ .../aztec_rpc_http/aztec_rpc_http_server.ts | 2 + .../kernel/historic_block_data.test.ts | 17 + .../src/structs/kernel/historic_block_data.ts | 12 +- yarn-project/package.json | 1 - yarn-project/rollup-provider/.dockerignore | 4 - yarn-project/rollup-provider/.eslintrc.cjs | 1 - yarn-project/rollup-provider/.gitignore | 1 - yarn-project/rollup-provider/Dockerfile | 15 - yarn-project/rollup-provider/README.md | 5 - yarn-project/rollup-provider/package.json | 65 --- yarn-project/rollup-provider/src/app.ts | 300 ---------- yarn-project/rollup-provider/src/index.ts | 40 -- yarn-project/rollup-provider/tsconfig.json | 23 - yarn-project/tsconfig.json | 1 - yarn-project/types/src/l2_block.test.ts | 8 + yarn-project/types/src/l2_block.ts | 22 + yarn-project/types/src/l2_tx.test.ts | 6 + yarn-project/types/src/l2_tx.ts | 21 + yarn-project/yarn-project-base/Dockerfile | 2 - yarn-project/yarn.lock | 41 -- 28 files changed, 156 insertions(+), 1438 deletions(-) delete mode 100644 yarn-project/aztec-node/src/aztec-node/http-node.test.ts delete mode 100644 yarn-project/aztec-node/src/aztec-node/http-node.ts create mode 100644 yarn-project/aztec-node/src/rpc/http_rpc_client.ts create mode 100644 yarn-project/aztec-node/src/rpc/http_rpc_server.ts create mode 100644 yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts delete mode 100644 yarn-project/rollup-provider/.dockerignore delete mode 100644 yarn-project/rollup-provider/.eslintrc.cjs delete mode 100644 yarn-project/rollup-provider/.gitignore delete mode 100644 yarn-project/rollup-provider/Dockerfile delete mode 100644 yarn-project/rollup-provider/README.md delete mode 100644 yarn-project/rollup-provider/package.json delete mode 100644 yarn-project/rollup-provider/src/app.ts delete mode 100644 yarn-project/rollup-provider/src/index.ts delete mode 100644 yarn-project/rollup-provider/tsconfig.json diff --git a/.circleci/config.yml b/.circleci/config.yml index 67896e61472f..336474a6a7a8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -671,17 +671,6 @@ jobs: name: "Build" command: build ethereum - rollup-provider: - machine: - image: ubuntu-2004:202010-01 - resource_class: large - steps: - - *checkout - - *setup_env - - run: - name: "Build" - command: build rollup-provider - e2e-2-rpc-servers: machine: image: ubuntu-2004:202010-01 @@ -1429,7 +1418,6 @@ workflows: - sequencer-client: *yarn_project - types: *yarn_project - circuits-js: *yarn_project - - rollup-provider: *yarn_project - aztec-sandbox-base: *yarn_project - canary: *yarn_project @@ -1470,7 +1458,6 @@ workflows: - sequencer-client - types - circuits-js - - rollup-provider - aztec-sandbox-ecr-manifest - canary <<: *defaults diff --git a/build_manifest.json b/build_manifest.json index 9379e39a965b..e142a8150068 100644 --- a/build_manifest.json +++ b/build_manifest.json @@ -220,10 +220,6 @@ "buildDir": "yarn-project", "projectDir": "yarn-project/prover-client" }, - "rollup-provider": { - "buildDir": "yarn-project", - "projectDir": "yarn-project/rollup-provider" - }, "aztec-node": { "buildDir": "yarn-project", "projectDir": "yarn-project/aztec-node" @@ -240,4 +236,4 @@ "buildDir": "yarn-project", "projectDir": "yarn-project/world-state" } -} \ No newline at end of file +} diff --git a/yarn-project/aztec-node/src/aztec-node/http-node.test.ts b/yarn-project/aztec-node/src/aztec-node/http-node.test.ts deleted file mode 100644 index fdf5d2b5522e..000000000000 --- a/yarn-project/aztec-node/src/aztec-node/http-node.test.ts +++ /dev/null @@ -1,519 +0,0 @@ -import { AztecAddress, CircuitsWasm, EthAddress, Fr, FunctionSelector, HistoricBlockData } from '@aztec/circuits.js'; -import { randomBytes } from '@aztec/foundation/crypto'; -import { Pedersen } from '@aztec/merkle-tree'; -import { - ContractData, - ExtendedContractData, - L1ToL2Message, - L2Block, - L2BlockL2Logs, - LogType, - MerkleTreeId, - SiblingPath, - SimulationError, - TxHash, - mockTx, -} from '@aztec/types'; - -import { jest } from '@jest/globals'; - -import { HttpNode } from './http-node.js'; - -const TEST_URL = 'http://aztec-node-url.com/'; - -const setFetchMock = (response: any, status = 200): void => { - global.fetch = jest - .fn() - .mockImplementation((_input: RequestInfo | URL, _init?: RequestInit | undefined) => { - return Promise.resolve({ - status, - ok: true, - json: () => response, - arrayBuffer: () => response, - } as Response); - }); -}; - -describe('HttpNode', () => { - let httpNode: HttpNode; - let pedersen: Pedersen; - - beforeAll(async () => { - httpNode = new HttpNode(TEST_URL); - pedersen = new Pedersen(await CircuitsWasm.get()); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - describe('isReady', () => { - it.each([true, false])('should return %s when the node is ready', async () => { - const response = { isReady: true }; - setFetchMock(response); - - const result = await httpNode.isReady(); - - expect(fetch).toHaveBeenCalledWith(TEST_URL); - expect(result).toBe(true); - }); - }); - - describe('getBlocks', () => { - it('should fetch and parse blocks', async () => { - const block1 = L2Block.random(1); - const block2 = L2Block.random(2); - const response = { - blocks: [block1.encode(), block2.encode()], - }; - setFetchMock(response); - - const result = await httpNode.getBlocks(0, 3); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-blocks?from=0&limit=3`); - expect(result).toEqual([block1, block2]); - }); - - it('should return an empty array if blocks are not available', async () => { - const response = { blocks: [] }; - setFetchMock(response); - - const result = await httpNode.getBlocks(0, 2); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-blocks?from=0&limit=2`); - expect(result).toEqual([]); - }); - }); - - describe('getBlock', () => { - it('should fetch and parse a block', async () => { - const block1 = L2Block.random(1); - const response = { - block: block1.encode(), - }; - setFetchMock(response); - - const result = await httpNode.getBlock(1); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-block?number=1`); - expect(result).toEqual(block1); - }); - - it('should return undefined if the block is not available', async () => { - const response = { block: undefined }; - setFetchMock(response); - - const result = await httpNode.getBlock(2); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-block?number=2`); - expect(result).toEqual(undefined); - }); - }); - - describe('getBlockNumber', () => { - it('should fetch and return current block number', async () => { - const response = { blockNumber: 100 }; - setFetchMock(response); - - const result = await httpNode.getBlockNumber(); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-block-number`); - expect(result).toBe(100); - }); - }); - - describe('getVersion', () => { - it('should fetch and return the version', async () => { - const response = { version: 5 }; - setFetchMock(response); - - const result = await httpNode.getVersion(); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-version`); - expect(result).toBe(5); - }); - }); - - describe('getChainId', () => { - it('should fetch and return the chain ID', async () => { - const response = { chainId: 1234 }; - setFetchMock(response); - - const result = await httpNode.getChainId(); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-chain-id`); - expect(result).toBe(1234); - }); - }); - - describe('getRollupAddress', () => { - it('should fetch and return the rollup address', async () => { - const addr = EthAddress.random(); - const response = { rollupAddress: addr.toString() }; - setFetchMock(response); - - const result = await httpNode.getRollupAddress(); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-rollup-address`); - expect(result).toEqual(addr); - }); - }); - - describe('getExtendedContractData', () => { - it('should fetch and return contract public data', async () => { - const extendedContractData = ExtendedContractData.random(); - const response = { - contractData: extendedContractData.toBuffer(), - }; - - setFetchMock(response); - - const result = await httpNode.getExtendedContractData(extendedContractData.contractData.contractAddress); - - expect(fetch).toHaveBeenCalledWith( - `${TEST_URL}contract-data-and-bytecode?address=${extendedContractData.contractData.contractAddress.toString()}`, - ); - expect(result).toEqual(extendedContractData); - }); - - it('should return undefined if contract data is not available', async () => { - const response = { - contractData: undefined, - }; - setFetchMock(response); - - const randomAddress = AztecAddress.random(); - - const result = await httpNode.getExtendedContractData(randomAddress); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-data-and-bytecode?address=${randomAddress.toString()}`); - expect(result).toEqual(undefined); - }); - }); - - describe('getLogs', () => { - it.each(['encrypted', 'unencrypted'])('should fetch and return %s logs', async logType => { - const processedLogType = logType === 'encrypted' ? LogType.ENCRYPTED : LogType.UNENCRYPTED; - - const from = 0; - const limit = 3; - const log1 = L2BlockL2Logs.random(2, 3, 4); - const log2 = L2BlockL2Logs.random(1, 5, 2); - const response = { - logs: [log1.toBuffer(), log2.toBuffer()], - }; - setFetchMock(response); - - const result = await httpNode.getLogs(from, limit, processedLogType); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-logs?from=${from}&limit=${limit}&logType=${processedLogType}`); - expect(result).toEqual([log1, log2]); - }); - - it.each(['encrypted', 'unencrypted'])( - 'should return an empty array if %s logs are not available', - async logType => { - const processedLogType = logType === 'encrypted' ? LogType.ENCRYPTED : LogType.UNENCRYPTED; - - const from = 0; - const limit = 2; - const response = {}; - setFetchMock(response); - - const result = await httpNode.getLogs(from, limit, processedLogType); - - expect(fetch).toHaveBeenCalledWith( - `${TEST_URL}get-logs?from=${from}&limit=${limit}&logType=${processedLogType}`, - ); - expect(result).toEqual([]); - }, - ); - }); - - describe('getContractData', () => { - it('should fetch and return contract data', async () => { - const contractData = ContractData.random(); - const response = { - contractData: contractData.toBuffer(), - }; - setFetchMock(response); - - const result = await httpNode.getContractData(contractData.contractAddress); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-data?address=${contractData.contractAddress.toString()}`); - expect(result).toEqual(contractData); - }); - - it('should return undefined if contract data is not available', async () => { - const response = { - contractData: undefined, - }; - setFetchMock(response); - - const randomAddress = AztecAddress.random(); - - const result = await httpNode.getContractData(randomAddress); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-data?address=${randomAddress.toString()}`); - expect(result).toBeUndefined(); - }); - }); - - describe('sendTx', () => { - it('should submit a transaction to the p2p pool', async () => { - const tx = mockTx(); - const irrelevantResponse = {}; - setFetchMock(irrelevantResponse); - - await httpNode.sendTx(tx); - - const init: RequestInit = { - method: 'POST', - body: tx.toBuffer(), - }; - const call = (fetch as jest.Mock).mock.calls[0] as any[]; - expect(call[0].href).toBe(`${TEST_URL}tx`); - expect(call[1]).toStrictEqual(init); - }); - }); - - describe('getPendingTxByHash', () => { - it('should fetch and return a pending tx', async () => { - const txHash = new TxHash(randomBytes(TxHash.SIZE)); - const tx = mockTx(); - const response = tx.toBuffer(); - setFetchMock(response); - - const result = await httpNode.getPendingTxByHash(txHash); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-pending-tx?hash=${txHash}`); - expect(result).toEqual(tx); - }); - - it('should return undefined if the pending tx does not exist', async () => { - const txHash = new TxHash(randomBytes(TxHash.SIZE)); - const response = undefined; - setFetchMock(response, 404); - - const result = await httpNode.getPendingTxByHash(txHash); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}get-pending-tx?hash=${txHash}`); - expect(result).toBeUndefined(); - }); - }); - - describe('findContractIndex', () => { - it('should fetch and return the index of the given contract', async () => { - const leafValue = Buffer.from('abc123', 'hex'); - const index = '123456'; - const response = { index }; - setFetchMock(response); - - const result = await httpNode.findContractIndex(leafValue); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-index?leaf=${leafValue.toString('hex')}`); - expect(result).toBe(BigInt(index)); - }); - - it('should return undefined if the contract index is not found', async () => { - const leafValue = Buffer.from('def456', 'hex'); - const response = {}; - setFetchMock(response); - - const result = await httpNode.findContractIndex(leafValue); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-index?leaf=${leafValue.toString('hex')}`); - expect(result).toBeUndefined(); - }); - }); - - describe('getContractPath', () => { - it('should fetch and return the sibling path for the given leaf index', async () => { - const leafIndex = BigInt(123456); - const siblingPath = SiblingPath.ZERO(3, Buffer.alloc(32), pedersen); - const response = { path: siblingPath.toBuffer().toString('hex') }; - setFetchMock(response); - - const result = await httpNode.getContractPath(leafIndex); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}contract-path?leaf=${leafIndex.toString()}`); - expect(result).toEqual(siblingPath); - }); - }); - - describe('findCommitmentIndex', () => { - it('should fetch and return the index of the given leaf', async () => { - const leafValue = Buffer.from('0123456789', 'hex'); - const expectedIndex = BigInt(123); - const response = { index: expectedIndex.toString() }; - setFetchMock(response); - - const result = await httpNode.findCommitmentIndex(leafValue); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}commitment-index?leaf=${leafValue.toString('hex')}`); - expect(result).toBe(expectedIndex); - }); - - it('should return undefined if the commitment index is not found', async () => { - const leafValue = Buffer.from('def456', 'hex'); - const response = {}; - setFetchMock(response); - - const result = await httpNode.findCommitmentIndex(leafValue); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}commitment-index?leaf=${leafValue.toString('hex')}`); - expect(result).toBeUndefined(); - }); - }); - - describe('getDataTreePath', () => { - it('should fetch and return the sibling path for the given leaf index', async () => { - const leafIndex = BigInt(123456); - const siblingPath = SiblingPath.ZERO(3, Buffer.alloc(32), pedersen); - const response = { path: siblingPath.toBuffer().toString('hex') }; - setFetchMock(response); - - const result = await httpNode.getDataTreePath(leafIndex); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}data-path?leaf=${leafIndex.toString()}`); - expect(result).toEqual(siblingPath); - }); - }); - - describe('getL1ToL2MessageAndIndex', () => { - it('should fetch and return the L1 to L2 message and index for the given message key', async () => { - const messageKey = new Fr(789); - const expectedMessage = L1ToL2Message.random(); - const expectedIndex = BigInt(123); - const response = { message: expectedMessage.toBuffer().toString('hex'), index: expectedIndex.toString() }; - setFetchMock(response); - - const result = await httpNode.getL1ToL2MessageAndIndex(messageKey); - - expect(fetch).toHaveBeenCalledWith(`${TEST_URL}l1-l2-message?messageKey=${messageKey.toString()}`); - expect(result).toEqual({ - message: expectedMessage, - index: expectedIndex, - }); - }); - }); - - describe('getL1ToL2MessagesTreePath', () => { - it('should fetch and return the sibling path for the given leaf index', async () => { - const leafIndex = BigInt(123456); - const siblingPath = SiblingPath.ZERO(3, Buffer.alloc(32), pedersen); - const response = { path: siblingPath.toBuffer().toString('hex') }; - setFetchMock(response); - - const result = await httpNode.getL1ToL2MessagesTreePath(leafIndex); - - const url = `${TEST_URL}l1-l2-path?leaf=${leafIndex.toString()}`; - expect(fetch).toHaveBeenCalledWith(url); - expect(result).toEqual(siblingPath); - }); - }); - - describe('getPublicStorageAt', () => { - it('should fetch and return the storage value at the given contract slot', async () => { - const contractAddress = AztecAddress.random(); - const slot = BigInt(789); - const storageValue = Buffer.from('0123456789', 'hex'); - const response = { value: storageValue.toString('hex') }; - setFetchMock(response); - - const result = await httpNode.getPublicStorageAt(contractAddress, slot); - - const url = `${TEST_URL}public-storage-at?address=${contractAddress}&slot=${slot.toString()}`; - expect(fetch).toHaveBeenCalledWith(url); - expect(result).toEqual(storageValue); - }); - - it('should return undefined if the storage value is not found', async () => { - const contractAddress = AztecAddress.random(); - const slot = BigInt(987); - const response = {}; - setFetchMock(response); - - const result = await httpNode.getPublicStorageAt(contractAddress, slot); - - const url = `${TEST_URL}public-storage-at?address=${contractAddress}&slot=${slot.toString()}`; - expect(fetch).toHaveBeenCalledWith(url); - expect(result).toBeUndefined(); - }); - }); - - describe('getTreeRoots', () => { - it('should fetch and return the current committed roots for the data trees', async () => { - const roots: Record = { - [MerkleTreeId.CONTRACT_TREE]: Fr.random(), - [MerkleTreeId.PRIVATE_DATA_TREE]: Fr.random(), - [MerkleTreeId.NULLIFIER_TREE]: Fr.random(), - [MerkleTreeId.PUBLIC_DATA_TREE]: Fr.random(), - [MerkleTreeId.L1_TO_L2_MESSAGES_TREE]: Fr.random(), - [MerkleTreeId.BLOCKS_TREE]: Fr.random(), - }; - - const rootsInResponse: Record = Object.fromEntries( - Object.entries(roots).map(([key, value]) => [key, value.toString()]), - ) as Record; - const response = { roots: rootsInResponse }; - - setFetchMock(response); - - const result = await httpNode.getTreeRoots(); - - const url = `${TEST_URL}tree-roots`; - expect(fetch).toHaveBeenCalledWith(url); - expect(result).toEqual(roots); - }); - }); - - describe('getHistoricBlockData', () => { - it('should fetch and return the current committed roots for the data trees', async () => { - const blockData = HistoricBlockData.random(); - - const response = { blockData }; - - setFetchMock(response); - - const result = await httpNode.getHistoricBlockData(); - - const url = `${TEST_URL}historic-block-data`; - expect(fetch).toHaveBeenCalledWith(url); - expect(result).toEqual(blockData); - }); - }); - - describe('simulatePublicCalls', () => { - it('should fetch a successful simulation response', async () => { - const tx = mockTx(); - const response = {}; - setFetchMock(response); - - await httpNode.simulatePublicCalls(tx); - - const init: RequestInit = { - method: 'POST', - body: tx.toBuffer(), - }; - const call = (fetch as jest.Mock).mock.calls[0] as any[]; - expect(call[0].href).toBe(`${TEST_URL}simulate-tx`); - expect(call[1]).toStrictEqual(init); - }); - - it('should fetch a simulation error', async () => { - const tx = mockTx(); - const simulationError = new SimulationError('test error', [ - { contractAddress: AztecAddress.ZERO, functionSelector: FunctionSelector.empty() }, - ]); - - const response = { - simulationError: simulationError.toJSON(), - }; - - setFetchMock(response); - - await expect(httpNode.simulatePublicCalls(tx)).rejects.toThrow(simulationError); - }); - }); -}); diff --git a/yarn-project/aztec-node/src/aztec-node/http-node.ts b/yarn-project/aztec-node/src/aztec-node/http-node.ts deleted file mode 100644 index 52f1d898cfa9..000000000000 --- a/yarn-project/aztec-node/src/aztec-node/http-node.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { - AztecAddress, - CONTRACT_TREE_HEIGHT, - EthAddress, - Fr, - HistoricBlockData, - L1_TO_L2_MSG_TREE_HEIGHT, - PRIVATE_DATA_TREE_HEIGHT, -} from '@aztec/circuits.js'; -import { DebugLogger, createDebugLogger } from '@aztec/foundation/log'; -import { - AztecNode, - ContractData, - ExtendedContractData, - L1ToL2Message, - L1ToL2MessageAndIndex, - L2Block, - L2BlockL2Logs, - L2Tx, - LogType, - MerkleTreeId, - SiblingPath, - SimulationError, - Tx, - TxHash, -} from '@aztec/types'; - -/** - * A Http client based implementation of Aztec Node. - */ -export class HttpNode implements AztecNode { - private baseUrl: string; - private log: DebugLogger; - - constructor(baseUrl: string, log = createDebugLogger('aztec:http-node')) { - this.baseUrl = baseUrl.toString().replace(/\/$/, ''); - this.log = log; - } - /** - * Method to determine if the node is ready to accept transactions. - * @returns - Flag indicating the readiness for tx submission. - */ - public async isReady(): Promise { - const url = new URL(this.baseUrl); - const response = await fetch(url.toString()); - const respJson = await response.json(); - return respJson.isReady; - } - - /** - * Method to request a block at the provided block number. - * @param number - The block number to request. - * @returns The block requested. Or undefined if it does not exist. - */ - async getBlock(number: number): Promise { - const url = new URL(`${this.baseUrl}/get-block`); - url.searchParams.append('number', number.toString()); - const response = await (await fetch(url.toString())).json(); - const { block } = response; - return Promise.resolve(block ? L2Block.decode(Buffer.from(block, 'hex')) : block); - } - - /** - * Method to request blocks. Will attempt to return all requested blocks but will return only those available. - * @param from - The start of the range of blocks to return. - * @param limit - Maximum number of blocks to obtain. - * @returns The blocks requested. - */ - async getBlocks(from: number, limit: number): Promise { - const url = new URL(`${this.baseUrl}/get-blocks`); - url.searchParams.append('from', from.toString()); - if (limit !== undefined) { - url.searchParams.append('limit', limit.toString()); - } - const response = await (await fetch(url.toString())).json(); - const blocks = response.blocks as string[]; - if (!blocks) { - return Promise.resolve([]); - } - return Promise.resolve(blocks.map(x => L2Block.decode(Buffer.from(x, 'hex')))); - } - - /** - * Method to fetch the current block number. - * @returns The current block number. - */ - async getBlockNumber(): Promise { - const url = new URL(`${this.baseUrl}/get-block-number`); - const response = await fetch(url.toString()); - const respJson = await response.json(); - return respJson.blockNumber; - } - - /** - * Method to fetch the version of the rollup the node is connected to. - * @returns The rollup version. - */ - public async getVersion(): Promise { - const url = new URL(`${this.baseUrl}/get-version`); - const response = await fetch(url.toString()); - const respJson = await response.json(); - return respJson.version; - } - - public async getRollupAddress(): Promise { - const url = new URL(`${this.baseUrl}/get-rollup-address`); - const response = await fetch(url.toString()); - const respJson = await response.json(); - return EthAddress.fromString(respJson.rollupAddress); - } - - /** - * Method to fetch the chain id of the base-layer for the rollup. - * @returns The chain id. - */ - public async getChainId(): Promise { - const url = new URL(`${this.baseUrl}/get-chain-id`); - const response = await fetch(url.toString()); - const respJson = await response.json(); - return respJson.chainId; - } - - /** - * Get the extended contract data for this contract. - * @param contractAddress - The contract data address. - * @returns The extended contract data or undefined if not found. - */ - async getExtendedContractData(contractAddress: AztecAddress): Promise { - const url = new URL(`${this.baseUrl}/contract-data-and-bytecode`); - url.searchParams.append('address', contractAddress.toString()); - const response = await (await fetch(url.toString())).json(); - if (!response || !response.contractData) { - return undefined; - } - const contract = response.contractData as string; - return Promise.resolve(ExtendedContractData.fromBuffer(Buffer.from(contract, 'hex'))); - } - - /** - * Gets up to `limit` amount of logs starting from `from`. - * @param from - Number of the L2 block to which corresponds the first logs to be returned. - * @param limit - The maximum number of logs to return. - * @param logType - Specifies whether to return encrypted or unencrypted logs. - * @returns The requested logs. - */ - public async getLogs(from: number, limit: number, logType: LogType): Promise { - const url = new URL(`${this.baseUrl}/get-logs`); - - url.searchParams.append('from', from.toString()); - url.searchParams.append('limit', limit.toString()); - url.searchParams.append('logType', logType.toString()); - - const response = await (await fetch(url.toString())).json(); - const logs = response.logs as string[]; - - if (!logs) { - return Promise.resolve([]); - } - return Promise.resolve(logs.map(x => L2BlockL2Logs.fromBuffer(Buffer.from(x, 'hex')))); - } - - /** - * Lookup the contract data for this contract. - * Contains the ethereum portal address. - * @param contractAddress - The contract data address. - * @returns The contract's address & portal address. - */ - async getContractData(contractAddress: AztecAddress): Promise { - const url = new URL(`${this.baseUrl}/contract-data`); - url.searchParams.append('address', contractAddress.toString()); - const response = await (await fetch(url.toString())).json(); - if (!response || !response.contractData) { - return undefined; - } - const contract = response.contractData as string; - return Promise.resolve(ContractData.fromBuffer(Buffer.from(contract, 'hex'))); - } - - /** - * Method to submit a transaction to the p2p pool. - * @param tx - The transaction to be submitted. - */ - async sendTx(tx: Tx): Promise { - const url = new URL(`${this.baseUrl}/tx`); - const init: RequestInit = {}; - init['method'] = 'POST'; - init['body'] = tx.toBuffer(); - await fetch(url, init); - } - - /** - * Gets an l2 tx. - * @param txHash - The txHash of the l2 tx. - * @returns The requested L2 tx. - */ - async getTx(txHash: TxHash): Promise { - const url = new URL(`${this.baseUrl}/get-tx`); - url.searchParams.append('hash', txHash.toString()); - const response = await fetch(url.toString()); - if (response.status === 404) { - this.log.info(`Tx ${txHash.toString()} not found`); - return undefined; - } - const txBuffer = Buffer.from(await response.arrayBuffer()); - const tx = L2Tx.fromBuffer(txBuffer); - return Promise.resolve(tx); - } - - /** - * Method to retrieve pending txs. - * @returns - The pending txs. - */ - getPendingTxs(): Promise { - return Promise.resolve([]); - } - - /** - * Method to retrieve a single pending tx. - * @param txHash - The transaction hash to return. - * @returns - The pending tx if it exists. - */ - async getPendingTxByHash(txHash: TxHash): Promise { - const url = new URL(`${this.baseUrl}/get-pending-tx`); - url.searchParams.append('hash', txHash.toString()); - const response = await fetch(url.toString()); - if (response.status === 404) { - this.log.info(`Tx ${txHash.toString()} not found`); - return undefined; - } - const txBuffer = Buffer.from(await response.arrayBuffer()); - const tx = Tx.fromBuffer(txBuffer); - return Promise.resolve(tx); - } - - /** - * Find the index of the given contract. - * @param leafValue - The value to search for. - * @returns The index of the given leaf in the contracts tree or undefined if not found. - */ - async findContractIndex(leafValue: Buffer): Promise { - const url = new URL(`${this.baseUrl}/contract-index`); - url.searchParams.append('leaf', leafValue.toString('hex')); - const response = await (await fetch(url.toString())).json(); - if (!response || !response.index) { - return undefined; - } - const index = response.index as string; - return Promise.resolve(BigInt(index)); - } - - /** - * Returns the sibling path for the given index in the contract tree. - * @param leafIndex - The index of the leaf for which the sibling path is required. - * @returns The sibling path for the leaf index. - */ - async getContractPath(leafIndex: bigint): Promise> { - const url = new URL(`${this.baseUrl}/contract-path`); - url.searchParams.append('leaf', leafIndex.toString()); - const response = await (await fetch(url.toString())).json(); - const path = response.path as string; - return Promise.resolve(SiblingPath.fromString(path)); - } - - /** - * Find the index of the given piece of data. - * @param leafValue - The value to search for. - * @returns The index of the given leaf in the data tree or undefined if not found. - */ - async findCommitmentIndex(leafValue: Buffer): Promise { - const url = new URL(`${this.baseUrl}/commitment-index`); - url.searchParams.append('leaf', leafValue.toString('hex')); - const response = await (await fetch(url.toString())).json(); - if (!response || !response.index) { - return undefined; - } - const index = response.index as string; - return Promise.resolve(BigInt(index)); - } - - /** - * Returns the sibling path for the given index in the data tree. - * @param leafIndex - The index of the leaf for which the sibling path is required. - * @returns The sibling path for the leaf index. - */ - async getDataTreePath(leafIndex: bigint): Promise> { - const url = new URL(`${this.baseUrl}/data-path`); - url.searchParams.append('leaf', leafIndex.toString()); - const response = await (await fetch(url.toString())).json(); - const path = response.path as string; - return Promise.resolve(SiblingPath.fromString(path)); - } - - /** - * Gets a consumed/confirmed L1 to L2 message for the given message key and its index in the merkle tree. - * @param messageKey - The message key. - * @returns the message (or throws if not found) - */ - async getL1ToL2MessageAndIndex(messageKey: Fr): Promise { - const url = new URL(`${this.baseUrl}/l1-l2-message`); - url.searchParams.append('messageKey', messageKey.toString()); - const response = await (await fetch(url.toString())).json(); - return Promise.resolve({ - message: L1ToL2Message.fromBuffer(Buffer.from(response.message as string, 'hex')), - index: BigInt(response.index as string), - }); - } - - /** - * Returns the sibling path for a leaf in the committed l1 to l2 data tree. - * @param leafIndex - Index of the leaf in the tree. - * @returns The sibling path. - */ - async getL1ToL2MessagesTreePath(leafIndex: bigint): Promise> { - const url = new URL(`${this.baseUrl}/l1-l2-path`); - url.searchParams.append('leaf', leafIndex.toString()); - const response = await (await fetch(url.toString())).json(); - const path = response.path as string; - return Promise.resolve(SiblingPath.fromString(path)); - } - - /** - * Gets the storage value at the given contract slot. - * @param contract - Address of the contract to query. - * @param slot - Slot to query. - * @returns Storage value at the given contract slot (or undefined if not found). - * Note: Aztec's version of `eth_getStorageAt`. - */ - async getPublicStorageAt(contract: AztecAddress, slot: bigint): Promise { - const url = new URL(`${this.baseUrl}/public-storage-at`); - url.searchParams.append('address', contract.toString()); - url.searchParams.append('slot', slot.toString()); - const response = await (await fetch(url.toString())).json(); - if (!response || !response.value) { - return undefined; - } - const value = response.value as string; - return Promise.resolve(Buffer.from(value, 'hex')); - } - - /** - * Returns the current committed roots for the data trees. - * @returns The current committed roots for the data trees. - */ - async getTreeRoots(): Promise> { - const url = new URL(`${this.baseUrl}/tree-roots`); - const response = await (await fetch(url.toString())).json(); - - const extractRoot = (treeId: MerkleTreeId) => { - // Buffer.from(...) returns an empty buffer when a hex string is prefixed with "0x" - const rootHexString = response.roots[treeId].replace(/^0x/, ''); - return Fr.fromBuffer(Buffer.from(rootHexString, 'hex')); - }; - - return { - [MerkleTreeId.CONTRACT_TREE]: extractRoot(MerkleTreeId.CONTRACT_TREE), - [MerkleTreeId.PRIVATE_DATA_TREE]: extractRoot(MerkleTreeId.PRIVATE_DATA_TREE), - [MerkleTreeId.NULLIFIER_TREE]: extractRoot(MerkleTreeId.NULLIFIER_TREE), - [MerkleTreeId.PUBLIC_DATA_TREE]: extractRoot(MerkleTreeId.PUBLIC_DATA_TREE), - [MerkleTreeId.L1_TO_L2_MESSAGES_TREE]: extractRoot(MerkleTreeId.L1_TO_L2_MESSAGES_TREE), - [MerkleTreeId.BLOCKS_TREE]: extractRoot(MerkleTreeId.BLOCKS_TREE), - }; - } - - /** - * Returns the currently committed historic block data. - * @returns The current committed block data. - */ - public async getHistoricBlockData(): Promise { - const url = new URL(`${this.baseUrl}/historic-block-data`); - const response = await (await fetch(url.toString())).json(); - return response.blockData; - } - - /** - * Simulates the public part of a transaction with the current state. - * @param tx - The transaction to simulate. - **/ - public async simulatePublicCalls(tx: Tx) { - const url = new URL(`${this.baseUrl}/simulate-tx`); - const init: RequestInit = {}; - init['method'] = 'POST'; - init['body'] = tx.toBuffer(); - const response = await (await fetch(url, init)).json(); - if (response.simulationError) { - throw SimulationError.fromJSON(response.simulationError); - } - } -} diff --git a/yarn-project/aztec-node/src/aztec-node/server.ts b/yarn-project/aztec-node/src/aztec-node/server.ts index f457247f9dbb..fcf509ff6cb2 100644 --- a/yarn-project/aztec-node/src/aztec-node/server.ts +++ b/yarn-project/aztec-node/src/aztec-node/server.ts @@ -259,7 +259,7 @@ export class AztecNodeService implements AztecNode { * @returns The index of the given leaf in the contracts tree or undefined if not found. */ public async findContractIndex(leafValue: Buffer): Promise { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); return committedDb.findLeafIndex(MerkleTreeId.CONTRACT_TREE, leafValue); } @@ -269,7 +269,7 @@ export class AztecNodeService implements AztecNode { * @returns The sibling path for the leaf index. */ public async getContractPath(leafIndex: bigint): Promise> { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); return committedDb.getSiblingPath(MerkleTreeId.CONTRACT_TREE, leafIndex); } @@ -279,7 +279,7 @@ export class AztecNodeService implements AztecNode { * @returns The index of the given leaf in the private data tree or undefined if not found. */ public async findCommitmentIndex(leafValue: Buffer): Promise { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); return committedDb.findLeafIndex(MerkleTreeId.PRIVATE_DATA_TREE, leafValue); } @@ -289,7 +289,7 @@ export class AztecNodeService implements AztecNode { * @returns The sibling path for the leaf index. */ public async getDataTreePath(leafIndex: bigint): Promise> { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); return committedDb.getSiblingPath(MerkleTreeId.PRIVATE_DATA_TREE, leafIndex); } @@ -301,7 +301,7 @@ export class AztecNodeService implements AztecNode { */ public async getL1ToL2MessageAndIndex(messageKey: Fr): Promise { // todo: #697 - make this one lookup. - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); const message = await this.l1ToL2MessageSource.getConfirmedL1ToL2Message(messageKey); const index = (await committedDb.findLeafIndex(MerkleTreeId.L1_TO_L2_MESSAGES_TREE, messageKey.toBuffer()))!; return Promise.resolve({ message, index }); @@ -313,7 +313,7 @@ export class AztecNodeService implements AztecNode { * @returns The sibling path. */ public async getL1ToL2MessagesTreePath(leafIndex: bigint): Promise> { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); return committedDb.getSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGES_TREE, leafIndex); } @@ -325,7 +325,7 @@ export class AztecNodeService implements AztecNode { * Note: Aztec's version of `eth_getStorageAt`. */ public async getPublicStorageAt(contract: AztecAddress, slot: bigint): Promise { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); const leafIndex = computePublicDataTreeLeafIndex(contract, new Fr(slot), await CircuitsWasm.get()); return committedDb.getLeafValue(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex); } @@ -335,7 +335,7 @@ export class AztecNodeService implements AztecNode { * @returns The current committed roots for the data trees. */ public async getTreeRoots(): Promise> { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); const getTreeRoot = async (id: MerkleTreeId) => Fr.fromBuffer((await committedDb.getTreeInfo(id)).root); const [privateDataTree, nullifierTree, contractTree, l1ToL2MessagesTree, blocksTree, publicDataTree] = @@ -363,7 +363,7 @@ export class AztecNodeService implements AztecNode { * @returns The current committed block data. */ public async getHistoricBlockData(): Promise { - const committedDb = await this.getWorldState(); + const committedDb = await this.#getWorldState(); const [roots, globalsHash] = await Promise.all([this.getTreeRoots(), committedDb.getLatestGlobalVariablesHash()]); return new HistoricBlockData( @@ -413,10 +413,10 @@ export class AztecNodeService implements AztecNode { * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched * @returns An instance of a committed MerkleTreeOperations */ - private async getWorldState() { + async #getWorldState() { try { // Attempt to sync the world state if necessary - await this.syncWorldState(); + await this.#syncWorldState(); } catch (err) { this.log.error(`Error getting world state: ${err}`); } @@ -427,7 +427,7 @@ export class AztecNodeService implements AztecNode { * Ensure we fully sync the world state * @returns A promise that fulfils once the world state is synced */ - private async syncWorldState() { + async #syncWorldState() { const blockSourceHeight = await this.blockSource.getBlockNumber(); await this.worldStateSynchroniser.syncImmediate(blockSourceHeight); } diff --git a/yarn-project/aztec-node/src/index.ts b/yarn-project/aztec-node/src/index.ts index 52ad4e50764d..853db6bae96f 100644 --- a/yarn-project/aztec-node/src/index.ts +++ b/yarn-project/aztec-node/src/index.ts @@ -1,3 +1,4 @@ export * from './aztec-node/config.js'; export * from './aztec-node/server.js'; -export * from './aztec-node/http-node.js'; +export * from './rpc/http_rpc_server.js'; +export * from './rpc/http_rpc_client.js'; diff --git a/yarn-project/aztec-node/src/rpc/http_rpc_client.ts b/yarn-project/aztec-node/src/rpc/http_rpc_client.ts new file mode 100644 index 000000000000..c19c787a35de --- /dev/null +++ b/yarn-project/aztec-node/src/rpc/http_rpc_client.ts @@ -0,0 +1,23 @@ +import { HistoricBlockData } from '@aztec/circuits.js'; +import { AztecAddress } from '@aztec/foundation/aztec-address'; +import { EthAddress } from '@aztec/foundation/eth-address'; +import { Fr } from '@aztec/foundation/fields'; +import { createJsonRpcClient, defaultFetch } from '@aztec/foundation/json-rpc/client'; +import { AztecNode, ContractData, ExtendedContractData, L2Block, L2BlockL2Logs, L2Tx, Tx, TxHash } from '@aztec/types'; + +/** + * Creates a JSON-RPC client to remotely talk to an AztecNode. + * @param url - The URL of the AztecNode + * @param fetch - The fetch implementation to use + * @returns A JSON-RPC client + */ +export function createAztecNodeRpcClient(url: string, fetch = defaultFetch): AztecNode { + const rpcClient = createJsonRpcClient( + url, + { AztecAddress, EthAddress, ExtendedContractData, ContractData, Fr, HistoricBlockData, L2Block, L2Tx, TxHash }, + { Tx, L2BlockL2Logs }, + false, + fetch, + ); + return rpcClient; +} diff --git a/yarn-project/aztec-node/src/rpc/http_rpc_server.ts b/yarn-project/aztec-node/src/rpc/http_rpc_server.ts new file mode 100644 index 000000000000..e1fb672952be --- /dev/null +++ b/yarn-project/aztec-node/src/rpc/http_rpc_server.ts @@ -0,0 +1,31 @@ +import { HistoricBlockData } from '@aztec/circuits.js'; +import { AztecAddress } from '@aztec/foundation/aztec-address'; +import { EthAddress } from '@aztec/foundation/eth-address'; +import { Fr } from '@aztec/foundation/fields'; +import { JsonRpcServer } from '@aztec/foundation/json-rpc/server'; +import { AztecNode, ContractData, ExtendedContractData, L2Block, L2BlockL2Logs, L2Tx, Tx, TxHash } from '@aztec/types'; + +/** + * Wrap an AztecNode instance with a JSON RPC HTTP server. + * @param node - The AztecNode + * @returns An JSON-RPC HTTP server + */ +export function createAztecNodeRpcServer(node: AztecNode) { + const rpc = new JsonRpcServer( + node, + { AztecAddress, EthAddress, ExtendedContractData, ContractData, Fr, HistoricBlockData, L2Block, L2Tx, TxHash }, + { Tx, L2BlockL2Logs }, + false, + // disable methods not part of the AztecNode interface + [ + 'start', + 'stop', + 'findContractIndex', + 'findCommitmentIndex', + 'getDataTreePath', + 'getL1ToL2MessageAndIndex', + 'getL1ToL2MessagesTreePath', + ], + ); + return rpc; +} diff --git a/yarn-project/aztec-rpc/src/aztec_rpc_http/aztec_rpc_http_server.ts b/yarn-project/aztec-rpc/src/aztec_rpc_http/aztec_rpc_http_server.ts index 5947aca09fda..162eb59183d9 100644 --- a/yarn-project/aztec-rpc/src/aztec_rpc_http/aztec_rpc_http_server.ts +++ b/yarn-project/aztec-rpc/src/aztec_rpc_http/aztec_rpc_http_server.ts @@ -7,6 +7,7 @@ import { CompleteAddress, ContractData, ExtendedContractData, + L2Block, L2BlockL2Logs, NotePreimage, Tx, @@ -41,6 +42,7 @@ export function getHttpRpcServer(aztecRpcServer: AztecRPC): JsonRpcServer { GrumpkinScalar, NotePreimage, AuthWitness, + L2Block, }, { Tx, TxReceipt, L2BlockL2Logs }, false, diff --git a/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts b/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts new file mode 100644 index 000000000000..0d95c9ad1386 --- /dev/null +++ b/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts @@ -0,0 +1,17 @@ +import { HistoricBlockData } from './historic_block_data.js'; + +describe('HistoricBlockData', () => { + it('serialises to buffer and back', () => { + const historicBlockData = HistoricBlockData.random(); + const serialised = historicBlockData.toBuffer(); + const deserialised = HistoricBlockData.fromBuffer(serialised); + expect(deserialised).toEqual(historicBlockData); + }); + + it('serialises to string and back', () => { + const historicBlockData = HistoricBlockData.random(); + const serialised = historicBlockData.toString(); + const deserialised = HistoricBlockData.fromString(serialised); + expect(deserialised).toEqual(historicBlockData); + }); +}); diff --git a/yarn-project/circuits.js/src/structs/kernel/historic_block_data.ts b/yarn-project/circuits.js/src/structs/kernel/historic_block_data.ts index 13645f2cf8bd..1423bee43e55 100644 --- a/yarn-project/circuits.js/src/structs/kernel/historic_block_data.ts +++ b/yarn-project/circuits.js/src/structs/kernel/historic_block_data.ts @@ -4,6 +4,11 @@ import { BufferReader } from '@aztec/foundation/serialize'; import { FieldsOf } from '../../utils/jsUtils.js'; import { serializeToBuffer } from '../../utils/serialize.js'; +/** + * The string encoding used for serialising HistoricBlockData objects. + */ +const STRING_ENCODING: BufferEncoding = 'hex'; + /** * Information about the tree roots used for both public and private kernels. */ @@ -78,7 +83,8 @@ export class HistoricBlockData { } toString() { - return this.toBuffer().toString(); + // originally this was encoding as utf-8 (the default). This caused problems decoding back the data. + return this.toBuffer().toString(STRING_ENCODING); } /** @@ -112,6 +118,10 @@ export class HistoricBlockData { ); } + static fromString(str: string) { + return HistoricBlockData.fromBuffer(Buffer.from(str, STRING_ENCODING)); + } + isEmpty() { return ( this.privateDataTreeRoot.isZero() && diff --git a/yarn-project/package.json b/yarn-project/package.json index 9af19177de9a..15e925499867 100644 --- a/yarn-project/package.json +++ b/yarn-project/package.json @@ -39,7 +39,6 @@ "boxes/blank", "boxes/private-token", "prover-client", - "rollup-provider", "aztec-node", "sequencer-client", "types", diff --git a/yarn-project/rollup-provider/.dockerignore b/yarn-project/rollup-provider/.dockerignore deleted file mode 100644 index 2b30eaf48967..000000000000 --- a/yarn-project/rollup-provider/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -data -dest -node_modules -Dockerfile \ No newline at end of file diff --git a/yarn-project/rollup-provider/.eslintrc.cjs b/yarn-project/rollup-provider/.eslintrc.cjs deleted file mode 100644 index e659927475c0..000000000000 --- a/yarn-project/rollup-provider/.eslintrc.cjs +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('@aztec/foundation/eslint'); diff --git a/yarn-project/rollup-provider/.gitignore b/yarn-project/rollup-provider/.gitignore deleted file mode 100644 index 81efe293f269..000000000000 --- a/yarn-project/rollup-provider/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/data* diff --git a/yarn-project/rollup-provider/Dockerfile b/yarn-project/rollup-provider/Dockerfile deleted file mode 100644 index 4c70de61f2bf..000000000000 --- a/yarn-project/rollup-provider/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -FROM 278380418400.dkr.ecr.eu-west-2.amazonaws.com/yarn-project-base AS builder - -COPY . . - -WORKDIR /usr/src/yarn-project/rollup-provider -RUN yarn build && yarn formatting - -# Prune dev dependencies. See comment in base image. -RUN yarn cache clean -RUN yarn workspaces focus --production > /dev/null - -FROM node:18-alpine -COPY --from=builder /usr/src /usr/src -WORKDIR /usr/src/yarn-project/rollup-provider -ENTRYPOINT ["yarn"] \ No newline at end of file diff --git a/yarn-project/rollup-provider/README.md b/yarn-project/rollup-provider/README.md deleted file mode 100644 index 923ae3b99bb8..000000000000 --- a/yarn-project/rollup-provider/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Rollup Provider - -This package contains a standalone instance of the Aztec Node with a simple http interface in front of it. - -To build, simply type `yarn build`. To start, type `yarn start`. diff --git a/yarn-project/rollup-provider/package.json b/yarn-project/rollup-provider/package.json deleted file mode 100644 index abb5e8169708..000000000000 --- a/yarn-project/rollup-provider/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "@aztec/rollup-provider", - "version": "0.1.0", - "main": "dest/index.js", - "type": "module", - "exports": "./dest/index.js", - "typedocOptions": { - "entryPoints": [ - "./src/index.ts" - ], - "name": "Rollup Provider", - "tsconfig": "./tsconfig.json" - }, - "scripts": { - "build": "yarn clean && tsc -b", - "build:dev": "tsc -b --watch", - "clean": "rm -rf ./dest .tsbuildinfo", - "formatting": "run -T prettier --check ./src && run -T eslint ./src", - "formatting:fix": "run -T prettier -w ./src", - "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules $(yarn bin jest) --passWithNoTests", - "start": "node ./dest/index.js" - }, - "inherits": [ - "../package.common.json" - ], - "jest": { - "preset": "ts-jest/presets/default-esm", - "moduleNameMapper": { - "^(\\.{1,2}/.*)\\.m?js$": "$1" - }, - "testRegex": "./src/.*\\.test\\.(js|mjs|ts)$", - "rootDir": "./src" - }, - "dependencies": { - "@aztec/aztec-node": "workspace:^", - "@aztec/circuits.js": "workspace:^", - "@aztec/foundation": "workspace:^", - "@aztec/types": "workspace:^", - "dotenv": "^16.0.3", - "koa": "^2.14.2", - "koa-router": "^12.0.0", - "promise-readable": "^6.0.0", - "tslib": "^2.4.0" - }, - "devDependencies": { - "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", - "@types/jest": "^29.5.0", - "@types/koa": "^2.13.6", - "@types/node": "^18.7.23", - "jest": "^29.5.0", - "ts-jest": "^29.1.0", - "ts-node": "^10.9.1", - "typescript": "^5.0.4" - }, - "files": [ - "dest", - "src", - "!*.test.*" - ], - "types": "./dest/index.d.ts", - "engines": { - "node": ">=18" - } -} diff --git a/yarn-project/rollup-provider/src/app.ts b/yarn-project/rollup-provider/src/app.ts deleted file mode 100644 index 7b1cf70ca746..000000000000 --- a/yarn-project/rollup-provider/src/app.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { Fr, HistoricBlockData } from '@aztec/circuits.js'; -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { createDebugLogger } from '@aztec/foundation/log'; -import { AztecNode, MerkleTreeId, SimulationError, Tx, TxHash } from '@aztec/types'; - -import Koa, { Context, DefaultState } from 'koa'; -import Router from 'koa-router'; -import { PromiseReadable } from 'promise-readable'; - -const logger = createDebugLogger('aztec:http_router'); - -/** - * Factory method for constructing the http service. - * @param node - An instance of Aztec Node into which calls are forwarded. - * @param prefix - A prefix for the http service's api routes - * @returns The constructed http service. - */ -export function appFactory(node: AztecNode, prefix: string) { - const router = new Router({ prefix }); - - const checkReady = async (ctx: Context, next: () => Promise) => { - if (!(await node.isReady())) { - ctx.status = 503; - ctx.body = { error: 'Server not ready. Try again later.' }; - } else { - await next(); - } - }; - - const exceptionHandler = async (ctx: Koa.Context, next: () => Promise) => { - try { - await next(); - } catch (err: any) { - logger.error(err); - ctx.status = 400; - ctx.body = { error: err.message }; - } - }; - - router.get('/', async (ctx: Koa.Context) => { - ctx.body = { - serviceName: 'aztec rollup', - isReady: await node.isReady(), - }; - ctx.set('content-type', 'application/json'); - ctx.status = 200; - }); - - router.get('/get-tx', async (ctx: Koa.Context) => { - const hash = ctx.query.hash!; - const txHash = new TxHash(Buffer.from(hash as string, 'hex')); - const tx = await node.getTx(txHash); - ctx.set('content-type', 'application/octet-stream'); - if (tx == undefined) { - ctx.status = 404; - } else { - ctx.status = 200; - ctx.body = tx.toBuffer(); - } - }); - - router.get('/get-block', async (ctx: Koa.Context) => { - const number = +ctx.query.number!; - const block = await node.getBlock(number); - const str = block?.encode().toString('hex'); - ctx.set('content-type', 'application/json'); - ctx.body = { - block: str, - }; - ctx.status = 200; - }); - - router.get('/get-blocks', async (ctx: Koa.Context) => { - const from = +ctx.query.from!; - const limit = +ctx.query.limit!; - const blocks = await node.getBlocks(from, limit); - const strs = blocks.map(x => x.encode().toString('hex')); - ctx.set('content-type', 'application/json'); - ctx.body = { - blocks: strs, - }; - ctx.status = 200; - }); - - router.get('/get-block-number', async (ctx: Koa.Context) => { - ctx.set('content-type', 'application/json'); - ctx.body = { - blockNumber: await node.getBlockNumber(), - }; - ctx.status = 200; - }); - - router.get('/get-version', async (ctx: Koa.Context) => { - ctx.set('content-type', 'application/json'); - ctx.body = { - version: await node.getVersion(), - }; - ctx.status = 200; - }); - - router.get('/get-chain-id', async (ctx: Koa.Context) => { - ctx.set('content-type', 'application/json'); - ctx.body = { - chainId: await node.getChainId(), - }; - ctx.status = 200; - }); - - router.get('/get-rollup-address', async (ctx: Koa.Context) => { - ctx.set('content-type', 'application/json'); - ctx.body = { - rollupAddress: (await node.getRollupAddress()).toString(), - }; - ctx.status = 200; - }); - - router.get('/contract-data-and-bytecode', async (ctx: Koa.Context) => { - const address = ctx.query.address; - ctx.set('content-type', 'application/json'); - ctx.body = { - contractData: await node.getExtendedContractData(AztecAddress.fromString(address as string)), - }; - ctx.status = 200; - }); - - router.get('/contract-data', async (ctx: Koa.Context) => { - const address = ctx.query.address; - ctx.set('content-type', 'application/json'); - ctx.body = { - contractData: await node.getContractData(AztecAddress.fromString(address as string)), - }; - ctx.status = 200; - }); - - router.get('/tree-roots', async (ctx: Koa.Context) => { - const roots: Record = await node.getTreeRoots(); - const output: { [key: string]: string } = {}; - for (const [key, value] of Object.entries(roots)) { - output[key] = value.toString(); - } - ctx.body = { - roots: output, - }; - ctx.status = 200; - }); - - router.get('/historic-block-data', async (ctx: Koa.Context) => { - const blockData: HistoricBlockData = await node.getHistoricBlockData(); - const output: { [key: string]: string } = {}; - for (const [key, value] of Object.entries(blockData)) { - output[key] = value.toString(); - } - ctx.body = { - blockData: output, - }; - ctx.status = 200; - }); - - router.get('/get-logs', async (ctx: Koa.Context) => { - const from = +ctx.query.from!; - const limit = +ctx.query.limit!; - const logType = Number(ctx.query.logType); - if (logType !== 0 && logType !== 1) { - throw new Error('Invalid log type: ' + ctx.query.logType); - } - - const logs = await node.getLogs(from, limit, logType); - const strs = logs.map(x => x.toBuffer().toString('hex')); - ctx.set('content-type', 'application/json'); - ctx.body = { - logs: strs, - }; - ctx.status = 200; - }); - - router.get('/get-pending-tx', async (ctx: Koa.Context) => { - const hash = ctx.query.hash!; - const txHash = new TxHash(Buffer.from(hash as string, 'hex')); - const tx = await node.getPendingTxByHash(txHash); - ctx.set('content-type', 'application/octet-stream'); - if (tx == undefined) { - ctx.status = 404; - } else { - ctx.status = 200; - ctx.body = tx.toBuffer(); - } - }); - - router.get('/contract-index', async (ctx: Koa.Context) => { - const leaf = ctx.query.leaf!; - const index = await node.findContractIndex(Buffer.from(leaf as string, 'hex')); - ctx.set('content-type', 'application/json'); - ctx.body = { - index, - }; - ctx.status = 200; - }); - - router.get('/contract-path', async (ctx: Koa.Context) => { - const leaf = ctx.query.leaf!; - const path = await node.getContractPath(BigInt(leaf as string)); - ctx.set('content-type', 'application/json'); - ctx.body = { - path: path.toString(), - }; - ctx.status = 200; - }); - - router.get('/commitment-index', async (ctx: Koa.Context) => { - const leaf = ctx.query.leaf!; - const index = await node.findCommitmentIndex(Buffer.from(leaf as string, 'hex')); - ctx.set('content-type', 'application/json'); - ctx.body = { - index, - }; - ctx.status = 200; - }); - - router.get('/data-path', async (ctx: Koa.Context) => { - const leaf = ctx.query.leaf!; - const index = BigInt(leaf as string); - const path = await node.getDataTreePath(index); - ctx.set('content-type', 'application/json'); - const pathAsString = path.toString(); - ctx.body = { - path: pathAsString, - }; - ctx.status = 200; - }); - - router.get('/l1-l2-message', async (ctx: Koa.Context) => { - const key = ctx.query.messageKey!; - const messageAndindex = await node.getL1ToL2MessageAndIndex(Fr.fromString(key as string)); - ctx.set('content-type', 'application/json'); - ctx.body = { - message: messageAndindex.message.toBuffer().toString('hex'), - index: messageAndindex.index, - }; - ctx.status = 200; - }); - - router.get('/l1-l2-path', async (ctx: Koa.Context) => { - const leaf = ctx.query.leaf!; - const path = await node.getL1ToL2MessagesTreePath(BigInt(leaf as string)); - ctx.set('content-type', 'application/json'); - ctx.body = { - path: path.toString(), - }; - ctx.status = 200; - }); - - router.get('/public-storage-at', async (ctx: Koa.Context) => { - logger('public-storage-at'); - const address = ctx.query.address!; - const slot = ctx.query.slot!; - const value = await node.getPublicStorageAt(AztecAddress.fromString(address as string), BigInt(slot as string)); - ctx.set('content-type', 'application/json'); - ctx.body = { - value: value?.toString('hex'), - }; - ctx.status = 200; - }); - - router.post('/tx', checkReady, async (ctx: Koa.Context) => { - const stream = new PromiseReadable(ctx.req); - const postData = (await stream.readAll()) as Buffer; - const tx = Tx.fromBuffer(postData); - await node.sendTx(tx); - ctx.status = 200; - }); - - router.post('/tx-simulate', checkReady, async (ctx: Koa.Context) => { - const stream = new PromiseReadable(ctx.req); - const postData = (await stream.readAll()) as Buffer; - const tx = Tx.fromBuffer(postData); - try { - await node.simulatePublicCalls(tx); - } catch (err) { - if (err instanceof SimulationError) { - ctx.body = { - simulationError: err.toJSON(), - }; - ctx.status = 400; - } else { - throw err; - } - } - }); - - const app = new Koa(); - app.on('error', error => { - logger.error(`KOA app-level error. ${JSON.stringify({ error })}`); - }); - app.proxy = true; - app.use(exceptionHandler); - app.use(router.routes()); - app.use(router.allowedMethods()); - - return app; -} diff --git a/yarn-project/rollup-provider/src/index.ts b/yarn-project/rollup-provider/src/index.ts deleted file mode 100644 index b64dcd6b3061..000000000000 --- a/yarn-project/rollup-provider/src/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { AztecNodeConfig, AztecNodeService, getConfigEnvVars } from '@aztec/aztec-node'; -import { createDebugLogger } from '@aztec/foundation/log'; - -import 'dotenv/config'; -import http from 'http'; - -import { appFactory } from './app.js'; - -const logger = createDebugLogger('aztec:rollup_provider'); - -const { SERVER_PORT = 9000 } = process.env; - -/** - * Entrypoint for the rollup provider service - * @returns An empty promise - */ -async function main() { - logger('Server started...'); - const aztecNodeConfig: AztecNodeConfig = getConfigEnvVars(); - const node = await AztecNodeService.createAndSync(aztecNodeConfig); - - const shutdown = async () => { - await node.stop(); - process.exit(0); - }; - - process.once('SIGINT', shutdown); - process.once('SIGTERM', shutdown); - - const app = appFactory(node, ''); - - const httpServer = http.createServer(app.callback()); - httpServer.listen(SERVER_PORT); - logger(`Server listening on port ${SERVER_PORT}.`); -} - -main().catch(err => { - logger.error(err); - process.exit(1); -}); diff --git a/yarn-project/rollup-provider/tsconfig.json b/yarn-project/rollup-provider/tsconfig.json deleted file mode 100644 index d664fee7b6d1..000000000000 --- a/yarn-project/rollup-provider/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "extends": "..", - "compilerOptions": { - "outDir": "dest", - "rootDir": "src", - "tsBuildInfoFile": ".tsbuildinfo" - }, - "references": [ - { - "path": "../aztec-node" - }, - { - "path": "../circuits.js" - }, - { - "path": "../foundation" - }, - { - "path": "../types" - } - ], - "include": ["src"] -} diff --git a/yarn-project/tsconfig.json b/yarn-project/tsconfig.json index c8682d550f77..5974c470c00b 100644 --- a/yarn-project/tsconfig.json +++ b/yarn-project/tsconfig.json @@ -37,7 +37,6 @@ { "path": "p2p/tsconfig.json" }, { "path": "p2p-bootstrap/tsconfig.json" }, { "path": "prover-client/tsconfig.json" }, - { "path": "rollup-provider/tsconfig.json" }, { "path": "sequencer-client/tsconfig.json" }, { "path": "types/tsconfig.json" }, { "path": "world-state/tsconfig.json" } diff --git a/yarn-project/types/src/l2_block.test.ts b/yarn-project/types/src/l2_block.test.ts index 55fd557a68b4..99d208805172 100644 --- a/yarn-project/types/src/l2_block.test.ts +++ b/yarn-project/types/src/l2_block.test.ts @@ -11,6 +11,14 @@ describe('L2Block', () => { expect(recovered).toEqual(block); }); + it('can encode a L2 block to string and back', () => { + const block = L2Block.random(42); + const serialised = block.toString(); + const recovered = L2Block.fromString(serialised); + + expect(recovered).toEqual(block); + }); + // TS equivalent of `testComputeKernelLogsIterationWithoutLogs` in `Decoder.t.sol` it('correctly computes kernel logs hash when there are no logs', () => { // The following 2 values are copied from `testComputeKernelLogsIterationWithoutLogs` in `Decoder.t.sol` diff --git a/yarn-project/types/src/l2_block.ts b/yarn-project/types/src/l2_block.ts index a3a7c1e7a209..a0a3950bed60 100644 --- a/yarn-project/types/src/l2_block.ts +++ b/yarn-project/types/src/l2_block.ts @@ -19,6 +19,11 @@ import times from 'lodash.times'; import { ContractData, L2Tx, LogType, PublicDataWrite, TxL2Logs } from './index.js'; import { L2BlockL2Logs } from './logs/l2_block_l2_logs.js'; +/** + * String encoding of serialised L2 block data. + */ +const STRING_ENCODING: BufferEncoding = 'hex'; + /** * The data that makes up the rollup proof, with encoder decoder functions. * TODO: Reuse data types and serialization functions from circuits package. @@ -388,6 +393,14 @@ export class L2Block { return this.encode(); } + /** + * Encodes the block as a hex string + * @returns The encoded L2 block data as a hex string. + */ + toString() { + return this.toBuffer().toString(STRING_ENCODING); + } + /** * Decode the L2 block data from a buffer. * @param encoded - The encoded L2 block data. @@ -447,6 +460,15 @@ export class L2Block { }); } + /** + * Decode the L2 block from a string + * @param str - The serialised L2 block + * @returns An L2 block + */ + static fromString(str: string): L2Block { + return L2Block.decode(Buffer.from(str, STRING_ENCODING)); + } + /** * Helper function to attach logs related to a block. * @param logs - The logs to be attached to a block. diff --git a/yarn-project/types/src/l2_tx.test.ts b/yarn-project/types/src/l2_tx.test.ts index 889ec8e6ee62..460943240cf7 100644 --- a/yarn-project/types/src/l2_tx.test.ts +++ b/yarn-project/types/src/l2_tx.test.ts @@ -6,4 +6,10 @@ describe('L2Tx', () => { const buf = tx.toBuffer(); expect(L2Tx.fromBuffer(buf)).toEqual(tx); }); + + it('converts to and from string', () => { + const tx = L2Tx.random(); + const str = tx.toString(); + expect(L2Tx.fromString(str)).toEqual(tx); + }); }); diff --git a/yarn-project/types/src/l2_tx.ts b/yarn-project/types/src/l2_tx.ts index 29452442a658..a101e678038d 100644 --- a/yarn-project/types/src/l2_tx.ts +++ b/yarn-project/types/src/l2_tx.ts @@ -15,6 +15,11 @@ import { ContractData } from './contract_data.js'; import { PublicDataWrite } from './public_data_write.js'; import { TxHash } from './tx/tx_hash.js'; +/** + * The string encoding used for serialising L2Tx objects to strings. + */ +const STRING_ENCODING: BufferEncoding = 'hex'; + /** * Represents an L2 transaction. */ @@ -81,6 +86,15 @@ export class L2Tx { ); } + /** + * Deserializes an L2Tx object from a string. + * @param str - String to deserialize. + * @returns An instance of L2Tx. + */ + static fromString(str: string) { + return L2Tx.fromBuffer(Buffer.from(str, STRING_ENCODING)); + } + /** * Serializes the Tx object into a Buffer. * @returns Buffer representation of the Tx object. @@ -98,6 +112,13 @@ export class L2Tx { ]); } + /** + * Returns a string representation of the Tx object. + */ + toString(): string { + return this.toBuffer().toString(STRING_ENCODING); + } + static random() { return new L2Tx( times(MAX_NEW_COMMITMENTS_PER_TX, Fr.random), diff --git a/yarn-project/yarn-project-base/Dockerfile b/yarn-project/yarn-project-base/Dockerfile index 7ab6961d39d3..3e3395182de5 100644 --- a/yarn-project/yarn-project-base/Dockerfile +++ b/yarn-project/yarn-project-base/Dockerfile @@ -42,7 +42,6 @@ COPY circuits.js/package.json circuits.js/package.json COPY p2p/package.json p2p/package.json COPY p2p-bootstrap/package.json p2p-bootstrap/package.json COPY prover-client/package.json prover-client/package.json -COPY rollup-provider/package.json rollup-provider/package.json COPY sequencer-client/package.json sequencer-client/package.json COPY types/package.json types/package.json COPY world-state/package.json world-state/package.json @@ -96,7 +95,6 @@ COPY p2p/tsconfig.json p2p/tsconfig.json COPY p2p-bootstrap/tsconfig.json p2p-bootstrap/tsconfig.json COPY prover-client/tsconfig.json prover-client/tsconfig.json COPY sequencer-client/tsconfig.json sequencer-client/tsconfig.json -COPY rollup-provider/tsconfig.json rollup-provider/tsconfig.json COPY types/tsconfig.json types/tsconfig.json COPY world-state/tsconfig.json world-state/tsconfig.json diff --git a/yarn-project/yarn.lock b/yarn-project/yarn.lock index 3853bf9f7a8c..1806b4a0e26e 100644 --- a/yarn-project/yarn.lock +++ b/yarn-project/yarn.lock @@ -685,31 +685,6 @@ __metadata: languageName: unknown linkType: soft -"@aztec/rollup-provider@workspace:rollup-provider": - version: 0.0.0-use.local - resolution: "@aztec/rollup-provider@workspace:rollup-provider" - dependencies: - "@aztec/aztec-node": "workspace:^" - "@aztec/circuits.js": "workspace:^" - "@aztec/foundation": "workspace:^" - "@aztec/types": "workspace:^" - "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 - "@types/jest": ^29.5.0 - "@types/koa": ^2.13.6 - "@types/node": ^18.7.23 - dotenv: ^16.0.3 - jest: ^29.5.0 - koa: ^2.14.2 - koa-router: ^12.0.0 - promise-readable: ^6.0.0 - ts-jest: ^29.1.0 - ts-node: ^10.9.1 - tslib: ^2.4.0 - typescript: ^5.0.4 - languageName: unknown - linkType: soft - "@aztec/sequencer-client@workspace:^, @aztec/sequencer-client@workspace:sequencer-client": version: 0.0.0-use.local resolution: "@aztec/sequencer-client@workspace:sequencer-client" @@ -8039,13 +8014,6 @@ __metadata: languageName: node linkType: hard -"core-js@npm:^3.6.5": - version: 3.32.0 - resolution: "core-js@npm:3.32.0" - checksum: 52921395028550e4c9d21d47b9836439bb5b6b9eefc34d45a3948a68d81fdd093acc0fadf69f9cf632b82f01f95f22f484408a93dd9e940b19119ac204cd2925 - languageName: node - linkType: hard - "core-util-is@npm:^1.0.2, core-util-is@npm:~1.0.0": version: 1.0.3 resolution: "core-util-is@npm:1.0.3" @@ -15555,15 +15523,6 @@ __metadata: languageName: node linkType: hard -"promise-readable@npm:^6.0.0": - version: 6.0.0 - resolution: "promise-readable@npm:6.0.0" - dependencies: - core-js: ^3.6.5 - checksum: 2e93f83457011ca721e7a55b9bb5045f2bf75dc1435d1912a2f20db1ba309e3343364eb68525e87b4c8b27baa0ab04619d0a3c064e944584260b620ebcbb1bef - languageName: node - linkType: hard - "promise-retry@npm:^2.0.1": version: 2.0.1 resolution: "promise-retry@npm:2.0.1" From 652bb0444deddfb72c323a07b5e88979a18c4f82 Mon Sep 17 00:00:00 2001 From: Rahul Kothari Date: Fri, 22 Sep 2023 17:39:18 +0100 Subject: [PATCH 11/12] feat: expose registry address in `getNodeInfo` (#2478) part of #2453 Users need `getNodeInfo` to add to the Portal contract! Added `registryAddress` in ArchiverConfig, archiver constructor, L2BlockSource, pass the address when deploying the sandbox, created relevant method on aztec node to expose, --- yarn-project/archiver/src/archiver/archiver.test.ts | 6 ++++-- yarn-project/archiver/src/archiver/archiver.ts | 7 +++++++ yarn-project/archiver/src/archiver/config.ts | 2 ++ yarn-project/archiver/src/index.ts | 10 +++++++++- yarn-project/aztec-node/src/aztec-node/server.ts | 4 ++++ .../aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts | 4 +++- yarn-project/aztec-sandbox/src/sandbox.ts | 1 + yarn-project/aztec.js/src/contract/contract.test.ts | 1 + yarn-project/end-to-end/src/canary/browser.ts | 4 ++-- .../src/e2e_public_cross_chain_messaging.test.ts | 1 - yarn-project/end-to-end/src/fixtures/utils.ts | 1 + .../end-to-end/src/integration_l1_publisher.test.ts | 4 ++++ yarn-project/p2p/src/client/mocks.ts | 8 ++++++++ yarn-project/sequencer-client/src/config.ts | 2 ++ yarn-project/types/src/interfaces/aztec-node.ts | 6 ++++++ yarn-project/types/src/interfaces/node-info.ts | 4 ++++ yarn-project/types/src/l1_addresses.ts | 5 +++++ yarn-project/types/src/l2_block_source.ts | 6 ++++++ 18 files changed, 69 insertions(+), 7 deletions(-) diff --git a/yarn-project/archiver/src/archiver/archiver.test.ts b/yarn-project/archiver/src/archiver/archiver.test.ts index 612223426a70..b3f0db13e556 100644 --- a/yarn-project/archiver/src/archiver/archiver.test.ts +++ b/yarn-project/archiver/src/archiver/archiver.test.ts @@ -12,8 +12,9 @@ import { Archiver } from './archiver.js'; import { ArchiverDataStore, MemoryArchiverStore } from './archiver_store.js'; describe('Archiver', () => { - const rollupAddress = '0x0000000000000000000000000000000000000000'; - const inboxAddress = '0x0000000000000000000000000000000000000000'; + const rollupAddress = EthAddress.ZERO.toString(); + const inboxAddress = EthAddress.ZERO.toString(); + const registryAddress = EthAddress.ZERO.toString(); const contractDeploymentEmitterAddress = '0x0000000000000000000000000000000000000001'; const blockNums = [1, 2, 3]; let publicClient: MockProxy>; @@ -29,6 +30,7 @@ describe('Archiver', () => { publicClient, EthAddress.fromString(rollupAddress), EthAddress.fromString(inboxAddress), + EthAddress.fromString(registryAddress), EthAddress.fromString(contractDeploymentEmitterAddress), 0, archiverStore, diff --git a/yarn-project/archiver/src/archiver/archiver.ts b/yarn-project/archiver/src/archiver/archiver.ts index 6c88251805d5..217df42dab63 100644 --- a/yarn-project/archiver/src/archiver/archiver.ts +++ b/yarn-project/archiver/src/archiver/archiver.ts @@ -65,6 +65,7 @@ export class Archiver implements L2BlockSource, L2LogsSource, ContractDataSource * @param publicClient - A client for interacting with the Ethereum node. * @param rollupAddress - Ethereum address of the rollup contract. * @param inboxAddress - Ethereum address of the inbox contract. + * @param registryAddress - Ethereum address of the registry contract. * @param contractDeploymentEmitterAddress - Ethereum address of the contractDeploymentEmitter contract. * @param searchStartBlock - The L1 block from which to start searching for new blocks. * @param pollingIntervalMs - The interval for polling for L1 logs (in milliseconds). @@ -75,6 +76,7 @@ export class Archiver implements L2BlockSource, L2LogsSource, ContractDataSource private readonly publicClient: PublicClient, private readonly rollupAddress: EthAddress, private readonly inboxAddress: EthAddress, + private readonly registryAddress: EthAddress, private readonly contractDeploymentEmitterAddress: EthAddress, searchStartBlock: number, private readonly store: ArchiverDataStore, @@ -103,6 +105,7 @@ export class Archiver implements L2BlockSource, L2LogsSource, ContractDataSource publicClient, config.rollupContract, config.inboxContract, + config.registryContract, config.contractDeploymentEmitterContract, config.searchStartBlock, archiverStore, @@ -264,6 +267,10 @@ export class Archiver implements L2BlockSource, L2LogsSource, ContractDataSource return Promise.resolve(this.rollupAddress); } + public getRegistryAddress(): Promise { + return Promise.resolve(this.registryAddress); + } + /** * Gets up to `limit` amount of L2 blocks starting from `from`. * @param from - Number of the first block to return (inclusive). diff --git a/yarn-project/archiver/src/archiver/config.ts b/yarn-project/archiver/src/archiver/config.ts index 675db4c278aa..f6604d8c6f2e 100644 --- a/yarn-project/archiver/src/archiver/config.ts +++ b/yarn-project/archiver/src/archiver/config.ts @@ -53,12 +53,14 @@ export function getConfigEnvVars(): ArchiverConfig { SEARCH_START_BLOCK, API_KEY, INBOX_CONTRACT_ADDRESS, + REGISTRY_CONTRACT_ADDRESS, } = process.env; return { rpcUrl: ETHEREUM_HOST || 'http://127.0.0.1:8545/', archiverPollingIntervalMS: ARCHIVER_POLLING_INTERVAL_MS ? +ARCHIVER_POLLING_INTERVAL_MS : 1_000, viemPollingIntervalMS: ARCHIVER_VIEM_POLLING_INTERVAL_MS ? +ARCHIVER_VIEM_POLLING_INTERVAL_MS : 1_000, rollupContract: ROLLUP_CONTRACT_ADDRESS ? EthAddress.fromString(ROLLUP_CONTRACT_ADDRESS) : EthAddress.ZERO, + registryContract: REGISTRY_CONTRACT_ADDRESS ? EthAddress.fromString(REGISTRY_CONTRACT_ADDRESS) : EthAddress.ZERO, inboxContract: INBOX_CONTRACT_ADDRESS ? EthAddress.fromString(INBOX_CONTRACT_ADDRESS) : EthAddress.ZERO, contractDeploymentEmitterContract: CONTRACT_DEPLOYMENT_EMITTER_ADDRESS ? EthAddress.fromString(CONTRACT_DEPLOYMENT_EMITTER_ADDRESS) diff --git a/yarn-project/archiver/src/index.ts b/yarn-project/archiver/src/index.ts index 1ab04d4c58e6..d132e23af902 100644 --- a/yarn-project/archiver/src/index.ts +++ b/yarn-project/archiver/src/index.ts @@ -17,7 +17,14 @@ const log = createDebugLogger('aztec:archiver'); // eslint-disable-next-line require-await async function main() { const config = getConfigEnvVars(); - const { rpcUrl, rollupContract, inboxContract, contractDeploymentEmitterContract, searchStartBlock } = config; + const { + rpcUrl, + rollupContract, + inboxContract, + registryContract, + contractDeploymentEmitterContract, + searchStartBlock, + } = config; const publicClient = createPublicClient({ chain: localhost, @@ -30,6 +37,7 @@ async function main() { publicClient, rollupContract, inboxContract, + registryContract, contractDeploymentEmitterContract, searchStartBlock, archiverStore, diff --git a/yarn-project/aztec-node/src/aztec-node/server.ts b/yarn-project/aztec-node/src/aztec-node/server.ts index fcf509ff6cb2..a2b3720b0a35 100644 --- a/yarn-project/aztec-node/src/aztec-node/server.ts +++ b/yarn-project/aztec-node/src/aztec-node/server.ts @@ -181,6 +181,10 @@ export class AztecNodeService implements AztecNode { return this.blockSource.getRollupAddress(); } + public getRegistryAddress(): Promise { + return this.blockSource.getRegistryAddress(); + } + /** * Get the extended contract data for this contract. * @param contractAddress - The contract data address. diff --git a/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts b/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts index fe754f7c6521..86555d6392b9 100644 --- a/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts +++ b/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts @@ -337,10 +337,11 @@ export class AztecRPCServer implements AztecRPC { } public async getNodeInfo(): Promise { - const [version, chainId, rollupAddress] = await Promise.all([ + const [version, chainId, rollupAddress, registryAddress] = await Promise.all([ this.node.getVersion(), this.node.getChainId(), this.node.getRollupAddress(), + this.node.getRegistryAddress(), ]); return { @@ -349,6 +350,7 @@ export class AztecRPCServer implements AztecRPC { chainId, protocolVersion: version, rollupAddress, + registryAddress, }; } diff --git a/yarn-project/aztec-sandbox/src/sandbox.ts b/yarn-project/aztec-sandbox/src/sandbox.ts index 8d25be5a2007..227cc7f6edbd 100644 --- a/yarn-project/aztec-sandbox/src/sandbox.ts +++ b/yarn-project/aztec-sandbox/src/sandbox.ts @@ -70,6 +70,7 @@ export async function createSandbox(config: Partial = {}) { aztecNodeConfig.rollupContract = l1Contracts.rollupAddress; aztecNodeConfig.contractDeploymentEmitterContract = l1Contracts.contractDeploymentEmitterAddress; aztecNodeConfig.inboxContract = l1Contracts.inboxAddress; + aztecNodeConfig.registryContract = l1Contracts.registryAddress; const node = await AztecNodeService.createAndSync(aztecNodeConfig); const rpcServer = await createAztecRPCServer(node, rpcConfig); diff --git a/yarn-project/aztec.js/src/contract/contract.test.ts b/yarn-project/aztec.js/src/contract/contract.test.ts index 1df16e7de1f8..a095b316b571 100644 --- a/yarn-project/aztec.js/src/contract/contract.test.ts +++ b/yarn-project/aztec.js/src/contract/contract.test.ts @@ -34,6 +34,7 @@ describe('Contract Class', () => { protocolVersion: 1, chainId: 2, rollupAddress: EthAddress.random(), + registryAddress: EthAddress.random(), }; const defaultAbi: ContractAbi = { diff --git a/yarn-project/end-to-end/src/canary/browser.ts b/yarn-project/end-to-end/src/canary/browser.ts index 42354dc6f904..c4f2506b59dc 100644 --- a/yarn-project/end-to-end/src/canary/browser.ts +++ b/yarn-project/end-to-end/src/canary/browser.ts @@ -27,11 +27,11 @@ const PORT = 3000; const { SANDBOX_URL } = process.env; -const conditionalDescribe = () => (SANDBOX_URL ? describe : describe.skip); +// const conditionalDescribe = () => (SANDBOX_URL ? describe: describe.skip); const privKey = AztecJs.GrumpkinScalar.random(); export const browserTestSuite = (setup: () => Server, pageLogger: AztecJs.DebugLogger) => - conditionalDescribe()('e2e_aztec.js_browser', () => { + describe.skip('e2e_aztec.js_browser', () => { const initialBalance = 33n; const transferAmount = 3n; diff --git a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts index 5ec2453ae2a4..68897f60a53d 100644 --- a/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts +++ b/yarn-project/end-to-end/src/e2e_public_cross_chain_messaging.test.ts @@ -44,7 +44,6 @@ describe('e2e_public_cross_chain_messaging', () => { logger_, cheatCodes, ); - l2Token = crossChainTestHarness.l2Token; l2Bridge = crossChainTestHarness.l2Bridge; ownerEthAddress = crossChainTestHarness.ethAccount; diff --git a/yarn-project/end-to-end/src/fixtures/utils.ts b/yarn-project/end-to-end/src/fixtures/utils.ts index df49c2dc438b..4c8d570e9873 100644 --- a/yarn-project/end-to-end/src/fixtures/utils.ts +++ b/yarn-project/end-to-end/src/fixtures/utils.ts @@ -230,6 +230,7 @@ export async function setup( config.rollupContract = deployL1ContractsValues.rollupAddress; config.contractDeploymentEmitterContract = deployL1ContractsValues.contractDeploymentEmitterAddress; config.inboxContract = deployL1ContractsValues.inboxAddress; + config.registryContract = deployL1ContractsValues.registryAddress; const aztecNode = await createAztecNode(config, logger); diff --git a/yarn-project/end-to-end/src/integration_l1_publisher.test.ts b/yarn-project/end-to-end/src/integration_l1_publisher.test.ts index 2ad33406c216..13bcd08e7608 100644 --- a/yarn-project/end-to-end/src/integration_l1_publisher.test.ts +++ b/yarn-project/end-to-end/src/integration_l1_publisher.test.ts @@ -68,6 +68,7 @@ describe('L1Publisher integration', () => { let rollupAddress: Address; let inboxAddress: Address; let outboxAddress: Address; + let registryAddress: Address; let contractDeploymentEmitterAddress: Address; let decoderHelperAddress: Address; @@ -95,6 +96,7 @@ describe('L1Publisher integration', () => { rollupAddress: rollupAddress_, inboxAddress: inboxAddress_, outboxAddress: outboxAddress_, + registryAddress: registryAddress_, contractDeploymentEmitterAddress: contractDeploymentEmitterAddress_, decoderHelperAddress: decoderHelperAddress_, publicClient: publicClient_, @@ -105,6 +107,7 @@ describe('L1Publisher integration', () => { rollupAddress = getAddress(rollupAddress_.toString()); inboxAddress = getAddress(inboxAddress_.toString()); outboxAddress = getAddress(outboxAddress_.toString()); + registryAddress = getAddress(registryAddress_.toString()); contractDeploymentEmitterAddress = getAddress(contractDeploymentEmitterAddress_.toString()); decoderHelperAddress = getAddress(decoderHelperAddress_!.toString()); @@ -145,6 +148,7 @@ describe('L1Publisher integration', () => { requiredConfirmations: 1, rollupContract: EthAddress.fromString(rollupAddress), inboxContract: EthAddress.fromString(inboxAddress), + registryContract: EthAddress.fromString(registryAddress), contractDeploymentEmitterContract: EthAddress.fromString(contractDeploymentEmitterAddress), publisherPrivateKey: sequencerPK, l1BlockPublishRetryIntervalMS: 100, diff --git a/yarn-project/p2p/src/client/mocks.ts b/yarn-project/p2p/src/client/mocks.ts index e98a3c42a62c..7face89993ed 100644 --- a/yarn-project/p2p/src/client/mocks.ts +++ b/yarn-project/p2p/src/client/mocks.ts @@ -24,6 +24,14 @@ export class MockBlockSource implements L2BlockSource { return Promise.resolve(EthAddress.random()); } + /** + * Method to fetch the registry contract address at the base-layer. + * @returns The registry address. + */ + getRegistryAddress(): Promise { + return Promise.resolve(EthAddress.random()); + } + /** * Gets the number of the latest L2 block processed by the block source implementation. * @returns In this mock instance, returns the number of L2 blocks that we've mocked. diff --git a/yarn-project/sequencer-client/src/config.ts b/yarn-project/sequencer-client/src/config.ts index 9060a659c269..3a5540f97b33 100644 --- a/yarn-project/sequencer-client/src/config.ts +++ b/yarn-project/sequencer-client/src/config.ts @@ -25,6 +25,7 @@ export function getConfigEnvVars(): SequencerClientConfig { SEQ_MAX_TX_PER_BLOCK, SEQ_MIN_TX_PER_BLOCK, ROLLUP_CONTRACT_ADDRESS, + REGISTRY_CONTRACT_ADDRESS, INBOX_CONTRACT_ADDRESS, CONTRACT_DEPLOYMENT_EMITTER_ADDRESS, } = process.env; @@ -45,6 +46,7 @@ export function getConfigEnvVars(): SequencerClientConfig { transactionPollingIntervalMS: SEQ_TX_POLLING_INTERVAL_MS ? +SEQ_TX_POLLING_INTERVAL_MS : 1_000, rollupContract: ROLLUP_CONTRACT_ADDRESS ? EthAddress.fromString(ROLLUP_CONTRACT_ADDRESS) : EthAddress.ZERO, inboxContract: INBOX_CONTRACT_ADDRESS ? EthAddress.fromString(INBOX_CONTRACT_ADDRESS) : EthAddress.ZERO, + registryContract: REGISTRY_CONTRACT_ADDRESS ? EthAddress.fromString(REGISTRY_CONTRACT_ADDRESS) : EthAddress.ZERO, contractDeploymentEmitterContract: CONTRACT_DEPLOYMENT_EMITTER_ADDRESS ? EthAddress.fromString(CONTRACT_DEPLOYMENT_EMITTER_ADDRESS) : EthAddress.ZERO, diff --git a/yarn-project/types/src/interfaces/aztec-node.ts b/yarn-project/types/src/interfaces/aztec-node.ts index ed61b46a11df..bac696c38502 100644 --- a/yarn-project/types/src/interfaces/aztec-node.ts +++ b/yarn-project/types/src/interfaces/aztec-node.ts @@ -67,6 +67,12 @@ export interface AztecNode extends DataCommitmentProvider, L1ToL2MessageProvider */ getRollupAddress(): Promise; + /** + * Method to fetch the registry contract address at the base-layer. + * @returns The registry address. + */ + getRegistryAddress(): Promise; + /** * Get the extended contract data for this contract. * @param contractAddress - The contract data address. diff --git a/yarn-project/types/src/interfaces/node-info.ts b/yarn-project/types/src/interfaces/node-info.ts index 4037d4917ed8..6c10d6b5ef86 100644 --- a/yarn-project/types/src/interfaces/node-info.ts +++ b/yarn-project/types/src/interfaces/node-info.ts @@ -24,4 +24,8 @@ export type NodeInfo = { * The rollup contract address */ rollupAddress: EthAddress; + /** + * The registry contract address + */ + registryAddress: EthAddress; }; diff --git a/yarn-project/types/src/l1_addresses.ts b/yarn-project/types/src/l1_addresses.ts index 3a9b9b772335..a85fb0f889ac 100644 --- a/yarn-project/types/src/l1_addresses.ts +++ b/yarn-project/types/src/l1_addresses.ts @@ -14,6 +14,11 @@ export interface L1Addresses { */ inboxContract: EthAddress; + /** + * Registry contract address. + */ + registryContract: EthAddress; + /** * ContractDeploymentEmitter contract address. */ diff --git a/yarn-project/types/src/l2_block_source.ts b/yarn-project/types/src/l2_block_source.ts index 4541f730b0ad..5da437eafebe 100644 --- a/yarn-project/types/src/l2_block_source.ts +++ b/yarn-project/types/src/l2_block_source.ts @@ -14,6 +14,12 @@ export interface L2BlockSource { */ getRollupAddress(): Promise; + /** + * Method to fetch the registry contract address at the base-layer. + * @returns The registry address. + */ + getRegistryAddress(): Promise; + /** * Gets the number of the latest L2 block processed by the block source implementation. * @returns The number of the latest L2 block processed by the block source implementation. From 2fe8f5e41879cc72bd208eb77fb5a2e3261d1cf8 Mon Sep 17 00:00:00 2001 From: Lasse Herskind <16536249+LHerskind@users.noreply.github.com> Date: Fri, 22 Sep 2023 18:21:38 +0100 Subject: [PATCH 12/12] chore: Use US spelling (#2475) Fixes #1934 --- .../cpp/src/aztec3/circuits/apps/.test.cpp | 8 +- .../apps/function_execution_context.hpp | 14 +- .../basic_contract_deployment.cpp | 2 +- .../apps/test_apps/escrow/deposit.cpp | 2 +- .../apps/test_apps/escrow/transfer.cpp | 2 +- .../apps/test_apps/escrow/withdraw.cpp | 2 +- .../function_1_1.cpp | 2 +- .../function_2_1.cpp | 2 +- .../communication/cross_chain_calls.md | 2 +- docs/docs/dev_docs/cli/main.md | 2 +- docs/docs/dev_docs/contracts/compiling.md | 18 +-- .../dev_docs/contracts/syntax/functions.md | 2 +- .../contracts/syntax/state_variables.md | 42 +++--- docs/docs/dev_docs/sandbox_errors/main.md | 2 +- docs/docs/dev_docs/testing/cheat_codes.md | 8 +- .../writing_dapp/contract_deployment.md | 4 +- .../writing_dapp/contract_interaction.md | 10 +- .../tutorials/writing_dapp/rpc_server.md | 4 +- .../tutorials/writing_token_contract.md | 4 +- .../dev_docs/sandbox/components.md | 2 +- .../src/client/private_execution.test.ts | 4 +- .../aztec-node/src/aztec-node/server.ts | 22 +-- yarn-project/aztec-nr/aztec/src/account.nr | 6 +- .../aztec-nr/aztec/src/note/lifecycle.nr | 4 +- .../aztec/src/note/note_getter_options.nr | 4 +- .../aztec-nr/aztec/src/note/note_interface.nr | 4 +- yarn-project/aztec-nr/aztec/src/note/utils.nr | 4 +- .../aztec-nr/aztec/src/oracle/notes.nr | 8 +- .../aztec-nr/aztec/src/oracle/storage.nr | 4 +- .../src/state_vars/immutable_singleton.nr | 4 +- .../aztec/src/state_vars/public_state.nr | 18 +-- .../aztec/src/state_vars/singleton.nr | 4 +- yarn-project/aztec-nr/aztec/src/types.nr | 2 +- .../aztec-nr/aztec/src/types/point.nr | 14 +- .../aztec/src/types/type_serialisation.nr | 13 -- .../type_serialisation/bool_serialisation.nr | 16 -- .../type_serialisation/field_serialisation.nr | 16 -- .../type_serialisation/u32_serialisation.nr | 16 -- .../aztec/src/types/type_serialization.nr | 13 ++ .../type_serialization/bool_serialization.nr | 16 ++ .../type_serialization/field_serialization.nr | 16 ++ .../type_serialization/u32_serialization.nr | 16 ++ yarn-project/aztec-nr/aztec/src/types/vec.nr | 2 +- .../src/easy_private_state.nr | 4 +- yarn-project/aztec-nr/value-note/src/utils.nr | 2 +- .../aztec-nr/value-note/src/value_note.nr | 16 +- yarn-project/aztec-rpc/README.md | 2 +- .../src/aztec_rpc_server/aztec_rpc_server.ts | 22 +-- .../test/aztec_rpc_test_suite.ts | 4 +- .../src/note_processor/note_processor.ts | 8 +- .../aztec-rpc/src/synchroniser/index.ts | 1 - .../aztec-rpc/src/synchronizer/index.ts | 1 + .../synchronizer.test.ts} | 44 +++--- .../synchronizer.ts} | 24 +-- .../aztec.js/src/wallet/base_wallet.ts | 8 +- .../boxes/blank-react/src/app/contract.tsx | 2 +- .../src/contracts/src/interface.nr | 6 +- .../blank/src/contracts/src/interface.nr | 6 +- .../boxes/private-token/src/app/contract.tsx | 2 +- .../src/contracts/src/interface.nr | 16 +- yarn-project/cli/src/unbox.ts | 2 +- .../end-to-end/src/e2e_2_rpc_servers.test.ts | 24 +-- .../foundation/src/abi/encoder.test.ts | 2 +- yarn-project/foundation/src/abi/encoder.ts | 2 +- .../foundation/src/abi/function_selector.ts | 2 +- .../foundation/src/fields/coordinate.ts | 10 +- .../foundation/src/json-rpc/convert.test.ts | 34 ++--- .../foundation/src/json-rpc/convert.ts | 4 +- .../standard_indexed_tree.ts | 4 +- .../src/__snapshots__/index.test.ts.snap | 8 +- .../src/contract-interface-gen/noir.ts | 26 ++-- .../contracts/card_game_contract/src/cards.nr | 2 +- .../contracts/card_game_contract/src/game.nr | 24 +-- .../contracts/card_game_contract/src/main.nr | 6 +- .../src/contracts/child_contract/src/main.nr | 6 +- .../docs_example_contract/src/actions.nr | 24 +-- .../docs_example_contract/src/main.nr | 14 +- .../src/types/card_note.nr | 16 +- .../src/types/profile_note.nr | 16 +- .../docs_example_contract/src/types/queen.nr | 14 +- .../src/types/rules_note.nr | 16 +- .../easy_private_token_contract/src/main.nr | 2 +- .../src/ecdsa_public_key_note.nr | 16 +- .../ecdsa_account_contract/src/main.nr | 4 +- .../escrow_contract/src/address_note.nr | 14 +- .../src/contracts/escrow_contract/src/main.nr | 2 +- .../contracts/lending_contract/src/asset.nr | 18 +-- .../contracts/lending_contract/src/main.nr | 24 +-- .../src/interface.nr | 138 +++++++++--------- .../non_native_token_contract/src/main.nr | 8 +- .../src/transparent_note.nr | 18 +-- .../pending_commitments_contract/src/main.nr | 6 +- .../src/address_note.nr | 14 +- .../pokeable_token_contract/src/main.nr | 4 +- .../price_feed_contract/src/asset.nr | 18 +-- .../contracts/price_feed_contract/src/main.nr | 6 +- .../src/claim_note.nr | 16 +- .../src/interface.nr | 128 ++++++++-------- .../private_token_contract/src/interface.nr | 16 +- .../public_token_contract/src/main.nr | 8 +- .../schnorr_account_contract/src/main.nr | 4 +- .../src/public_key_note.nr | 16 +- .../stateful_test_contract/src/main.nr | 8 +- .../contracts/test_contract/src/interface.nr | 116 +++++++-------- .../token_bridge_contract/src/main.nr | 6 +- .../src/contracts/token_contract/src/main.nr | 20 +-- .../src/contracts/token_contract/src/types.nr | 18 +-- .../p2p/src/service/tx_messages.test.ts | 8 +- yarn-project/sequencer-client/README.md | 2 +- .../src/client/sequencer-client.ts | 10 +- .../src/sequencer/sequencer.test.ts | 6 +- .../src/sequencer/sequencer.ts | 6 +- .../types/src/interfaces/aztec_rpc.ts | 12 +- .../types/src/logs/l2_block_l2_logs.test.ts | 2 +- .../types/src/tx_execution_request.ts | 4 +- yarn-project/world-state/README.md | 6 +- yarn-project/world-state/src/index.ts | 4 +- .../world-state/src/synchroniser/index.ts | 2 - .../{synchroniser => synchronizer}/config.ts | 6 +- .../world-state/src/synchronizer/index.ts | 2 + .../server_world_state_synchronizer.test.ts} | 48 +++--- .../server_world_state_synchronizer.ts} | 10 +- .../world_state_synchronizer.ts} | 20 +-- .../src/world-state-db/merkle_trees.ts | 58 ++++---- 124 files changed, 819 insertions(+), 819 deletions(-) delete mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr delete mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr delete mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr delete mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr create mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialization.nr create mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialization/bool_serialization.nr create mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialization/field_serialization.nr create mode 100644 yarn-project/aztec-nr/aztec/src/types/type_serialization/u32_serialization.nr delete mode 100644 yarn-project/aztec-rpc/src/synchroniser/index.ts create mode 100644 yarn-project/aztec-rpc/src/synchronizer/index.ts rename yarn-project/aztec-rpc/src/{synchroniser/synchroniser.test.ts => synchronizer/synchronizer.test.ts} (82%) rename yarn-project/aztec-rpc/src/{synchroniser/synchroniser.ts => synchronizer/synchronizer.ts} (94%) delete mode 100644 yarn-project/world-state/src/synchroniser/index.ts rename yarn-project/world-state/src/{synchroniser => synchronizer}/config.ts (91%) create mode 100644 yarn-project/world-state/src/synchronizer/index.ts rename yarn-project/world-state/src/{synchroniser/server_world_state_synchroniser.test.ts => synchronizer/server_world_state_synchronizer.test.ts} (91%) rename yarn-project/world-state/src/{synchroniser/server_world_state_synchroniser.ts => synchronizer/server_world_state_synchronizer.ts} (95%) rename yarn-project/world-state/src/{synchroniser/world_state_synchroniser.ts => synchronizer/world_state_synchronizer.ts} (70%) diff --git a/circuits/cpp/src/aztec3/circuits/apps/.test.cpp b/circuits/cpp/src/aztec3/circuits/apps/.test.cpp index d2bbc2cbd9db..9d841a0cebc5 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/.test.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/.test.cpp @@ -208,7 +208,7 @@ TEST_F(state_var_tests, circuit_utxo_of_default_private_note_fr) .creator_address = msg_sender, .memo = 1234 }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -270,7 +270,7 @@ TEST_F(state_var_tests, circuit_utxo_set_of_default_private_notes_fr) .memo = 1234, }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -318,7 +318,7 @@ TEST_F(state_var_tests, circuit_initialise_utxo_of_default_singleton_private_not my_utxo.initialise({ .value = 100, .owner = owner_of_initialised_note }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -367,7 +367,7 @@ TEST_F(state_var_tests, circuit_modify_utxo_of_default_singleton_private_note_fr .owner = msg_sender, }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. diff --git a/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp b/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp index ad1b597f4ba1..ab48743b1192 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp +++ b/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp @@ -67,7 +67,7 @@ template class FunctionExecutionContext { PrivateCircuitPublicInputs final_private_circuit_public_inputs{}; - bool is_finalised = false; + bool is_finalized = false; public: FunctionExecutionContext(Builder& builder, OracleWrapperInterface& oracle) @@ -101,8 +101,8 @@ template class FunctionExecutionContext { PrivateCircuitPublicInputs get_final_private_circuit_public_inputs() { // For safety, only return this if the circuit is complete. - if (!is_finalised) { - throw_or_abort("You need to call exec_ctx.finalise() in your circuit first."); + if (!is_finalized) { + throw_or_abort("You need to call exec_ctx.finalize() in your circuit first."); } return final_private_circuit_public_inputs; } @@ -287,7 +287,7 @@ template class FunctionExecutionContext { * TODO: Might need some refactoring. Roles between: Opcodes modifying exec_ctx members; and the exec_ctx directly * modifying its members, are somewhat blurred at the moment. */ - void finalise_utxos() + void finalize_utxos() { // Copy some vectors, as we can't control whether they'll be pushed-to further, when we call Note methods. auto new_nullifiers_copy = new_nullifiers; @@ -319,16 +319,16 @@ template class FunctionExecutionContext { std::copy(new_nonces.begin(), new_nonces.end(), std::back_inserter(new_nullifiers)); } - void finalise() + void finalize() { - finalise_utxos(); + finalize_utxos(); private_circuit_public_inputs.set_commitments(new_commitments); private_circuit_public_inputs.set_nullifiers(new_nullifiers); private_circuit_public_inputs.set_nullified_commitments(nullified_commitments); private_circuit_public_inputs.set_public(builder); final_private_circuit_public_inputs = private_circuit_public_inputs.remove_optionality().template to_native_type(); - is_finalised = true; + is_finalized = true; } }; diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp index 2aff1c41490f..5a9e39fe27f3 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp @@ -43,7 +43,7 @@ OptionalPrivateCircuitPublicInputs constructor(FunctionExecutionContext& exe auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ arg0, arg1, arg2 }); - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp index 59d2ccb50d63..61703be8a8ca 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp @@ -55,7 +55,7 @@ OptionalPrivateCircuitPublicInputs deposit(FunctionExecutionContext& exec_ct auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ amount, asset_id, memo }); - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp index 51e1a0be733c..241fa2f5de19 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp @@ -95,7 +95,7 @@ OptionalPrivateCircuitPublicInputs transfer(FunctionExecutionContext& exec_c /// TODO: merkle membership check // public_inputs.historic_private_data_tree_root - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp index fdba8ab35e1e..1e586bc242cd 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp @@ -83,7 +83,7 @@ OptionalPrivateCircuitPublicInputs withdraw(FunctionExecutionContext& exec_c auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ amount, asset_id, memo, l1_withdrawal_address, fee }); - exec_ctx.finalise(); + exec_ctx.finalize(); /// TODO: merkle membership check // public_inputs.historic_private_data_tree_root diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp index 4377da64a9b5..13507d6b83c3 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp @@ -80,7 +80,7 @@ void function_1_1(FunctionExecutionContext& exec_ctx, std::vector const& auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ a, b, c }); - exec_ctx.finalise(); + exec_ctx.finalize(); }; } // namespace aztec3::circuits::apps::test_apps::private_to_private_function_call \ No newline at end of file diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp index ac424411667e..ba5f5197e594 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp @@ -63,7 +63,7 @@ void function_2_1(FunctionExecutionContext& exec_ctx, std::vector const& public_inputs.return_values[0] = product; - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/docs/docs/concepts/foundation/communication/cross_chain_calls.md b/docs/docs/concepts/foundation/communication/cross_chain_calls.md index 4daf9672a056..86554a820901 100644 --- a/docs/docs/concepts/foundation/communication/cross_chain_calls.md +++ b/docs/docs/concepts/foundation/communication/cross_chain_calls.md @@ -77,7 +77,7 @@ The L2 -> L1 pending messages set only exist logically, as it is practically unn ### Rollup Contract -The rollup contract has a few very important responsibilities. The contract must keep track of the _L2 rollup state root_, perform _state transitions_ and ensure that the data is available for anyone else to synchronise to the current state. +The rollup contract has a few very important responsibilities. The contract must keep track of the _L2 rollup state root_, perform _state transitions_ and ensure that the data is available for anyone else to synchronize to the current state. To ensure that _state transitions_ are performed correctly, the contract will derive public inputs for the **rollup circuit** based on the input data, and then use a _verifier_ contract to validate that inputs correctly transition the current state to the next. All data needed for the public inputs to the circuit must be from the rollup block, ensuring that the block is available. For a valid proof, the _rollup state root_ is updated and it will emit an _event_ to make it easy for anyone to find the data by event spotting. diff --git a/docs/docs/dev_docs/cli/main.md b/docs/docs/dev_docs/cli/main.md index 3bcf02ead78e..363677b4c2e1 100644 --- a/docs/docs/dev_docs/cli/main.md +++ b/docs/docs/dev_docs/cli/main.md @@ -79,7 +79,7 @@ Let's double check that the accounts have been registered with the sandbox using #include_code get-accounts yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash -You will see a that a number of accounts exist that we did not create. The Sandbox initialises itself with 3 default accounts. Save one of the printed accounts (not the one that you generated above) in an environment variable. We will use it later. +You will see a that a number of accounts exist that we did not create. The Sandbox initializes itself with 3 default accounts. Save one of the printed accounts (not the one that you generated above) in an environment variable. We will use it later. ```bash export ADDRESS2= diff --git a/docs/docs/dev_docs/contracts/compiling.md b/docs/docs/dev_docs/contracts/compiling.md index e9c624954700..ac14588acfbd 100644 --- a/docs/docs/dev_docs/contracts/compiling.md +++ b/docs/docs/dev_docs/contracts/compiling.md @@ -102,25 +102,25 @@ impl PrivateTokenPrivateContextInterface { fn mint( self, context: &mut PrivateContext, amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; // 0x1dc9c3c0 is the function selector for `mint(field,field)` - context.call_private_function(self.address, 0x1dc9c3c0, serialised_args) + context.call_private_function(self.address, 0x1dc9c3c0, serialized_args) } fn transfer( self, context: &mut PrivateContext, amount: Field, sender: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 3]; - serialised_args[0] = amount; - serialised_args[1] = sender; - serialised_args[2] = recipient; + let mut serialized_args = [0; 3]; + serialized_args[0] = amount; + serialized_args[1] = sender; + serialized_args[2] = recipient; // 0xdcd4c318 is the function selector for `transfer(field,field,field)` - context.call_private_function(self.address, 0xdcd4c318, serialised_args) + context.call_private_function(self.address, 0xdcd4c318, serialized_args) } } ``` diff --git a/docs/docs/dev_docs/contracts/syntax/functions.md b/docs/docs/dev_docs/contracts/syntax/functions.md index 93e2f0a58872..da39abcdef82 100644 --- a/docs/docs/dev_docs/contracts/syntax/functions.md +++ b/docs/docs/dev_docs/contracts/syntax/functions.md @@ -38,7 +38,7 @@ While `staticcall` and `delegatecall` both have flags in the call context, they ## `constructor` - A special `constructor` function MUST be declared within a contract's scope. -- A constructor doesn't have a name, because its purpose is clear: to initialise contract state. +- A constructor doesn't have a name, because its purpose is clear: to initialize contract state. - In Aztec terminology, a constructor is always a '`private` function' (i.e. it cannot be a `public` function, in the current version of the sandbox it cannot call public functions either). - A constructor behaves almost identically to any other function. It's just important for Aztec to be able to identify this function as special: it may only be called once, and will not be deployed as part of the contract. diff --git a/docs/docs/dev_docs/contracts/syntax/state_variables.md b/docs/docs/dev_docs/contracts/syntax/state_variables.md index c9868cc47bfb..830d35388240 100644 --- a/docs/docs/dev_docs/contracts/syntax/state_variables.md +++ b/docs/docs/dev_docs/contracts/syntax/state_variables.md @@ -2,9 +2,9 @@ title: State Variables --- -State variables come in two flavours: [**public** state](#publicstatet-t_serialised_len) and [**private** state](#private-state-variables). +State variables come in two flavours: [**public** state](#publicstatet-t_serialized_len) and [**private** state](#private-state-variables). -## `PublicState` +## `PublicState` Public state is persistent state that is _publicly visible_ to anyone in the world. @@ -12,7 +12,7 @@ For developers coming from other blockchain ecosystems (such as Ethereum), this Aztec public state follows an account-based model. That is, each state occupies a leaf in an account-based merkle tree: the public state tree. See [here](/concepts/advanced/data_structures/trees#public-state-tree) for more of the technical details. -The `PublicState` struct serves as a wrapper around conventional Noir types `T`, allowing these types to be written to and read from the public state tree. +The `PublicState` struct serves as a wrapper around conventional Noir types `T`, allowing these types to be written to and read from the public state tree. ### `::new` @@ -22,13 +22,13 @@ In the following example, we define a public state with a boolean type: #include_code state_vars-PublicState /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -The BoolSerialisationMethods is part of the Aztec stdlib: +The BoolSerializationMethods is part of the Aztec stdlib: #include_code state_vars-PublicStateBoolImport /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -It contains methods that instruct its PublicState wrapper how to serialise and deserialise a boolean to and from a Field, which is the data type being saved in the public state tree. +It contains methods that instruct its PublicState wrapper how to serialize and deserialize a boolean to and from a Field, which is the data type being saved in the public state tree. -The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/types/type_serialisation) for the complete list. +The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/types/type_serialization) for the complete list. ### Custom types @@ -36,17 +36,17 @@ It's possible to create a public state for any types. Simply define methods that The methods should be implemented in a struct that conforms to the following interface: -#include_code TypeSerialisationInterface /yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr rust +#include_code TypeSerializationInterface /yarn-project/aztec-nr/aztec/src/types/type_serialization.nr rust For example, to create a public state for the following type: #include_code state_vars-CustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr rust -First, define how to serialise and deserialise the custom type: +First, define how to serialize and deserialize the custom type: #include_code state_vars-PublicStateCustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr rust -And then initialise the PublicState with it: +And then initialize the PublicState with it: #include_code state_vars-PublicStateCustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust @@ -66,7 +66,7 @@ Every public state can be read before its value is written. The default value is The currently-stored value of a private state variable can be overwritten with `.write()`. -Due to the way public states are [declared](#new), a public state knows how to serialise a given value and store it in the protocol's public state tree. +Due to the way public states are [declared](#new), a public state knows how to serialize a given value and store it in the protocol's public state tree. We can pass the associated type directly to the `write()` method: @@ -133,7 +133,7 @@ The interplay between a private state variable and its notes can be confusing. H ## `Singleton` -Singleton is a private state variable that is unique in a way. When a Singleton is initialised, a note is created to represent its value. And the way to update the value is to destroy the current note, and create a new one with the updated value. +Singleton is a private state variable that is unique in a way. When a Singleton is initialized, a note is created to represent its value. And the way to update the value is to destroy the current note, and create a new one with the updated value. ### `::new` @@ -141,15 +141,15 @@ Here we define a Singleton for storing a `CardNote`: #include_code state_vars-Singleton /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -### `.initialise` +### `.initialize` -The initial value of a Singleton is set via calling `initialise`: +The initial value of a Singleton is set via calling `initialize`: #include_code state_vars-SingletonInit /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr rust -When this function is called, a nullifier of the storage slot is created, preventing this Singleton from being initialised again. +When this function is called, a nullifier of the storage slot is created, preventing this Singleton from being initialized again. -Unlike public states, which have a default initial value of `0` (or many zeros, in the case of a struct, array or map), a private state (of type `Singleton`, `ImmutableSingleton` or `Set`) does not have a default initial value. The `initialise` method (or `insert`, in the case of a `Set`) must be called. +Unlike public states, which have a default initial value of `0` (or many zeros, in the case of a struct, array or map), a private state (of type `Singleton`, `ImmutableSingleton` or `Set`) does not have a default initial value. The `initialize` method (or `insert`, in the case of a `Set`) must be called. ### `.replace` @@ -179,9 +179,9 @@ In the following example, we define an ImmutableSingleton that utilises the `Rul #include_code state_vars-ImmutableSingleton /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -### `.initialise` +### `.initialize` -Set the initial value of an ImmutableSingleton by calling the `initialise` method: +Set the initial value of an ImmutableSingleton by calling the `initialize` method: #include_code state_vars-ImmutableSingletonInit /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr rust @@ -195,7 +195,7 @@ Use this method to retrieve the value of an initialized ImmutableSingleton: Unlike a [`singleton`](#get_note-1), the `get_note` function for an ImmutableSingleton doesn't destroy the current note in the background. This means that multiple accounts can concurrently call this function to read the value. -This function will throw if the ImmutableSingleton hasn't been initialised. +This function will throw if the ImmutableSingleton hasn't been initialized. ## `Set` @@ -269,11 +269,11 @@ Several methods are available on `NoteGetterOptions` to construct the options in #### `fn new() -> NoteGetterOptions` -This function initialises a `NoteGetterOptions` that simply returns the maximum number of notes allowed in a call. +This function initializes a `NoteGetterOptions` that simply returns the maximum number of notes allowed in a call. #### `fn with_filter(filter, filter_args) -> NoteGetterOptions` -This function initialises a `NoteGetterOptions` with a [`filter`](#filter-fn-optionnote-max_read_requests_per_call-filter_args---optionnote-max_read_requests_per_call) and [`filter_args`](#filter_args-filter_args). +This function initializes a `NoteGetterOptions` with a [`filter`](#filter-fn-optionnote-max_read_requests_per_call-filter_args---optionnote-max_read_requests_per_call) and [`filter_args`](#filter_args-filter_args). #### `.select` @@ -347,7 +347,7 @@ The `NoteViewerOptions` is essentially similar to the [`NoteGetterOptions`](#not ## `Map` -`Map` is a state variable that maps a `Field` to another state variable, which can be [`PublicState`](#publicstatet-t_serialised_len), all the [private state variables](#private-state-variables), and even another Map. +`Map` is a state variable that maps a `Field` to another state variable, which can be [`PublicState`](#publicstatet-t_serialized_len), all the [private state variables](#private-state-variables), and even another Map. > `Map` can map from `Field` or any native Noir type which is convertible to `Field`. diff --git a/docs/docs/dev_docs/sandbox_errors/main.md b/docs/docs/dev_docs/sandbox_errors/main.md index c13345e00ddc..1c6561d02ca7 100644 --- a/docs/docs/dev_docs/sandbox_errors/main.md +++ b/docs/docs/dev_docs/sandbox_errors/main.md @@ -31,7 +31,7 @@ You cannot execute a public Aztec.nr function in the private kernel #### 2011 - PRIVATE_KERNEL__UNSUPPORTED_OP You are trying to do something that is currently unsupported in the private kernel. If this is a blocker feel free to open up an issue on our monorepo [aztec3-packages](https://github.com/AztecProtocol/aztec3-packages/tree/master) or reach out to us on discord -Note that certain operations are unsupported on certain versions of the private kernel. Eg static calls are allowed for all but the initial iteration of the private kernel (which initialises the kernel for subsequent function calls). +Note that certain operations are unsupported on certain versions of the private kernel. Eg static calls are allowed for all but the initial iteration of the private kernel (which initializes the kernel for subsequent function calls). #### 2012 - PRIVATE_KERNEL__CONTRACT_ADDRESS_MISMATCH For the initial iteration of the private kernel, only the expected Aztec.nr contract should be the entrypoint. Static and delegate calls are not allowed in the initial iteration. diff --git a/docs/docs/dev_docs/testing/cheat_codes.md b/docs/docs/dev_docs/testing/cheat_codes.md index 4e2ca1ac0997..3fd12b183256 100644 --- a/docs/docs/dev_docs/testing/cheat_codes.md +++ b/docs/docs/dev_docs/testing/cheat_codes.md @@ -458,13 +458,13 @@ The baseSlot is specified in the Aztec.nr contract. ```rust struct Storage { - balances: Map>, + balances: Map>, } impl Storage { fn init() -> Self { Storage { - balances: Map::new(1, |slot| PublicState::new(slot, FieldSerialisationMethods)), + balances: Map::new(1, |slot| PublicState::new(slot, FieldSerializationMethods)), } } } @@ -496,13 +496,13 @@ Note: One Field element occupies a storage slot. Hence, structs with multiple fi ```rust struct Storage { - balances: Map>, + balances: Map>, } impl Storage { fn init() -> Self { Storage { - balances: Map::new(1, |slot| PublicState::new(slot, FieldSerialisationMethods)), + balances: Map::new(1, |slot| PublicState::new(slot, FieldSerializationMethods)), } } } diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md index 033f155ccfd2..34ce039738de 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md @@ -6,9 +6,9 @@ To add contracts to your application, we'll start by creating a new `nargo` proj Follow the instructions [here](../../contracts/setup.md) to install `nargo` if you haven't done so already. ::: -## Initialise nargo project +## initialize nargo project -Create a new `contracts` folder, and from there, initialise a new project called `token`: +Create a new `contracts` folder, and from there, initialize a new project called `token`: ```sh mkdir contracts && cd contracts diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md index 545cc8271003..c33fc40d16c3 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md @@ -12,7 +12,7 @@ Let's start by showing our user's private balance for the token across their acc Note that this function will only return a valid response for accounts registered in the RPC Server, since it requires access to the [user's private state](../../wallets/main.md#private-state). In other words, you cannot query the private balance of another user for the token contract. ::: -To do this, let's first initialise a new `Contract` instance using `aztec.js` that represents our deployed token contracts. Create a new `src/contracts.mjs` file with the imports for our artifacts and other dependencies: +To do this, let's first initialize a new `Contract` instance using `aztec.js` that represents our deployed token contracts. Create a new `src/contracts.mjs` file with the imports for our artifacts and other dependencies: ```js // src/contracts.mjs @@ -45,7 +45,7 @@ Balance of 0x0e1f60e8566e2c6d32378bdcadb7c63696e853281be798c107266b8c3a88ea9b: 0 Now that we can see the balance for each user, let's transfer tokens from one account to another. To do this, we will first need access to a `Wallet` object. This wraps access to an RPC Server and also provides an interface to craft and sign transactions on behalf of one of the user accounts. -We can initialise a wallet using one of the `getAccount` methods from `aztec.js`, along with the corresponding signing and encryption keys: +We can initialize a wallet using one of the `getAccount` methods from `aztec.js`, along with the corresponding signing and encryption keys: ```js import { getSchnorrAccount } from "@aztec/aztec.js"; @@ -56,17 +56,17 @@ const wallet = await getSchnorrAccount( ).getWallet(); ``` -For ease of use, `aztec.js` also ships with a helper `getSandboxAccountsWallets` method that returns a wallet for each of the pre-initialised accounts in the Sandbox, so you can send transactions as any of them. +For ease of use, `aztec.js` also ships with a helper `getSandboxAccountsWallets` method that returns a wallet for each of the pre-initialized accounts in the Sandbox, so you can send transactions as any of them. ```js import { getSandboxAccountsWallets } from '@aztec/aztec.js'; ``` -We'll use one of these wallets to initialise the `Contract` instance that represents our private token contract, so every transaction sent through it will be sent through that wallet. +We'll use one of these wallets to initialize the `Contract` instance that represents our private token contract, so every transaction sent through it will be sent through that wallet. #include_code transferPrivateFunds yarn-project/end-to-end/src/sample-dapp/index.mjs javascript -Let's go step-by-step on this snippet. We first get wallets for two of the Sandbox accounts, and name them `owner` and `recipient`. Then, we initialise the private token `Contract` instance using the `owner` wallet, meaning that any transactions sent through it will have the `owner` as sender. +Let's go step-by-step on this snippet. We first get wallets for two of the Sandbox accounts, and name them `owner` and `recipient`. Then, we initialize the private token `Contract` instance using the `owner` wallet, meaning that any transactions sent through it will have the `owner` as sender. Next, we send a transfer transaction, moving 1 unit of balance to the `recipient` account address. This has no immediate effect, since the transaction first needs to be simulated locally and then submitted and mined. Only once this has finished we can query the balances again and see the effect of our transaction. We are using a `showPrivateBalances` helper function here which has the code we wrote in the section above. diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md index 23767890cb91..407295dca707 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md @@ -2,7 +2,7 @@ As an app developer, the [Aztec RPC Server](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec-rpc) interface provides you with access to the user's accounts and their private state, as well as a connection to the network for accessing public global state. -During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../getting_started/sandbox.md), which runs a local RPC Server and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialised accounts that you can use from your app. +During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../getting_started/sandbox.md), which runs a local RPC Server and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialized accounts that you can use from your app. In this section, we'll connect to the Sandbox from our project. @@ -26,7 +26,7 @@ Should the above fail due to a connection error, make sure the Sandbox is runnin ## Load user accounts -With our connection to the RPC server, let's try loading the accounts that are pre-initialised in the Sandbox: +With our connection to the RPC server, let's try loading the accounts that are pre-initialized in the Sandbox: #include_code showAccounts yarn-project/end-to-end/src/sample-dapp/index.mjs javascript diff --git a/docs/docs/dev_docs/tutorials/writing_token_contract.md b/docs/docs/dev_docs/tutorials/writing_token_contract.md index 018592b978fe..44acee30adbb 100644 --- a/docs/docs/dev_docs/tutorials/writing_token_contract.md +++ b/docs/docs/dev_docs/tutorials/writing_token_contract.md @@ -256,7 +256,7 @@ Below the dependencies, paste the following Storage struct: Reading through the storage variables: -- `admin` a single Field value stored in public state. `FIELD_SERIALISED_LEN` indicates the length of the variable, which is 1 in this case because it's a single Field element. A `Field` is basically an unsigned integer with a maximum value determined by the underlying cryptographic curve. +- `admin` a single Field value stored in public state. `FIELD_SERIALIZED_LEN` indicates the length of the variable, which is 1 in this case because it's a single Field element. A `Field` is basically an unsigned integer with a maximum value determined by the underlying cryptographic curve. - `minters` is a mapping of Fields in public state. This will store whether an account is an approved minter on the contract. - `balances` is a mapping of private balances. Private balances are stored in a `Set` of `ValueNote`s. The balance is the sum of all of an account's `ValueNote`s. - `total_supply` is a Field value stored in public state and represents the total number of tokens minted. @@ -269,7 +269,7 @@ You can read more about it [here](../contracts/syntax/storage.md). Once we have Storage defined, we need to specify how to initialize it. The `init` method creates and initializes an instance of `Storage`. We define an initialization method for each of the storage variables defined above. Storage initialization is generic and can largely be reused for similar types, across different contracts, but it is important to note that each storage variable specifies it's storage slot, starting at 1. -Also, the public storage variables define the type that they store by passing the methods by which they are serialized. Because all `PublicState` in this contract is storing Field elements, each storage variable takes `FieldSerialisationMethods`. +Also, the public storage variables define the type that they store by passing the methods by which they are serialized. Because all `PublicState` in this contract is storing Field elements, each storage variable takes `FieldSerializationMethods`. #include_code storage_init /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust diff --git a/docs/internal_notes/dev_docs/sandbox/components.md b/docs/internal_notes/dev_docs/sandbox/components.md index cb07a4b6139b..0db084b65082 100644 --- a/docs/internal_notes/dev_docs/sandbox/components.md +++ b/docs/internal_notes/dev_docs/sandbox/components.md @@ -223,7 +223,7 @@ Implementation notes for this milestone: Responsibilities: -- Wins a period of time to become the sequencer (depending on finalised protocol). +- Wins a period of time to become the sequencer (depending on finalized protocol). - Chooses a set of txs from the tx pool to be in the rollup. - Simulate the rollup of txs. - Adds proof requests to the request pool (not for this milestone). diff --git a/yarn-project/acir-simulator/src/client/private_execution.test.ts b/yarn-project/acir-simulator/src/client/private_execution.test.ts index ad1551990059..59c3993460dd 100644 --- a/yarn-project/acir-simulator/src/client/private_execution.test.ts +++ b/yarn-project/acir-simulator/src/client/private_execution.test.ts @@ -644,8 +644,8 @@ describe('Private Execution test suite', () => { const deepStruct = { aField: 1, aBool: true, aNote: dummyNote, manyNotes: [dummyNote, dummyNote, dummyNote] }; args = [1, true, 1, [1, 2], dummyNote, deepStruct]; testCodeGenAbi = TestContractAbi.functions.find(f => f.name === 'testCodeGen')!; - const serialisedArgs = encodeArguments(testCodeGenAbi, args); - argsHash = await computeVarArgsHash(await CircuitsWasm.get(), serialisedArgs); + const serializedArgs = encodeArguments(testCodeGenAbi, args); + argsHash = await computeVarArgsHash(await CircuitsWasm.get(), serializedArgs); }); it('test function should be directly callable', async () => { diff --git a/yarn-project/aztec-node/src/aztec-node/server.ts b/yarn-project/aztec-node/src/aztec-node/server.ts index a2b3720b0a35..4c07e444bee9 100644 --- a/yarn-project/aztec-node/src/aztec-node/server.ts +++ b/yarn-project/aztec-node/src/aztec-node/server.ts @@ -38,9 +38,9 @@ import { } from '@aztec/types'; import { MerkleTrees, - ServerWorldStateSynchroniser, + ServerWorldStateSynchronizer, WorldStateConfig, - WorldStateSynchroniser, + WorldStateSynchronizer, computePublicDataTreeLeafIndex, getConfigEnvVars as getWorldStateConfig, } from '@aztec/world-state'; @@ -63,7 +63,7 @@ export class AztecNodeService implements AztecNode { protected unencryptedLogsSource: L2LogsSource, protected contractDataSource: ContractDataSource, protected l1ToL2MessageSource: L1ToL2MessageSource, - protected worldStateSynchroniser: WorldStateSynchroniser, + protected worldStateSynchronizer: WorldStateSynchronizer, protected sequencer: SequencerClient, protected chainId: number, protected version: number, @@ -73,7 +73,7 @@ export class AztecNodeService implements AztecNode { ) {} /** - * Initialises the Aztec Node, wait for component to sync. + * initializes the Aztec Node, wait for component to sync. * @param config - The configuration to be used by the aztec node. * @returns - A fully synced Aztec Node for use in development/testing. */ @@ -92,16 +92,16 @@ export class AztecNodeService implements AztecNode { const merkleTreesDb = levelup(createMemDown()); const merkleTrees = await MerkleTrees.new(merkleTreesDb, await CircuitsWasm.get()); const worldStateConfig: WorldStateConfig = getWorldStateConfig(); - const worldStateSynchroniser = new ServerWorldStateSynchroniser(merkleTrees, archiver, worldStateConfig); + const worldStateSynchronizer = new ServerWorldStateSynchronizer(merkleTrees, archiver, worldStateConfig); // start both and wait for them to sync from the block source - await Promise.all([p2pClient.start(), worldStateSynchroniser.start()]); + await Promise.all([p2pClient.start(), worldStateSynchronizer.start()]); // now create the sequencer const sequencer = await SequencerClient.new( config, p2pClient, - worldStateSynchroniser, + worldStateSynchronizer, archiver, archiver, archiver, @@ -113,7 +113,7 @@ export class AztecNodeService implements AztecNode { archiver, archiver, archiver, - worldStateSynchroniser, + worldStateSynchronizer, sequencer, config.chainId, config.version, @@ -235,7 +235,7 @@ export class AztecNodeService implements AztecNode { public async stop() { await this.sequencer.stop(); await this.p2pClient.stop(); - await this.worldStateSynchroniser.stop(); + await this.worldStateSynchronizer.stop(); await this.blockSource.stop(); this.log.info(`Stopped`); } @@ -424,7 +424,7 @@ export class AztecNodeService implements AztecNode { } catch (err) { this.log.error(`Error getting world state: ${err}`); } - return this.worldStateSynchroniser.getCommitted(); + return this.worldStateSynchronizer.getCommitted(); } /** @@ -433,6 +433,6 @@ export class AztecNodeService implements AztecNode { */ async #syncWorldState() { const blockSourceHeight = await this.blockSource.getBlockNumber(); - await this.worldStateSynchroniser.syncImmediate(blockSourceHeight); + await this.worldStateSynchronizer.syncImmediate(blockSourceHeight); } } diff --git a/yarn-project/aztec-nr/aztec/src/account.nr b/yarn-project/aztec-nr/aztec/src/account.nr index c0bfc739e35c..3437dbd85198 100644 --- a/yarn-project/aztec-nr/aztec/src/account.nr +++ b/yarn-project/aztec-nr/aztec/src/account.nr @@ -2,13 +2,13 @@ use crate::entrypoint::EntrypointPayload; use crate::context::{PrivateContext, PublicContext, Context}; use crate::oracle::compute_selector::compute_selector; use crate::state_vars::{map::Map, public_state::PublicState}; -use crate::types::type_serialisation::bool_serialisation::{BoolSerialisationMethods,BOOL_SERIALISED_LEN}; +use crate::types::type_serialization::bool_serialization::{BoolSerializationMethods,BOOL_SERIALIZED_LEN}; use crate::auth::IS_VALID_SELECTOR; struct AccountActions { context: Context, is_valid_impl: fn(&mut PrivateContext, Field) -> bool, - approved_action: Map>, + approved_action: Map>, } impl AccountActions { @@ -20,7 +20,7 @@ impl AccountActions { context, approved_action_storage_slot, |context, slot| { - PublicState::new(context, slot, BoolSerialisationMethods) + PublicState::new(context, slot, BoolSerializationMethods) }, ), } diff --git a/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr b/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr index 43ccdfad5562..5f4c6b2e8f91 100644 --- a/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr +++ b/yarn-project/aztec-nr/aztec/src/note/lifecycle.nr @@ -25,8 +25,8 @@ fn create_note( set_header(note, header); let inner_note_hash = compute_inner_note_hash(note_interface, *note); - let serialise = note_interface.serialise; - let preimage = serialise(*note); + let serialize = note_interface.serialize; + let preimage = serialize(*note); assert(notify_created_note(storage_slot, preimage, inner_note_hash) == 0); context.push_new_note_hash(inner_note_hash); diff --git a/yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr b/yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr index 092249a218a0..f927cebd85a2 100644 --- a/yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr +++ b/yarn-project/aztec-nr/aztec/src/note/note_getter_options.nr @@ -60,7 +60,7 @@ struct NoteGetterOptions { // `selects` to specify fields, `sorts` to establish sorting criteria, `offset` to skip items, and `limit` to cap the result size. // And finally, a custom filter to refine the outcome further. impl NoteGetterOptions { - // This function initialises a NoteGetterOptions that simply returns the maximum number of notes allowed in a call. + // This function initializes a NoteGetterOptions that simply returns the maximum number of notes allowed in a call. fn new() -> NoteGetterOptions { NoteGetterOptions { selects: BoundedVec::new(Option::none()), @@ -72,7 +72,7 @@ impl NoteGetterOptions { } } - // This function initialises a NoteGetterOptions with a filter, which takes the notes returned from the database and filter_args as its parameters. + // This function initializes a NoteGetterOptions with a filter, which takes the notes returned from the database and filter_args as its parameters. // `filter_args` allows you to provide additional data or context to the custom filter. fn with_filter( filter: fn ([Option; MAX_READ_REQUESTS_PER_CALL], FILTER_ARGS) -> [Option; MAX_READ_REQUESTS_PER_CALL], diff --git a/yarn-project/aztec-nr/aztec/src/note/note_interface.nr b/yarn-project/aztec-nr/aztec/src/note/note_interface.nr index 84d171fd5bae..a98d3f499546 100644 --- a/yarn-project/aztec-nr/aztec/src/note/note_interface.nr +++ b/yarn-project/aztec-nr/aztec/src/note/note_interface.nr @@ -2,9 +2,9 @@ use crate::note::note_header::NoteHeader; // docs:start:NoteInterface struct NoteInterface { - deserialise: fn ([Field; N]) -> Note, + deserialize: fn ([Field; N]) -> Note, - serialise: fn (Note) -> [Field; N], + serialize: fn (Note) -> [Field; N], compute_note_hash: fn (Note) -> Field, diff --git a/yarn-project/aztec-nr/aztec/src/note/utils.nr b/yarn-project/aztec-nr/aztec/src/note/utils.nr index d8a459286f2f..2c9e49efa320 100644 --- a/yarn-project/aztec-nr/aztec/src/note/utils.nr +++ b/yarn-project/aztec-nr/aztec/src/note/utils.nr @@ -68,9 +68,9 @@ fn compute_note_hash_and_nullifier( note_header: NoteHeader, preimage: [Field; S], ) -> [Field; 4] { - let deserialise = note_interface.deserialise; + let deserialize = note_interface.deserialize; let set_header = note_interface.set_header; - let mut note = deserialise(arr_copy_slice(preimage, [0; N], 0)); + let mut note = deserialize(arr_copy_slice(preimage, [0; N], 0)); set_header(&mut note, note_header); let compute_note_hash = note_interface.compute_note_hash; diff --git a/yarn-project/aztec-nr/aztec/src/oracle/notes.nr b/yarn-project/aztec-nr/aztec/src/oracle/notes.nr index 356cf5de4aad..efae0ed9e2f0 100644 --- a/yarn-project/aztec-nr/aztec/src/oracle/notes.nr +++ b/yarn-project/aztec-nr/aztec/src/oracle/notes.nr @@ -85,13 +85,13 @@ unconstrained fn get_notes( sort_order: [u2; M], limit: u32, offset: u32, - mut placeholder_opt_notes: [Option; S], // TODO: Remove it and use `limit` to initialise the note array. - placeholder_fields: [Field; NS], // TODO: Remove it and use `limit` to initialise the note array. + mut placeholder_opt_notes: [Option; S], // TODO: Remove it and use `limit` to initialize the note array. + placeholder_fields: [Field; NS], // TODO: Remove it and use `limit` to initialize the note array. ) -> [Option; S] { let fields = get_notes_oracle_wrapper(storage_slot, num_selects, select_by, select_values, sort_by, sort_order, limit, offset, placeholder_fields); let num_notes = fields[0] as u32; let contract_address = fields[1]; - let deserialise = note_interface.deserialise; + let deserialize = note_interface.deserialize; let set_header = note_interface.set_header; for i in 0..placeholder_opt_notes.len() { if i as u32 < num_notes { @@ -104,7 +104,7 @@ unconstrained fn get_notes( let is_some = fields[read_offset + 1] as bool; if is_some { let preimage = arr_copy_slice(fields, [0; N], read_offset + 2); - let mut note = deserialise(preimage); + let mut note = deserialize(preimage); set_header(&mut note, header); placeholder_opt_notes[i] = Option::some(note); } diff --git a/yarn-project/aztec-nr/aztec/src/oracle/storage.nr b/yarn-project/aztec-nr/aztec/src/oracle/storage.nr index 78c3869f2b1b..7b367360cd42 100644 --- a/yarn-project/aztec-nr/aztec/src/oracle/storage.nr +++ b/yarn-project/aztec-nr/aztec/src/oracle/storage.nr @@ -11,10 +11,10 @@ unconstrained fn storage_read_oracle_wrapper(_storage_slot: Field)-> [Field; fn storage_read( storage_slot: Field, - deserialise: fn ([Field; N]) -> T, + deserialize: fn ([Field; N]) -> T, ) -> T { let fields = storage_read_oracle_wrapper(storage_slot); - deserialise(fields) + deserialize(fields) } #[oracle(storageWrite)] diff --git a/yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr b/yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr index f419e7a0c32c..5581c60868e9 100644 --- a/yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr +++ b/yarn-project/aztec-nr/aztec/src/state_vars/immutable_singleton.nr @@ -30,12 +30,12 @@ impl ImmutableSingleton { } } - unconstrained fn is_initialised(self) -> bool { + unconstrained fn is_initialized(self) -> bool { let nullifier = self.compute_initialisation_nullifier(); oracle::notes::is_nullifier_emitted(nullifier) } - fn initialise(self, note: &mut Note) { + fn initialize(self, note: &mut Note) { // Nullify the storage slot. let nullifier = self.compute_initialisation_nullifier(); self.context.private diff --git a/yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr b/yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr index 5216ae906f30..41dfdaf261e8 100644 --- a/yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr +++ b/yarn-project/aztec-nr/aztec/src/state_vars/public_state.nr @@ -1,35 +1,35 @@ use crate::context::{Context}; use crate::oracle::storage::storage_read; use crate::oracle::storage::storage_write; -use crate::types::type_serialisation::TypeSerialisationInterface; +use crate::types::type_serialization::TypeSerializationInterface; use dep::std::option::Option; -struct PublicState { +struct PublicState { storage_slot: Field, - serialisation_methods: TypeSerialisationInterface, + serialization_methods: TypeSerializationInterface, } -impl PublicState { +impl PublicState { fn new( // Note: Passing the contexts to new(...) just to have an interface compatible with a Map. _: Context, storage_slot: Field, - serialisation_methods: TypeSerialisationInterface, + serialization_methods: TypeSerializationInterface, ) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); PublicState { storage_slot, - serialisation_methods, + serialization_methods, } } fn read(self) -> T { - storage_read(self.storage_slot, self.serialisation_methods.deserialise) + storage_read(self.storage_slot, self.serialization_methods.deserialize) } fn write(self, value: T) { - let serialise = self.serialisation_methods.serialise; - let fields = serialise(value); + let serialize = self.serialization_methods.serialize; + let fields = serialize(value); storage_write(self.storage_slot, fields); } } diff --git a/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr b/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr index 6b7afcba2ce7..dd12110fab96 100644 --- a/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr +++ b/yarn-project/aztec-nr/aztec/src/state_vars/singleton.nr @@ -30,12 +30,12 @@ impl Singleton { } } - unconstrained fn is_initialised(self) -> bool { + unconstrained fn is_initialized(self) -> bool { let nullifier = self.compute_initialisation_nullifier(); oracle::notes::is_nullifier_emitted(nullifier) } - fn initialise(self, note: &mut Note) { + fn initialize(self, note: &mut Note) { let context = self.context.unwrap(); // Nullify the storage slot. let nullifier = self.compute_initialisation_nullifier(); diff --git a/yarn-project/aztec-nr/aztec/src/types.nr b/yarn-project/aztec-nr/aztec/src/types.nr index 802ce648c491..a93267973be8 100644 --- a/yarn-project/aztec-nr/aztec/src/types.nr +++ b/yarn-project/aztec-nr/aztec/src/types.nr @@ -1,4 +1,4 @@ mod address; mod point; mod vec; // This can/should be moved out into an official noir library -mod type_serialisation; \ No newline at end of file +mod type_serialization; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/point.nr b/yarn-project/aztec-nr/aztec/src/types/point.nr index 47ea73ffcde4..6b3913548747 100644 --- a/yarn-project/aztec-nr/aztec/src/types/point.nr +++ b/yarn-project/aztec-nr/aztec/src/types/point.nr @@ -1,4 +1,4 @@ -use crate::types::type_serialisation::TypeSerialisationInterface; +use crate::types::type_serialization::TypeSerializationInterface; struct Point { x: Field, @@ -11,20 +11,20 @@ impl Point { } } -global POINT_SERIALISED_LEN: Field = 2; +global POINT_SERIALIZED_LEN: Field = 2; -fn deserialisePoint(fields: [Field; POINT_SERIALISED_LEN]) -> Point { +fn deserializePoint(fields: [Field; POINT_SERIALIZED_LEN]) -> Point { Point { x: fields[0], y: fields[1], } } -fn serialisePoint(point: Point) -> [Field; POINT_SERIALISED_LEN] { +fn serializePoint(point: Point) -> [Field; POINT_SERIALIZED_LEN] { [point.x, point.y] } -global PointSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialisePoint, - serialise: serialisePoint, +global PointSerializationMethods = TypeSerializationInterface { + deserialize: deserializePoint, + serialize: serializePoint, }; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr deleted file mode 100644 index e1ccdde98f9b..000000000000 --- a/yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr +++ /dev/null @@ -1,13 +0,0 @@ -mod bool_serialisation; -mod field_serialisation; -mod u32_serialisation; - -/** - * Before Noir supports traits, a way of specifying the serialisation and deserialisation methods for a type. - */ -// docs:start:TypeSerialisationInterface -struct TypeSerialisationInterface { - deserialise: fn ([Field; N]) -> T, - serialise: fn (T) -> [Field; N], -} -// docs:end:TypeSerialisationInterface \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr deleted file mode 100644 index 734f725f35b7..000000000000 --- a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/bool_serialisation.nr +++ /dev/null @@ -1,16 +0,0 @@ -use crate::types::type_serialisation::TypeSerialisationInterface; - -global BOOL_SERIALISED_LEN: Field = 1; - -fn deserialiseBool(fields: [Field; BOOL_SERIALISED_LEN]) -> bool { - fields[0] as bool -} - -fn serialiseBool(value: bool) -> [Field; BOOL_SERIALISED_LEN] { - [value as Field] -} - -global BoolSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseBool, - serialise: serialiseBool, -}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr deleted file mode 100644 index 5fcaf3705236..000000000000 --- a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/field_serialisation.nr +++ /dev/null @@ -1,16 +0,0 @@ -use crate::types::type_serialisation::TypeSerialisationInterface; - -global FIELD_SERIALISED_LEN: Field = 1; - -fn deserialiseField(fields: [Field; FIELD_SERIALISED_LEN]) -> Field { - fields[0] -} - -fn serialiseField(value: Field) -> [Field; FIELD_SERIALISED_LEN] { - [value] -} - -global FieldSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseField, - serialise: serialiseField, -}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr deleted file mode 100644 index dd00ebfedfd6..000000000000 --- a/yarn-project/aztec-nr/aztec/src/types/type_serialisation/u32_serialisation.nr +++ /dev/null @@ -1,16 +0,0 @@ -use crate::types::type_serialisation::TypeSerialisationInterface; - -global U32_SERIALISED_LEN: Field = 1; - -fn deserialiseU32(fields: [Field; U32_SERIALISED_LEN]) -> u32 { - fields[0] as u32 -} - -fn serialiseU32(value: u32) -> [Field; U32_SERIALISED_LEN] { - [value as Field] -} - -global U32SerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseU32, - serialise: serialiseU32, -}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialization.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialization.nr new file mode 100644 index 000000000000..b45dcd7c8551 --- /dev/null +++ b/yarn-project/aztec-nr/aztec/src/types/type_serialization.nr @@ -0,0 +1,13 @@ +mod bool_serialization; +mod field_serialization; +mod u32_serialization; + +/** + * Before Noir supports traits, a way of specifying the serialization and deserialization methods for a type. + */ +// docs:start:TypeSerializationInterface +struct TypeSerializationInterface { + deserialize: fn ([Field; N]) -> T, + serialize: fn (T) -> [Field; N], +} +// docs:end:TypeSerializationInterface \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialization/bool_serialization.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialization/bool_serialization.nr new file mode 100644 index 000000000000..ac9829ecfb0a --- /dev/null +++ b/yarn-project/aztec-nr/aztec/src/types/type_serialization/bool_serialization.nr @@ -0,0 +1,16 @@ +use crate::types::type_serialization::TypeSerializationInterface; + +global BOOL_SERIALIZED_LEN: Field = 1; + +fn deserializeBool(fields: [Field; BOOL_SERIALIZED_LEN]) -> bool { + fields[0] as bool +} + +fn serializeBool(value: bool) -> [Field; BOOL_SERIALIZED_LEN] { + [value as Field] +} + +global BoolSerializationMethods = TypeSerializationInterface { + deserialize: deserializeBool, + serialize: serializeBool, +}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialization/field_serialization.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialization/field_serialization.nr new file mode 100644 index 000000000000..4fd3ee5d3506 --- /dev/null +++ b/yarn-project/aztec-nr/aztec/src/types/type_serialization/field_serialization.nr @@ -0,0 +1,16 @@ +use crate::types::type_serialization::TypeSerializationInterface; + +global FIELD_SERIALIZED_LEN: Field = 1; + +fn deserializeField(fields: [Field; FIELD_SERIALIZED_LEN]) -> Field { + fields[0] +} + +fn serializeField(value: Field) -> [Field; FIELD_SERIALIZED_LEN] { + [value] +} + +global FieldSerializationMethods = TypeSerializationInterface { + deserialize: deserializeField, + serialize: serializeField, +}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/type_serialization/u32_serialization.nr b/yarn-project/aztec-nr/aztec/src/types/type_serialization/u32_serialization.nr new file mode 100644 index 000000000000..e04cf948a53c --- /dev/null +++ b/yarn-project/aztec-nr/aztec/src/types/type_serialization/u32_serialization.nr @@ -0,0 +1,16 @@ +use crate::types::type_serialization::TypeSerializationInterface; + +global U32_SERIALIZED_LEN: Field = 1; + +fn deserializeU32(fields: [Field; U32_SERIALIZED_LEN]) -> u32 { + fields[0] as u32 +} + +fn serializeU32(value: u32) -> [Field; U32_SERIALIZED_LEN] { + [value as Field] +} + +global U32SerializationMethods = TypeSerializationInterface { + deserialize: deserializeU32, + serialize: serializeU32, +}; \ No newline at end of file diff --git a/yarn-project/aztec-nr/aztec/src/types/vec.nr b/yarn-project/aztec-nr/aztec/src/types/vec.nr index 9442f9774398..38fafa05d84d 100644 --- a/yarn-project/aztec-nr/aztec/src/types/vec.nr +++ b/yarn-project/aztec-nr/aztec/src/types/vec.nr @@ -92,7 +92,7 @@ fn test_vec_get_not_declared() { } #[test(should_fail)] -fn test_vec_get_uninitialised() { +fn test_vec_get_uninitialized() { let mut vec: BoundedVec = BoundedVec::new(0); let _x = vec.get(0); } diff --git a/yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr b/yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr index 62f6e85d6e0f..005c8990f6ff 100644 --- a/yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr +++ b/yarn-project/aztec-nr/easy-private-state/src/easy_private_state.nr @@ -52,7 +52,7 @@ impl EasyPrivateUint { (*context).this_address(), self.set.storage_slot, owner_key, - addend_note.serialise(), + addend_note.serialize(), ); } @@ -87,7 +87,7 @@ impl EasyPrivateUint { // Emit the newly created encrypted note preimages via oracle calls. let mut encrypted_data = [0; VALUE_NOTE_LEN]; if result_value != 0 { - encrypted_data = result_note.serialise(); + encrypted_data = result_note.serialize(); }; let owner_key = get_public_key(owner); diff --git a/yarn-project/aztec-nr/value-note/src/utils.nr b/yarn-project/aztec-nr/value-note/src/utils.nr index 4b7fcebd127f..56204cdd97ac 100644 --- a/yarn-project/aztec-nr/value-note/src/utils.nr +++ b/yarn-project/aztec-nr/value-note/src/utils.nr @@ -98,7 +98,7 @@ fn create_note( let application_contract_address = (*context).this_address(); let note_storage_slot = balance.storage_slot; let encryption_pub_key = get_public_key(owner); - let encrypted_data = (*note).serialise(); + let encrypted_data = (*note).serialize(); emit_encrypted_log( context, diff --git a/yarn-project/aztec-nr/value-note/src/value_note.nr b/yarn-project/aztec-nr/value-note/src/value_note.nr index 2f9ed483068b..7b7855e37f39 100644 --- a/yarn-project/aztec-nr/value-note/src/value_note.nr +++ b/yarn-project/aztec-nr/value-note/src/value_note.nr @@ -31,11 +31,11 @@ impl ValueNote { } } - fn serialise(self) -> [Field; VALUE_NOTE_LEN] { + fn serialize(self) -> [Field; VALUE_NOTE_LEN] { [self.value, self.owner, self.randomness] } - fn deserialise(preimage: [Field; VALUE_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; VALUE_NOTE_LEN]) -> Self { ValueNote { value: preimage[0], owner: preimage[1], @@ -73,12 +73,12 @@ impl ValueNote { } } -fn deserialise(preimage: [Field; VALUE_NOTE_LEN]) -> ValueNote { - ValueNote::deserialise(preimage) +fn deserialize(preimage: [Field; VALUE_NOTE_LEN]) -> ValueNote { + ValueNote::deserialize(preimage) } -fn serialise(note: ValueNote) -> [Field; VALUE_NOTE_LEN] { - note.serialise() +fn serialize(note: ValueNote) -> [Field; VALUE_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: ValueNote) -> Field { @@ -98,8 +98,8 @@ fn set_header(note: &mut ValueNote, header: NoteHeader) { } global ValueNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/aztec-rpc/README.md b/yarn-project/aztec-rpc/README.md index dad598d665eb..9f50fa1cf0f9 100644 --- a/yarn-project/aztec-rpc/README.md +++ b/yarn-project/aztec-rpc/README.md @@ -8,4 +8,4 @@ - [Acir Simulator](../acir-simulator/) - [Key Store](../key-store/) -- [Account State](./src/account_state/account_state.ts): It coordinates other components to synchronise and decrypt data, simulate transactions, and generate kernel proofs, for a specific account. +- [Account State](./src/account_state/account_state.ts): It coordinates other components to synchronize and decrypt data, simulate transactions, and generate kernel proofs, for a specific account. diff --git a/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts b/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts index 86555d6392b9..2dc0cedf2a7d 100644 --- a/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts +++ b/yarn-project/aztec-rpc/src/aztec_rpc_server/aztec_rpc_server.ts @@ -58,13 +58,13 @@ import { Database } from '../database/index.js'; import { KernelOracle } from '../kernel_oracle/index.js'; import { KernelProver } from '../kernel_prover/kernel_prover.js'; import { getAcirSimulator } from '../simulator/index.js'; -import { Synchroniser } from '../synchroniser/index.js'; +import { Synchronizer } from '../synchronizer/index.js'; /** * A remote Aztec RPC Client implementation. */ export class AztecRPCServer implements AztecRPC { - private synchroniser: Synchroniser; + private synchronizer: Synchronizer; private contractDataOracle: ContractDataOracle; private simulator: AcirSimulator; private log: DebugLogger; @@ -78,7 +78,7 @@ export class AztecRPCServer implements AztecRPC { logSuffix?: string, ) { this.log = createDebugLogger(logSuffix ? `aztec:rpc_server_${logSuffix}` : `aztec:rpc_server`); - this.synchroniser = new Synchroniser(node, db, logSuffix); + this.synchronizer = new Synchronizer(node, db, logSuffix); this.contractDataOracle = new ContractDataOracle(db, node); this.simulator = getAcirSimulator(db, node, node, node, keyStore, this.contractDataOracle); @@ -91,7 +91,7 @@ export class AztecRPCServer implements AztecRPC { * @returns A promise that resolves when the server has started successfully. */ public async start() { - await this.synchroniser.start(INITIAL_L2_BLOCK_NUM, 1, this.config.l2BlockPollingIntervalMS); + await this.synchronizer.start(INITIAL_L2_BLOCK_NUM, 1, this.config.l2BlockPollingIntervalMS); const info = await this.getNodeInfo(); this.log.info(`Started RPC server connected to chain ${info.chainId} version ${info.protocolVersion}`); } @@ -104,7 +104,7 @@ export class AztecRPCServer implements AztecRPC { * @returns A Promise resolving once the server has been stopped successfully. */ public async stop() { - await this.synchroniser.stop(); + await this.synchronizer.stop(); this.log.info('Stopped'); } @@ -117,7 +117,7 @@ export class AztecRPCServer implements AztecRPC { const wasAdded = await this.db.addCompleteAddress(completeAddress); if (wasAdded) { const pubKey = this.keyStore.addAccount(privKey); - this.synchroniser.addAccount(pubKey, this.keyStore); + this.synchronizer.addAccount(pubKey, this.keyStore); this.log.info(`Registered account ${completeAddress.address.toString()}`); this.log.debug(`Registered account\n ${completeAddress.toReadableString()}`); } else { @@ -578,15 +578,15 @@ export class AztecRPCServer implements AztecRPC { ); } - public async isGlobalStateSynchronised() { - return await this.synchroniser.isGlobalStateSynchronised(); + public async isGlobalStateSynchronized() { + return await this.synchronizer.isGlobalStateSynchronized(); } - public async isAccountStateSynchronised(account: AztecAddress) { - return await this.synchroniser.isAccountStateSynchronised(account); + public async isAccountStateSynchronized(account: AztecAddress) { + return await this.synchronizer.isAccountStateSynchronized(account); } public getSyncStatus() { - return Promise.resolve(this.synchroniser.getSyncStatus()); + return Promise.resolve(this.synchronizer.getSyncStatus()); } } diff --git a/yarn-project/aztec-rpc/src/aztec_rpc_server/test/aztec_rpc_test_suite.ts b/yarn-project/aztec-rpc/src/aztec_rpc_server/test/aztec_rpc_test_suite.ts index 79f68176cb02..9698c1f08ac5 100644 --- a/yarn-project/aztec-rpc/src/aztec_rpc_server/test/aztec_rpc_test_suite.ts +++ b/yarn-project/aztec-rpc/src/aztec_rpc_server/test/aztec_rpc_test_suite.ts @@ -138,7 +138,7 @@ export const aztecRpcTestSuite = (testName: string, aztecRpcSetup: () => Promise expect(nodeInfo.rollupAddress.toString()).toMatch(/0x[a-fA-F0-9]+/); }); - // Note: Not testing `isGlobalStateSynchronised`, `isAccountStateSynchronised` and `getSyncStatus` as these methods - // only call synchroniser. + // Note: Not testing `isGlobalStateSynchronized`, `isAccountStateSynchronized` and `getSyncStatus` as these methods + // only call synchronizer. }); }; diff --git a/yarn-project/aztec-rpc/src/note_processor/note_processor.ts b/yarn-project/aztec-rpc/src/note_processor/note_processor.ts index 1b1f3617cc07..f8a7c115eb11 100644 --- a/yarn-project/aztec-rpc/src/note_processor/note_processor.ts +++ b/yarn-project/aztec-rpc/src/note_processor/note_processor.ts @@ -45,13 +45,13 @@ export class NoteProcessor { ) {} /** - * Check if the NoteProcessor is synchronised with the remote block number. + * Check if the NoteProcessor is synchronized with the remote block number. * The function queries the remote block number from the AztecNode and compares it with the syncedToBlock value in the NoteProcessor. - * If the values are equal, then the NoteProcessor is considered to be synchronised, otherwise not. + * If the values are equal, then the NoteProcessor is considered to be synchronized, otherwise not. * - * @returns A boolean indicating whether the NoteProcessor is synchronised with the remote block number or not. + * @returns A boolean indicating whether the NoteProcessor is synchronized with the remote block number or not. */ - public async isSynchronised() { + public async isSynchronized() { const remoteBlockNumber = await this.node.getBlockNumber(); return this.syncedToBlock === remoteBlockNumber; } diff --git a/yarn-project/aztec-rpc/src/synchroniser/index.ts b/yarn-project/aztec-rpc/src/synchroniser/index.ts deleted file mode 100644 index bf023056508e..000000000000 --- a/yarn-project/aztec-rpc/src/synchroniser/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './synchroniser.js'; diff --git a/yarn-project/aztec-rpc/src/synchronizer/index.ts b/yarn-project/aztec-rpc/src/synchronizer/index.ts new file mode 100644 index 000000000000..9bc27710e6f4 --- /dev/null +++ b/yarn-project/aztec-rpc/src/synchronizer/index.ts @@ -0,0 +1 @@ +export * from './synchronizer.js'; diff --git a/yarn-project/aztec-rpc/src/synchroniser/synchroniser.test.ts b/yarn-project/aztec-rpc/src/synchronizer/synchronizer.test.ts similarity index 82% rename from yarn-project/aztec-rpc/src/synchroniser/synchroniser.test.ts rename to yarn-project/aztec-rpc/src/synchronizer/synchronizer.test.ts index 631b294f3b3e..1f16d15e4fc5 100644 --- a/yarn-project/aztec-rpc/src/synchroniser/synchroniser.test.ts +++ b/yarn-project/aztec-rpc/src/synchronizer/synchronizer.test.ts @@ -7,12 +7,12 @@ import { MockProxy, mock } from 'jest-mock-extended'; import omit from 'lodash.omit'; import { Database, MemoryDB } from '../database/index.js'; -import { Synchroniser } from './synchroniser.js'; +import { Synchronizer } from './synchronizer.js'; -describe('Synchroniser', () => { +describe('Synchronizer', () => { let aztecNode: MockProxy; let database: Database; - let synchroniser: TestSynchroniser; + let synchronizer: TestSynchronizer; let roots: Record; let blockData: HistoricBlockData; @@ -29,14 +29,14 @@ describe('Synchroniser', () => { aztecNode = mock(); database = new MemoryDB(); - synchroniser = new TestSynchroniser(aztecNode, database); + synchronizer = new TestSynchronizer(aztecNode, database); }); it('sets tree roots from aztec node on initial sync', async () => { aztecNode.getBlockNumber.mockResolvedValue(3); aztecNode.getHistoricBlockData.mockResolvedValue(blockData); - await synchroniser.initialSync(); + await synchronizer.initialSync(); expect(database.getTreeRoots()).toEqual(roots); }); @@ -46,7 +46,7 @@ describe('Synchroniser', () => { aztecNode.getBlocks.mockResolvedValue([L2Block.fromFields(omit(block, 'newEncryptedLogs', 'newUnencryptedLogs'))]); aztecNode.getLogs.mockResolvedValueOnce([block.newEncryptedLogs!]).mockResolvedValue([block.newUnencryptedLogs!]); - await synchroniser.work(); + await synchronizer.work(); const roots = database.getTreeRoots(); expect(roots[MerkleTreeId.CONTRACT_TREE]).toEqual(block.endContractTreeSnapshot.root); @@ -57,7 +57,7 @@ describe('Synchroniser', () => { aztecNode.getBlockNumber.mockResolvedValue(3); aztecNode.getHistoricBlockData.mockResolvedValue(blockData); - await synchroniser.initialSync(); + await synchronizer.initialSync(); const roots0 = database.getTreeRoots(); expect(roots0[MerkleTreeId.CONTRACT_TREE]).toEqual(roots[MerkleTreeId.CONTRACT_TREE]); @@ -68,7 +68,7 @@ describe('Synchroniser', () => { ]); aztecNode.getLogs.mockResolvedValue([block1.newEncryptedLogs!]).mockResolvedValue([block1.newUnencryptedLogs!]); - await synchroniser.work(); + await synchronizer.work(); const roots1 = database.getTreeRoots(); expect(roots1[MerkleTreeId.CONTRACT_TREE]).toEqual(roots[MerkleTreeId.CONTRACT_TREE]); expect(roots1[MerkleTreeId.CONTRACT_TREE]).not.toEqual(block1.endContractTreeSnapshot.root); @@ -79,7 +79,7 @@ describe('Synchroniser', () => { L2Block.fromFields(omit(block5, 'newEncryptedLogs', 'newUnencryptedLogs')), ]); - await synchroniser.work(); + await synchronizer.work(); const roots5 = database.getTreeRoots(); expect(roots5[MerkleTreeId.CONTRACT_TREE]).not.toEqual(roots[MerkleTreeId.CONTRACT_TREE]); expect(roots5[MerkleTreeId.CONTRACT_TREE]).toEqual(block5.endContractTreeSnapshot.root); @@ -88,36 +88,36 @@ describe('Synchroniser', () => { it('note processor successfully catches up', async () => { const block = L2Block.random(1, 4); - // getBlocks is called by both synchroniser.work and synchroniser.workNoteProcessorCatchUp + // getBlocks is called by both synchronizer.work and synchronizer.workNoteProcessorCatchUp aztecNode.getBlocks.mockResolvedValue([L2Block.fromFields(omit(block, 'newEncryptedLogs', 'newUnencryptedLogs'))]); aztecNode.getLogs - .mockResolvedValueOnce([block.newEncryptedLogs!]) // called by synchroniser.work - .mockResolvedValueOnce([block.newUnencryptedLogs!]) // called by synchroniser.work - .mockResolvedValueOnce([block.newEncryptedLogs!]); // called by synchroniser.workNoteProcessorCatchUp + .mockResolvedValueOnce([block.newEncryptedLogs!]) // called by synchronizer.work + .mockResolvedValueOnce([block.newUnencryptedLogs!]) // called by synchronizer.work + .mockResolvedValueOnce([block.newEncryptedLogs!]); // called by synchronizer.workNoteProcessorCatchUp - // Sync the synchroniser so that note processor has something to catch up to - await synchroniser.work(); + // Sync the synchronizer so that note processor has something to catch up to + await synchronizer.work(); - // Used in synchroniser.isAccountStateSynchronised + // Used in synchronizer.isAccountStateSynchronized aztecNode.getBlockNumber.mockResolvedValueOnce(1); - // Manually adding account to database so that we can call synchroniser.isAccountStateSynchronised + // Manually adding account to database so that we can call synchronizer.isAccountStateSynchronized const keyStore = new TestKeyStore(await Grumpkin.new()); const privateKey = GrumpkinScalar.random(); keyStore.addAccount(privateKey); const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(privateKey, Fr.random()); await database.addCompleteAddress(completeAddress); - // Add the account which will add the note processor to the synchroniser - synchroniser.addAccount(completeAddress.publicKey, keyStore); + // Add the account which will add the note processor to the synchronizer + synchronizer.addAccount(completeAddress.publicKey, keyStore); - await synchroniser.workNoteProcessorCatchUp(); + await synchronizer.workNoteProcessorCatchUp(); - expect(await synchroniser.isAccountStateSynchronised(completeAddress.address)).toBe(true); + expect(await synchronizer.isAccountStateSynchronized(completeAddress.address)).toBe(true); }); }); -class TestSynchroniser extends Synchroniser { +class TestSynchronizer extends Synchronizer { public work() { return super.work(); } diff --git a/yarn-project/aztec-rpc/src/synchroniser/synchroniser.ts b/yarn-project/aztec-rpc/src/synchronizer/synchronizer.ts similarity index 94% rename from yarn-project/aztec-rpc/src/synchroniser/synchroniser.ts rename to yarn-project/aztec-rpc/src/synchronizer/synchronizer.ts index 57a0471addb8..b3cc55363a38 100644 --- a/yarn-project/aztec-rpc/src/synchroniser/synchroniser.ts +++ b/yarn-project/aztec-rpc/src/synchronizer/synchronizer.ts @@ -8,13 +8,13 @@ import { Database } from '../database/index.js'; import { NoteProcessor } from '../note_processor/index.js'; /** - * The Synchroniser class manages the synchronization of note processors and interacts with the Aztec node + * The Synchronizer class manages the synchronization of note processors and interacts with the Aztec node * to obtain encrypted logs, blocks, and other necessary information for the accounts. * It provides methods to start or stop the synchronization process, add new accounts, retrieve account - * details, and fetch transactions by hash. The Synchroniser ensures that it maintains the note processors + * details, and fetch transactions by hash. The Synchronizer ensures that it maintains the note processors * in sync with the blockchain while handling retries and errors gracefully. */ -export class Synchroniser { +export class Synchronizer { private runningPromise?: Promise; private noteProcessors: NoteProcessor[] = []; private interruptableSleep = new InterruptableSleep(); @@ -26,7 +26,7 @@ export class Synchroniser { constructor(private node: AztecNode, private db: Database, logSuffix = '') { this.log = createDebugLogger( - logSuffix ? `aztec:aztec_rpc_synchroniser_${logSuffix}` : 'aztec:aztec_rpc_synchroniser', + logSuffix ? `aztec:aztec_rpc_synchronizer_${logSuffix}` : 'aztec:aztec_rpc_synchronizer', ); } @@ -224,13 +224,13 @@ export class Synchroniser { } /** - * Add a new account to the Synchroniser with the specified private key. + * Add a new account to the Synchronizer with the specified private key. * Creates a NoteProcessor instance for the account and pushes it into the noteProcessors array. * The method resolves immediately after pushing the new note processor. * * @param publicKey - The public key for the account. * @param keyStore - The key store. - * @returns A promise that resolves once the account is added to the Synchroniser. + * @returns A promise that resolves once the account is added to the Synchronizer. */ public addAccount(publicKey: PublicKey, keyStore: KeyStore) { const processor = this.noteProcessors.find(x => x.publicKey.equals(publicKey)); @@ -242,13 +242,13 @@ export class Synchroniser { } /** - * Checks if the specified account is synchronised. + * Checks if the specified account is synchronized. * @param account - The aztec address for which to query the sync status. * @returns True if the account is fully synched, false otherwise. * @remarks Checks whether all the notes from all the blocks have been processed. If it is not the case, the * retrieved information from contracts might be old/stale (e.g. old token balance). */ - public async isAccountStateSynchronised(account: AztecAddress) { + public async isAccountStateSynchronized(account: AztecAddress) { const completeAddress = await this.db.getCompleteAddress(account); if (!completeAddress) { return false; @@ -257,7 +257,7 @@ export class Synchroniser { if (!processor) { return false; } - return await processor.isSynchronised(); + return await processor.isSynchronized(); } /** @@ -266,14 +266,14 @@ export class Synchroniser { * @remarks This indicates that blocks and transactions are synched even if notes are not. * @remarks Compares local block number with the block number from aztec node. */ - public async isGlobalStateSynchronised() { + public async isGlobalStateSynchronized() { const latest = await this.node.getBlockNumber(); return latest <= this.synchedToBlock; } /** - * Returns the latest block that has been synchronised by the synchronizer and each account. - * @returns The latest block synchronised for blocks, and the latest block synched for notes for each public key being tracked. + * Returns the latest block that has been synchronized by the synchronizer and each account. + * @returns The latest block synchronized for blocks, and the latest block synched for notes for each public key being tracked. */ public getSyncStatus() { return { diff --git a/yarn-project/aztec.js/src/wallet/base_wallet.ts b/yarn-project/aztec.js/src/wallet/base_wallet.ts index dac3fc0c8186..cec54b0cb3d0 100644 --- a/yarn-project/aztec.js/src/wallet/base_wallet.ts +++ b/yarn-project/aztec.js/src/wallet/base_wallet.ts @@ -91,11 +91,11 @@ export abstract class BaseWallet implements Wallet { getNodeInfo(): Promise { return this.rpc.getNodeInfo(); } - isGlobalStateSynchronised() { - return this.rpc.isGlobalStateSynchronised(); + isGlobalStateSynchronized() { + return this.rpc.isGlobalStateSynchronized(); } - isAccountStateSynchronised(account: AztecAddress) { - return this.rpc.isAccountStateSynchronised(account); + isAccountStateSynchronized(account: AztecAddress) { + return this.rpc.isAccountStateSynchronized(account); } getSyncStatus(): Promise { return this.rpc.getSyncStatus(); diff --git a/yarn-project/boxes/blank-react/src/app/contract.tsx b/yarn-project/boxes/blank-react/src/app/contract.tsx index 510aa16719f0..04003d01c400 100644 --- a/yarn-project/boxes/blank-react/src/app/contract.tsx +++ b/yarn-project/boxes/blank-react/src/app/contract.tsx @@ -31,7 +31,7 @@ export function Contract({ wallet }: Props) { setResult(`Contract deployed at: ${address}`); }; const handleResult = (returnValues: any) => { - // TODO: Serialise returnValues to string according to the returnTypes defined in the function abi. + // TODO: serialize returnValues to string according to the returnTypes defined in the function abi. setResult(`Return values: ${returnValues}`); }; const handleClosePopup = () => { diff --git a/yarn-project/boxes/blank-react/src/contracts/src/interface.nr b/yarn-project/boxes/blank-react/src/contracts/src/interface.nr index 56314a40a7fc..5e15a7765cc5 100644 --- a/yarn-project/boxes/blank-react/src/contracts/src/interface.nr +++ b/yarn-project/boxes/blank-react/src/contracts/src/interface.nr @@ -23,10 +23,10 @@ impl BlankPrivateContextInterface { context: &mut PrivateContext, address: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = address; + let mut serialized_args = [0; 1]; + serialized_args[0] = address; - context.call_private_function(self.address, 0x88f0753b, serialised_args) + context.call_private_function(self.address, 0x88f0753b, serialized_args) } } diff --git a/yarn-project/boxes/blank/src/contracts/src/interface.nr b/yarn-project/boxes/blank/src/contracts/src/interface.nr index 56314a40a7fc..5e15a7765cc5 100644 --- a/yarn-project/boxes/blank/src/contracts/src/interface.nr +++ b/yarn-project/boxes/blank/src/contracts/src/interface.nr @@ -23,10 +23,10 @@ impl BlankPrivateContextInterface { context: &mut PrivateContext, address: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = address; + let mut serialized_args = [0; 1]; + serialized_args[0] = address; - context.call_private_function(self.address, 0x88f0753b, serialised_args) + context.call_private_function(self.address, 0x88f0753b, serialized_args) } } diff --git a/yarn-project/boxes/private-token/src/app/contract.tsx b/yarn-project/boxes/private-token/src/app/contract.tsx index 31664691187b..96d013e11dfb 100644 --- a/yarn-project/boxes/private-token/src/app/contract.tsx +++ b/yarn-project/boxes/private-token/src/app/contract.tsx @@ -31,7 +31,7 @@ export function Contract({ wallet }: Props) { setResult(`Contract deployed at: ${address}`); }; const handleResult = (returnValues: any) => { - // TODO: Serialise returnValues to string according to the returnTypes defined in the function abi. + // TODO: serialize returnValues to string according to the returnTypes defined in the function abi. setResult(`Return values: ${returnValues}`); }; const handleClosePopup = () => { diff --git a/yarn-project/boxes/private-token/src/contracts/src/interface.nr b/yarn-project/boxes/private-token/src/contracts/src/interface.nr index 1eee266adcb8..0f59f541a245 100644 --- a/yarn-project/boxes/private-token/src/contracts/src/interface.nr +++ b/yarn-project/boxes/private-token/src/contracts/src/interface.nr @@ -24,11 +24,11 @@ impl PrivateTokenPrivateContextInterface { amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; - context.call_private_function(self.address, 0x1535439c, serialised_args) + context.call_private_function(self.address, 0x1535439c, serialized_args) } @@ -38,11 +38,11 @@ impl PrivateTokenPrivateContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_private_function(self.address, 0xc0888d22, serialised_args) + context.call_private_function(self.address, 0xc0888d22, serialized_args) } } diff --git a/yarn-project/cli/src/unbox.ts b/yarn-project/cli/src/unbox.ts index 7adef2931f84..6c646586ae75 100644 --- a/yarn-project/cli/src/unbox.ts +++ b/yarn-project/cli/src/unbox.ts @@ -284,7 +284,7 @@ export async function unboxContract( await updatePackagingConfigurations(packageVersion, tag, outputPath, log); log(''); - log(`${contractName} has been successfully initialised!`); + log(`${contractName} has been successfully initialized!`); log('To get started, simply run the following commands:'); log(` cd ${outputDirectoryName}`); log(' yarn'); diff --git a/yarn-project/end-to-end/src/e2e_2_rpc_servers.test.ts b/yarn-project/end-to-end/src/e2e_2_rpc_servers.test.ts index 6b7f7e97b49f..856b6c354da6 100644 --- a/yarn-project/end-to-end/src/e2e_2_rpc_servers.test.ts +++ b/yarn-project/end-to-end/src/e2e_2_rpc_servers.test.ts @@ -54,11 +54,11 @@ describe('e2e_2_rpc_servers', () => { } }); - const awaitUserSynchronised = async (wallet: Wallet, owner: AztecAddress) => { - const isUserSynchronised = async () => { - return await wallet.isAccountStateSynchronised(owner); + const awaitUserSynchronized = async (wallet: Wallet, owner: AztecAddress) => { + const isUserSynchronized = async () => { + return await wallet.isAccountStateSynchronized(owner); }; - await retryUntil(isUserSynchronised, `synch of user ${owner.toString()}`, 10); + await retryUntil(isUserSynchronized, `synch of user ${owner.toString()}`, 10); }; const expectTokenBalance = async ( @@ -67,8 +67,8 @@ describe('e2e_2_rpc_servers', () => { owner: AztecAddress, expectedBalance: bigint, ) => { - // First wait until the corresponding RPC server has synchronised the account - await awaitUserSynchronised(wallet, owner); + // First wait until the corresponding RPC server has synchronized the account + await awaitUserSynchronized(wallet, owner); // Then check the balance const contractWithWallet = await TokenContract.at(tokenAddress, wallet); @@ -158,11 +158,11 @@ describe('e2e_2_rpc_servers', () => { return contract.completeAddress; }; - const awaitServerSynchronised = async (server: AztecRPC) => { - const isServerSynchronised = async () => { - return await server.isGlobalStateSynchronised(); + const awaitServerSynchronized = async (server: AztecRPC) => { + const isServerSynchronized = async () => { + return await server.isGlobalStateSynchronized(); }; - await retryUntil(isServerSynchronised, 'server sync', 10); + await retryUntil(isServerSynchronized, 'server sync', 10); }; const getChildStoredValue = (child: { address: AztecAddress }, aztecRpcServer: AztecRPC) => @@ -171,7 +171,7 @@ describe('e2e_2_rpc_servers', () => { it('user calls a public function on a contract deployed by a different user using a different RPC server', async () => { const childCompleteAddress = await deployChildContractViaServerA(); - await awaitServerSynchronised(aztecRpcServerA); + await awaitServerSynchronized(aztecRpcServerA); // Add Child to RPC server B await aztecRpcServerB.addContracts([ @@ -187,7 +187,7 @@ describe('e2e_2_rpc_servers', () => { const childContractWithWalletB = await ChildContract.at(childCompleteAddress.address, walletB); await childContractWithWalletB.methods.pubIncValue(newValueToSet).send().wait({ interval: 0.1 }); - await awaitServerSynchronised(aztecRpcServerA); + await awaitServerSynchronized(aztecRpcServerA); const storedValue = await getChildStoredValue(childCompleteAddress, aztecRpcServerB); expect(storedValue).toBe(newValueToSet); diff --git a/yarn-project/foundation/src/abi/encoder.test.ts b/yarn-project/foundation/src/abi/encoder.test.ts index 4d8a5de60272..67cb6223c42d 100644 --- a/yarn-project/foundation/src/abi/encoder.test.ts +++ b/yarn-project/foundation/src/abi/encoder.test.ts @@ -128,7 +128,7 @@ describe('abi/encoder', () => { ]; expect(() => encodeArguments(testFunctionAbi, args)).toThrowError( - 'Argument for owner cannot be serialised to a field', + 'Argument for owner cannot be serialized to a field', ); }); }); diff --git a/yarn-project/foundation/src/abi/encoder.ts b/yarn-project/foundation/src/abi/encoder.ts index 9faa6213c1e8..5f0c903b8b3d 100644 --- a/yarn-project/foundation/src/abi/encoder.ts +++ b/yarn-project/foundation/src/abi/encoder.ts @@ -34,7 +34,7 @@ class ArgumentEncoder { } else if (typeof arg.toField === 'function') { this.flattened.push(arg.toField()); } else { - throw new Error(`Argument for ${name} cannot be serialised to a field`); + throw new Error(`Argument for ${name} cannot be serialized to a field`); } } else { throw new Error(`Invalid argument "${arg}" of type ${abiType.kind}`); diff --git a/yarn-project/foundation/src/abi/function_selector.ts b/yarn-project/foundation/src/abi/function_selector.ts index 236acfedd793..88c7919e4a55 100644 --- a/yarn-project/foundation/src/abi/function_selector.ts +++ b/yarn-project/foundation/src/abi/function_selector.ts @@ -99,7 +99,7 @@ export class FunctionSelector { static fromNameAndParameters(name: string, parameters: ABIParameter[]) { const signature = decodeFunctionSignature(name, parameters); const selector = FunctionSelector.fromSignature(signature); - // If using the debug logger here it kill the typing in the `server_world_state_synchroniser` and jest tests. + // If using the debug logger here it kill the typing in the `server_world_state_synchronizer` and jest tests. // console.log(`Function selector for ${signature} is ${selector}`); return selector; } diff --git a/yarn-project/foundation/src/fields/coordinate.ts b/yarn-project/foundation/src/fields/coordinate.ts index 33fb55f80e68..aada6d1ff806 100644 --- a/yarn-project/foundation/src/fields/coordinate.ts +++ b/yarn-project/foundation/src/fields/coordinate.ts @@ -8,7 +8,7 @@ import { Fr } from './fields.js'; * The coordinate value is split across 2 fields to ensure that the max size of a field is not breached. * This is achieved by placing the most significant byte of the lower field into the least significant byte of the higher field. * Calls to 'toBuffer' or 'toBigInt' undo this change and simply return the original 32 byte value. - * Calls to 'toFieldsBuffer' will return a 64 bytes buffer containing the serialised fields. + * Calls to 'toFieldsBuffer' will return a 64 bytes buffer containing the serialized fields. */ export class Coordinate { static ZERO = new Coordinate([Fr.ZERO, Fr.ZERO]); @@ -37,16 +37,16 @@ export class Coordinate { } /** - * Serialises the oblect to buffer of 2 fields. - * @returns A buffer serialisation of the object. + * serializes the oblect to buffer of 2 fields. + * @returns A buffer serialization of the object. */ toFieldsBuffer(): Buffer { return Buffer.concat([this.fields[0].toBuffer(), this.fields[1].toBuffer()]); } /** - * Serialises the coordinate to a single 32 byte buffer. - * @returns A buffer serialisation of the object. + * serializes the coordinate to a single 32 byte buffer. + * @returns A buffer serialization of the object. */ toBuffer(): Buffer { const buf0 = this.fields[0].toBuffer(); diff --git a/yarn-project/foundation/src/json-rpc/convert.test.ts b/yarn-project/foundation/src/json-rpc/convert.test.ts index 53b567769046..ddad7fa09bdb 100644 --- a/yarn-project/foundation/src/json-rpc/convert.test.ts +++ b/yarn-project/foundation/src/json-rpc/convert.test.ts @@ -30,11 +30,11 @@ test('does not convert a string', () => { test('converts a registered class', () => { const cc = new ClassConverter({ ToStringClass: ToStringClassA }); const obj = { content: new ToStringClassA('a', 'b') }; - const serialised = convertToJsonObj(cc, obj); - const deserialised = convertFromJsonObj(cc, serialised) as { content: ToStringClassA }; - expect(deserialised.content).toBeInstanceOf(ToStringClassA); - expect(deserialised.content.x).toEqual('a'); - expect(deserialised.content.y).toEqual('b'); + const serialized = convertToJsonObj(cc, obj); + const deserialized = convertFromJsonObj(cc, serialized) as { content: ToStringClassA }; + expect(deserialized.content).toBeInstanceOf(ToStringClassA); + expect(deserialized.content.x).toEqual('a'); + expect(deserialized.content.y).toEqual('b'); }); test('converts a class by name in the event of duplicate modules being loaded', () => { @@ -42,21 +42,21 @@ test('converts a class by name in the event of duplicate modules being loaded', expect(ToStringClassB.prototype.constructor.name).toEqual('ToStringClass'); const cc = new ClassConverter({ ToStringClass: ToStringClassA }); const obj = { content: new ToStringClassB('a', 'b') }; - const serialised = convertToJsonObj(cc, obj); - const deserialised = convertFromJsonObj(cc, serialised) as { content: ToStringClassA }; - expect(deserialised.content).toBeInstanceOf(ToStringClassA); - expect(deserialised.content.x).toEqual('a'); - expect(deserialised.content.y).toEqual('b'); + const serialized = convertToJsonObj(cc, obj); + const deserialized = convertFromJsonObj(cc, serialized) as { content: ToStringClassA }; + expect(deserialized.content).toBeInstanceOf(ToStringClassA); + expect(deserialized.content.x).toEqual('a'); + expect(deserialized.content.y).toEqual('b'); }); test('converts a class by constructor instead of name in the event of minified bundle', () => { const cc = new ClassConverter({ NotMinifiedToStringClassName: ToStringClassA }); const obj = { content: new ToStringClassA('a', 'b') }; - const serialised = convertToJsonObj(cc, obj); - const deserialised = convertFromJsonObj(cc, serialised) as { content: ToStringClassA }; - expect(deserialised.content).toBeInstanceOf(ToStringClassA); - expect(deserialised.content.x).toEqual('a'); - expect(deserialised.content.y).toEqual('b'); + const serialized = convertToJsonObj(cc, obj); + const deserialized = convertFromJsonObj(cc, serialized) as { content: ToStringClassA }; + expect(deserialized.content).toBeInstanceOf(ToStringClassA); + expect(deserialized.content.x).toEqual('a'); + expect(deserialized.content.y).toEqual('b'); }); test('converts a plain object', () => { @@ -72,6 +72,6 @@ test('refuses to convert to json an unknown class', () => { test('refuses to convert from json an unknown class', () => { const cc = new ClassConverter({ ToStringClass: ToStringClassA }); - const serialised = convertToJsonObj(cc, { content: new ToStringClassA('a', 'b') }); - expect(() => convertFromJsonObj(new ClassConverter(), serialised)).toThrowError(/not registered/); + const serialized = convertToJsonObj(cc, { content: new ToStringClassA('a', 'b') }); + expect(() => convertFromJsonObj(new ClassConverter(), serialized)).toThrowError(/not registered/); }); diff --git a/yarn-project/foundation/src/json-rpc/convert.ts b/yarn-project/foundation/src/json-rpc/convert.ts index 53a3fe0d3b30..af378fa4cc11 100644 --- a/yarn-project/foundation/src/json-rpc/convert.ts +++ b/yarn-project/foundation/src/json-rpc/convert.ts @@ -88,7 +88,7 @@ export function convertFromJsonObj(cc: ClassConverter, obj: any): any { if (cc.isRegisteredClassName(obj.type)) { return cc.toClassObj(obj); } else { - throw new Error(`Object ${obj.type} not registered for serialisation FROM JSON`); + throw new Error(`Object ${obj.type} not registered for serialization FROM JSON`); } } @@ -154,7 +154,7 @@ export function convertToJsonObj(cc: ClassConverter, obj: any): any { return newObj; } else { // Throw if this is a non-primitive class that was not registered - throw new Error(`Object ${obj.constructor.name} not registered for serialisation TO JSON`); + throw new Error(`Object ${obj.constructor.name} not registered for serialization TO JSON`); } } diff --git a/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts b/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts index 743840fe2172..93d88e71befa 100644 --- a/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts +++ b/yarn-project/merkle-tree/src/standard_indexed_tree/standard_indexed_tree.ts @@ -552,12 +552,12 @@ export class StandardIndexedTree extends TreeBase implements IndexedTree { private async encodeAndAppendLeaves(leaves: LeafData[], hash0Leaf: boolean): Promise { const startInsertionIndex = Number(this.getNumLeaves(true)); - const serialisedLeaves = leaves.map((leaf, i) => { + const serializedLeaves = leaves.map((leaf, i) => { this.cachedLeaves[startInsertionIndex + i] = leaf; return this.encodeLeaf(leaf, hash0Leaf); }); - await super.appendLeaves(serialisedLeaves); + await super.appendLeaves(serializedLeaves); } /** diff --git a/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap b/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap index 5defbe9affe5..eb6aa1b5ec7a 100644 --- a/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap +++ b/yarn-project/noir-compiler/src/__snapshots__/index.test.ts.snap @@ -223,9 +223,9 @@ impl TestContractPrivateContextInterface { self, context: &mut PrivateContext ) { - let mut serialised_args = [0; 0]; + let mut serialized_args = [0; 0]; - context.call_public_function(self.address, 0x46be982e, serialised_args) + context.call_public_function(self.address, 0x46be982e, serialized_args) } } @@ -249,9 +249,9 @@ impl TestContractPublicContextInterface { self, context: PublicContext ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 0]; + let mut serialized_args = [0; 0]; - context.call_public_function(self.address, 0x46be982e, serialised_args) + context.call_public_function(self.address, 0x46be982e, serialized_args) } } diff --git a/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts b/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts index 8f81f7697bac..d1fd96bea215 100644 --- a/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts +++ b/yarn-project/noir-compiler/src/contract-interface-gen/noir.ts @@ -32,7 +32,7 @@ function isPrivateCall(functionType: FunctionType) { function generateCallStatement(selector: FunctionSelector, functionType: FunctionType) { const callMethod = isPrivateCall(functionType) ? 'call_private_function' : 'call_public_function'; return ` - context.${callMethod}(self.address, 0x${selector.toString()}, serialised_args)`; + context.${callMethod}(self.address, 0x${selector.toString()}, serialized_args)`; } /** @@ -91,23 +91,23 @@ function generateParameter(param: ABIParameter, functionData: FunctionAbi) { } /** - * Collects all parameters for a given function and flattens them according to how they should be serialised. + * Collects all parameters for a given function and flattens them according to how they should be serialized. * @param parameters - Parameters for a function. * @returns List of parameters flattened to basic data types. */ -function collectParametersForSerialisation(parameters: ABIVariable[]) { +function collectParametersForSerialization(parameters: ABIVariable[]) { const flattened: string[] = []; for (const parameter of parameters) { const { name } = parameter; if (parameter.type.kind === 'array') { const nestedType = parameter.type.type; const nested = times(parameter.type.length, i => - collectParametersForSerialisation([{ name: `${name}[${i}]`, type: nestedType }]), + collectParametersForSerialization([{ name: `${name}[${i}]`, type: nestedType }]), ); flattened.push(...nested.flat()); } else if (parameter.type.kind === 'struct') { const nested = parameter.type.fields.map(field => - collectParametersForSerialisation([{ name: `${name}.${field.name}`, type: field.type }]), + collectParametersForSerialization([{ name: `${name}.${field.name}`, type: field.type }]), ); flattened.push(...nested.flat()); } else if (parameter.type.kind === 'string') { @@ -123,13 +123,13 @@ function collectParametersForSerialisation(parameters: ABIVariable[]) { /** * Generates Noir code for serialising the parameters into an array of fields. - * @param parameters - Parameters to serialise. - * @returns The serialisation code. + * @param parameters - Parameters to serialize. + * @returns The serialization code. */ -function generateSerialisation(parameters: ABIParameter[]) { - const flattened = collectParametersForSerialisation(parameters); - const declaration = ` let mut serialised_args = [0; ${flattened.length}];`; - const lines = flattened.map((param, i) => ` serialised_args[${i}] = ${param};`); +function generateSerialization(parameters: ABIParameter[]) { + const flattened = collectParametersForSerialization(parameters); + const declaration = ` let mut serialized_args = [0; ${flattened.length}];`; + const lines = flattened.map((param, i) => ` serialized_args[${i}] = ${param};`); return [declaration, ...lines].join('\n'); } @@ -142,7 +142,7 @@ function generateSerialisation(parameters: ABIParameter[]) { function generateFunctionInterface(functionData: FunctionAbi, kind: 'private' | 'public') { const { name, parameters } = functionData; const selector = FunctionSelector.fromNameAndParameters(name, parameters); - const serialisation = generateSerialisation(parameters); + const serialization = generateSerialization(parameters); const contextType = kind === 'private' ? '&mut PrivateContext' : 'PublicContext'; const callStatement = generateCallStatement(selector, functionData.functionType); const allParams = ['self', `context: ${contextType}`, ...parameters.map(p => generateParameter(p, functionData))]; @@ -154,7 +154,7 @@ function generateFunctionInterface(functionData: FunctionAbi, kind: 'private' | fn ${name}( ${allParams.join(',\n ')} ) ${retType}{ -${serialisation} +${serialization} ${callStatement} } `; diff --git a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/cards.nr b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/cards.nr index d5698677b464..219728e3f90f 100644 --- a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/cards.nr +++ b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/cards.nr @@ -145,7 +145,7 @@ impl Deck { (*context).this_address(), self.set.storage_slot, owner_key, - card_note.note.serialise(), + card_note.note.serialize(), ); inserted_cards = inserted_cards.push_back(card_note); } diff --git a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/game.nr b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/game.nr index e68e8799f6e3..30a8c722bd10 100644 --- a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/game.nr +++ b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/game.nr @@ -1,4 +1,4 @@ -use dep::aztec::types::type_serialisation::TypeSerialisationInterface; +use dep::aztec::types::type_serialization::TypeSerializationInterface; use crate::cards::Card; global NUMBER_OF_PLAYERS = 2; @@ -11,7 +11,7 @@ struct PlayerEntry { } impl PlayerEntry { - fn is_initialised(self) -> bool { + fn is_initialized(self) -> bool { self.address != 0 } } @@ -28,9 +28,9 @@ struct Game { current_round: u32, } -global GAME_SERIALISED_LEN: Field = 15; +global GAME_SERIALIZED_LEN: Field = 15; -fn deserialiseGame(fields: [Field; GAME_SERIALISED_LEN]) -> Game { +fn deserializeGame(fields: [Field; GAME_SERIALIZED_LEN]) -> Game { let players = [ PlayerEntry { address: fields[0], @@ -58,7 +58,7 @@ fn deserialiseGame(fields: [Field; GAME_SERIALISED_LEN]) -> Game { } } -fn serialiseGame(game: Game) -> [Field; GAME_SERIALISED_LEN] { +fn serializeGame(game: Game) -> [Field; GAME_SERIALIZED_LEN] { [ game.players[0].address, game.players[0].deck_strength as Field, @@ -79,8 +79,8 @@ fn serialiseGame(game: Game) -> [Field; GAME_SERIALISED_LEN] { } impl Game { - fn serialize(self: Self) -> [Field; GAME_SERIALISED_LEN] { - serialiseGame(self) + fn serialize(self: Self) -> [Field; GAME_SERIALIZED_LEN] { + serializeGame(self) } fn add_player(&mut self, player_entry: PlayerEntry) -> bool { @@ -88,7 +88,7 @@ impl Game { for i in 0..NUMBER_OF_PLAYERS { let entry = self.players[i]; - if entry.is_initialised() { + if entry.is_initialized() { assert(entry.address != player_entry.address, "Player already in game"); } else if !added { self.players[i] = player_entry; @@ -103,7 +103,7 @@ impl Game { assert(!self.started, "Game already started"); for i in 0..NUMBER_OF_PLAYERS { let entry = self.players[i]; - assert(entry.is_initialised(), "Game not full"); + assert(entry.is_initialized(), "Game not full"); } let sorted_by_deck_strength = self.players.sort_via(|a: PlayerEntry, b: PlayerEntry| a.deck_strength < b.deck_strength); self.players = sorted_by_deck_strength; @@ -166,7 +166,7 @@ impl Game { } } -global GameSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseGame, - serialise: serialiseGame, +global GameSerializationMethods = TypeSerializationInterface { + deserialize: deserializeGame, + serialize: serializeGame, }; \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/main.nr index 1d53056a5d1b..b570ad3a42b3 100644 --- a/yarn-project/noir-contracts/src/contracts/card_game_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/card_game_contract/src/main.nr @@ -12,12 +12,12 @@ use dep::aztec::{ use dep::std::option::Option; use cards::{Deck}; -use game::{Game, GameSerialisationMethods, GAME_SERIALISED_LEN}; +use game::{Game, GameSerializationMethods, GAME_SERIALIZED_LEN}; struct Storage { collections: Map, game_decks: Map>, - games: Map>, + games: Map>, } impl Storage { @@ -58,7 +58,7 @@ impl Storage { PublicState::new( context, slot, - GameSerialisationMethods, + GameSerializationMethods, ) }, ) diff --git a/yarn-project/noir-contracts/src/contracts/child_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/child_contract/src/main.nr index 98641d7054db..84cc262c879c 100644 --- a/yarn-project/noir-contracts/src/contracts/child_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/child_contract/src/main.nr @@ -10,11 +10,11 @@ contract Child { compute_selector::compute_selector, }, state_vars::public_state::PublicState, - types::type_serialisation::field_serialisation::{FieldSerialisationMethods, FIELD_SERIALISED_LEN}, + types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN}, }; struct Storage { - current_value: PublicState, + current_value: PublicState, } impl Storage { @@ -23,7 +23,7 @@ contract Child { current_value: PublicState::new( context, 1, - FieldSerialisationMethods, + FieldSerializationMethods, ), } } diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr index 94b5981e1f3d..28c43227c250 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr @@ -6,40 +6,40 @@ use dep::aztec::state_vars::{ immutable_singleton::ImmutableSingleton, map::Map, public_state::PublicState, set::Set, singleton::Singleton, }; -use dep::aztec::types::type_serialisation::bool_serialisation::BOOL_SERIALISED_LEN; +use dep::aztec::types::type_serialization::bool_serialization::BOOL_SERIALIZED_LEN; use dep::std::option::Option; use crate::types::{ card_note::{CardNote, CARD_NOTE_LEN}, profile_note::{ProfileNote, PROFILE_NOTE_LEN}, - queen::{Queen, QUEEN_SERIALISED_LEN}, + queen::{Queen, QUEEN_SERIALIZED_LEN}, rules_note::{RulesNote, RULES_NOTE_LEN}, }; // docs:start:state_vars-PublicStateRead -fn is_locked(state_var: PublicState) -> bool { +fn is_locked(state_var: PublicState) -> bool { state_var.read() } // docs:end:state_vars-PublicStateRead // docs:start:state_vars-PublicStateWrite -fn lock(state_var: PublicState) { +fn lock(state_var: PublicState) { state_var.write(true); } // docs:end:state_vars-PublicStateWrite -fn unlock(state_var: PublicState) { +fn unlock(state_var: PublicState) { state_var.write(false); } // docs:start:state_vars-PublicStateReadCustom -fn get_current_queen(state_var: PublicState) -> Queen { +fn get_current_queen(state_var: PublicState) -> Queen { state_var.read() } // docs:end:state_vars-PublicStateReadCustom fn can_replace_queen( - state_var: PublicState, + state_var: PublicState, new_queen: Queen, ) -> bool { let current_queen = get_current_queen(state_var); @@ -47,13 +47,13 @@ fn can_replace_queen( } // docs:start:state_vars-PublicStateWriteCustom -fn replace_queen(state_var: PublicState, new_queen: Queen) { +fn replace_queen(state_var: PublicState, new_queen: Queen) { state_var.write(new_queen); } // docs:end:state_vars-PublicStateWriteCustom // docs:start:state_vars-PublicStateReadWriteCustom -fn add_points_to_queen(state_var: PublicState, new_points: u8) { +fn add_points_to_queen(state_var: PublicState, new_points: u8) { let mut queen = state_var.read(); queen.points += new_points; state_var.write(queen); @@ -62,7 +62,7 @@ fn add_points_to_queen(state_var: PublicState, new_ // docs:start:state_vars-SingletonInit fn init_legendary_card(state_var: Singleton, card: &mut CardNote) { - state_var.initialise(card); + state_var.initialize(card); } // docs:end:state_vars-SingletonInit @@ -83,7 +83,7 @@ fn init_game_rules( state_var: ImmutableSingleton, rules: &mut RulesNote, ) { - state_var.initialise(rules); + state_var.initialize(rules); } // docs:end:state_vars-ImmutableSingletonInit @@ -161,7 +161,7 @@ fn add_new_profile( account: Field, profile: &mut ProfileNote, ) { - state_var.at(account).initialise(profile); + state_var.at(account).initialize(profile); } // docs:end:state_vars-MapAtSingletonInit diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr index 961de5cc9aec..1bf53dc922da 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr @@ -13,8 +13,8 @@ contract DocsExample { }, }; // docs:start:state_vars-PublicStateBoolImport - use dep::aztec::types::type_serialisation::bool_serialisation::{ - BoolSerialisationMethods, BOOL_SERIALISED_LEN, + use dep::aztec::types::type_serialization::bool_serialization::{ + BoolSerializationMethods, BOOL_SERIALIZED_LEN, }; // docs:end:state_vars-PublicStateBoolImport use crate::account_contract_interface::AccountContractInterface; @@ -23,14 +23,14 @@ contract DocsExample { use crate::types::{ card_note::{CardNote, CardNoteMethods, CARD_NOTE_LEN}, profile_note::{ProfileNote, ProfileNoteMethods, PROFILE_NOTE_LEN}, - queen::{Queen, QueenSerialisationMethods, QUEEN_SERIALISED_LEN}, + queen::{Queen, QueenSerializationMethods, QUEEN_SERIALIZED_LEN}, rules_note::{RulesNote, RulesNoteMethods, RULES_NOTE_LEN}, }; // docs:start:storage-struct-declaration struct Storage { - locked: PublicState, - queen: PublicState, + locked: PublicState, + queen: PublicState, game_rules: ImmutableSingleton, legendary_card: Singleton, cards: Set, @@ -49,12 +49,12 @@ contract DocsExample { fn init(context: Context) -> pub Self { Storage { // highlight-next-line:state_vars-PublicState - locked: PublicState::new(context, 1, BoolSerialisationMethods), + locked: PublicState::new(context, 1, BoolSerializationMethods), // highlight-next-line:state_vars-PublicStateCustomStruct queen: PublicState::new( context, 2, - QueenSerialisationMethods, + QueenSerializationMethods, ), // highlight-next-line:state_vars-ImmutableSingleton game_rules: ImmutableSingleton::new(context, 3, RulesNoteMethods), diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/card_note.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/card_note.nr index f5b526cb0d7a..c193534e5941 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/card_note.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/card_note.nr @@ -28,11 +28,11 @@ impl CardNote { } } - fn serialise(self) -> [Field; CARD_NOTE_LEN] { + fn serialize(self) -> [Field; CARD_NOTE_LEN] { [self.points as Field, self.secret, self.owner] } - fn deserialise(preimage: [Field; CARD_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; CARD_NOTE_LEN]) -> Self { CardNote { points: preimage[0] as u8, secret: preimage[1], @@ -64,12 +64,12 @@ impl CardNote { } } -fn deserialise(preimage: [Field; CARD_NOTE_LEN]) -> CardNote { - CardNote::deserialise(preimage) +fn deserialize(preimage: [Field; CARD_NOTE_LEN]) -> CardNote { + CardNote::deserialize(preimage) } -fn serialise(note: CardNote) -> [Field; CARD_NOTE_LEN] { - note.serialise() +fn serialize(note: CardNote) -> [Field; CARD_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: CardNote) -> Field { @@ -89,8 +89,8 @@ fn set_header(note: &mut CardNote, header: NoteHeader) { } global CardNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/profile_note.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/profile_note.nr index 9e8436e62c62..2a25e726bf2d 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/profile_note.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/profile_note.nr @@ -21,11 +21,11 @@ impl ProfileNote { } } - fn serialise(self) -> [Field; PROFILE_NOTE_LEN] { + fn serialize(self) -> [Field; PROFILE_NOTE_LEN] { [self.avatar, self.xp] } - fn deserialise(preimage: [Field; PROFILE_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; PROFILE_NOTE_LEN]) -> Self { ProfileNote { avatar: preimage[1], xp: preimage[0], @@ -50,12 +50,12 @@ impl ProfileNote { } } -fn deserialise(preimage: [Field; PROFILE_NOTE_LEN]) -> ProfileNote { - ProfileNote::deserialise(preimage) +fn deserialize(preimage: [Field; PROFILE_NOTE_LEN]) -> ProfileNote { + ProfileNote::deserialize(preimage) } -fn serialise(note: ProfileNote) -> [Field; PROFILE_NOTE_LEN] { - note.serialise() +fn serialize(note: ProfileNote) -> [Field; PROFILE_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: ProfileNote) -> Field { @@ -75,8 +75,8 @@ fn set_header(note: &mut ProfileNote, header: NoteHeader) { } global ProfileNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr index eb85a5d11f25..635205ecd6f6 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr @@ -1,4 +1,4 @@ -use dep::aztec::types::type_serialisation::TypeSerialisationInterface; +use dep::aztec::types::type_serialization::TypeSerializationInterface; // docs:start:state_vars-CustomStruct struct Queen { @@ -8,21 +8,21 @@ struct Queen { // docs:end:state_vars-CustomStruct // docs:start:state_vars-PublicStateCustomStruct -global QUEEN_SERIALISED_LEN: Field = 2; +global QUEEN_SERIALIZED_LEN: Field = 2; -fn deserialise(fields: [Field; QUEEN_SERIALISED_LEN]) -> Queen { +fn deserialize(fields: [Field; QUEEN_SERIALIZED_LEN]) -> Queen { Queen { account: fields[0], points: fields[1] as u8, } } -fn serialise(queen: Queen) -> [Field; QUEEN_SERIALISED_LEN] { +fn serialize(queen: Queen) -> [Field; QUEEN_SERIALIZED_LEN] { [queen.account, queen.points as Field] } -global QueenSerialisationMethods = TypeSerialisationInterface { - deserialise, - serialise, +global QueenSerializationMethods = TypeSerializationInterface { + deserialize, + serialize, }; // docs:end:state_vars-PublicStateCustomStruct \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/rules_note.nr b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/rules_note.nr index c204842484e5..1492f56127f6 100644 --- a/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/rules_note.nr +++ b/yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/rules_note.nr @@ -21,11 +21,11 @@ impl RulesNote { } } - fn serialise(self) -> [Field; RULES_NOTE_LEN] { + fn serialize(self) -> [Field; RULES_NOTE_LEN] { [self.min_points as Field, self.max_points as Field] } - fn deserialise(preimage: [Field; RULES_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; RULES_NOTE_LEN]) -> Self { RulesNote { min_points: preimage[0] as u8, max_points: preimage[1] as u8, @@ -50,12 +50,12 @@ impl RulesNote { } } -fn deserialise(preimage: [Field; RULES_NOTE_LEN]) -> RulesNote { - RulesNote::deserialise(preimage) +fn deserialize(preimage: [Field; RULES_NOTE_LEN]) -> RulesNote { + RulesNote::deserialize(preimage) } -fn serialise(note: RulesNote) -> [Field; RULES_NOTE_LEN] { - note.serialise() +fn serialize(note: RulesNote) -> [Field; RULES_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: RulesNote) -> Field { @@ -75,8 +75,8 @@ fn set_header(note: &mut RulesNote, header: NoteHeader) { } global RulesNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/src/main.nr index a4fdd1951acf..dd1cc3162135 100644 --- a/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/easy_private_token_contract/src/main.nr @@ -37,7 +37,7 @@ contract EasyPrivateToken { } /** - * Initialise the contract's initial state variables. + * initialize the contract's initial state variables. */ #[aztec(private)] fn constructor( diff --git a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/ecdsa_public_key_note.nr b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/ecdsa_public_key_note.nr index ccd5084d8fdf..c80188fff21d 100644 --- a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/ecdsa_public_key_note.nr +++ b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/ecdsa_public_key_note.nr @@ -24,13 +24,13 @@ impl EcdsaPublicKeyNote { } } - // Serialise the note as 5 fields where: + // serialize the note as 5 fields where: // [0] = x[0..31] (upper bound excluded) // [1] = x[31] // [2] = y[0..31] // [3] = y[31] // [4] = owner - fn serialise(self) -> [Field; ECDSA_PUBLIC_KEY_NOTE_LEN] { + fn serialize(self) -> [Field; ECDSA_PUBLIC_KEY_NOTE_LEN] { let mut x: Field = 0; let mut y: Field = 0; let mut mul: Field = 1; @@ -66,7 +66,7 @@ impl EcdsaPublicKeyNote { } } -fn deserialise(preimage: [Field; ECDSA_PUBLIC_KEY_NOTE_LEN]) -> EcdsaPublicKeyNote { +fn deserialize(preimage: [Field; ECDSA_PUBLIC_KEY_NOTE_LEN]) -> EcdsaPublicKeyNote { let mut x: [u8; 32] = [0;32]; let mut y: [u8; 32] = [0;32]; @@ -86,13 +86,13 @@ fn deserialise(preimage: [Field; ECDSA_PUBLIC_KEY_NOTE_LEN]) -> EcdsaPublicKeyNo } } -fn serialise(note: EcdsaPublicKeyNote) -> [Field; ECDSA_PUBLIC_KEY_NOTE_LEN] { - note.serialise() +fn serialize(note: EcdsaPublicKeyNote) -> [Field; ECDSA_PUBLIC_KEY_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: EcdsaPublicKeyNote) -> Field { // TODO(#1205) Should use a non-zero generator index. - dep::std::hash::pedersen(note.serialise())[0] + dep::std::hash::pedersen(note.serialize())[0] } fn compute_nullifier(note: EcdsaPublicKeyNote) -> Field { @@ -108,8 +108,8 @@ fn set_header(note: &mut EcdsaPublicKeyNote, header: NoteHeader) { } global EcdsaPublicKeyNoteInterface = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/main.nr index 1b3f6c50993a..7a460b87f0a4 100644 --- a/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/ecdsa_account_contract/src/main.nr @@ -49,14 +49,14 @@ contract EcdsaAccount { let this = context.this_address(); let mut pub_key_note = EcdsaPublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this); - storage.public_key.initialise(&mut pub_key_note); + storage.public_key.initialize(&mut pub_key_note); emit_encrypted_log( &mut context, this, storage.public_key.storage_slot, get_public_key(this), - pub_key_note.serialise(), + pub_key_note.serialize(), ); } diff --git a/yarn-project/noir-contracts/src/contracts/escrow_contract/src/address_note.nr b/yarn-project/noir-contracts/src/contracts/escrow_contract/src/address_note.nr index 652c664dcb2d..6d83dcff9f96 100644 --- a/yarn-project/noir-contracts/src/contracts/escrow_contract/src/address_note.nr +++ b/yarn-project/noir-contracts/src/contracts/escrow_contract/src/address_note.nr @@ -21,7 +21,7 @@ impl AddressNote { } } - fn serialise(self) -> [Field; ADDRESS_NOTE_LEN]{ + fn serialize(self) -> [Field; ADDRESS_NOTE_LEN]{ [self.address, self.owner] } @@ -41,7 +41,7 @@ impl AddressNote { } } -fn deserialise(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote { +fn deserialize(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote { AddressNote { address: preimage[0], owner: preimage[1], @@ -49,13 +49,13 @@ fn deserialise(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote { } } -fn serialise(note: AddressNote) -> [Field; ADDRESS_NOTE_LEN]{ - note.serialise() +fn serialize(note: AddressNote) -> [Field; ADDRESS_NOTE_LEN]{ + note.serialize() } fn compute_note_hash(note: AddressNote) -> Field { // TODO(#1205) Should use a non-zero generator index. - dep::std::hash::pedersen(note.serialise())[0] + dep::std::hash::pedersen(note.serialize())[0] } fn compute_nullifier(note: AddressNote) -> Field { @@ -71,8 +71,8 @@ fn set_header(note: &mut AddressNote, header: NoteHeader) { } global AddressNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/escrow_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/escrow_contract/src/main.nr index 6d70728eac47..0a9fd70c4926 100644 --- a/yarn-project/noir-contracts/src/contracts/escrow_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/escrow_contract/src/main.nr @@ -55,7 +55,7 @@ contract Escrow { this, storage.owners.storage_slot, get_public_key(this), - note.serialise(), + note.serialize(), ); } // docs:end:constructor diff --git a/yarn-project/noir-contracts/src/contracts/lending_contract/src/asset.nr b/yarn-project/noir-contracts/src/contracts/lending_contract/src/asset.nr index 5fbc903abca6..76a6744c9e34 100644 --- a/yarn-project/noir-contracts/src/contracts/lending_contract/src/asset.nr +++ b/yarn-project/noir-contracts/src/contracts/lending_contract/src/asset.nr @@ -1,4 +1,4 @@ -use dep::aztec::types::type_serialisation::TypeSerialisationInterface; +use dep::aztec::types::type_serialization::TypeSerializationInterface; // Struct to be used to represent "totals". Generally, there should be one per asset. // It stores the global values that are shared among all users, such as an accumulator @@ -12,11 +12,11 @@ struct Asset { oracle_address: Field, } -global ASSET_SERIALISED_LEN: Field = 4; +global ASSET_SERIALIZED_LEN: Field = 4; // Right now we are wasting so many writes. If changing last_updated_ts // we will end up rewriting all of them, wasting writes. -fn deserialiseAsset(fields: [Field; ASSET_SERIALISED_LEN]) -> Asset { +fn deserializeAsset(fields: [Field; ASSET_SERIALIZED_LEN]) -> Asset { Asset { interest_accumulator: fields[0] as u120, last_updated_ts: fields[1] as u120, @@ -25,7 +25,7 @@ fn deserialiseAsset(fields: [Field; ASSET_SERIALISED_LEN]) -> Asset { } } -fn serialiseAsset(asset: Asset) -> [Field; ASSET_SERIALISED_LEN] { +fn serializeAsset(asset: Asset) -> [Field; ASSET_SERIALIZED_LEN] { [ asset.interest_accumulator as Field, asset.last_updated_ts as Field, @@ -35,12 +35,12 @@ fn serialiseAsset(asset: Asset) -> [Field; ASSET_SERIALISED_LEN] { } impl Asset { - fn serialize(self: Self) -> [Field; ASSET_SERIALISED_LEN] { - serialiseAsset(self) + fn serialize(self: Self) -> [Field; ASSET_SERIALIZED_LEN] { + serializeAsset(self) } } -global AssetSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseAsset, - serialise: serialiseAsset, +global AssetSerializationMethods = TypeSerializationInterface { + deserialize: deserializeAsset, + serialize: serializeAsset, }; diff --git a/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr index c26af11e3402..bdb432e41b6c 100644 --- a/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/lending_contract/src/main.nr @@ -20,12 +20,12 @@ contract Lending { map::Map, public_state::PublicState, }, - types::type_serialisation::{ - field_serialisation::{FieldSerialisationMethods, FIELD_SERIALISED_LEN}, - TypeSerialisationInterface, + types::type_serialization::{ + field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN}, + TypeSerializationInterface, }, }; - use crate::asset::{ASSET_SERIALISED_LEN, Asset, AssetSerialisationMethods}; + use crate::asset::{ASSET_SERIALIZED_LEN, Asset, AssetSerializationMethods}; use crate::interest_math::compute_multiplier; use crate::helpers::{covered_by_collateral, DebtReturn, debt_updates, debt_value, compute_identifier}; use crate::interfaces::{Token, Lending, PriceFeed}; @@ -34,9 +34,9 @@ contract Lending { struct Storage { collateral_asset: PublicState, stable_coin: PublicState, - assets: Map>, - collateral: Map>, - static_debt: Map>, // abusing keys very heavily + assets: Map>, + collateral: Map>, + static_debt: Map>, // abusing keys very heavily } impl Storage { @@ -45,12 +45,12 @@ contract Lending { collateral_asset: PublicState::new( context, 1, - FieldSerialisationMethods, + FieldSerializationMethods, ), stable_coin: PublicState::new( context, 2, - FieldSerialisationMethods, + FieldSerializationMethods, ), assets: Map::new( context, @@ -59,7 +59,7 @@ contract Lending { PublicState::new( context, slot, - AssetSerialisationMethods, + AssetSerializationMethods, ) }, ), @@ -70,7 +70,7 @@ contract Lending { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), @@ -81,7 +81,7 @@ contract Lending { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), diff --git a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/interface.nr b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/interface.nr index 21be69b3a1f6..f81e987051a2 100644 --- a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/interface.nr +++ b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/interface.nr @@ -24,11 +24,11 @@ impl NonNativeTokenPrivateContextInterface { amount: Field, recipient: Field ) { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_public_function(self.address, 0x716a727f, serialised_args) + context.call_public_function(self.address, 0x716a727f, serialized_args) } @@ -41,14 +41,14 @@ impl NonNativeTokenPrivateContextInterface { secret: Field, canceller: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 5]; - serialised_args[0] = amount; - serialised_args[1] = owner; - serialised_args[2] = msg_key; - serialised_args[3] = secret; - serialised_args[4] = canceller; - - context.call_private_function(self.address, 0x641662d1, serialised_args) + let mut serialized_args = [0; 5]; + serialized_args[0] = amount; + serialized_args[1] = owner; + serialized_args[2] = msg_key; + serialized_args[3] = secret; + serialized_args[4] = canceller; + + context.call_private_function(self.address, 0x641662d1, serialized_args) } @@ -61,14 +61,14 @@ impl NonNativeTokenPrivateContextInterface { secret: Field, canceller: Field ) { - let mut serialised_args = [0; 5]; - serialised_args[0] = amount; - serialised_args[1] = owner_address; - serialised_args[2] = msg_key; - serialised_args[3] = secret; - serialised_args[4] = canceller; - - context.call_public_function(self.address, 0x93343cc1, serialised_args) + let mut serialized_args = [0; 5]; + serialized_args[0] = amount; + serialized_args[1] = owner_address; + serialized_args[2] = msg_key; + serialized_args[3] = secret; + serialized_args[4] = canceller; + + context.call_public_function(self.address, 0x93343cc1, serialized_args) } @@ -79,12 +79,12 @@ impl NonNativeTokenPrivateContextInterface { secret: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 3]; - serialised_args[0] = amount; - serialised_args[1] = secret; - serialised_args[2] = owner; + let mut serialized_args = [0; 3]; + serialized_args[0] = amount; + serialized_args[1] = secret; + serialized_args[2] = owner; - context.call_private_function(self.address, 0x8ecff612, serialised_args) + context.call_private_function(self.address, 0x8ecff612, serialized_args) } @@ -94,11 +94,11 @@ impl NonNativeTokenPrivateContextInterface { amount: Field, secretHash: Field ) { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0x72451161, serialised_args) + context.call_public_function(self.address, 0x72451161, serialized_args) } @@ -108,11 +108,11 @@ impl NonNativeTokenPrivateContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_private_function(self.address, 0xc0888d22, serialised_args) + context.call_private_function(self.address, 0xc0888d22, serialized_args) } @@ -122,11 +122,11 @@ impl NonNativeTokenPrivateContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_private_function(self.address, 0x906b1f4f, serialised_args) + context.call_private_function(self.address, 0x906b1f4f, serialized_args) } @@ -138,13 +138,13 @@ impl NonNativeTokenPrivateContextInterface { recipient: Field, callerOnL1: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 4]; - serialised_args[0] = amount; - serialised_args[1] = sender; - serialised_args[2] = recipient; - serialised_args[3] = callerOnL1; + let mut serialized_args = [0; 4]; + serialized_args[0] = amount; + serialized_args[1] = sender; + serialized_args[2] = recipient; + serialized_args[3] = callerOnL1; - context.call_private_function(self.address, 0x760d58ea, serialised_args) + context.call_private_function(self.address, 0x760d58ea, serialized_args) } @@ -155,12 +155,12 @@ impl NonNativeTokenPrivateContextInterface { recipient: Field, callerOnL1: Field ) { - let mut serialised_args = [0; 3]; - serialised_args[0] = amount; - serialised_args[1] = recipient; - serialised_args[2] = callerOnL1; + let mut serialized_args = [0; 3]; + serialized_args[0] = amount; + serialized_args[1] = recipient; + serialized_args[2] = callerOnL1; - context.call_public_function(self.address, 0xc80c80d3, serialised_args) + context.call_public_function(self.address, 0xc80c80d3, serialized_args) } } @@ -186,11 +186,11 @@ impl NonNativeTokenPublicContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_public_function(self.address, 0x716a727f, serialised_args) + context.call_public_function(self.address, 0x716a727f, serialized_args) } @@ -203,14 +203,14 @@ impl NonNativeTokenPublicContextInterface { secret: Field, canceller: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 5]; - serialised_args[0] = amount; - serialised_args[1] = owner_address; - serialised_args[2] = msg_key; - serialised_args[3] = secret; - serialised_args[4] = canceller; - - context.call_public_function(self.address, 0x93343cc1, serialised_args) + let mut serialized_args = [0; 5]; + serialized_args[0] = amount; + serialized_args[1] = owner_address; + serialized_args[2] = msg_key; + serialized_args[3] = secret; + serialized_args[4] = canceller; + + context.call_public_function(self.address, 0x93343cc1, serialized_args) } @@ -220,11 +220,11 @@ impl NonNativeTokenPublicContextInterface { amount: Field, secretHash: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0x72451161, serialised_args) + context.call_public_function(self.address, 0x72451161, serialized_args) } @@ -235,12 +235,12 @@ impl NonNativeTokenPublicContextInterface { recipient: Field, callerOnL1: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 3]; - serialised_args[0] = amount; - serialised_args[1] = recipient; - serialised_args[2] = callerOnL1; + let mut serialized_args = [0; 3]; + serialized_args[0] = amount; + serialized_args[1] = recipient; + serialized_args[2] = callerOnL1; - context.call_public_function(self.address, 0xc80c80d3, serialised_args) + context.call_public_function(self.address, 0xc80c80d3, serialized_args) } } diff --git a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr index 1f747faa89c3..8c27d3c39f4c 100644 --- a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/main.nr @@ -40,15 +40,15 @@ contract NonNativeToken { }, oracle::compute_selector::compute_selector, state_vars::{map::Map, public_state::PublicState, set::Set}, - types::type_serialisation::field_serialisation::{ - FieldSerialisationMethods, FIELD_SERIALISED_LEN, + types::type_serialization::field_serialization::{ + FieldSerializationMethods, FIELD_SERIALIZED_LEN, }, }; struct Storage { balances: Map>, pending_shields: Set, - public_balances: Map>, + public_balances: Map>, } impl Storage { @@ -69,7 +69,7 @@ contract NonNativeToken { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), diff --git a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/transparent_note.nr b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/transparent_note.nr index 5d2feef509c4..2c9bcbe2461a 100644 --- a/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/transparent_note.nr +++ b/yarn-project/noir-contracts/src/contracts/non_native_token_contract/src/transparent_note.nr @@ -14,7 +14,7 @@ global TRANSPARENT_NOTE_LEN: Field = 2; struct TransparentNote { amount: Field, secret_hash: Field, - // the fields below are not serialised/deserialised + // the fields below are not serialized/deserialized secret: Field, header: NoteHeader, } @@ -46,11 +46,11 @@ impl TransparentNote { // STANDARD NOTE_INTERFACE FUNCTIONS - fn serialise(self) -> [Field; TRANSPARENT_NOTE_LEN] { + fn serialize(self) -> [Field; TRANSPARENT_NOTE_LEN] { [self.amount, self.secret_hash] } - fn deserialise(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> Self { TransparentNote { amount: preimage[0], secret_hash: preimage[1], @@ -93,12 +93,12 @@ impl TransparentNote { } } -fn deserialise(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> TransparentNote { - TransparentNote::deserialise(preimage) +fn deserialize(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> TransparentNote { + TransparentNote::deserialize(preimage) } -fn serialise(note: TransparentNote) -> [Field; TRANSPARENT_NOTE_LEN] { - note.serialise() +fn serialize(note: TransparentNote) -> [Field; TRANSPARENT_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: TransparentNote) -> Field { @@ -118,8 +118,8 @@ fn set_header(note: &mut TransparentNote, header: NoteHeader) { } global TransparentNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/src/main.nr index 85525a264482..145712b5fb75 100644 --- a/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/pending_commitments_contract/src/main.nr @@ -67,7 +67,7 @@ contract PendingCommitments { context.inputs.call_context.storage_contract_address, owner_balance.storage_slot, get_public_key(owner), - note.serialise(), + note.serialize(), ); let options = NoteGetterOptions::with_filter(filter_notes_min_sum, amount); @@ -108,7 +108,7 @@ contract PendingCommitments { context.inputs.call_context.storage_contract_address, owner_balance.storage_slot, get_public_key(owner), - note.serialise(), + note.serialize(), ); 0 @@ -139,7 +139,7 @@ contract PendingCommitments { context.inputs.call_context.storage_contract_address, owner_balance.storage_slot, get_public_key(owner), - note.serialise(), + note.serialize(), ); } diff --git a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/address_note.nr b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/address_note.nr index 6801a040542b..e931dcb04d1f 100644 --- a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/address_note.nr +++ b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/address_note.nr @@ -18,7 +18,7 @@ impl AddressNote { } } - fn serialise(self) -> [Field; ADDRESS_NOTE_LEN] { + fn serialize(self) -> [Field; ADDRESS_NOTE_LEN] { let mut res: [Field; ADDRESS_NOTE_LEN] = [0; ADDRESS_NOTE_LEN]; res[0] = self.address; res @@ -40,20 +40,20 @@ impl AddressNote { } } -fn deserialise(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote { +fn deserialize(preimage: [Field; ADDRESS_NOTE_LEN]) -> AddressNote { AddressNote { address: preimage[0], header: NoteHeader::empty(), } } -fn serialise(note: AddressNote) -> [Field; ADDRESS_NOTE_LEN] { - note.serialise() +fn serialize(note: AddressNote) -> [Field; ADDRESS_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: AddressNote) -> Field { // TODO(#1205) Should use a non-zero generator index. - dep::std::hash::pedersen(note.serialise())[0] + dep::std::hash::pedersen(note.serialize())[0] } fn compute_nullifier(note: AddressNote) -> Field { @@ -69,8 +69,8 @@ fn set_header(note: &mut AddressNote, header: NoteHeader) { } global AddressNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/main.nr index 706c734d6025..7137c2920f64 100644 --- a/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/pokeable_token_contract/src/main.nr @@ -55,8 +55,8 @@ contract PokeableToken { let mut sender_note = AddressNote::new(sender); let mut recipient_note = AddressNote::new(recipient); - storage.sender.initialise(&mut sender_note); - storage.recipient.initialise(&mut recipient_note); + storage.sender.initialize(&mut sender_note); + storage.recipient.initialize(&mut recipient_note); // Insert new note to a set of user notes and emit the newly created encrypted note preimage via oracle call. let sender_balance = storage.balances.at(sender); diff --git a/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/asset.nr b/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/asset.nr index dc942b40d8ec..9686d74a28dc 100644 --- a/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/asset.nr +++ b/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/asset.nr @@ -1,28 +1,28 @@ -use dep::aztec::types::type_serialisation::TypeSerialisationInterface; +use dep::aztec::types::type_serialization::TypeSerializationInterface; struct Asset { price: u120, } -global ASSET_SERIALISED_LEN: Field = 1; +global ASSET_SERIALIZED_LEN: Field = 1; -fn deserialiseAsset(fields: [Field; ASSET_SERIALISED_LEN]) -> Asset { +fn deserializeAsset(fields: [Field; ASSET_SERIALIZED_LEN]) -> Asset { Asset { price: fields[0] as u120, } } -fn serialiseAsset(asset: Asset) -> [Field; ASSET_SERIALISED_LEN] { +fn serializeAsset(asset: Asset) -> [Field; ASSET_SERIALIZED_LEN] { [asset.price as Field] } impl Asset { - fn serialize(self: Self) -> [Field; ASSET_SERIALISED_LEN] { - serialiseAsset(self) + fn serialize(self: Self) -> [Field; ASSET_SERIALIZED_LEN] { + serializeAsset(self) } } -global AssetSerialisationMethods = TypeSerialisationInterface { - deserialise: deserialiseAsset, - serialise: serialiseAsset, +global AssetSerializationMethods = TypeSerializationInterface { + deserialize: deserializeAsset, + serialize: serializeAsset, }; diff --git a/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/main.nr index 6adea42406b6..565956e710bc 100644 --- a/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/price_feed_contract/src/main.nr @@ -9,11 +9,11 @@ contract PriceFeed { public_state::PublicState, }, }; - use crate::asset::{ASSET_SERIALISED_LEN, Asset, AssetSerialisationMethods}; + use crate::asset::{ASSET_SERIALIZED_LEN, Asset, AssetSerializationMethods}; // Storage structure, containing all storage, and specifying what slots they use. struct Storage { - assets: Map>, + assets: Map>, } impl Storage { @@ -26,7 +26,7 @@ contract PriceFeed { PublicState::new( context, slot, - AssetSerialisationMethods, + AssetSerializationMethods, ) }, ), diff --git a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/claim_note.nr b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/claim_note.nr index 49ed92e15b54..1126e4405806 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/claim_note.nr +++ b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/claim_note.nr @@ -22,11 +22,11 @@ impl ClaimNote { } } - fn serialise(self) -> [Field; CLAIM_NOTE_LEN] { + fn serialize(self) -> [Field; CLAIM_NOTE_LEN] { [self.value, self.secret_hash] } - fn deserialise(preimage: [Field; CLAIM_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; CLAIM_NOTE_LEN]) -> Self { ClaimNote { value: preimage[0], secret_hash: preimage[1], @@ -56,12 +56,12 @@ impl ClaimNote { } } -fn deserialise(preimage: [Field; CLAIM_NOTE_LEN]) -> ClaimNote { - ClaimNote::deserialise(preimage) +fn deserialize(preimage: [Field; CLAIM_NOTE_LEN]) -> ClaimNote { + ClaimNote::deserialize(preimage) } -fn serialise(note: ClaimNote) -> [Field; CLAIM_NOTE_LEN] { - note.serialise() +fn serialize(note: ClaimNote) -> [Field; CLAIM_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: ClaimNote) -> Field { @@ -81,8 +81,8 @@ fn set_header(note: &mut ClaimNote, header: NoteHeader) { } global ClaimNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr index 9581bbd11cb4..848c52b87abe 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr +++ b/yarn-project/noir-contracts/src/contracts/private_token_airdrop_contract/src/interface.nr @@ -26,17 +26,17 @@ impl PrivateTokenAirdropPrivateContextInterface { recipients: [Field;3], spend_note_offset: u32 ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 8]; - serialised_args[0] = sender; - serialised_args[1] = amounts[0]; - serialised_args[2] = amounts[1]; - serialised_args[3] = amounts[2]; - serialised_args[4] = recipients[0]; - serialised_args[5] = recipients[1]; - serialised_args[6] = recipients[2]; - serialised_args[7] = spend_note_offset as Field; - - context.call_private_function(self.address, 0xbf748730, serialised_args) + let mut serialized_args = [0; 8]; + serialized_args[0] = sender; + serialized_args[1] = amounts[0]; + serialized_args[2] = amounts[1]; + serialized_args[3] = amounts[2]; + serialized_args[4] = recipients[0]; + serialized_args[5] = recipients[1]; + serialized_args[6] = recipients[2]; + serialized_args[7] = spend_note_offset as Field; + + context.call_private_function(self.address, 0xbf748730, serialized_args) } @@ -46,11 +46,11 @@ impl PrivateTokenAirdropPrivateContextInterface { amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; - context.call_private_function(self.address, 0xa4fa3a6f, serialised_args) + context.call_private_function(self.address, 0xa4fa3a6f, serialized_args) } @@ -62,13 +62,13 @@ impl PrivateTokenAirdropPrivateContextInterface { owner: Field, nonce: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 4]; - serialised_args[0] = amount; - serialised_args[1] = secret; - serialised_args[2] = owner; - serialised_args[3] = nonce; + let mut serialized_args = [0; 4]; + serialized_args[0] = amount; + serialized_args[1] = secret; + serialized_args[2] = owner; + serialized_args[3] = nonce; - context.call_private_function(self.address, 0xa9220f0f, serialised_args) + context.call_private_function(self.address, 0xa9220f0f, serialized_args) } @@ -78,41 +78,41 @@ impl PrivateTokenAirdropPrivateContextInterface { amounts: [Field;16], secrets: [Field;16] ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 32]; - serialised_args[0] = amounts[0]; - serialised_args[1] = amounts[1]; - serialised_args[2] = amounts[2]; - serialised_args[3] = amounts[3]; - serialised_args[4] = amounts[4]; - serialised_args[5] = amounts[5]; - serialised_args[6] = amounts[6]; - serialised_args[7] = amounts[7]; - serialised_args[8] = amounts[8]; - serialised_args[9] = amounts[9]; - serialised_args[10] = amounts[10]; - serialised_args[11] = amounts[11]; - serialised_args[12] = amounts[12]; - serialised_args[13] = amounts[13]; - serialised_args[14] = amounts[14]; - serialised_args[15] = amounts[15]; - serialised_args[16] = secrets[0]; - serialised_args[17] = secrets[1]; - serialised_args[18] = secrets[2]; - serialised_args[19] = secrets[3]; - serialised_args[20] = secrets[4]; - serialised_args[21] = secrets[5]; - serialised_args[22] = secrets[6]; - serialised_args[23] = secrets[7]; - serialised_args[24] = secrets[8]; - serialised_args[25] = secrets[9]; - serialised_args[26] = secrets[10]; - serialised_args[27] = secrets[11]; - serialised_args[28] = secrets[12]; - serialised_args[29] = secrets[13]; - serialised_args[30] = secrets[14]; - serialised_args[31] = secrets[15]; - - context.call_private_function(self.address, 0x2eebe7ab, serialised_args) + let mut serialized_args = [0; 32]; + serialized_args[0] = amounts[0]; + serialized_args[1] = amounts[1]; + serialized_args[2] = amounts[2]; + serialized_args[3] = amounts[3]; + serialized_args[4] = amounts[4]; + serialized_args[5] = amounts[5]; + serialized_args[6] = amounts[6]; + serialized_args[7] = amounts[7]; + serialized_args[8] = amounts[8]; + serialized_args[9] = amounts[9]; + serialized_args[10] = amounts[10]; + serialized_args[11] = amounts[11]; + serialized_args[12] = amounts[12]; + serialized_args[13] = amounts[13]; + serialized_args[14] = amounts[14]; + serialized_args[15] = amounts[15]; + serialized_args[16] = secrets[0]; + serialized_args[17] = secrets[1]; + serialized_args[18] = secrets[2]; + serialized_args[19] = secrets[3]; + serialized_args[20] = secrets[4]; + serialized_args[21] = secrets[5]; + serialized_args[22] = secrets[6]; + serialized_args[23] = secrets[7]; + serialized_args[24] = secrets[8]; + serialized_args[25] = secrets[9]; + serialized_args[26] = secrets[10]; + serialized_args[27] = secrets[11]; + serialized_args[28] = secrets[12]; + serialized_args[29] = secrets[13]; + serialized_args[30] = secrets[14]; + serialized_args[31] = secrets[15]; + + context.call_private_function(self.address, 0x2eebe7ab, serialized_args) } @@ -122,11 +122,11 @@ impl PrivateTokenAirdropPrivateContextInterface { amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; - context.call_private_function(self.address, 0x1535439c, serialised_args) + context.call_private_function(self.address, 0x1535439c, serialized_args) } @@ -136,11 +136,11 @@ impl PrivateTokenAirdropPrivateContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_private_function(self.address, 0xc0888d22, serialised_args) + context.call_private_function(self.address, 0xc0888d22, serialized_args) } } diff --git a/yarn-project/noir-contracts/src/contracts/private_token_contract/src/interface.nr b/yarn-project/noir-contracts/src/contracts/private_token_contract/src/interface.nr index 1eee266adcb8..0f59f541a245 100644 --- a/yarn-project/noir-contracts/src/contracts/private_token_contract/src/interface.nr +++ b/yarn-project/noir-contracts/src/contracts/private_token_contract/src/interface.nr @@ -24,11 +24,11 @@ impl PrivateTokenPrivateContextInterface { amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; - context.call_private_function(self.address, 0x1535439c, serialised_args) + context.call_private_function(self.address, 0x1535439c, serialized_args) } @@ -38,11 +38,11 @@ impl PrivateTokenPrivateContextInterface { amount: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = recipient; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = recipient; - context.call_private_function(self.address, 0xc0888d22, serialised_args) + context.call_private_function(self.address, 0xc0888d22, serialized_args) } } diff --git a/yarn-project/noir-contracts/src/contracts/public_token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/public_token_contract/src/main.nr index 37ef09b7cb13..3b0babfb684e 100644 --- a/yarn-project/noir-contracts/src/contracts/public_token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/public_token_contract/src/main.nr @@ -12,13 +12,13 @@ contract PublicToken { map::Map, public_state::PublicState, }, - types::type_serialisation::field_serialisation::{ - FieldSerialisationMethods, FIELD_SERIALISED_LEN, + types::type_serialization::field_serialization::{ + FieldSerializationMethods, FIELD_SERIALIZED_LEN, }, }; struct Storage { - balances: Map>, + balances: Map>, } impl Storage { @@ -28,7 +28,7 @@ contract PublicToken { context, 1, |context, slot| { - PublicState::new(context, slot, FieldSerialisationMethods) + PublicState::new(context, slot, FieldSerializationMethods) }, ), } diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/main.nr index b20379efa5fe..a26d6fe6de19 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/main.nr @@ -41,14 +41,14 @@ contract SchnorrAccount { let this = context.this_address(); let mut pub_key_note = PublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this); - storage.signing_public_key.initialise(&mut pub_key_note); + storage.signing_public_key.initialize(&mut pub_key_note); emit_encrypted_log( &mut context, this, storage.signing_public_key.storage_slot, get_public_key(this), - pub_key_note.serialise(), + pub_key_note.serialize(), ); } diff --git a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/public_key_note.nr b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/public_key_note.nr index 771ca860327e..ceb64ac8cb42 100644 --- a/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/public_key_note.nr +++ b/yarn-project/noir-contracts/src/contracts/schnorr_account_contract/src/public_key_note.nr @@ -24,8 +24,8 @@ impl PublicKeyNote { } } - // Serialise the note as 3 fields - fn serialise(self) -> [Field; PUBLIC_KEY_NOTE_LEN] { + // serialize the note as 3 fields + fn serialize(self) -> [Field; PUBLIC_KEY_NOTE_LEN] { [self.x, self.y, self.owner] } @@ -45,7 +45,7 @@ impl PublicKeyNote { } } -fn deserialise(preimage: [Field; PUBLIC_KEY_NOTE_LEN]) -> PublicKeyNote { +fn deserialize(preimage: [Field; PUBLIC_KEY_NOTE_LEN]) -> PublicKeyNote { PublicKeyNote { x: preimage[0], y: preimage[1], @@ -54,13 +54,13 @@ fn deserialise(preimage: [Field; PUBLIC_KEY_NOTE_LEN]) -> PublicKeyNote { } } -fn serialise(note: PublicKeyNote) -> [Field; PUBLIC_KEY_NOTE_LEN] { - note.serialise() +fn serialize(note: PublicKeyNote) -> [Field; PUBLIC_KEY_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: PublicKeyNote) -> Field { // TODO(#1205) Should use a non-zero generator index. - dep::std::hash::pedersen(note.serialise())[0] + dep::std::hash::pedersen(note.serialize())[0] } fn compute_nullifier(note: PublicKeyNote) -> Field { @@ -76,8 +76,8 @@ fn set_header(note: &mut PublicKeyNote, header: NoteHeader) { } global PublicKeyNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/noir-contracts/src/contracts/stateful_test_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/stateful_test_contract/src/main.nr index e8bb13a2a662..56bb4634532c 100644 --- a/yarn-project/noir-contracts/src/contracts/stateful_test_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/stateful_test_contract/src/main.nr @@ -13,14 +13,14 @@ contract StatefulTest { utils as note_utils, }, state_vars::{map::Map, public_state::PublicState, set::Set}, - types::type_serialisation::field_serialisation::{ - FieldSerialisationMethods, FIELD_SERIALISED_LEN, + types::type_serialization::field_serialization::{ + FieldSerializationMethods, FIELD_SERIALIZED_LEN, }, }; struct Storage { notes: Map>, - public_values: Map>, + public_values: Map>, } impl Storage { @@ -40,7 +40,7 @@ contract StatefulTest { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), diff --git a/yarn-project/noir-contracts/src/contracts/test_contract/src/interface.nr b/yarn-project/noir-contracts/src/contracts/test_contract/src/interface.nr index 1a11db0ac4f4..e5e6ab61f647 100644 --- a/yarn-project/noir-contracts/src/contracts/test_contract/src/interface.nr +++ b/yarn-project/noir-contracts/src/contracts/test_contract/src/interface.nr @@ -45,11 +45,11 @@ impl TestPrivateContextInterface { amount: Field, secretHash: Field ) { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0xbac98727, serialised_args) + context.call_public_function(self.address, 0xbac98727, serialized_args) } @@ -59,11 +59,11 @@ impl TestPrivateContextInterface { amount: Field, secretHash: Field ) { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0x42040a24, serialised_args) + context.call_public_function(self.address, 0x42040a24, serialized_args) } @@ -72,10 +72,10 @@ impl TestPrivateContextInterface { context: &mut PrivateContext, value: Field ) { - let mut serialised_args = [0; 1]; - serialised_args[0] = value; + let mut serialized_args = [0; 1]; + serialized_args[0] = value; - context.call_public_function(self.address, 0x817a64cb, serialised_args) + context.call_public_function(self.address, 0x817a64cb, serialized_args) } @@ -84,10 +84,10 @@ impl TestPrivateContextInterface { context: &mut PrivateContext, aztec_address: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = aztec_address; + let mut serialized_args = [0; 1]; + serialized_args[0] = aztec_address; - context.call_private_function(self.address, 0xaf15a45f, serialised_args) + context.call_private_function(self.address, 0xaf15a45f, serialized_args) } @@ -96,10 +96,10 @@ impl TestPrivateContextInterface { context: &mut PrivateContext, address: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = address; + let mut serialized_args = [0; 1]; + serialized_args[0] = address; - context.call_private_function(self.address, 0x88f0753b, serialised_args) + context.call_private_function(self.address, 0x88f0753b, serialized_args) } @@ -107,9 +107,9 @@ impl TestPrivateContextInterface { self, context: &mut PrivateContext ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 0]; + let mut serialized_args = [0; 0]; - context.call_private_function(self.address, 0xd3953822, serialised_args) + context.call_private_function(self.address, 0xd3953822, serialized_args) } @@ -117,9 +117,9 @@ impl TestPrivateContextInterface { self, context: &mut PrivateContext ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 0]; + let mut serialized_args = [0; 0]; - context.call_private_function(self.address, 0x82cc9431, serialised_args) + context.call_private_function(self.address, 0x82cc9431, serialized_args) } @@ -128,10 +128,10 @@ impl TestPrivateContextInterface { context: &mut PrivateContext, time: Field ) { - let mut serialised_args = [0; 1]; - serialised_args[0] = time; + let mut serialized_args = [0; 1]; + serialized_args[0] = time; - context.call_public_function(self.address, 0xfff6026c, serialised_args) + context.call_public_function(self.address, 0xfff6026c, serialized_args) } @@ -145,26 +145,26 @@ impl TestPrivateContextInterface { aStruct: AStructTestCodeGenStruct, aDeepStruct: ADeepStructTestCodeGenStruct ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 17]; - serialised_args[0] = aField; - serialised_args[1] = aBool as Field; - serialised_args[2] = aNumber as Field; - serialised_args[3] = anArray[0]; - serialised_args[4] = anArray[1]; - serialised_args[5] = aStruct.amount; - serialised_args[6] = aStruct.secretHash; - serialised_args[7] = aDeepStruct.aField; - serialised_args[8] = aDeepStruct.aBool as Field; - serialised_args[9] = aDeepStruct.aNote.amount; - serialised_args[10] = aDeepStruct.aNote.secretHash; - serialised_args[11] = aDeepStruct.manyNotes[0].amount; - serialised_args[12] = aDeepStruct.manyNotes[0].secretHash; - serialised_args[13] = aDeepStruct.manyNotes[1].amount; - serialised_args[14] = aDeepStruct.manyNotes[1].secretHash; - serialised_args[15] = aDeepStruct.manyNotes[2].amount; - serialised_args[16] = aDeepStruct.manyNotes[2].secretHash; - - context.call_private_function(self.address, 0x81d7c118, serialised_args) + let mut serialized_args = [0; 17]; + serialized_args[0] = aField; + serialized_args[1] = aBool as Field; + serialized_args[2] = aNumber as Field; + serialized_args[3] = anArray[0]; + serialized_args[4] = anArray[1]; + serialized_args[5] = aStruct.amount; + serialized_args[6] = aStruct.secretHash; + serialized_args[7] = aDeepStruct.aField; + serialized_args[8] = aDeepStruct.aBool as Field; + serialized_args[9] = aDeepStruct.aNote.amount; + serialized_args[10] = aDeepStruct.aNote.secretHash; + serialized_args[11] = aDeepStruct.manyNotes[0].amount; + serialized_args[12] = aDeepStruct.manyNotes[0].secretHash; + serialized_args[13] = aDeepStruct.manyNotes[1].amount; + serialized_args[14] = aDeepStruct.manyNotes[1].secretHash; + serialized_args[15] = aDeepStruct.manyNotes[2].amount; + serialized_args[16] = aDeepStruct.manyNotes[2].secretHash; + + context.call_private_function(self.address, 0x81d7c118, serialized_args) } } @@ -190,11 +190,11 @@ impl TestPublicContextInterface { amount: Field, secretHash: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0xbac98727, serialised_args) + context.call_public_function(self.address, 0xbac98727, serialized_args) } @@ -204,11 +204,11 @@ impl TestPublicContextInterface { amount: Field, secretHash: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = secretHash; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = secretHash; - context.call_public_function(self.address, 0x42040a24, serialised_args) + context.call_public_function(self.address, 0x42040a24, serialized_args) } @@ -217,10 +217,10 @@ impl TestPublicContextInterface { context: PublicContext, value: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = value; + let mut serialized_args = [0; 1]; + serialized_args[0] = value; - context.call_public_function(self.address, 0x817a64cb, serialised_args) + context.call_public_function(self.address, 0x817a64cb, serialized_args) } @@ -229,10 +229,10 @@ impl TestPublicContextInterface { context: PublicContext, time: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 1]; - serialised_args[0] = time; + let mut serialized_args = [0; 1]; + serialized_args[0] = time; - context.call_public_function(self.address, 0xfff6026c, serialised_args) + context.call_public_function(self.address, 0xfff6026c, serialized_args) } } diff --git a/yarn-project/noir-contracts/src/contracts/token_bridge_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/token_bridge_contract/src/main.nr index 0b32db5f7275..b760403b04a8 100644 --- a/yarn-project/noir-contracts/src/contracts/token_bridge_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/token_bridge_contract/src/main.nr @@ -10,8 +10,8 @@ contract TokenBridge { use dep::aztec::{ context::{Context}, state_vars::{public_state::PublicState}, - types::type_serialisation::field_serialisation::{ - FieldSerialisationMethods, FIELD_SERIALISED_LEN, + types::type_serialization::field_serialization::{ + FieldSerializationMethods, FIELD_SERIALIZED_LEN, }, types::address::{AztecAddress, EthereumAddress}, oracle::compute_selector::compute_selector, @@ -31,7 +31,7 @@ contract TokenBridge { token: PublicState::new( context, 1, - FieldSerialisationMethods, + FieldSerializationMethods, ), } } diff --git a/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr index 5bdd2bfbb68d..7b67527fd689 100644 --- a/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr +++ b/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr @@ -29,8 +29,8 @@ contract Token { }, context::{PrivateContext, PublicContext, Context}, state_vars::{map::Map, public_state::PublicState, set::Set}, - types::type_serialisation::field_serialisation::{ - FieldSerialisationMethods, FIELD_SERIALISED_LEN, + types::type_serialization::field_serialization::{ + FieldSerializationMethods, FIELD_SERIALIZED_LEN, }, types::address::{AztecAddress}, oracle::compute_selector::compute_selector, @@ -43,12 +43,12 @@ contract Token { // docs:start:storage_struct struct Storage { - admin: PublicState, - minters: Map>, + admin: PublicState, + minters: Map>, balances: Map>, - total_supply: PublicState, + total_supply: PublicState, pending_shields: Set, - public_balances: Map>, + public_balances: Map>, } // docs:end:storage_struct @@ -59,7 +59,7 @@ contract Token { admin: PublicState::new( context, 1, - FieldSerialisationMethods, + FieldSerializationMethods, ), minters: Map::new( context, @@ -68,7 +68,7 @@ contract Token { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), @@ -82,7 +82,7 @@ contract Token { total_supply: PublicState::new( context, 4, - FieldSerialisationMethods, + FieldSerializationMethods, ), pending_shields: Set::new(context, 5, TransparentNoteMethods), public_balances: Map::new( @@ -92,7 +92,7 @@ contract Token { PublicState::new( context, slot, - FieldSerialisationMethods, + FieldSerializationMethods, ) }, ), diff --git a/yarn-project/noir-contracts/src/contracts/token_contract/src/types.nr b/yarn-project/noir-contracts/src/contracts/token_contract/src/types.nr index 438f7ab53d41..8b7e250cec94 100644 --- a/yarn-project/noir-contracts/src/contracts/token_contract/src/types.nr +++ b/yarn-project/noir-contracts/src/contracts/token_contract/src/types.nr @@ -16,7 +16,7 @@ global TRANSPARENT_NOTE_LEN: Field = 2; struct TransparentNote { amount: Field, secret_hash: Field, - // the fields below are not serialised/deserialised + // the fields below are not serialized/deserialized secret: Field, header: NoteHeader, } @@ -48,11 +48,11 @@ impl TransparentNote { // STANDARD NOTE_INTERFACE FUNCTIONS - fn serialise(self) -> [Field; TRANSPARENT_NOTE_LEN] { + fn serialize(self) -> [Field; TRANSPARENT_NOTE_LEN] { [self.amount, self.secret_hash] } - fn deserialise(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> Self { + fn deserialize(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> Self { TransparentNote { amount: preimage[0], secret_hash: preimage[1], @@ -95,12 +95,12 @@ impl TransparentNote { } } -fn deserialise(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> TransparentNote { - TransparentNote::deserialise(preimage) +fn deserialize(preimage: [Field; TRANSPARENT_NOTE_LEN]) -> TransparentNote { + TransparentNote::deserialize(preimage) } -fn serialise(note: TransparentNote) -> [Field; TRANSPARENT_NOTE_LEN] { - note.serialise() +fn serialize(note: TransparentNote) -> [Field; TRANSPARENT_NOTE_LEN] { + note.serialize() } fn compute_note_hash(note: TransparentNote) -> Field { @@ -120,8 +120,8 @@ fn set_header(note: &mut TransparentNote, header: NoteHeader) { } global TransparentNoteMethods = NoteInterface { - deserialise, - serialise, + deserialize, + serialize, compute_note_hash, compute_nullifier, get_header, diff --git a/yarn-project/p2p/src/service/tx_messages.test.ts b/yarn-project/p2p/src/service/tx_messages.test.ts index 80dc2eac3331..cdbc0dc63538 100644 --- a/yarn-project/p2p/src/service/tx_messages.test.ts +++ b/yarn-project/p2p/src/service/tx_messages.test.ts @@ -32,14 +32,14 @@ const verifyTx = (actual: Tx, expected: Tx) => { }; describe('Messages', () => { - it('Correctly serialises and deserialises a single private transaction', () => { + it('Correctly serializes and deserializes a single private transaction', () => { const transaction = mockTx(); const message = toTxMessage(transaction); const decodedTransaction = fromTxMessage(message); verifyTx(decodedTransaction, transaction); }); - it('Correctly serialises and deserialises transactions messages', () => { + it('Correctly serializes and deserializes transactions messages', () => { const privateTransactions = [mockTx(), mockTx(), mockTx()]; const message = createTransactionsMessage(privateTransactions); expect(decodeMessageType(message)).toBe(Messages.POOLED_TRANSACTIONS); @@ -49,7 +49,7 @@ describe('Messages', () => { verifyTx(decodedTransactions[2], privateTransactions[2]); }); - it('Correctly serialises and deserialises transaction hashes message', () => { + it('Correctly serializes and deserializes transaction hashes message', () => { const txHashes = [makeTxHash(), makeTxHash(), makeTxHash()]; const message = createTransactionHashesMessage(txHashes); expect(decodeMessageType(message)).toEqual(Messages.POOLED_TRANSACTION_HASHES); @@ -57,7 +57,7 @@ describe('Messages', () => { expect(decodedHashes.map(x => x.toString())).toEqual(txHashes.map(x => x.toString())); }); - it('Correctly serialises and deserialises get transactions message', () => { + it('Correctly serializes and deserializes get transactions message', () => { const txHashes = [makeTxHash(), makeTxHash(), makeTxHash()]; const message = createGetTransactionsRequestMessage(txHashes); expect(decodeMessageType(message)).toEqual(Messages.GET_TRANSACTIONS); diff --git a/yarn-project/sequencer-client/README.md b/yarn-project/sequencer-client/README.md index d45011cd9402..de825e7078ee 100644 --- a/yarn-project/sequencer-client/README.md +++ b/yarn-project/sequencer-client/README.md @@ -2,7 +2,7 @@ The sequencer is a module responsible for creating and publishing new rollup blocks. This involves fetching txs from the P2P pool, ordering them, executing any public functions, running them through the rollup circuits, assembling the L2 block, and posting it to the L1 rollup contract along with any contract deployment public data. -The client itself is implemented as a continuous loop. After being started, it polls the P2P pool for new txs, assembles a new block if any is found, and goes back to sleep. On every new block assembled, it modifies the world state database to reflect the txs processed, but these changes are only committed once the world state synchroniser sees the new block on L1. +The client itself is implemented as a continuous loop. After being started, it polls the P2P pool for new txs, assembles a new block if any is found, and goes back to sleep. On every new block assembled, it modifies the world state database to reflect the txs processed, but these changes are only committed once the world state synchronizer sees the new block on L1. ## Components diff --git a/yarn-project/sequencer-client/src/client/sequencer-client.ts b/yarn-project/sequencer-client/src/client/sequencer-client.ts index 47d9b976df74..d049b30dc3e0 100644 --- a/yarn-project/sequencer-client/src/client/sequencer-client.ts +++ b/yarn-project/sequencer-client/src/client/sequencer-client.ts @@ -1,6 +1,6 @@ import { P2P } from '@aztec/p2p'; import { ContractDataSource, L1ToL2MessageSource, L2BlockSource } from '@aztec/types'; -import { WorldStateSynchroniser } from '@aztec/world-state'; +import { WorldStateSynchronizer } from '@aztec/world-state'; import { SoloBlockBuilder } from '../block_builder/solo_block_builder.js'; import { SequencerClientConfig } from '../config.js'; @@ -20,7 +20,7 @@ export class SequencerClient { * Initializes and starts a new instance. * @param config - Configuration for the sequencer, publisher, and L1 tx sender. * @param p2pClient - P2P client that provides the txs to be sequenced. - * @param worldStateSynchroniser - Provides access to world state. + * @param worldStateSynchronizer - Provides access to world state. * @param contractDataSource - Provides access to contract bytecode for public executions. * @param l2BlockSource - Provides information about the previously published blocks. * @param l1ToL2MessageSource - Provides access to L1 to L2 messages. @@ -29,14 +29,14 @@ export class SequencerClient { public static async new( config: SequencerClientConfig, p2pClient: P2P, - worldStateSynchroniser: WorldStateSynchroniser, + worldStateSynchronizer: WorldStateSynchronizer, contractDataSource: ContractDataSource, l2BlockSource: L2BlockSource, l1ToL2MessageSource: L1ToL2MessageSource, ) { const publisher = getL1Publisher(config); const globalsBuilder = getGlobalVariableBuilder(config); - const merkleTreeDb = worldStateSynchroniser.getLatest(); + const merkleTreeDb = worldStateSynchronizer.getLatest(); const blockBuilder = new SoloBlockBuilder( merkleTreeDb, @@ -51,7 +51,7 @@ export class SequencerClient { publisher, globalsBuilder, p2pClient, - worldStateSynchroniser, + worldStateSynchronizer, blockBuilder, l2BlockSource, l1ToL2MessageSource, diff --git a/yarn-project/sequencer-client/src/sequencer/sequencer.test.ts b/yarn-project/sequencer-client/src/sequencer/sequencer.test.ts index 4d8483ee7a1e..1f1c76cc2acb 100644 --- a/yarn-project/sequencer-client/src/sequencer/sequencer.test.ts +++ b/yarn-project/sequencer-client/src/sequencer/sequencer.test.ts @@ -7,7 +7,7 @@ import { } from '@aztec/circuits.js'; import { P2P, P2PClientState } from '@aztec/p2p'; import { L1ToL2MessageSource, L2Block, L2BlockSource, MerkleTreeId, Tx, TxHash, mockTx } from '@aztec/types'; -import { MerkleTreeOperations, WorldStateRunningState, WorldStateSynchroniser } from '@aztec/world-state'; +import { MerkleTreeOperations, WorldStateRunningState, WorldStateSynchronizer } from '@aztec/world-state'; import { MockProxy, mock } from 'jest-mock-extended'; import times from 'lodash.times'; @@ -23,7 +23,7 @@ describe('sequencer', () => { let publisher: MockProxy; let globalVariableBuilder: MockProxy; let p2p: MockProxy; - let worldState: MockProxy; + let worldState: MockProxy; let blockBuilder: MockProxy; let merkleTreeOps: MockProxy; let publicProcessor: MockProxy; @@ -50,7 +50,7 @@ describe('sequencer', () => { getStatus: () => Promise.resolve({ state: P2PClientState.IDLE, syncedToL2Block: lastBlockNumber }), }); - worldState = mock({ + worldState = mock({ getLatest: () => merkleTreeOps, status: () => Promise.resolve({ state: WorldStateRunningState.IDLE, syncedToL2Block: lastBlockNumber }), }); diff --git a/yarn-project/sequencer-client/src/sequencer/sequencer.ts b/yarn-project/sequencer-client/src/sequencer/sequencer.ts index 083df1ac5a27..e51a0d9595bc 100644 --- a/yarn-project/sequencer-client/src/sequencer/sequencer.ts +++ b/yarn-project/sequencer-client/src/sequencer/sequencer.ts @@ -4,7 +4,7 @@ import { createDebugLogger } from '@aztec/foundation/log'; import { RunningPromise } from '@aztec/foundation/running-promise'; import { P2P } from '@aztec/p2p'; import { L1ToL2MessageSource, L2Block, L2BlockSource, MerkleTreeId, Tx } from '@aztec/types'; -import { WorldStateStatus, WorldStateSynchroniser } from '@aztec/world-state'; +import { WorldStateStatus, WorldStateSynchronizer } from '@aztec/world-state'; import times from 'lodash.times'; @@ -18,7 +18,7 @@ import { PublicProcessorFactory } from './public_processor.js'; /** * Sequencer client - * - Wins a period of time to become the sequencer (depending on finalised protocol). + * - Wins a period of time to become the sequencer (depending on finalized protocol). * - Chooses a set of txs from the tx pool to be in the rollup. * - Simulate the rollup of txs. * - Adds proof requests to the request pool (not for this milestone). @@ -39,7 +39,7 @@ export class Sequencer { private publisher: L1Publisher, private globalsBuilder: GlobalVariableBuilder, private p2pClient: P2P, - private worldState: WorldStateSynchroniser, + private worldState: WorldStateSynchronizer, private blockBuilder: BlockBuilder, private l2BlockSource: L2BlockSource, private l1ToL2MessageSource: L1ToL2MessageSource, diff --git a/yarn-project/types/src/interfaces/aztec_rpc.ts b/yarn-project/types/src/interfaces/aztec_rpc.ts index 0a5d1fdddd96..d362e4fc7289 100644 --- a/yarn-project/types/src/interfaces/aztec_rpc.ts +++ b/yarn-project/types/src/interfaces/aztec_rpc.ts @@ -34,7 +34,7 @@ export interface AztecRPC { * * @param authWitness - The auth witness to insert. Composed of an identifier, which is the hash of * the action to be authorised, and the actual witness as an array of fields, which are to be - * deserialised and processed by the account contract. + * deserialized and processed by the account contract. */ addAuthWitness(authWitness: AuthWitness): Promise; @@ -232,23 +232,23 @@ export interface AztecRPC { * @remarks This indicates that blocks and transactions are synched even if notes are not. Compares local block number with the block number from aztec node. * @deprecated Use `getSyncStatus` instead. */ - isGlobalStateSynchronised(): Promise; + isGlobalStateSynchronized(): Promise; /** - * Checks if the specified account is synchronised. + * Checks if the specified account is synchronized. * @param account - The aztec address for which to query the sync status. * @returns True if the account is fully synched, false otherwise. * @deprecated Use `getSyncStatus` instead. * @remarks Checks whether all the notes from all the blocks have been processed. If it is not the case, the * retrieved information from contracts might be old/stale (e.g. old token balance). */ - isAccountStateSynchronised(account: AztecAddress): Promise; + isAccountStateSynchronized(account: AztecAddress): Promise; /** - * Returns the latest block that has been synchronised globally and for each account. The global block number + * Returns the latest block that has been synchronized globally and for each account. The global block number * indicates whether global state has been updated up to that block, whereas each address indicates up to which * block the private state has been synced for that account. - * @returns The latest block synchronised for blocks, and the latest block synched for notes for each public key being tracked. + * @returns The latest block synchronized for blocks, and the latest block synched for notes for each public key being tracked. */ getSyncStatus(): Promise; } diff --git a/yarn-project/types/src/logs/l2_block_l2_logs.test.ts b/yarn-project/types/src/logs/l2_block_l2_logs.test.ts index 755ab366e3e2..d3a231c347f1 100644 --- a/yarn-project/types/src/logs/l2_block_l2_logs.test.ts +++ b/yarn-project/types/src/logs/l2_block_l2_logs.test.ts @@ -19,7 +19,7 @@ describe('L2BlockL2Logs', () => { expect(recovered.getSerializedLength()).toEqual(buffer.length); }); - it('serialises to and from JSON', () => { + it('serializes to and from JSON', () => { const l2Logs = L2BlockL2Logs.random(3, 6, 2); const json = l2Logs.toJSON(); const recovered = L2BlockL2Logs.fromJSON(json); diff --git a/yarn-project/types/src/tx_execution_request.ts b/yarn-project/types/src/tx_execution_request.ts index 890314339ea2..f9abc90104b5 100644 --- a/yarn-project/types/src/tx_execution_request.ts +++ b/yarn-project/types/src/tx_execution_request.ts @@ -83,7 +83,7 @@ export class TxExecutionRequest { /** * Deserializes from a buffer or reader, corresponding to a write in cpp. * @param buffer - Buffer to read from. - * @returns The deserialised TxRequest object. + * @returns The deserialized TxRequest object. */ static fromBuffer(buffer: Buffer | BufferReader): TxExecutionRequest { const reader = BufferReader.asReader(buffer); @@ -100,7 +100,7 @@ export class TxExecutionRequest { /** * Deserializes from a string, corresponding to a write in cpp. * @param str - String to read from. - * @returns The deserialised TxRequest object. + * @returns The deserialized TxRequest object. */ static fromString(str: string): TxExecutionRequest { return TxExecutionRequest.fromBuffer(Buffer.from(str, 'hex')); diff --git a/yarn-project/world-state/README.md b/yarn-project/world-state/README.md index 86b16783bf62..b8704e8c54b9 100644 --- a/yarn-project/world-state/README.md +++ b/yarn-project/world-state/README.md @@ -23,11 +23,11 @@ As of the time of writing the collection consisted of the following trees. - The Public Data Tree. A tree whose leaves are the current value of every item of public state in the system, addressed as `leaf_index = hash(contract_address, storage_slot_in_contract)` -### The Synchroniser +### The Synchronizer -The synchroniser's role is to periodically poll for new block information and reconcile that information with the current state of the Merkle Trees. +The synchronizer's role is to periodically poll for new block information and reconcile that information with the current state of the Merkle Trees. -Once a new block is received, the synchroniser checks the uncommitted root values of all of the trees against the roots published as part of the block. If they are all equal, the tree state is committed. If they are not equal, the tree states are rolled back to the last committed state before the published data is inserted and committed. +Once a new block is received, the synchronizer checks the uncommitted root values of all of the trees against the roots published as part of the block. If they are all equal, the tree state is committed. If they are not equal, the tree states are rolled back to the last committed state before the published data is inserted and committed. ### The Merkle Tree Interface diff --git a/yarn-project/world-state/src/index.ts b/yarn-project/world-state/src/index.ts index b373fe2a0248..b0b168e54e52 100644 --- a/yarn-project/world-state/src/index.ts +++ b/yarn-project/world-state/src/index.ts @@ -1,4 +1,4 @@ -export * from './synchroniser/index.js'; +export * from './synchronizer/index.js'; export * from './world-state-db/index.js'; export * from './utils.js'; -export * from './synchroniser/config.js'; +export * from './synchronizer/config.js'; diff --git a/yarn-project/world-state/src/synchroniser/index.ts b/yarn-project/world-state/src/synchroniser/index.ts deleted file mode 100644 index b875061d458c..000000000000 --- a/yarn-project/world-state/src/synchroniser/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './server_world_state_synchroniser.js'; -export * from './world_state_synchroniser.js'; diff --git a/yarn-project/world-state/src/synchroniser/config.ts b/yarn-project/world-state/src/synchronizer/config.ts similarity index 91% rename from yarn-project/world-state/src/synchroniser/config.ts rename to yarn-project/world-state/src/synchronizer/config.ts index 0c0e7a5718dd..5d42930d5b7a 100644 --- a/yarn-project/world-state/src/synchroniser/config.ts +++ b/yarn-project/world-state/src/synchronizer/config.ts @@ -1,5 +1,5 @@ /** - * World State synchroniser configuration values. + * World State synchronizer configuration values. */ export interface WorldStateConfig { /** @@ -14,8 +14,8 @@ export interface WorldStateConfig { } /** - * Returns the configuration values for the world state synchroniser. - * @returns The configuration values for the world state synchroniser. + * Returns the configuration values for the world state synchronizer. + * @returns The configuration values for the world state synchronizer. */ export function getConfigEnvVars(): WorldStateConfig { const { WS_BLOCK_CHECK_INTERVAL_MS, WS_L2_BLOCK_QUEUE_SIZE } = process.env; diff --git a/yarn-project/world-state/src/synchronizer/index.ts b/yarn-project/world-state/src/synchronizer/index.ts new file mode 100644 index 000000000000..c0c744ca7f90 --- /dev/null +++ b/yarn-project/world-state/src/synchronizer/index.ts @@ -0,0 +1,2 @@ +export * from './server_world_state_synchronizer.js'; +export * from './world_state_synchronizer.js'; diff --git a/yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.test.ts b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.test.ts similarity index 91% rename from yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.test.ts rename to yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.test.ts index d4fafd16e3d6..c45e00903a1d 100644 --- a/yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.test.ts +++ b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.test.ts @@ -27,8 +27,8 @@ import { jest } from '@jest/globals'; import times from 'lodash.times'; import { MerkleTreeDb, MerkleTrees, WorldStateConfig } from '../index.js'; -import { ServerWorldStateSynchroniser } from './server_world_state_synchroniser.js'; -import { WorldStateRunningState } from './world_state_synchroniser.js'; +import { ServerWorldStateSynchronizer } from './server_world_state_synchronizer.js'; +import { WorldStateRunningState } from './world_state_synchronizer.js'; /** * Generic mock implementation. @@ -96,17 +96,17 @@ const getMockBlock = (blockNumber: number, newContractsCommitments?: Buffer[]) = return block; }; -const createSynchroniser = (merkleTreeDb: any, rollupSource: any, blockCheckInterval = 100) => { +const createSynchronizer = (merkleTreeDb: any, rollupSource: any, blockCheckInterval = 100) => { const worldStateConfig: WorldStateConfig = { worldStateBlockCheckIntervalMS: blockCheckInterval, l2QueueSize: 1000, }; - return new ServerWorldStateSynchroniser(merkleTreeDb as MerkleTrees, rollupSource as L2BlockSource, worldStateConfig); + return new ServerWorldStateSynchronizer(merkleTreeDb as MerkleTrees, rollupSource as L2BlockSource, worldStateConfig); }; -const log = createDebugLogger('aztec:server_world_state_synchroniser_test'); +const log = createDebugLogger('aztec:server_world_state_synchronizer_test'); -describe('server_world_state_synchroniser', () => { +describe('server_world_state_synchronizer', () => { const rollupSource: Mockify> = { getBlockNumber: jest.fn().mockImplementation(getLatestBlockNumber), getL2Blocks: jest.fn().mockImplementation(consumeNextBlocks), @@ -134,7 +134,7 @@ describe('server_world_state_synchroniser', () => { stop: jest.fn().mockImplementation(() => Promise.resolve()), } as any; - const performInitialSync = async (server: ServerWorldStateSynchroniser) => { + const performInitialSync = async (server: ServerWorldStateSynchronizer) => { // test initial state let status = await server.status(); expect(status.syncedToL2Block).toEqual(0); @@ -153,11 +153,11 @@ describe('server_world_state_synchroniser', () => { }; it('can be constructed', () => { - expect(() => createSynchroniser(merkleTreeDb, rollupSource)).not.toThrow(); + expect(() => createSynchronizer(merkleTreeDb, rollupSource)).not.toThrow(); }); it('updates sync progress', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); // test initial state let status = await server.status(); @@ -196,7 +196,7 @@ describe('server_world_state_synchroniser', () => { expect(status.state).toEqual(WorldStateRunningState.RUNNING); expect(status.syncedToL2Block).toEqual(LATEST_BLOCK_NUMBER); - // stop the synchroniser + // stop the synchronizer await server.stop(); // check the final status @@ -206,7 +206,7 @@ describe('server_world_state_synchroniser', () => { }); it('enables blocking until synced', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); let currentBlockNumber = 0; const newBlocks = async () => { @@ -237,7 +237,7 @@ describe('server_world_state_synchroniser', () => { }); it('handles multiple calls to start', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); let currentBlockNumber = 0; const newBlocks = async () => { @@ -264,7 +264,7 @@ describe('server_world_state_synchroniser', () => { }); it('immediately syncs if no new blocks', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); rollupSource.getBlockNumber.mockImplementationOnce(() => { return Promise.resolve(0); }); @@ -282,7 +282,7 @@ describe('server_world_state_synchroniser', () => { }); it("can't be started if already stopped", async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); rollupSource.getBlockNumber.mockImplementationOnce(() => { return Promise.resolve(0); }); @@ -297,7 +297,7 @@ describe('server_world_state_synchroniser', () => { it('adds the received L2 blocks', async () => { merkleTreeDb.handleL2Block.mockReset(); - const server = createSynchroniser(merkleTreeDb, rollupSource); + const server = createSynchronizer(merkleTreeDb, rollupSource); const totalBlocks = LATEST_BLOCK_NUMBER + 1; nextBlocks = Array(totalBlocks) .fill(0) @@ -310,7 +310,7 @@ describe('server_world_state_synchroniser', () => { }); it('can immediately sync to latest', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource, 10000); + const server = createSynchronizer(merkleTreeDb, rollupSource, 10000); await performInitialSync(server); @@ -328,7 +328,7 @@ describe('server_world_state_synchroniser', () => { status = await server.status(); expect(status.syncedToL2Block).toBe(LATEST_BLOCK_NUMBER + 3); - // stop the synchroniser + // stop the synchronizer await server.stop(); // check the final status @@ -338,7 +338,7 @@ describe('server_world_state_synchroniser', () => { }); it('can immediately sync to a minimum block number', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource, 10000); + const server = createSynchronizer(merkleTreeDb, rollupSource, 10000); await performInitialSync(server); @@ -353,7 +353,7 @@ describe('server_world_state_synchroniser', () => { let status = await server.status(); expect(status.syncedToL2Block).toBe(LATEST_BLOCK_NUMBER + 20); - // stop the synchroniser + // stop the synchronizer await server.stop(); // check the final status @@ -363,7 +363,7 @@ describe('server_world_state_synchroniser', () => { }); it('can immediately sync to a minimum block in the past', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource, 10000); + const server = createSynchronizer(merkleTreeDb, rollupSource, 10000); await performInitialSync(server); // syncing to a block in the past should succeed @@ -375,7 +375,7 @@ describe('server_world_state_synchroniser', () => { let status = await server.status(); expect(status.syncedToL2Block).toBe(LATEST_BLOCK_NUMBER); - // stop the synchroniser + // stop the synchronizer await server.stop(); // check the final status @@ -385,7 +385,7 @@ describe('server_world_state_synchroniser', () => { }); it('throws if you try to sync to an unavailable block', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource, 10000); + const server = createSynchronizer(merkleTreeDb, rollupSource, 10000); await performInitialSync(server); @@ -401,7 +401,7 @@ describe('server_world_state_synchroniser', () => { let status = await server.status(); expect(status.syncedToL2Block).toBe(LATEST_BLOCK_NUMBER + 2); - // stop the synchroniser + // stop the synchronizer await server.stop(); // check the final status @@ -411,7 +411,7 @@ describe('server_world_state_synchroniser', () => { }); it('throws if you try to immediate sync when not running', async () => { - const server = createSynchroniser(merkleTreeDb, rollupSource, 10000); + const server = createSynchronizer(merkleTreeDb, rollupSource, 10000); // test initial state const status = await server.status(); diff --git a/yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.ts b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts similarity index 95% rename from yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.ts rename to yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts index f96c432c05e3..042a6b344ba3 100644 --- a/yarn-project/world-state/src/synchroniser/server_world_state_synchroniser.ts +++ b/yarn-project/world-state/src/synchronizer/server_world_state_synchronizer.ts @@ -5,14 +5,14 @@ import { L2Block, L2BlockDownloader, L2BlockSource } from '@aztec/types'; import { MerkleTreeOperations, MerkleTrees } from '../index.js'; import { MerkleTreeOperationsFacade } from '../merkle-tree/merkle_tree_operations_facade.js'; import { WorldStateConfig } from './config.js'; -import { WorldStateRunningState, WorldStateStatus, WorldStateSynchroniser } from './world_state_synchroniser.js'; +import { WorldStateRunningState, WorldStateStatus, WorldStateSynchronizer } from './world_state_synchronizer.js'; /** - * Synchronises the world state with the L2 blocks from a L2BlockSource. - * The synchroniser will download the L2 blocks from the L2BlockSource and insert the new commitments into the merkle + * Synchronizes the world state with the L2 blocks from a L2BlockSource. + * The synchronizer will download the L2 blocks from the L2BlockSource and insert the new commitments into the merkle * tree. */ -export class ServerWorldStateSynchroniser implements WorldStateSynchroniser { +export class ServerWorldStateSynchronizer implements WorldStateSynchronizer { private currentL2BlockNum = 0; private latestBlockNumberAtStart = 0; @@ -47,7 +47,7 @@ export class ServerWorldStateSynchroniser implements WorldStateSynchroniser { public async start() { if (this.currentState === WorldStateRunningState.STOPPED) { - throw new Error('Synchroniser already stopped'); + throw new Error('Synchronizer already stopped'); } if (this.currentState !== WorldStateRunningState.IDLE) { return this.syncPromise; diff --git a/yarn-project/world-state/src/synchroniser/world_state_synchroniser.ts b/yarn-project/world-state/src/synchronizer/world_state_synchronizer.ts similarity index 70% rename from yarn-project/world-state/src/synchroniser/world_state_synchroniser.ts rename to yarn-project/world-state/src/synchronizer/world_state_synchronizer.ts index 8266e3016114..39e75cb91cb9 100644 --- a/yarn-project/world-state/src/synchroniser/world_state_synchroniser.ts +++ b/yarn-project/world-state/src/synchronizer/world_state_synchronizer.ts @@ -1,7 +1,7 @@ import { MerkleTreeOperations } from '../index.js'; /** - * Defines the possible states of the world state synchroniser. + * Defines the possible states of the world state synchronizer. */ export enum WorldStateRunningState { IDLE, @@ -11,37 +11,37 @@ export enum WorldStateRunningState { } /** - * Defines the status of the world state synchroniser. + * Defines the status of the world state synchronizer. */ export interface WorldStateStatus { /** - * The current state of the world state synchroniser. + * The current state of the world state synchronizer. */ state: WorldStateRunningState; /** - * The block number that the world state synchroniser is synced to. + * The block number that the world state synchronizer is synced to. */ syncedToL2Block: number; } /** - * Defines the interface for a world state synchroniser. + * Defines the interface for a world state synchronizer. */ -export interface WorldStateSynchroniser { +export interface WorldStateSynchronizer { /** - * Starts the synchroniser. + * Starts the synchronizer. * @returns A promise that resolves once the initial sync is completed. */ start(): void; /** - * Returns the current status of the synchroniser. - * @returns The current status of the synchroniser. + * Returns the current status of the synchronizer. + * @returns The current status of the synchronizer. */ status(): Promise; /** - * Stops the synchroniser. + * Stops the synchronizer. */ stop(): Promise; diff --git a/yarn-project/world-state/src/world-state-db/merkle_trees.ts b/yarn-project/world-state/src/world-state-db/merkle_trees.ts index 5d01d107f4bf..0d04eee180ad 100644 --- a/yarn-project/world-state/src/world-state-db/merkle_trees.ts +++ b/yarn-project/world-state/src/world-state-db/merkle_trees.ts @@ -45,7 +45,7 @@ import { } from './index.js'; /** - * Data necessary to reinitialise the merkle trees from Db. + * Data necessary to reinitialize the merkle trees from Db. */ interface FromDbOptions { /** @@ -67,24 +67,24 @@ export class MerkleTrees implements MerkleTreeDb { } /** - * Initialises the collection of Merkle Trees. + * initializes the collection of Merkle Trees. * @param optionalWasm - WASM instance to use for hashing (if not provided PrimitivesWasm will be used). - * @param fromDbOptions - Options to initialise the trees from the database. + * @param fromDbOptions - Options to initialize the trees from the database. */ public async init(optionalWasm?: IWasmModule, fromDbOptions?: FromDbOptions) { const fromDb = fromDbOptions !== undefined; - const initialiseTree = fromDb ? loadTree : newTree; + const initializeTree = fromDb ? loadTree : newTree; const wasm = optionalWasm ?? (await CircuitsWasm.get()); const hasher = new Pedersen(wasm); - const contractTree: AppendOnlyTree = await initialiseTree( + const contractTree: AppendOnlyTree = await initializeTree( StandardTree, this.db, hasher, `${MerkleTreeId[MerkleTreeId.CONTRACT_TREE]}`, CONTRACT_TREE_HEIGHT, ); - const nullifierTree = await initialiseTree( + const nullifierTree = await initializeTree( StandardIndexedTree, this.db, hasher, @@ -92,28 +92,28 @@ export class MerkleTrees implements MerkleTreeDb { NULLIFIER_TREE_HEIGHT, INITIAL_NULLIFIER_TREE_SIZE, ); - const privateDataTree: AppendOnlyTree = await initialiseTree( + const privateDataTree: AppendOnlyTree = await initializeTree( StandardTree, this.db, hasher, `${MerkleTreeId[MerkleTreeId.PRIVATE_DATA_TREE]}`, PRIVATE_DATA_TREE_HEIGHT, ); - const publicDataTree: UpdateOnlyTree = await initialiseTree( + const publicDataTree: UpdateOnlyTree = await initializeTree( SparseTree, this.db, hasher, `${MerkleTreeId[MerkleTreeId.PUBLIC_DATA_TREE]}`, PUBLIC_DATA_TREE_HEIGHT, ); - const l1Tol2MessagesTree: AppendOnlyTree = await initialiseTree( + const l1Tol2MessagesTree: AppendOnlyTree = await initializeTree( StandardTree, this.db, hasher, `${MerkleTreeId[MerkleTreeId.L1_TO_L2_MESSAGES_TREE]}`, L1_TO_L2_MSG_TREE_HEIGHT, ); - const historicBlocksTree: AppendOnlyTree = await initialiseTree( + const historicBlocksTree: AppendOnlyTree = await initializeTree( StandardTree, this.db, hasher, @@ -136,10 +136,10 @@ export class MerkleTrees implements MerkleTreeDb { } /** - * Method to asynchronously create and initialise a MerkleTrees instance. + * Method to asynchronously create and initialize a MerkleTrees instance. * @param db - The db instance to use for data persistance. * @param wasm - WASM instance to use for hashing (if not provided PrimitivesWasm will be used). - * @returns - A fully initialised MerkleTrees instance. + * @returns - A fully initialized MerkleTrees instance. */ public static async new(db: levelup.LevelUp, wasm?: IWasmModule) { const merkleTrees = new MerkleTrees(db); @@ -177,7 +177,7 @@ export class MerkleTrees implements MerkleTreeDb { * @param includeUncommitted - Indicates whether to include uncommitted data. */ public async updateHistoricBlocksTree(globalsHash: Fr, includeUncommitted: boolean) { - await this.synchronise(() => this._updateHistoricBlocksTree(globalsHash, includeUncommitted)); + await this.synchronize(() => this._updateHistoricBlocksTree(globalsHash, includeUncommitted)); } /** @@ -185,7 +185,7 @@ export class MerkleTrees implements MerkleTreeDb { * @param globalVariablesHash - The latest global variables hash */ public async updateLatestGlobalVariablesHash(globalVariablesHash: Fr) { - return await this.synchronise(() => this._updateLatestGlobalVariablesHash(globalVariablesHash)); + return await this.synchronize(() => this._updateLatestGlobalVariablesHash(globalVariablesHash)); } /** @@ -193,7 +193,7 @@ export class MerkleTrees implements MerkleTreeDb { * @param includeUncommitted - Indicates whether to include uncommitted data. */ public async getLatestGlobalVariablesHash(includeUncommitted: boolean): Promise { - return await this.synchronise(() => this._getGlobalVariablesHash(includeUncommitted)); + return await this.synchronize(() => this._getGlobalVariablesHash(includeUncommitted)); } /** @@ -203,7 +203,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns The tree info for the specified tree. */ public async getTreeInfo(treeId: MerkleTreeId, includeUncommitted: boolean): Promise { - return await this.synchronise(() => this._getTreeInfo(treeId, includeUncommitted)); + return await this.synchronize(() => this._getTreeInfo(treeId, includeUncommitted)); } /** @@ -212,7 +212,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns The current roots of the trees. */ public async getTreeRoots(includeUncommitted: boolean): Promise { - const roots = await this.synchronise(() => Promise.resolve(this._getAllTreeRoots(includeUncommitted))); + const roots = await this.synchronize(() => Promise.resolve(this._getAllTreeRoots(includeUncommitted))); return { privateDataTreeRoot: roots[0], @@ -255,7 +255,7 @@ export class MerkleTrees implements MerkleTreeDb { index: bigint, includeUncommitted: boolean, ): Promise { - return await this.synchronise(() => this.trees[treeId].getLeafValue(index, includeUncommitted)); + return await this.synchronize(() => this.trees[treeId].getLeafValue(index, includeUncommitted)); } /** @@ -270,7 +270,7 @@ export class MerkleTrees implements MerkleTreeDb { index: bigint, includeUncommitted: boolean, ): Promise> { - return await this.synchronise(() => this._getSiblingPath(treeId, index, includeUncommitted)); + return await this.synchronize(() => this._getSiblingPath(treeId, index, includeUncommitted)); } /** @@ -280,7 +280,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns Empty promise. */ public async appendLeaves(treeId: MerkleTreeId, leaves: Buffer[]): Promise { - return await this.synchronise(() => this._appendLeaves(treeId, leaves)); + return await this.synchronize(() => this._appendLeaves(treeId, leaves)); } /** @@ -288,7 +288,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns Empty promise. */ public async commit(): Promise { - return await this.synchronise(() => this._commit()); + return await this.synchronize(() => this._commit()); } /** @@ -296,7 +296,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns Empty promise. */ public async rollback(): Promise { - return await this.synchronise(() => this._rollback()); + return await this.synchronize(() => this._rollback()); } /** @@ -320,7 +320,7 @@ export class MerkleTrees implements MerkleTreeDb { */ alreadyPresent: boolean; }> { - return await this.synchronise(() => + return await this.synchronize(() => Promise.resolve(this._getIndexedTree(treeId).findIndexOfPreviousValue(value, includeUncommitted)), ); } @@ -337,7 +337,7 @@ export class MerkleTrees implements MerkleTreeDb { index: number, includeUncommitted: boolean, ): Promise { - return await this.synchronise(() => + return await this.synchronize(() => Promise.resolve(this._getIndexedTree(treeId).getLatestLeafDataCopy(index, includeUncommitted)), ); } @@ -354,7 +354,7 @@ export class MerkleTrees implements MerkleTreeDb { value: Buffer, includeUncommitted: boolean, ): Promise { - return await this.synchronise(async () => { + return await this.synchronize(async () => { const tree = this.trees[treeId]; for (let i = 0n; i < tree.getNumLeaves(includeUncommitted); i++) { const currentValue = await tree.getLeafValue(i, includeUncommitted); @@ -374,7 +374,7 @@ export class MerkleTrees implements MerkleTreeDb { * @returns Empty promise. */ public async updateLeaf(treeId: IndexedTreeId | PublicTreeId, leaf: LeafData | Buffer, index: bigint): Promise { - return await this.synchronise(() => this._updateLeaf(treeId, leaf, index)); + return await this.synchronize(() => this._updateLeaf(treeId, leaf, index)); } /** @@ -382,7 +382,7 @@ export class MerkleTrees implements MerkleTreeDb { * @param block - The L2 block to handle. */ public async handleL2Block(block: L2Block): Promise { - await this.synchronise(() => this._handleL2Block(block)); + await this.synchronize(() => this._handleL2Block(block)); } /** @@ -408,7 +408,7 @@ export class MerkleTrees implements MerkleTreeDb { if (!('batchInsert' in tree)) { throw new Error('Tree does not support `batchInsert` method'); } - return await this.synchronise(() => tree.batchInsert(leaves, subtreeHeight)); + return await this.synchronize(() => tree.batchInsert(leaves, subtreeHeight)); } /** @@ -416,7 +416,7 @@ export class MerkleTrees implements MerkleTreeDb { * @param fn - The function to execute. * @returns Promise containing the result of the function. */ - private async synchronise(fn: () => Promise): Promise { + private async synchronize(fn: () => Promise): Promise { return await this.jobQueue.put(fn); }