Aztec 백서

Aztec

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 71쪽

ote-types "Direct link to Changes to Aztec.nr note types") If you're using any of the following note types, please be aware that `randomness` no longer is an explicit attribute in them. * ValueNote * UintNote * NFTNote * AddressNote #### Migrating your custom note types: refer to UintNote as an example of how to migrate[​](#migrating-your-custom-note-types-refer-to-uintnote-as-an-example-of-how-to-migrate "Direct link to Migrating your custom note types: refer to UintNote as an example of how to migrate") We show the changes to `UintNote` below since it serves as a good example of the adjustments you will need to make to your own custom note types, including those that need to support partial notes. ##### Remove `randomness` from note struct[​](#remove-randomness-from-note-struct "Direct link to remove-randomness-from-note-struct") ``` pub struct UintNote { /// The owner of the note, i.e. the account whose nullifier secret key is required to compute the nullifier. owner: AztecAddress, - /// Random value, protects against note hash preimage attacks. - randomness: Field, /// The number stored in the note. value: u128, } impl UintNote { pub fn new(value: u128, owner: AztecAddress) -> Self { - let randomness = unsafe { random() }; - Self { value, owner, randomness } + Self { value, owner } } ``` ##### Add `randomness` to `compute_note_hash` implementation[​](#add-randomness-to-compute_note_hash-implementation "Direct link to add-randomness-to-compute_note_hash-implementation") The `NoteHash` trait now requires `compute_note_hash` to receive a `randomness` field. This impacts ``` pub trait NoteHash { /// ... - fn compute_note_hash(self, storage_slot: Field) -> Field; + fn compute_note_hash(self, storage_slot: Field, randomness: Field) -> Field; ``` Then in trait implementations: ``` impl NoteHash for UintNote { - fn compute_note_hash(self, storage_slot: Field) -> Field { + fn compute_note_hash(self, storage_slot: Field, randomness: Field) -> Field { /// ... - let private_content = - UintPartialNotePrivateContent { owner: self.owner, randomness: self.randomness }; - let partial_note = PartialUintNote { - commitment: private_content.compute_partial_commitment(storage_slot), - }; + let private_content = + UintPartialNotePrivateContent { owner: self.owner }; + let partial_note = PartialUintNote { + commitment: private_content.compute_partial_commitment(storage_slot, randomness), + }; ``` It's worth noting that this change also affects how partial notes are structured and handled. ``` pub fn partial( owner: AztecAddress, storage_slot: Field, randomness: Field, context: &mut PrivateContext, recipient: AztecAddress, completer: AztecAddress, ) -> PartialUintNote { - let commitment = UintPartialNotePrivateContent { owner, randomness } - .compute_partial_commitment(storage_slot); + let commitment = UintPartialNotePrivateContent { owner } + .compute_partial_commitment(storage_slot, randomness); let private_log_content = - UintPartialNotePrivateLogContent { owner, randomness, public_log_tag: commitment }; + UintPartialNotePrivateLogContent { owner, public_log_tag: commitment }; let encrypted_log = note::compute_partial_note_private_content_log( private_log_content, storage_slot, + randomness, recipient, ); /// ... } struct UintPartialNotePrivateContent { owner: AztecAddress, - randomness: Field, } impl UintPartialNotePrivateContent { - fn compute_partial_commitment(self, storage_slot: Field) -> Field { + fn compute_partial_commitment(self, storage_slot: Field, randomness: Field) -> Field { poseidon2_hash_with_separator( - self.pack().concat([storage_slot]), + self.pack().concat([storage_slot, randomness]), DOM_SEP__NOTE_HASH, ) } } struct UintPartialNotePrivateLogContent { public_log_tag: Field, owner: AztecAddress, - randomness: Field, } ``` ##### Note size[​](#note-size "Direct link to Note size") As a result of this change, the maximum packed length of the content of a note is 11 fields, down from 12. This is a direct consequence of moving the randomness field from the note content structure to the note's metadata. #### HintedNote now includes randomness field[​](#hintednote-now-includes-randomness-field "Direct link to HintedNote now includes randomness field") ``` pub struct HintedNote<Note> { pub note: Note, pub contract_address: AztecAddress, + pub randomness: Field, pub metadata: NoteMetadata, } ``` ### \[L1 Contracts] `Block` is now `Checkpoint`[​](#l1-contracts-block-is-now-checkpoint "Direct link to l1-contracts-block-is-now-checkpoint") A `checkpoint` is now the primary unit handled by the L1 contracts. A checkpoint may contain one or more L2 blocks. The protocol circuits already support producing multiple blocks per checkpoint. Updating the L1 contracts to operate on checkpoints allow L2 blockchain to advance faster. Below are the API and event renames reflecting this change: ``` - event L2BlockProposed + event CheckpointProposed ``` ``` - event BlockInvalidated + event CheckpointInvalidated ``` ``` - function getEpochForBlock(uint256 _blockNumber) external view returns (Epoch); + function getEpochForCheckpoint(uint256 _checkpointNumber) external view returns (Epoch); ``` ``` - function getProvenBlockNumber() external view returns (uint256); + function getProvenCheckpointNumber() external view returns (uint256); ``` ``` - function getPendingBlockNumber() external view returns (uint256); + function getPendingCheckpointNumber() external view returns (uint256); ``` ``` - function getBlock(uint256 _blockNumber) external view returns (BlockLog memory); + function getCheckpoint(uint256 _checkpointNumber) external view returns (CheckpointLog memory); ``` ``` - function getBlockReward() external view returns (uint256); + function getCheckpointReward() external view returns (uint256); ``` Additionally, any function or struct that previously referenced an L2 block number now uses a checkpoint number instead: ``` - function status(uint256 _blockNumber) external view returns ( + function status(uint256 _checkpointNumber) external view returns ( - uint256 provenBlockNumber, + uint256 provenCheckpointNumber, bytes32 provenArchive, - uint256 pendingBlockNumber, + uint256 pendingCheckpointNumber, bytes32 pendingArchive, bytes32 archiveOfMyBlock, Epoch provenEpochNumber ); ``` Note: current node softwares still produce exactly one L2 block per checkpoint, so for now checkpoint numbers and L2 block numbers remain equal. This may change once multi-block checkpoints are enabled. ### \[L1 Contracts] L2-to-L1 messages are now grouped by epoch.[​](#l1-contracts-l2-to-l1-messages-are-now-grouped-by-epoch "Direct link to \[L1 Contracts] L2-to-L1 messages are now grouped by epoch.") L2-to-L1 messages are aggregated and organized per epoch rather than per block, but callers should now ask the node to compute the membership witness directly from the emitting transaction hash. The node resolves the epoch and Outbox root internally. **Note**: This is only an API change. The protocol behavior remains the same - messages can still only be consumed once an epoch is proven as before. #### What changed[​](#what-changed "Direct link to What changed") Previously, callers fetched epoch messages and computed the witness client-side. Now, call `getL2ToL1MembershipWitness` on the node: ``` const witness = await node.getL2ToL1MembershipWitness( l2TxReceipt.txHash, l2ToL1Message, ); ``` ### \[Aztec.js] Wallet interface changes[​](#aztecjs-wallet-interface-changes "Direct link to \[Aztec.js] Wallet interface changes") #### `simulateTx` is now batchable[​](#simulatetx-is-now-batchable "Direct link to simulatetx-is-now-batchable") The `simulateTx` method on the `Wallet` interface is now batchable, meaning it can be called as part of a batch operation using `wallet.batch()`. This allows you to batch simulations together with other wallet operations like `registerContract`, `sendTx`, and `registerSender`. ``` - // Could not batch simulations - const simulationResult = await wallet.simulateTx(executionPayload, options); + // Can now batch simulations with other operations + const results = await wallet.batch([ + { name: 'registerContract', args: [instance, artifact] }, + { name: 'simulateTx', args: [executionPayload, options] }, + { name: 'sendTx', args: [anotherPayload, sendOptions] }, + ]); ``` #### `ExecutionPayload` moved to `@aztec/stdlib/tx`[​](#executionpayload-moved-to-aztecstdlibtx "Direct link to executionpayload-moved-to-aztecstdlibtx") The `ExecutionPayload` type has been moved from `@aztec/aztec.js` to `@aztec/stdlib/tx`. Update your imports accordingly. ``` - import { ExecutionPayload } from '@aztec/aztec.js'; + import { ExecutionPayload } from '@aztec/stdlib/tx'; + // Or import from the re-export in aztec.js/tx: + import { ExecutionPayload } from '@aztec/aztec.js/tx'; ``` #### `ExecutionPayload` now includes `feePayer` property[​](#executionpayload-now-includes-feepayer-property "Direct link to executionpayload-now-includes-feepayer-property") The `ExecutionPayload` class now includes an optional `feePayer` property that specifies which address is paying for the fee in the execution payload (if any) ``` const payload = new ExecutionPayload( calls, authWitnesses, capsules, extraHashedArgs, + feePayer // optional AztecAddress ); ``` This was previously provided as part of the `SendOptions` (and others) in the wallet interface, which could cause problems if a payload was assembled with a payment method and the parameter was later omitted. This means `SendOptions` now loses `embeddedPaymentMethodFeePayer` ``` -wallet.simulateTx(executionPayload, { from: address, embeddedFeePaymentMethodFeePayer: feePayer }); +wallet.simulateTx(executionPayload, { from: address }); ``` #### `simulateUtility` signature and return type changed[​](#simulateutility-signature-and-return-type-changed "Direct link to simulateutility-signature-and-return-type-changed") The `simulateUtility` method signature has changed to accept a `FunctionCall` object instead of separate `functionName`, `args`, and `to` parameters. Additionally, the return type has changed from `AbiDecoded` to `Fr[]`. ``` - const result: AbiDecoded = await wallet.simulateUtility(functionName, args, to, authWitnesses); + const result: UtilitySimulationResult = await wallet.simulateUtility(functionCall, authWitnesses?); + // result.result is now Fr[] instead of AbiDecoded ``` The new signature takes: * `functionCall`: A `FunctionCall` object containing `name`, `args`, `to`, `selector`, `type`, `isStatic`, `hideMsgSender`, and `returnTypes` * `authWitnesses` (optional): An array of `AuthWitness` objects The first argument is exactly the same as what goes into `ExecutionPayload.calls`. As such, the data is already encoded. The return value is now `UtilitySimulationResult` with `result: Fr[]` instead of returning an `AbiDecoded` value directly. You'll need to decode the `Fr[]` array yourself if you need typed results. #### `Contract.at()` is now synchronous and no longer calls `registerContract`[​](#contractat-is-now-synchronous-and-no-longer-calls-registercontract "Direct link to contractat-is-now-synchronous-and-no-longer-calls-registercontract") The `Contract.at()` method (and generated contract `.at()` methods) is now synchronous and no longer automatically registers the contract with the wallet. This reduces unnecessary artifact storage and RPC calls. ``` - const contract = await TokenContract.at(address, wallet); + const contract = TokenContract.at(address, wallet); ``` **Important:** You now need to explicitly call `registerContract` if you want the wallet to store the contract instance and artifact. This is only necessary when: * An app first registers a contract * An app tries to update a contract's artifact If you need to register the contract, do so explicitly: ``` // Get the instance from deployment const { contract, instance } = await TokenContract.deploy(wallet, ...args) .send({ from: address }) .wait(); // wallet already has it registered, since the deploy method does it by default // to avoid it, set skipContractRegistration: true in the send options. // Register it with another wallet await otherWallet.registerContract(instance, TokenContract.artifact); // Now you can use the contract const otherContract = TokenContract.at(instance.address, otherWallet); ``` Publicly deployed contract instances can be retrieved via `node.getContract(address)`. Otherwise and if deployment parameters are known, an instance can be computed via the `getContractInstanceFromInstantiationParams` from `@aztec/aztec.js/contracts` #### `registerContract` signature simplified[​](#registercontract-signature-simplified "Direct link to registercontract-signature-simplified") The `registerContract` method now takes a `ContractInstanceWithAddress` instead of a `Contract` object, and the `artifact` parameter is now optional. If the artifact is not provided, the wallet will attempt to look it up from its contract class storage. ``` - await wallet.registerContract(contract); + await wallet.registerContract(instance, artifact?); ``` The method now only accepts: * `instance`: A `ContractInstanceWithAddress` object * `artifact` (optional): A `ContractArtifact` object * `secretKey` (optional): A secret key for privacy keys registration #### Return value of `getNotes` no longer contains a recipient and it contains some other additional info[​](#return-value-of-getnotes-no-longer-contains-a-recipient-and-it-contains-some-other-additional-info "Direct link to return-value-of-getnotes-no-longer-contains-a-recipient-and-it-contains-some-other-additional-info") Return value of `getNotes` used to be defined as `Promise<UniqueNote[]>` and is now defined as `Promise<NoteDao[]>`. `NoteDao` is mostly a super-set of `UniqueNote` but it doesn't contain a `recipient`. Having the recipient in the return value has been redundant as the same outcome can be achieved by populating the `scopes` array in `NoteFilter` with the `recipient` value. #### Changes to `getPrivateEvents`[​](#changes-to-getprivateevents "Direct link to changes-to-getprivateevents") The signature of `getPrivateEvents` has changed for two reasons: 1. To align it with how other query methods that include filtering by block range work (for example, `AztecNode#getPublicLogs`) 2. To enrich the returned private events with metadata. ``` getPrivateEvents<T>( - contractAddress: AztecAddress, - eventMetadata: EventMetadataDefinition, - from: number, - numBlocks: number, - recipients: AztecAddress[], - ): Promise<T[]>; + eventFilter: PrivateEventFilter, + ): Promise<PrivateEvent<T>[]>; ``` `PrivateEvent<T>` bundles together an ABI decoded event of type `T`, with `metadata` of type `InTx`: ``` export type InBlock = { l2BlockNumber: BlockNumber; l2BlockHash: L2BlockHash; }; export type InTx = InBlock & { txHash: TxHash; }; export type PrivateEvent<T> = { event: T; metadata: InTx; }; ``` You will need to update any calls to `Wallet#getPrivateEvents` accordingly. See below for before/after comparison which conserves semantics. Pay special attention to the fact that the old method expects a `numBlocks` parameter that instructs it to return `numBlocks` blocks after `fromBlock`, whereas the new version expects an (exclusive) `toBlock` block number. Also note we're replacing *recipient* terminology with *scope*. While underlying data types are equivalent (they are Aztec addresses), they have different semantics. Messages have a recipient who will be able to receive and process them. As a result of processing messages for a given recipient address, PXE might discover events. Those events are then said to be *in scope* for that address. ``` - const events = await context.client.getPrivateEvents(contractAddress, eventMetadata, 42, 10, [recipient]); - doSomethingWithAnEvent(events[0]); + const events = await context.client.getPrivateEvents(eventMetadata, { + contractAddress, + fromBlock: BlockNumber(42), + toBlock: BlockNumber(42 + 10), + scopes: [scope], + }); + doSomethingWithAnEvent(events[0].event); ``` Please refer to the wallet interface js-docs for further details. ### \[CLI] Command refactor[​](#cli-command-refactor "Direct link to \[CLI] Command refactor") The sandbox command has been renamed and remapped to "local network". We believe this conveys better what is actually being spun up when running it. **REMOVED/RENAMED**: * `aztec start --sandbox`: now `aztec start --local-network` ### \[Aztec.nr] - Contract API redesign[​](#aztecnr---contract-api-redesign "Direct link to \[Aztec.nr] - Contract API redesign") In this release we decided to largely redesign our contract API. Most of the changes here are not a breaking change (only renaming of original `#[internal]` to `#[only_self]` and `storage` now being available on the newly introduced `self` struct are a breaking change). #### 1. Renaming of original #\[internal] as #\[only\_self][​](#1-renaming-of-original-internal-as-only_self "Direct link to 1. Renaming of original #\[internal] as #\[only_self]") We want for internal to mean the same as in Solidity where internal function can be called only from the same contract and is also inlined (EVM JUMP opcode and not EVM CALL). The original implementation of our `#[internal]` macro also results in the function being callable only from the same contract but it results in a different call (hence it doesn't map to EVM JUMP). This is very confusing for people that know Solidity hence we are doing the rename. A true `#[internal]` will be introduced in the future. To migrate your contracts simply rename all the occurrences of `#[internal]` with `#[only_self]` and update the imports: ``` - use aztec::macros::functions::internal; + use aztec::macros::functions::only_self; ``` ``` #[external("public")] - #[internal] + #[only_self] fn _deduct_public_balance(owner: AztecAddress, amount: u64) { ... } ``` #### 2. Introducing of new #\[internal][​](#2-introducing-of-new-internal "Direct link to 2. Introducing of new #\[internal]") Same as in Solidity internal functions are functions that are callable from inside the contract. Unlike #\[only\_self] functions, internal functions are inlined (e.g. akin to EVM's JUMP and not EVM's CALL). Internal function can be called using the following API which leverages the new `self` struct (see change 3 below for details): ``` self.internal.my_internal_function(...) ``` Private internal functions can only be called from other private external or internal functions. Public internal functions can only be called from other public external or internal functions. #### 3. Introducing `self` in contracts and a new call interface[​](#3-introducing-self-in-contracts-and-a-new-call-interface "Direct link to 3-introducing-self-in-contracts-and-a-new-call-interface") Aztec contracts now automatically inject a `self` parameter into every contract function, providing a unified interface for accessing the contract's address, storage, calling of function and an execution context. ##### What is `self`?[​](#what-is-self "Direct link to what-is-self") `self` is an instance of `ContractSelf<Context, Storage>` that provides: * `self.address` - The contract's own address * `self.storage` - Access to your contract's storage * `self.context` - The execution context (private, public, or utility) * `self.msg_sender()` - Get the address of the caller * `self.emit(...)` - Emit events * `self.call(...)` - Call an external function * `self.view(...)` - Call an external function statically * `self.enqueue(...)` - Enqueue a call to an external function * `self.enqueue_view(...)` - Enqueue a call to an external function * `self.enqueue_incognito(...)` - Enqueue a call to an external function but hides the `m
프로젝트로 돌아가기