diff --git a/docs/docs-developers/docs/aztec-js/aztec_js_reference.md b/docs/docs-developers/docs/aztec-js/aztec_js_reference.md index 9ae2605af87f..5a1a0cb6209e 100644 --- a/docs/docs-developers/docs/aztec-js/aztec_js_reference.md +++ b/docs/docs-developers/docs/aztec-js/aztec_js_reference.md @@ -16,7 +16,7 @@ This is an auto-generated reference. For tutorials and guides, see the [Aztec.js *Package: @aztec/aztec.js* -*Generated: 2025-12-10T22:27:41.987Z* +*Generated: 2026-08-18T15:38:28.901Z* This document provides a comprehensive reference for all public APIs in the Aztec.js library. @@ -25,58 +25,68 @@ Each section is organized by module, with classes, interfaces, types, and functi ## Table of Contents - [Account](#account) + - [AuthorizationProvider](#authorizationprovider) + - [Account](#account-1) + - [BaseAccount](#baseaccount) - [AccountContract](#accountcontract) - [getAccountContractAddress](#getaccountcontractaddress) - - [AccountWithSecretKey](#accountwithsecretkey) - - [Account](#account) - - [BaseAccount](#baseaccount) - - [AccountInterface](#accountinterface) - - [SignerlessAccount](#signerlessaccount) - [Authorization](#authorization) - [CallAuthorizationRequest](#callauthorizationrequest) - [Contract](#contract) - [BaseContractInteraction](#basecontractinteraction) - [BatchCall](#batchcall) - [abiChecker](#abichecker) + - [Contract](#contract-1) - [ContractMethod](#contractmethod) - [ContractStorageLayout](#contractstoragelayout) - [ContractBase](#contractbase) - [ContractFunctionInteraction](#contractfunctioninteraction) - - [Contract](#contract) + - [DeployInstantiationOptions](#deployinstantiationoptions) + - [BoundInstantiationOptions](#boundinstantiationoptions) + - [UniversalInstantiationOptions](#universalinstantiationoptions) + - [PendingInstantiationOptions](#pendinginstantiationoptions) + - [DeployMethodContract](#deploymethodcontract) + - [DeployMethodPayload](#deploymethodpayload) - [RequestDeployOptions](#requestdeployoptions) + - [DeployOptionsWithoutWait](#deployoptionswithoutwait) - [DeployOptions](#deployoptions) - [SimulateDeployOptions](#simulatedeployoptions) + - [DeployResultMined](#deployresultmined) + - [DeployReturn](#deployreturn) - [DeployMethod](#deploymethod) - - [DeployedWaitOpts](#deployedwaitopts) - - [DeployTxReceipt](#deploytxreceipt) - - [DeploySentTx](#deploysenttx) - - [getGasLimits](#getgaslimits) - - [FeeEstimationOptions](#feeestimationoptions) + - [BoundDeployMethod](#bounddeploymethod) + - [UniversalDeployMethod](#universaldeploymethod) + - [PendingDeployMethod](#pendingdeploymethod) + - [fastForwardContractUpdate](#fastforwardcontractupdate) - [FeePaymentMethodOption](#feepaymentmethodoption) - [GasSettingsOption](#gassettingsoption) - [InteractionFeeOptions](#interactionfeeoptions) - - [SimulationInteractionFeeOptions](#simulationinteractionfeeoptions) - [RequestInteractionOptions](#requestinteractionoptions) + - [NO_WAIT](#no_wait) + - [NoWait](#nowait) + - [NO_FROM](#no_from) + - [NoFrom](#nofrom) + - [InteractionWaitOptions](#interactionwaitoptions) + - [SendInteractionOptionsWithoutWait](#sendinteractionoptionswithoutwait) - [SendInteractionOptions](#sendinteractionoptions) - [SimulateInteractionOptions](#simulateinteractionoptions) - [ProfileInteractionOptions](#profileinteractionoptions) - - [SimulationReturn](#simulationreturn) + - [OffchainMessage](#offchainmessage) + - [OffchainOutput](#offchainoutput) + - [extractOffchainOutput](#extractoffchainoutput) + - [SimulationResult](#simulationresult) + - [TxSendResultImmediate](#txsendresultimmediate) + - [TxSendResultMined](#txsendresultmined) + - [SendReturn](#sendreturn) - [toSendOptions](#tosendoptions) - [toSimulateOptions](#tosimulateoptions) - [toProfileOptions](#toprofileoptions) - - [getClassRegistryContract](#getclassregistrycontract) - - [getInstanceRegistryContract](#getinstanceregistrycontract) - - [getFeeJuice](#getfeejuice) - - [WaitOpts](#waitopts) - - [DefaultWaitOpts](#defaultwaitopts) - - [SentTx](#senttx) - - [UnsafeContract](#unsafecontract) - [WaitForProvenOpts](#waitforprovenopts) - [DefaultWaitForProvenOpts](#defaultwaitforprovenopts) - [waitForProven](#waitforproven) + - [WaitOpts](#waitopts) + - [DefaultWaitOpts](#defaultwaitopts) - [Deployment](#deployment) - - [broadcastPrivateFunction](#broadcastprivatefunction) - - [broadcastUtilityFunction](#broadcastutilityfunction) - [ContractDeployer](#contractdeployer) - [publishContractClass](#publishcontractclass) - [publishInstance](#publishinstance) @@ -89,7 +99,7 @@ Each section is organized by module, with classes, interfaces, types, and functi - [L1FeeJuicePortalManager](#l1feejuiceportalmanager) - [L1ToL2TokenPortalManager](#l1tol2tokenportalmanager) - [L1TokenPortalManager](#l1tokenportalmanager) -- [Fee](#fee) +- [Fee](#fee-4) - [FeeJuicePaymentMethodWithClaim](#feejuicepaymentmethodwithclaim) - [FeePaymentMethod](#feepaymentmethod) - [PrivateFeePaymentMethod](#privatefeepaymentmethod) @@ -103,9 +113,11 @@ Each section is organized by module, with classes, interfaces, types, and functi - [EventSelectorLike](#eventselectorlike) - [U128Like](#u128like) - [WrappedFieldLike](#wrappedfieldlike) + - [OptionLike](#optionlike) - [IntentInnerHash](#intentinnerhash) - [CallIntent](#callintent) - [ContractFunctionInteractionCallIntent](#contractfunctioninteractioncallintent) + - [isContractFunctionInteractionCallIntent](#iscontractfunctioninteractioncallintent) - [computeAuthWitMessageHash](#computeauthwitmessagehash) - [getMessageHashFromIntent](#getmessagehashfromintent) - [computeInnerAuthWitHashFromAction](#computeinnerauthwithashfromaction) @@ -116,16 +128,39 @@ Each section is organized by module, with classes, interfaces, types, and functi - [getFeeJuiceBalance](#getfeejuicebalance) - [readFieldCompressedString](#readfieldcompressedstring) - [waitForNode](#waitfornode) + - [waitForTx](#waitfortx) - [createAztecNodeClient](#createaztecnodeclient) - [AztecNode](#aztecnode) + - [AztecNodeClientOptions](#aztecnodeclientoptions) - [generatePublicKey](#generatepublickey) - [Wallet](#wallet) - [AccountEntrypointMetaPaymentMethod](#accountentrypointmetapaymentmethod) + - [AccountManagerCreateOptions](#accountmanagercreateoptions) - [AccountManager](#accountmanager) + - [CAPABILITY_VERSION](#capability_version) + - [ContractFunctionPattern](#contractfunctionpattern) + - [AccountsCapability](#accountscapability) + - [GrantedAccountsCapability](#grantedaccountscapability) + - [ContractsCapability](#contractscapability) + - [GrantedContractsCapability](#grantedcontractscapability) + - [ContractClassesCapability](#contractclassescapability) + - [GrantedContractClassesCapability](#grantedcontractclassescapability) + - [SimulationCapability](#simulationcapability) + - [GrantedSimulationCapability](#grantedsimulationcapability) + - [TransactionCapability](#transactioncapability) + - [GrantedTransactionCapability](#grantedtransactioncapability) + - [DataCapability](#datacapability) + - [GrantedDataCapability](#granteddatacapability) + - [Capability](#capability) + - [GrantedCapability](#grantedcapability) + - [AppCapabilities](#appcapabilities) + - [WalletCapabilities](#walletcapabilities) + - [DeployAccountFeePaymentMethodOption](#deployaccountfeepaymentmethodoption) - [RequestDeployAccountOptions](#requestdeployaccountoptions) - [DeployAccountOptions](#deployaccountoptions) - [SimulateDeployAccountOptions](#simulatedeployaccountoptions) - [DeployAccountMethod](#deployaccountmethod) + - [TxSimulationResultWithAppOffset](#txsimulationresultwithappoffset) - [Aliased](#aliased) - [SimulateOptions](#simulateoptions) - [ProfileOptions](#profileoptions) @@ -135,23 +170,49 @@ Each section is organized by module, with classes, interfaces, types, and functi - [BatchedMethodResult](#batchedmethodresult) - [BatchedMethodResultWrapper](#batchedmethodresultwrapper) - [BatchResults](#batchresults) + - [EventFilterBase](#eventfilterbase) - [PrivateEventFilter](#privateeventfilter) + - [PublicEventFilter](#publiceventfilter) + - [Event](#event) - [PrivateEvent](#privateevent) - - [Wallet](#wallet) - - [FunctionCallSchema](#functioncallschema) + - [PublicEvent](#publicevent) + - [ContractMetadata](#contractmetadata) + - [ContractClassMetadata](#contractclassmetadata) + - [ExecuteUtilityOptions](#executeutilityoptions) + - [Wallet](#wallet-2) - [ExecutionPayloadSchema](#executionpayloadschema) - [GasSettingsOptionSchema](#gassettingsoptionschema) - - [WalletSimulationFeeOptionSchema](#walletsimulationfeeoptionschema) + - [WaitOptsSchema](#waitoptsschema) - [SendOptionsSchema](#sendoptionsschema) - [SimulateOptionsSchema](#simulateoptionsschema) - [ProfileOptionsSchema](#profileoptionsschema) - [MessageHashOrIntentSchema](#messagehashorintentschema) - - [BatchedMethodSchema](#batchedmethodschema) - - [ContractMetadataSchema](#contractmetadataschema) - - [ContractClassMetadataSchema](#contractclassmetadataschema) - [EventMetadataDefinitionSchema](#eventmetadatadefinitionschema) - - [PrivateEventSchema](#privateeventschema) - [PrivateEventFilterSchema](#privateeventfilterschema) + - [PublicEventFilterSchema](#publiceventfilterschema) + - [PrivateEventSchema](#privateeventschema) + - [PublicEventSchema](#publiceventschema) + - [ContractMetadataSchema](#contractmetadataschema) + - [ContractClassMetadataSchema](#contractclassmetadataschema) + - [ContractFunctionPatternSchema](#contractfunctionpatternschema) + - [AccountsCapabilitySchema](#accountscapabilityschema) + - [GrantedAccountsCapabilitySchema](#grantedaccountscapabilityschema) + - [ContractsCapabilitySchema](#contractscapabilityschema) + - [GrantedContractsCapabilitySchema](#grantedcontractscapabilityschema) + - [ContractClassesCapabilitySchema](#contractclassescapabilityschema) + - [GrantedContractClassesCapabilitySchema](#grantedcontractclassescapabilityschema) + - [SimulationCapabilitySchema](#simulationcapabilityschema) + - [GrantedSimulationCapabilitySchema](#grantedsimulationcapabilityschema) + - [TransactionCapabilitySchema](#transactioncapabilityschema) + - [GrantedTransactionCapabilitySchema](#grantedtransactioncapabilityschema) + - [DataCapabilitySchema](#datacapabilityschema) + - [GrantedDataCapabilitySchema](#granteddatacapabilityschema) + - [CapabilitySchema](#capabilityschema) + - [GrantedCapabilitySchema](#grantedcapabilityschema) + - [AppCapabilitiesSchema](#appcapabilitiesschema) + - [WalletCapabilitiesSchema](#walletcapabilitiesschema) + - [BatchedMethodSchema](#batchedmethodschema) + - [BatchedResultSchema](#batchedresultschema) - [WalletSchema](#walletschema) --- @@ -162,209 +223,87 @@ Each section is organized by module, with classes, interfaces, types, and functi --- -### `account/account_contract.ts` +### `account/account.ts` -#### AccountContract +#### AuthorizationProvider **Type:** Interface -An account contract instance. Knows its artifact, deployment arguments, how to create transaction execution requests out of function calls, and how to authorize actions. +Provides authorization for actions via the AuthWitness mechanism. #### Methods -##### getContractArtifact - -Returns the artifact of this account contract. - -**Signature:** - -```typescript -getContractArtifact(): Promise -``` - -**Returns:** - -`Promise` - -##### getInitializationFunctionAndArgs - -Returns the initializer function name and arguments for this instance, or undefined if this contract does not require initialization. - -**Signature:** - -```typescript -getInitializationFunctionAndArgs(): Promise<{ - constructorName: string; - constructorArgs: any[]; - } | undefined> -``` - -**Returns:** - -```typescript -Promise< - | { - /** The name of the function used to initialize the contract */ - constructorName: string; - /** The args to the function used to initialize the contract */ - constructorArgs: any[]; - } - | undefined - > -``` - -##### getInterface +##### createAuthWit -Returns the account interface for this account contract given an instance at the provided address. The account interface is responsible for assembling tx requests given requested function calls, and for creating signed auth witnesses given action identifiers (message hashes). +Creates an authentication witness from an inner hash with consumer, or a call intent **Signature:** ```typescript -getInterface( - address: CompleteAddress, +createAuthWit( + intent: IntentInnerHash | CallIntent, chainInfo: ChainInfo -): AccountInterface +): Promise ``` **Parameters:** -- `address`: `CompleteAddress` - - Address of this account contract. +- `intent`: `IntentInnerHash | CallIntent` + - The action (or inner hash) to authorize - `chainInfo`: `ChainInfo` - - Chain id and version of the rollup where the account contract is initialized / published. + - Chain information needed for message hash computation **Returns:** -`AccountInterface` - An account interface instance for creating tx requests and authorizing actions. - -##### getAuthWitnessProvider - -Returns the auth witness provider for the given address. - -**Signature:** - -```typescript -getAuthWitnessProvider(address: CompleteAddress): AuthWitnessProvider -``` - -**Parameters:** - -- `address`: `CompleteAddress` - - Address for which to create auth witnesses. - -**Returns:** - -`AuthWitnessProvider` - -#### getAccountContractAddress - -**Type:** Function - -Compute the address of an account contract from secret and salt. - -**Signature:** - -```typescript -export async getAccountContractAddress( - accountContract: AccountContract, - secret: Fr, - salt: Fr -) -``` - -**Parameters:** - -- `accountContract`: `AccountContract` -- `secret`: `Fr` -- `salt`: `Fr` - -**Returns:** - -`Promise` - ---- - -### `account/account_with_secret_key.ts` - - -#### AccountWithSecretKey - -**Type:** Class - -Extends Account with the encryption private key. Not required for implementing the wallet interface but useful for testing purposes or exporting an account to another pxe. +`Promise` -**Extends:** `BaseAccount` +#### Account +**Type:** Type Alias -#### Constructor +Minimal interface for transaction execution and authorization. **Signature:** ```typescript -constructor( - account: AccountInterface, - private secretKey: Fr, - public readonly salt: Salt -) +export type Account = EntrypointInterface & + AuthorizationProvider & { + getCompleteAddress(): CompleteAddress; + getAddress(): AztecAddress; + }; ``` -**Parameters:** - -- `account`: `AccountInterface` -- `secretKey`: `Fr` -- `salt`: `Salt` - - Deployment salt for this account contract. - -#### Methods - +**Type Members:** -##### getSecretKey +##### getCompleteAddress -Returns the encryption private key associated with this account. +Returns the complete address for this account. **Signature:** ```typescript -public getSecretKey() +getCompleteAddress(): CompleteAddress ``` **Returns:** -`Fr` - -##### getEncryptionSecret +`CompleteAddress` +##### getAddress -Returns the encryption secret, the secret of the encryption point—the point that others use to encrypt messages to this account note - this ensures that the address secret always corresponds to an address point with y being positive dev - this is also referred to as the address secret, which decrypts payloads encrypted to an address point +Returns the address for this account. **Signature:** ```typescript -public async getEncryptionSecret() +getAddress(): AztecAddress ``` **Returns:** -`Promise` - ---- - -### `account/account.ts` - - -#### Account - -**Type:** Type Alias - -A type defining an account, capable of both creating authwits and using them to authenticate transaction execution requests. - -**Signature:** - -```typescript -export type Account = AccountInterface & AuthwitnessIntentProvider; -``` +`AztecAddress` #### BaseAccount @@ -380,12 +319,18 @@ An account implementation that uses authwits as an authentication mechanism and **Signature:** ```typescript -constructor(protected account: AccountInterface) +constructor( + private entrypoint: EntrypointInterface, + private authWitnessProvider: AuthWitnessProvider, + private completeAddress: CompleteAddress +) ``` **Parameters:** -- `account`: `AccountInterface` +- `entrypoint`: `EntrypointInterface` +- `authWitnessProvider`: `AuthWitnessProvider` +- `completeAddress`: `CompleteAddress` #### Methods @@ -398,6 +343,7 @@ constructor(protected account: AccountInterface) createTxExecutionRequest( exec: ExecutionPayload, gasSettings: GasSettings, + chainInfo: ChainInfo, options: DefaultAccountEntrypointOptions ): Promise ``` @@ -406,44 +352,61 @@ createTxExecutionRequest( - `exec`: `ExecutionPayload` - `gasSettings`: `GasSettings` +- `chainInfo`: `ChainInfo` - `options`: `DefaultAccountEntrypointOptions` **Returns:** `Promise` -##### getChainId +##### wrapExecutionPayload **Signature:** ```typescript -getChainId(): Fr +wrapExecutionPayload( + exec: ExecutionPayload, + chainInfo: ChainInfo, + options?: any +): Promise ``` +**Parameters:** + +- `exec`: `ExecutionPayload` +- `chainInfo`: `ChainInfo` +- `options` (optional): `any` + **Returns:** -`Fr` +`Promise` -##### getVersion +##### createAuthWit **Signature:** ```typescript -getVersion(): Fr +async createAuthWit( + messageHashOrIntent: CallIntent | IntentInnerHash, + chainInfo: ChainInfo +): Promise ``` +**Parameters:** + +- `messageHashOrIntent`: `CallIntent | IntentInnerHash` +- `chainInfo`: `ChainInfo` + **Returns:** -`Fr` +`Promise` ##### getCompleteAddress -Returns the complete address of the account that implements this wallet. - **Signature:** ```typescript -public getCompleteAddress() +getCompleteAddress(): CompleteAddress ``` **Returns:** @@ -452,222 +415,151 @@ public getCompleteAddress() ##### getAddress -Returns the address of the account that implements this wallet. - -**Signature:** - -```typescript -public getAddress() -``` - -**Returns:** - -`any` - -##### createAuthWit - -Computes an authentication witness from either a message hash or an intent. If a message hash is provided, it will create a witness for the hash directly. Otherwise, it will compute the message hash using the intent, along with the chain id and the version values provided by the wallet. - **Signature:** ```typescript -async createAuthWit(messageHashOrIntent: Fr | Buffer | CallIntent | IntentInnerHash): Promise +getAddress(): AztecAddress ``` -**Parameters:** - -- `messageHashOrIntent`: `Fr | Buffer | CallIntent | IntentInnerHash` - - The message hash of the intent to approve - **Returns:** -`Promise` - The authentication witness +`AztecAddress` --- -### `account/interface.ts` +### `account/account_contract.ts` -#### AccountInterface +#### AccountContract **Type:** Interface -Handler for interfacing with an account. Knows how to create transaction execution requests and authorize actions for its corresponding account. - -**Extends:** `EntrypointInterface`, `AuthWitnessProvider` +An account contract instance. Knows its artifact, deployment arguments, how to create transaction execution requests out of function calls, and how to authorize actions. #### Methods -##### getCompleteAddress +##### getContractArtifact -Returns the complete address for this account. +Returns the artifact of this account contract. **Signature:** ```typescript -getCompleteAddress(): CompleteAddress +getContractArtifact(): Promise ``` **Returns:** -`CompleteAddress` +`Promise` -##### getAddress +##### getInitializationFunctionAndArgs -Returns the address for this account. +Returns the initializer function name and arguments for this instance, or undefined if this contract does not require initialization. **Signature:** ```typescript -getAddress(): AztecAddress +getInitializationFunctionAndArgs(): Promise<{ + constructorName: string; + constructorArgs: any[]; + } | undefined> ``` **Returns:** -`AztecAddress` +```typescript +Promise< + | { + /** The name of the function used to initialize the contract */ + constructorName: string; + /** The args to the function used to initialize the contract */ + constructorArgs: any[]; + } + | undefined + > +``` -##### getChainId +##### getImmutablesHash -Returns the chain id for this account +The hash of this account's immutable instantiation params, committed into its address. Returns undefined for accounts that have no immutables (these are instead deployed via an onchain initializer, which contributes to the address through its initialization hash). **Signature:** ```typescript -getChainId(): Fr +getImmutablesHash(): Promise ``` **Returns:** -`Fr` +`Promise` -##### getVersion +##### getAccount -Returns the rollup version for this account +Returns the account implementation for this account contract given an instance at the provided address. The account is responsible for assembling tx requests given requested function calls, and for creating signed auth witnesses given action identifiers (message hashes). **Signature:** ```typescript -getVersion(): Fr +getAccount(address: CompleteAddress): Account ``` -**Returns:** - -`Fr` - ---- - -### `account/signerless_account.ts` - - -#### SignerlessAccount +**Parameters:** -**Type:** Class +- `address`: `CompleteAddress` + - Address of this account contract. -Account implementation which creates a transaction using the multicall protocol contract as entrypoint. +**Returns:** -**Implements:** `Account` +`Account` - An account instance for creating tx requests and authorizing actions. +##### getAuthWitnessProvider -#### Constructor +Returns the auth witness provider for the given address. **Signature:** ```typescript -constructor(chainInfo: ChainInfo) +getAuthWitnessProvider(address: CompleteAddress): AuthWitnessProvider ``` **Parameters:** -- `chainInfo`: `ChainInfo` +- `address`: `CompleteAddress` + - Address for which to create auth witnesses. -#### Methods +**Returns:** +`AuthWitnessProvider` -##### createTxExecutionRequest - -**Signature:** - -```typescript -createTxExecutionRequest( - exec: ExecutionPayload, - gasSettings: GasSettings -): Promise -``` - -**Parameters:** - -- `exec`: `ExecutionPayload` -- `gasSettings`: `GasSettings` - -**Returns:** - -`Promise` - -##### getChainId - -**Signature:** - -```typescript -getChainId(): Fr -``` - -**Returns:** - -`Fr` - -##### getVersion - -**Signature:** - -```typescript -getVersion(): Fr -``` - -**Returns:** - -`Fr` - -##### getCompleteAddress - -**Signature:** - -```typescript -getCompleteAddress(): CompleteAddress -``` - -**Returns:** - -`CompleteAddress` - -##### getAddress - -**Signature:** - -```typescript -getAddress(): AztecAddress -``` - -**Returns:** +#### getAccountContractAddress -`AztecAddress` +**Type:** Function -##### createAuthWit +Compute the address of an account contract from secret, salt and optional immutables hash **Signature:** ```typescript -createAuthWit(_intent: Fr | Buffer | IntentInnerHash | CallIntent): Promise +export async getAccountContractAddress( + accountContract: AccountContract, + secret: Fr, + salt: Fr, + immutablesHash?: Fr +): Promise ``` **Parameters:** -- `_intent`: `Fr | Buffer | IntentInnerHash | CallIntent` +- `accountContract`: `AccountContract` +- `secret`: `Fr` +- `salt`: `Fr` +- `immutablesHash` (optional): `Fr` **Returns:** -`Promise` +`Promise` ## Authorization @@ -689,9 +581,10 @@ An authwit request for a function call. Includes the preimage of the data to be **Signature:** ```typescript -constructor( +private constructor( public selector: AuthorizationSelector, public innerHash: Fr, + public onBehalfOf: AztecAddress, public msgSender: AztecAddress, public functionSelector: FunctionSelector, public argsHash: Fr, @@ -705,6 +598,8 @@ constructor( - The selector of the authwit type, used to identify it when emitted from `emit_offchain_effect`oracle. Computed as poseidon2("CallAuthwit((Field),(u32),Field)".to_bytes()) - `innerHash`: `Fr` - The inner hash of the authwit, computed as poseidon2([msg_sender, selector, args_hash]) +- `onBehalfOf`: `AztecAddress` + - The address on whose behalf the auth witness should be created. This is the account that must sign the authorization. - `msgSender`: `AztecAddress` - The address performing the call - `functionSelector`: `FunctionSelector` @@ -810,22 +705,54 @@ public abstract request(options?: RequestInteractionOptions): Promise(options: SendInteractionOptionsWithoutWait): Promise> +``` + +**Parameters:** + +- `options`: `SendInteractionOptionsWithoutWait` + - An object containing 'from' property representing the AztecAddress of the sender, optional fee configuration, and optional wait settings + +**Returns:** + +`Promise>` - TReturn (if wait is undefined/WaitOpts) or TxHash (if wait is NO_WAIT) + +##### send + +**Signature:** + +```typescript +public send(options: SendInteractionOptions): Promise> +``` + +**Parameters:** + +- `options`: `SendInteractionOptions` + +**Returns:** + +`Promise>` + +##### send **Signature:** ```typescript -public send(options: SendInteractionOptions): SentTx +public async send(options: SendInteractionOptions): Promise> ``` **Parameters:** -- `options`: `SendInteractionOptions` - - An object containing 'from' property representing the AztecAddress of the sender and optional fee configuration +- `options`: `SendInteractionOptions` **Returns:** -`SentTx` - A SentTx instance for tracking the transaction status and information. +`Promise>` --- @@ -848,7 +775,8 @@ A batch of function calls to be sent as a single transaction through a wallet. ```typescript constructor( wallet: Wallet, - protected interactions: (BaseContractInteraction | ExecutionPayload)[] + protected interactions: (BaseContractInteraction | ExecutionPayload)[], + private extraHashedArgs: HashedValues[] = [] ) ``` @@ -856,6 +784,7 @@ constructor( - `wallet`: `Wallet` - `interactions`: `(BaseContractInteraction | ExecutionPayload)[]` +- `extraHashedArgs` (optional): `HashedValues[]` #### Methods @@ -881,12 +810,12 @@ public async request(options: RequestInteractionOptions = {}): Promise +public async simulate(options: SimulateInteractionOptions): Promise ``` **Parameters:** @@ -896,7 +825,7 @@ public async simulate(options: SimulateInteractionOptions): Promise **Returns:** -`Promise` - The results of all the interactions that make up the batch +`Promise` - The results of all the interactions that make up the batch ##### getExecutionPayloads @@ -938,6 +867,83 @@ export abiChecker(artifact: ContractArtifact) --- +### `contract/contract.ts` + + +#### Contract + +**Type:** Class + +The Contract class represents a contract and provides utility methods for interacting with it. It enables the creation of ContractFunctionInteraction instances for each function in the contract's ABI, allowing users to call or send transactions to these functions. Additionally, the Contract class can be used to attach the contract instance to a deployed contract onchain through the PXE, which facilitates interaction with Aztec's privacy protocol. + +**Extends:** `ContractBase` + + +#### Methods + + +##### at + +Gets a contract instance. + +**Signature:** + +```typescript +public static at( + address: AztecAddress, + artifact: ContractArtifact, + wallet: Wallet +): Contract +``` + +**Parameters:** + +- `address`: `AztecAddress` + - The address of the contract instance. +- `artifact`: `ContractArtifact` + - Build artifact of the contract. +- `wallet`: `Wallet` + - The wallet to use when interacting with the contract. + +**Returns:** + +`Contract` - A promise that resolves to a new Contract instance. + +##### deploy + +Creates a tx to deploy (initialize and/or publish) a new instance of a contract. + +**Signature:** + +```typescript +public static deploy( + wallet: Wallet, + artifact: ContractArtifact, + args: any[], + constructorName?: string, + instantiation?: DeployInstantiationOptions +) +``` + +**Parameters:** + +- `wallet`: `Wallet` + - The wallet for executing the deployment. +- `artifact`: `ContractArtifact` + - Build artifact of the contract to deploy +- `args`: `any[]` + - Arguments for the constructor. +- `constructorName` (optional): `string` + - The name of the constructor function to call. +- `instantiation` (optional): `DeployInstantiationOptions` + - Other address-affecting parameters (salt, deployer / universalDeploy, publicKeys). + +**Returns:** + +`DeployMethod` + +--- + ### `contract/contract_base.ts` @@ -1099,12 +1105,12 @@ Returns the encoded function call wrapped by this interaction Useful when genera **Signature:** ```typescript -public async getFunctionCall() +public async getFunctionCall(): Promise ``` **Returns:** -`Promise<{ name: any; args: any; selector: any; type: any; to: AztecAddress; isStatic: any; hideMsgSender: boolean; returnTypes: any; }>` - An encoded function call +`Promise` - An encoded function call ##### request @@ -1132,49 +1138,17 @@ Simulate a transaction and get information from its execution. Differs from prov **Signature:** ```typescript -public async simulate(options: T): Promise['estimateGas']>> +public async simulate(options: SimulateInteractionOptions = {} as SimulateInteractionOptions): Promise ``` **Parameters:** -- `options`: `T` +- `options` (optional): `SimulateInteractionOptions` - An optional object containing additional configuration for the simulation. **Returns:** -`Promise['estimateGas']>>` - Depending on the simulation options, this method directly returns the result value of the executed function or a rich object containing extra metadata, such as estimated gas costs (if requested via options), execution statistics and emitted offchain effects - -##### simulate - -**Signature:** - -```typescript -public async simulate(options: T): Promise> -``` - -**Parameters:** - -- `options`: `T` - -**Returns:** - -`Promise>` - -##### simulate - -**Signature:** - -```typescript -public async simulate(options: SimulateInteractionOptions): Promise> -``` - -**Parameters:** - -- `options`: `SimulateInteractionOptions` - -**Returns:** - -`Promise>` +`Promise` - Depending on the simulation options, this method directly returns the result value of the executed function or a rich object containing extra metadata, such as estimated gas costs (if requested via options), execution statistics and emitted offchain effects ##### profile @@ -1211,18 +1185,19 @@ public with({ authWitnesses = [], capsules = [], extraHashedArgs = [], }: { **Parameters:** -- `{ - authWitnesses = [], - capsules = [], - extraHashedArgs = [], - }`: `{ - /** The authWitnesses to add to the interaction */ - authWitnesses?: AuthWitness[]; - /** The capsules to add to the interaction */ - capsules?: Capsule[]; - /** The extra hashed args to add to the interaction */ - extraHashedArgs?: HashedValues[]; - }` +- `{ authWitnesses = [], capsules = [], extraHashedArgs = [], }`: + + ```typescript + { + /** The authWitnesses to add to the interaction */ + authWitnesses?: AuthWitness[]; + /** The capsules to add to the interaction */ + capsules?: Capsule[]; + /** The extra hashed args to add to the interaction */ + extraHashedArgs?: HashedValues[]; + } + ``` + **Returns:** @@ -1230,148 +1205,249 @@ public with({ authWitnesses = [], capsules = [], extraHashedArgs = [], }: { --- -### `contract/contract.ts` +### `contract/deploy_method.ts` -#### Contract +#### DeployInstantiationOptions -**Type:** Class +**Type:** Type Alias -The Contract class represents a contract and provides utility methods for interacting with it. It enables the creation of ContractFunctionInteraction instances for each function in the contract's ABI, allowing users to call or send transactions to these functions. Additionally, the Contract class can be used to attach the contract instance to a deployed contract onchain through the PXE, which facilitates interaction with Aztec's privacy protocol. +Inputs that determine the contract's deployment address. `salt` and `publicKeys` are optional and default to a random Fr and `PublicKeys.default()` respectively. `deployer` and `universalDeploy` are mutually exclusive and both optional: - If neither is supplied, the deployer is locked lazily on the first `send` / `simulate` / `profile` call from `options.from` (NO_FROM/undefined → universal). This preserves the ergonomics of `MyContract.deploy(wallet, ...args).send({ from: alice })`. - If `deployer` or `universalDeploy: true` is supplied, the deployer is locked at construction. Once locked, the deployer cannot change. Subsequent calls with a `from` that would imply a different deployer throw — except when locked to `AztecAddress.ZERO` (universal), which is compatible with any sender. -**Extends:** `ContractBase` +**Signature:** +```typescript +export type DeployInstantiationOptions = { + salt?: Fr; + deployer?: AztecAddress; + universalDeploy?: boolean; + publicKeys?: PublicKeys; + immutablesHash?: Fr; +}; +``` -#### Methods +**Type Members:** +##### salt -##### at +Salt used to derive the contract address. Defaults to a random Fr. -Gets a contract instance. +**Type:** `Fr` -**Signature:** +##### deployer -```typescript -public static at( - address: AztecAddress, - artifact: ContractArtifact, - wallet: Wallet -): Contract -``` +Deployer address mixed into the address preimage. Mutually exclusive with `universalDeploy`. -**Parameters:** +**Type:** `AztecAddress` -- `address`: `AztecAddress` - - The address of the contract instance. -- `artifact`: `ContractArtifact` - - Build artifact of the contract. -- `wallet`: `Wallet` - - The wallet to use when interacting with the contract. +##### universalDeploy -**Returns:** +If true, the contract is deployed universally (deployer = AztecAddress.ZERO in the address preimage). Mutually exclusive with `deployer`. -`Contract` - A promise that resolves to a new Contract instance. +**Type:** `boolean` -##### deploy +##### publicKeys -Creates a tx to deploy (initialize and/or publish) a new instance of a contract. +Public keys mixed into the address. Defaults to PublicKeys.default(). -**Signature:** +**Type:** `PublicKeys` -```typescript -public static deploy( - wallet: Wallet, - artifact: ContractArtifact, - args: any[], - constructorName?: string -) -``` +##### immutablesHash -**Parameters:** +Commitment to the contract's immutable storage values. Folded into the salted initialization hash, so a non-zero value affects the derived address. Defaults to `Fr.ZERO`. -- `wallet`: `Wallet` - - The wallet for executing the deployment. -- `artifact`: `ContractArtifact` - - Build artifact of the contract to deploy -- `args`: `any[]` - - Arguments for the constructor. -- `constructorName` (optional): `string` - - The name of the constructor function to call. +**Type:** `Fr` -**Returns:** -`DeployMethod` +#### BoundInstantiationOptions -##### deployWithPublicKeys +**Type:** Type Alias -Creates a tx to deploy (initialize and/or publish) a new instance of a contract using the specified public keys hash to derive the address. +Narrowed `DeployInstantiationOptions` accepted by BoundDeployMethod: requires a concrete `deployer` and forbids `universalDeploy`. The runtime check that `deployer` is non-zero stays as defense in depth (it's a value-level invariant the type system can't model). **Signature:** ```typescript -public static deployWithPublicKeys( - publicKeys: PublicKeys, - wallet: Wallet, - artifact: ContractArtifact, - args: any[], - constructorName?: string -) +export type BoundInstantiationOptions = SharedInstantiationOptions & { + deployer: AztecAddress; + universalDeploy?: never; +}; ``` -**Parameters:** +**Type Members:** -- `publicKeys`: `PublicKeys` - - Hash of public keys to use for deriving the address. -- `wallet`: `Wallet` - - The wallet for executing the deployment. -- `artifact`: `ContractArtifact` - - Build artifact of the contract. -- `args`: `any[]` - - Arguments for the constructor. -- `constructorName` (optional): `string` - - The name of the constructor function to call. +##### deployer -**Returns:** +Concrete deployer mixed into the address preimage. Required, must be non-zero. -`DeployMethod` +**Type:** `AztecAddress` ---- +##### universalDeploy -### `contract/deploy_method.ts` +Forbidden on `BoundDeployMethod`; use `UniversalDeployMethod` for universal deploys. +**Type:** `never` -#### RequestDeployOptions + +#### UniversalInstantiationOptions **Type:** Type Alias -Options for deploying a contract on the Aztec network. Allows specifying a contract address salt and different options to tweak contract publication and initialization +Narrowed `DeployInstantiationOptions` accepted by UniversalDeployMethod: forbids `deployer` and requires `universalDeploy: true` (so the call site reads as a universal deploy). **Signature:** ```typescript -export type RequestDeployOptions = RequestInteractionOptions & { - contractAddressSalt?: Fr; - deployer?: AztecAddress; - skipClassPublication?: boolean; - skipInstancePublication?: boolean; - skipInitialization?: boolean; - skipRegistration?: boolean; +export type UniversalInstantiationOptions = SharedInstantiationOptions & { + deployer?: never; + universalDeploy: true; }; ``` **Type Members:** -##### contractAddressSalt +##### deployer -An optional salt value used to deterministically calculate the contract address. +Forbidden on `UniversalDeployMethod`; use `BoundDeployMethod` if you need a concrete deployer. -**Type:** `Fr` +**Type:** `never` + +##### universalDeploy + +Marks this as a universal deploy. Required for clarity at the call site. + +**Type:** `true` + + +#### PendingInstantiationOptions + +**Type:** Type Alias + +Narrowed `DeployInstantiationOptions` accepted by PendingDeployMethod: forbids both `deployer` and `universalDeploy`. The deploy is locked from the first send-time `from` instead. + +**Signature:** + +```typescript +export type PendingInstantiationOptions = SharedInstantiationOptions & { + deployer?: never; + universalDeploy?: never; +}; +``` + +**Type Members:** ##### deployer -Deployer address that will be used for the deployed contract's address computation. If set to 0, the sender's address won't be mixed in +Forbidden on `PendingDeployMethod`; use `BoundDeployMethod` for a concrete deployer. -**Type:** `AztecAddress` +**Type:** `never` + +##### universalDeploy + +Forbidden on `PendingDeployMethod`; use `UniversalDeployMethod` for a universal deploy. + +**Type:** `never` + + +#### DeployMethodContract + +**Type:** Type Alias + +Identifies *which contract* is being deployed and *with what initializer*. + +**Signature:** + +```typescript +export type DeployMethodContract = { + artifact: ContractArtifact; + postDeployCtor: (instance: ContractInstanceWithAddress, wallet: Wallet) => TContract; + args?: any[]; + constructorNameOrArtifact?: string | FunctionArtifact; +}; +``` + +**Type Members:** + +##### artifact + +Build artifact of the contract being deployed. + +**Type:** `ContractArtifact` + +##### postDeployCtor + +Factory invoked after deployment to produce the typed contract handle. + +**Type:** `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` + +##### args + +Encoded constructor arguments for the contract. Defaults to `[]`. + +**Type:** `any[]` + +##### constructorNameOrArtifact + +Name (or full artifact) of the initializer to call. + +**Type:** `string | FunctionArtifact` + + +#### DeployMethodPayload + +**Type:** Type Alias + +Execution-payload metadata propagated through `request` / `send` / `simulate` / `profile`. + +**Signature:** + +```typescript +export type DeployMethodPayload = { + authWitnesses?: AuthWitness[]; + capsules?: Capsule[]; + extraHashedArgs?: HashedValues[]; +}; +``` + +**Type Members:** + +##### authWitnesses + +Auth witnesses propagated to the deploy interaction. + +**Type:** `AuthWitness[]` + +##### capsules + +Capsules propagated to the deploy interaction. + +**Type:** `Capsule[]` + +##### extraHashedArgs + +Extra hashed args propagated to the deploy interaction. + +**Type:** `HashedValues[]` + + +#### RequestDeployOptions + +**Type:** Type Alias + +Options for deploying a contract on the Aztec network. Controls publication and registration policy for this deployment. + +**Signature:** + +```typescript +export type RequestDeployOptions = RequestInteractionOptions & { + skipClassPublication?: boolean; + skipInstancePublication?: boolean; + skipInitialization?: boolean; + skipRegistration?: boolean; +}; +``` + +**Type Members:** ##### skipClassPublication @@ -1398,27 +1474,40 @@ Skip contract registration in the wallet **Type:** `boolean` +#### DeployOptionsWithoutWait + +**Type:** Type Alias + +Base deployment options without wait parameter. + +**Signature:** + +```typescript +export type DeployOptionsWithoutWait = RequestDeployOptions & + Pick; +``` + #### DeployOptions **Type:** Type Alias -Extends the deployment options with the required parameters to send the transaction +Extends the deployment options with the required parameters to send the transaction. **Signature:** ```typescript -export type DeployOptions = Omit & { - universalDeploy?: boolean; -} & Pick; +export type DeployOptions = DeployOptionsWithoutWait & { + wait?: W; +}; ``` **Type Members:** -##### universalDeploy +##### wait -Set to true to *not* include the sender in the address computation. This option is mutually exclusive with "deployer" +Options for waiting for the transaction to be mined. - undefined (default): wait with default options and return the contract instance - WaitOpts: wait with custom options - NO_WAIT: return TxHash immediately without waiting -**Type:** `boolean` +**Type:** `W` #### SimulateDeployOptions @@ -1430,8 +1519,8 @@ Options for simulating the deployment of a contract Allows skipping certain vali **Signature:** ```typescript -export type SimulateDeployOptions = Omit & { - fee?: SimulationInteractionFeeOptions; +export type SimulateDeployOptions = Omit & { + fee?: InteractionFeeOptions; skipTxValidation?: boolean; skipFeeEnforcement?: boolean; includeMetadata?: boolean; @@ -1444,7 +1533,7 @@ export type SimulateDeployOptions = Omit & { The fee options for the transaction. -**Type:** `SimulationInteractionFeeOptions` +**Type:** `InteractionFeeOptions` ##### skipTxValidation @@ -1465,1631 +1554,1583 @@ Whether to include metadata such as offchain effects and performance statistics **Type:** `boolean` -#### DeployMethod - -**Type:** Class - -Contract interaction for deployment. Handles class publication, instance publication, and initialization of the contract. Note that for some contracts, a tx is not required as part of its "creation": If there are no public functions, and if there are no initialization functions, then technically the contract has already been "created", and all of the contract's functions (private and utility) can be interacted-with immediately, without any "deployment tx". Extends the BaseContractInteraction class. - -**Extends:** `BaseContractInteraction` +#### DeployResultMined +**Type:** Type Alias -#### Constructor +Result of deploying a contract when waiting for mining (default case). **Signature:** ```typescript -constructor( - private publicKeys: PublicKeys, - wallet: Wallet, - protected artifact: ContractArtifact, - protected postDeployCtor: (instance: ContractInstanceWithAddress, wallet: Wallet) => TContract, - private args: any[] = [], - constructorNameOrArtifact?: string | FunctionArtifact, - authWitnesses: AuthWitness[] = [], - capsules: Capsule[] = [] -) +export type DeployResultMined = { + contract: TContract; + instance: ContractInstanceWithAddress; + receipt: TxReceipt; +} & OffchainOutput; ``` -**Parameters:** +**Type Members:** -- `publicKeys`: `PublicKeys` -- `wallet`: `Wallet` -- `artifact`: `ContractArtifact` -- `postDeployCtor`: `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` -- `args` (optional): `any[]` -- `constructorNameOrArtifact` (optional): `string | FunctionArtifact` -- `authWitnesses` (optional): `AuthWitness[]` -- `capsules` (optional): `Capsule[]` +##### contract -#### Methods +The deployed contract instance. +**Type:** `TContract` -##### request +##### instance -Returns the execution payload that allows this operation to happen on chain. +The deployed contract instance with address and metadata. -**Signature:** +**Type:** `ContractInstanceWithAddress` -```typescript -public async request(options?: RequestDeployOptions): Promise -``` +##### receipt -**Parameters:** +The deploy transaction receipt. -- `options` (optional): `RequestDeployOptions` - - Configuration options. +**Type:** `TxReceipt` -**Returns:** -`Promise` - The execution payload for this operation +#### DeployReturn -##### convertDeployOptionsToRequestOptions +**Type:** Type Alias + +Conditional return type for deploy based on wait options. **Signature:** ```typescript -convertDeployOptionsToRequestOptions(options: DeployOptions): RequestDeployOptions +export type DeployReturn = W extends NoWait + ? TxSendResultImmediate + : DeployResultMined; ``` -**Parameters:** +#### DeployMethod -- `options`: `DeployOptions` +**Type:** Class -**Returns:** +Umbrella type for a contract deployment interaction. `DeployMethod` is abstract: callers always interact with one of three concrete flavors — BoundDeployMethod, UniversalDeployMethod, or PendingDeployMethod — picked by DeployMethod.create based on the supplied DeployInstantiationOptions. The flavors only differ in their initial deployer-lock state; the full API (`request` / `send` / `simulate` / `profile` / `getInstance` / `getAddress` / `getPartialAddress` / `register` / `with`) lives on this base, so consumers can type variables as `DeployMethod` and treat all three uniformly. The deployer (and therefore the deployed address) is locked once and never changes. Locking happens either at construction (via `deployer` or `universalDeploy: true` in the instantiation options) or lazily on the first `send` / `simulate` / `profile` call, which lock from `options.from`. Once locked: - The address is stable for the lifetime of this object. - Subsequent `send` / `simulate` / `profile` calls with a `from` that would imply a different deployer throw, to prevent silently deploying at a different address than `getAddress()` reported. - A locked universal deployer (`AztecAddress.ZERO`) is compatible with any `from`, since the address does not depend on the sender. Note that for some contracts, a tx is not required as part of its "creation": If there are no public functions, and if there are no initialization functions, then technically the contract has already been "created", and all of the contract's functions (private and utility) can be interacted-with immediately, without any "deployment tx". -`RequestDeployOptions` +**Extends:** `BaseContractInteraction` -##### register -Adds this contract to the wallet and returns the Contract object. +#### Constructor **Signature:** ```typescript -public async register(options?: RequestDeployOptions): Promise +protected constructor( + wallet: Wallet, + contract: DeployMethodContract, + salt: Fr | undefined, + publicKeys: PublicKeys | undefined, + immutablesHash: Fr | undefined, + payload: DeployMethodPayload = {} +) ``` **Parameters:** -- `options` (optional): `RequestDeployOptions` - - Deployment options. +- `wallet`: `Wallet` +- `contract`: `DeployMethodContract` +- `salt`: `Fr | undefined` +- `publicKeys`: `PublicKeys | undefined` +- `immutablesHash`: `Fr | undefined` +- `payload` (optional): `DeployMethodPayload` -**Returns:** +#### Properties -`Promise` -##### getPublicationExecutionPayload +##### salt -Returns an execution payload for: - publication of the contract class and - publication of the contract instance to enable public execution depending on the provided options. +Salt used in the address preimage. -**Signature:** +**Type:** `Fr` -```typescript -protected async getPublicationExecutionPayload(options?: RequestDeployOptions): Promise -``` -**Parameters:** +##### publicKeys -- `options` (optional): `RequestDeployOptions` - - Contract creation options. +Public keys mixed into the address preimage. -**Returns:** +**Type:** `PublicKeys` -`Promise` - An execution payload with potentially calls (and bytecode capsule) to the class registry and instance registry. -##### getInitializationExecutionPayload +##### immutablesHash -Returns the calls necessary to initialize the contract. +Immutables hash folded into the salted initialization hash. -**Signature:** +**Type:** `Fr` -```typescript -protected async getInitializationExecutionPayload(options?: RequestDeployOptions): Promise -``` -**Parameters:** +##### #instancePromise -- `options` (optional): `RequestDeployOptions` - - Deployment options. +Cached instance promise; resolved once the deployer is known. -**Returns:** +**Type:** `Promise` -`Promise` - An array of function calls. -##### send +##### #resolvedInstance -Send a contract deployment transaction (initialize and/or publish) using the provided options. This function extends the 'send' method from the ContractFunctionInteraction class, allowing us to send a transaction specifically for contract deployment. +Resolved value of `#instancePromise`, populated synchronously once the promise settles. -**Signature:** +**Type:** `ContractInstanceWithAddress` -```typescript -public override send(options: DeployOptions): DeploySentTx -``` -**Parameters:** +##### constructorArtifact -- `options`: `DeployOptions` - - An object containing various deployment options such as contractAddressSalt and from. +Constructor function to call. -**Returns:** +**Type:** `FunctionAbi | undefined` -`DeploySentTx` - A SentTx object that returns the receipt and the deployed contract instance. -##### getInstance +##### artifact -Builds the contract instance and returns it. +Build artifact of the contract being deployed. -**Signature:** +**Type:** `ContractArtifact` -```typescript -public async getInstance(options?: RequestDeployOptions): Promise -``` -**Parameters:** +##### postDeployCtor -- `options` (optional): `RequestDeployOptions` - - An object containing various initialization and publication options. +Factory invoked after deployment to produce the typed contract handle. -**Returns:** +**Type:** `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` -`Promise` - An instance object. -##### simulate +##### args -Simulate the deployment +Encoded constructor arguments for the contract. -**Signature:** +**Type:** `any[]` -```typescript -public async simulate(options: SimulateDeployOptions): Promise> -``` -**Parameters:** +##### extraHashedArgs -- `options`: `SimulateDeployOptions` - - An optional object containing additional configuration for the simulation. +Extra hashed args propagated through `with(...)` and into the deploy payload. -**Returns:** +**Type:** `HashedValues[]` -`Promise>` - A simulation result object containing metadata of the execution, including gas estimations (if requested via options), execution statistics and emitted offchain effects -##### profile +#### Methods -Simulate a deployment and profile the gate count for each function in the transaction. + +##### getDeployerAddress + +The address that will be mixed into the contract's address preimage. Owned returns the concrete deployer; Universal returns `AztecAddress.ZERO`; Pending throws unless a prior `send` / `simulate` / `profile` call has already locked it. **Signature:** ```typescript -public async profile(options: DeployOptions & ProfileInteractionOptions): Promise +public abstract getDeployerAddress(): AztecAddress ``` -**Parameters:** - -- `options`: `DeployOptions & ProfileInteractionOptions` - - Same options as `send`, plus extra profiling options. - **Returns:** -`Promise` - An object containing the function return value and profile result. +`AztecAddress` -##### with +##### lockDeployer -Augments this DeployMethod with additional metadata, such as authWitnesses and capsules. +Reconciles a send-time `from` with the deploy's deployer. Owned asserts an exact match; Universal accepts anything; Pending uses the first call to lock its deployer (transitioning into an Owned/Universal sibling), then defers to that sibling's assertion on subsequent calls. The "locks-or-asserts" name is intentional: only Pending mutates state, and only on its first invocation. Owned and Universal are pure assertions. **Signature:** ```typescript -public with({ authWitnesses = [], capsules = [], }: { - authWitnesses?: AuthWitness[]; - capsules?: Capsule[]; -}): DeployMethod +public abstract lockDeployer(from: SendInteractionOptionsWithoutWait['from'] | undefined): void ``` **Parameters:** -- `{ - authWitnesses = [], - capsules = [], - }`: `{ - /** The authWitnesses to add to the deployment */ - authWitnesses?: AuthWitness[]; - /** The capsules to add to the deployment */ - capsules?: Capsule[]; - }` +- `from`: `SendInteractionOptionsWithoutWait['from'] | undefined` + - The send-time `from` value (`AztecAddress`, `NO_FROM`, or `undefined`). **Returns:** -`DeployMethod` - A new DeployMethod with the added metadata, but calling the same original function in the same manner +`void` -#### Getters - - -##### address (getter) +##### cloneInstantiation -Return this deployment address. +Returns the DeployInstantiationOptions that match this flavor. Used by `with(...)` to spawn a sibling instance carrying the same lock state. **Signature:** ```typescript -public get address() { +public abstract cloneInstantiation(): DeployInstantiationOptions ``` -**Returns:** `any` +**Returns:** -##### partialAddress (getter) +`DeployInstantiationOptions` -Returns the partial address for this deployment. +##### create + +Constructs the right concrete `DeployMethod` flavor for the supplied instantiation options: - `{ deployer: }` → BoundDeployMethod - `{ universalDeploy: true }` → UniversalDeployMethod - neither set → PendingDeployMethod Mixing `deployer` and `universalDeploy` throws. Returns the umbrella `DeployMethod` type so callers can use the result generically without narrowing. **Signature:** ```typescript -public get partialAddress() { +public static create( + wallet: Wallet, + contract: DeployMethodContract, + instantiation: DeployInstantiationOptions = {}, + payload: DeployMethodPayload = {} +): DeployMethod ``` -**Returns:** `any` - ---- +**Parameters:** -### `contract/deploy_sent_tx.ts` +- `wallet`: `Wallet` + - Wallet used to send / simulate the deploy tx. +- `contract`: `DeployMethodContract` + - The contract being deployed (artifact, factory, args, initializer). +- `instantiation` (optional): `DeployInstantiationOptions` + - Address-affecting parameters (salt, deployer / universalDeploy, publicKeys). Defaults to pending. +- `payload` (optional): `DeployMethodPayload` + - Auth witnesses, capsules, and extra hashed args propagated to the deploy. Defaults to empty. +**Returns:** -#### DeployedWaitOpts +`DeployMethod` -**Type:** Type Alias +##### request -Options related to waiting for a deployment tx. +Returns the execution payload that allows this operation to happen on chain. Requires the deployer to be known — call `getDeployerAddress()` first; on a `PendingDeployMethod` this throws unless a prior `send` / `simulate` / `profile` has already locked the deployer. **Signature:** ```typescript -export type DeployedWaitOpts = WaitOpts & { - wallet?: Wallet; -}; +public async request(options: RequestDeployOptions = {}): Promise ``` -**Type Members:** - -##### wallet - -Wallet to use for creating a contract instance. Uses the one set in the deployer constructor if not set. +**Parameters:** -**Type:** `Wallet` +- `options` (optional): `RequestDeployOptions` + - Configuration options. +**Returns:** -#### DeployTxReceipt +`Promise` - The execution payload for this operation -**Type:** Type Alias +##### convertDeployOptionsToSendOptions -Extends a transaction receipt with a contract instance that represents the newly deployed contract. +Converts DeployOptions to SendOptions. **Signature:** ```typescript -export type DeployTxReceipt = FieldsOf & { - contract: TContract; - instance: ContractInstanceWithAddress; -}; +protected convertDeployOptionsToSendOptions(options: DeployOptions): SendOptions ``` -**Type Members:** +**Parameters:** -##### contract +- `options`: `DeployOptions` + - Deploy options with wait parameter. -Instance of the newly deployed contract. +**Returns:** -**Type:** `TContract` +`SendOptions` -##### instance +##### convertDeployOptionsToSimulateOptions -The deployed contract instance with address and metadata. +Converts deploy simulation options into wallet-level simulate options. -**Type:** `ContractInstanceWithAddress` +**Signature:** +```typescript +protected convertDeployOptionsToSimulateOptions(options: SimulateDeployOptions): SimulateOptions +``` -#### DeploySentTx +**Parameters:** -**Type:** Class +- `options`: `SimulateDeployOptions` + - The deploy simulation options to convert. -A contract deployment transaction sent to the network, extending SentTx with methods to publish a contract instance. +**Returns:** -**Extends:** `SentTx` +`SimulateOptions` +##### convertDeployOptionsToProfileOptions -#### Constructor +Converts deploy profile options into wallet-level profile options. **Signature:** ```typescript -constructor( - wallet: Wallet, - sendTx: () => Promise, - private postDeployCtor: (instance: ContractInstanceWithAddress, wallet: Wallet) => TContract, - private instanceGetter: () => Promise -) +protected convertDeployOptionsToProfileOptions(options: DeployOptionsWithoutWait & ProfileInteractionOptions): ProfileOptions ``` **Parameters:** -- `wallet`: `Wallet` -- `sendTx`: `() => Promise` -- `postDeployCtor`: `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` -- `instanceGetter`: `() => Promise` - - A getter for the deployed contract instance +- `options`: `DeployOptionsWithoutWait & ProfileInteractionOptions` + - The deploy profile options to convert. -#### Methods +**Returns:** +`ProfileOptions` -##### getInstance +##### register -Returns the contract instance for this deployment. +Adds this contract to the wallet and returns the Contract object. **Signature:** ```typescript -public async getInstance(): Promise +public async register(): Promise ``` **Returns:** -`Promise` - The deployed contract instance with address and metadata. +`Promise` -##### deployed +##### getPublicationExecutionPayload -Awaits for the tx to be mined and returns the contract instance. Throws if tx is not mined. +Returns an execution payload for: - publication of the contract class and - publication of the contract instance to enable public execution depending on the provided options. **Signature:** ```typescript -public async deployed(opts?: DeployedWaitOpts): Promise +protected async getPublicationExecutionPayload(options?: RequestDeployOptions): Promise ``` **Parameters:** -- `opts` (optional): `DeployedWaitOpts` - - Options for configuring the waiting for the tx to be mined. +- `options` (optional): `RequestDeployOptions` + - Contract creation options. **Returns:** -`Promise` - The deployed contract instance. +`Promise` - An execution payload with potentially calls (and bytecode capsule) to the class registry and instance registry. -##### wait +##### getInitializationExecutionPayload -Awaits for the tx to be mined and returns the receipt along with a contract instance. Throws if tx is not mined. +Returns the calls necessary to initialize the contract. **Signature:** ```typescript -public override async wait(opts?: DeployedWaitOpts): Promise> +protected async getInitializationExecutionPayload(options?: RequestDeployOptions): Promise ``` **Parameters:** -- `opts` (optional): `DeployedWaitOpts` - - Options for configuring the waiting for the tx to be mined. +- `options` (optional): `RequestDeployOptions` + - Deployment options. **Returns:** -`Promise>` - The transaction receipt with the deployed contract instance. +`Promise` - An array of function calls. + +##### send + +Send a contract deployment transaction (initialize and/or publish) using the provided options. By default, waits for the transaction to be mined and returns the deployed contract instance. ---- +**Signature:** + +```typescript +public override send(options: DeployOptionsWithoutWait): Promise> +``` -### `contract/get_gas_limits.ts` +**Parameters:** +- `options`: `DeployOptionsWithoutWait` + - An object containing various deployment options such as `from` and `fee`. -#### getGasLimits +**Returns:** -**Type:** Function +`Promise>` - TxHash (if wait is NO_WAIT), or DeployResultMined with contract, receipt, and instance (otherwise) -Returns suggested total and teardown gas limits for a simulated tx. +##### send **Signature:** ```typescript -export getGasLimits( - simulationResult: TxSimulationResult, - pad = 0.1 -): { - gasLimits: Gas; - teardownGasLimits: Gas; -} +public override send(options: DeployOptions): Promise> ``` **Parameters:** -- `simulationResult`: `TxSimulationResult` -- `pad` (optional): `any` - - Percentage to pad the suggested gas limits by, (as decimal, e.g., 0.10 for 10%). +- `options`: `DeployOptions` **Returns:** +`Promise>` + +##### send + +**Signature:** + ```typescript -{ - /** - * Gas limit for the tx, excluding teardown gas - */ - gasLimits: Gas; - /** - * Gas limit for the teardown phase - */ - teardownGasLimits: Gas; -} +public override async send(options: DeployOptions): Promise ``` ---- +**Parameters:** -### `contract/interaction_options.ts` +- `options`: `DeployOptions` +**Returns:** -#### FeeEstimationOptions +`Promise` -**Type:** Type Alias +##### getInstance -Options used to tweak the simulation and add gas estimation capabilities +Builds the contract instance and returns it. The instance is computed once and cached for the lifetime of this DeployMethod; subsequent calls return the same instance. On a PendingDeployMethod this throws unless a prior `send` / `simulate` / `profile` call has already locked the deployer — otherwise the resolved address could silently differ from the eventually-deployed one. **Signature:** ```typescript -export type FeeEstimationOptions = { - estimateGas?: boolean; - estimatedGasPadding?: number; -}; +public getInstance(): Promise ``` -**Type Members:** +**Returns:** -##### estimateGas +`Promise` - An instance object. -Whether to modify the fee settings of the simulation with high gas limit to figure out actual gas settings. +##### simulate -**Type:** `boolean` +Simulate the deployment -##### estimatedGasPadding +**Signature:** -Percentage to pad the estimated gas limits by, if empty, defaults to 0.1. Only relevant if estimateGas is set. +```typescript +public async simulate(options: SimulateDeployOptions): Promise +``` -**Type:** `number` +**Parameters:** +- `options`: `SimulateDeployOptions` + - An optional object containing additional configuration for the simulation. -#### FeePaymentMethodOption +**Returns:** -**Type:** Type Alias +`Promise` - A simulation result object containing metadata of the execution, including gas estimations (if requested via options), execution statistics and emitted offchain effects -Interactions allow configuring a custom fee payment method that gets bundled with the transaction before sending it to the wallet +##### profile + +Simulate a deployment and profile the gate count for each function in the transaction. **Signature:** ```typescript -export type FeePaymentMethodOption = { - paymentMethod?: FeePaymentMethod; -}; +public async profile(options: DeployOptionsWithoutWait & ProfileInteractionOptions): Promise ``` -**Type Members:** - -##### paymentMethod - -Fee payment method to embed in the interaction +**Parameters:** -**Type:** `FeePaymentMethod` +- `options`: `DeployOptionsWithoutWait & ProfileInteractionOptions` + - Same options as `send`, plus extra profiling options. +**Returns:** -#### GasSettingsOption +`Promise` - An object containing the function return value and profile result. -**Type:** Type Alias +##### getAddress -User-defined partial gas settings for the interaction. This type is completely optional since the wallet will fill in the missing options +Returns the deployed contract address. **Signature:** ```typescript -export type GasSettingsOption = { - gasSettings?: Partial>; -}; +public async getAddress(): Promise ``` -**Type Members:** - -##### gasSettings - -The gas settings - -**Type:** `Partial>` - +**Returns:** -#### InteractionFeeOptions +`Promise` -**Type:** Type Alias +##### getPartialAddress -Fee options as set by a user. +Returns the partial address for this deployment. **Signature:** ```typescript -export type InteractionFeeOptions = GasSettingsOption & FeePaymentMethodOption; +public async getPartialAddress(): Promise ``` -#### SimulationInteractionFeeOptions +**Returns:** + +`Promise` -**Type:** Type Alias +##### getCachedInstanceOrThrow -Fee options that can be set for simulation *only* +Returns the cached resolved instance synchronously, or throws if no instance has been computed yet. Intended for subclasses that run inside a code path where `getInstance()` is guaranteed to have already been awaited (e.g. `request()` invoked it). Not part of the public API. **Signature:** ```typescript -export type SimulationInteractionFeeOptions = InteractionFeeOptions & FeeEstimationOptions; +protected getCachedInstanceOrThrow(): ContractInstanceWithAddress ``` -#### RequestInteractionOptions +**Returns:** -**Type:** Type Alias +`ContractInstanceWithAddress` -Represents the options to configure a request from a contract interaction. Allows specifying additional auth witnesses and capsules to use during execution +##### with + +Augments this DeployMethod with additional metadata, such as authWitnesses and capsules. The deployer lock is preserved: a Pending that has not yet been locked stays Pending; a Pending that has already locked, along with Owned and Universal, returns the matching locked flavor so the cloned method deploys at the same address as `this`. **Signature:** ```typescript -export type RequestInteractionOptions = { - authWitnesses?: AuthWitness[]; - capsules?: Capsule[]; - fee?: FeePaymentMethodOption; -}; +public with({ authWitnesses = [], capsules = [], extraHashedArgs = [], }: { + authWitnesses?: AuthWitness[]; + capsules?: Capsule[]; + extraHashedArgs?: HashedValues[]; +}): DeployMethod ``` -**Type Members:** - -##### authWitnesses - -Extra authwits to use during execution +**Parameters:** -**Type:** `AuthWitness[]` +- `{ authWitnesses = [], capsules = [], extraHashedArgs = [], }`: -##### capsules + ```typescript + { + /** The authWitnesses to add to the deployment */ + authWitnesses?: AuthWitness[]; + /** The capsules to add to the deployment */ + capsules?: Capsule[]; + /** The extra hashed args to add to the deployment */ + extraHashedArgs?: HashedValues[]; + } + ``` -Extra capsules to use during execution -**Type:** `Capsule[]` +**Returns:** -##### fee +`DeployMethod` - A new DeployMethod with the added metadata, but calling the same original function in the same manner -Fee payment method to embed in the interaction request +#### BoundDeployMethod -**Type:** `FeePaymentMethodOption` +**Type:** Class +Deploy method whose deployer is fixed at construction to a concrete AztecAddress. The deployer is mixed into the address preimage, so the contract address is fully determined. Sending from a different account throws — letting it through would silently produce a deployed address different from the one `getAddress()` reported. -#### SendInteractionOptions +**Extends:** `DeployMethod` -**Type:** Type Alias -Represents options for calling a (constrained) function in a contract. +#### Constructor **Signature:** ```typescript -export type SendInteractionOptions = RequestInteractionOptions & { - from: AztecAddress; - fee?: InteractionFeeOptions; -}; +public constructor( + wallet: Wallet, + contract: DeployMethodContract, + instantiation: BoundInstantiationOptions, + payload: DeployMethodPayload = {} +) ``` -**Type Members:** +**Parameters:** -##### from +- `wallet`: `Wallet` +- `contract`: `DeployMethodContract` +- `instantiation`: `BoundInstantiationOptions` +- `payload` (optional): `DeployMethodPayload` -The sender's Aztec address. +#### Properties -**Type:** `AztecAddress` -##### fee +##### deployer -The fee options for the transaction. +The address baked into the address preimage. Read-only — set at construction. -**Type:** `InteractionFeeOptions` +**Type:** `AztecAddress` -#### SimulateInteractionOptions +#### Methods -**Type:** Type Alias -Represents the options for simulating a contract function interaction. Allows specifying the address from which the method should be called. Disregarded for simulation of public functions +##### getDeployerAddress + +Returns the locked deployer baked into the address preimage. **Signature:** ```typescript -export type SimulateInteractionOptions = Omit & { - fee?: SimulationInteractionFeeOptions; - skipTxValidation?: boolean; - skipFeeEnforcement?: boolean; - includeMetadata?: boolean; -}; +public getDeployerAddress(): AztecAddress ``` -**Type Members:** +**Returns:** -##### fee +`AztecAddress` -The fee options for the transaction. +##### lockDeployer -**Type:** `SimulationInteractionFeeOptions` +Throws unless `from` matches the locked deployer; the deployer is part of the address. -##### skipTxValidation +**Signature:** -Simulate without checking for the validity of the resulting transaction, e.g. whether it emits any existing nullifiers. +```typescript +public lockDeployer(from: SendInteractionOptionsWithoutWait['from'] | undefined): void +``` -**Type:** `boolean` +**Parameters:** -##### skipFeeEnforcement +- `from`: `SendInteractionOptionsWithoutWait['from'] | undefined` + - The send-time `from` value (`AztecAddress`, `NO_FROM`, or `undefined`). -Whether to ensure the fee payer is not empty and has enough balance to pay for the fee. +**Returns:** -**Type:** `boolean` +`void` -##### includeMetadata +##### cloneInstantiation -Whether to include metadata such as offchain effects and performance statistics (e.g. timing information of the different circuits and oracles) in the simulation result, instead of just the return value of the function +Re-emits this method's `DeployInstantiationOptions` for `with(...)` to consume. -**Type:** `boolean` +**Signature:** +```typescript +public cloneInstantiation(): DeployInstantiationOptions +``` -#### ProfileInteractionOptions +**Returns:** -**Type:** Type Alias +`DeployInstantiationOptions` -Represents the options for profiling an interaction. +#### UniversalDeployMethod -**Signature:** +**Type:** Class -```typescript -export type ProfileInteractionOptions = SimulateInteractionOptions & { - profileMode: 'gates' | 'execution-steps' | 'full'; - skipProofGeneration?: boolean; -}; -``` +Deploy method whose deployer is fixed at construction to AztecAddress.ZERO (universal deploy). The address does not depend on the sender, so any account may sign the deploy tx. -**Type Members:** +**Extends:** `DeployMethod` -##### profileMode -Whether to return gates information or the bytecode/witnesses. +#### Constructor -**Type:** `'gates' | 'execution-steps' | 'full'` +**Signature:** -##### skipProofGeneration +```typescript +public constructor( + wallet: Wallet, + contract: DeployMethodContract, + instantiation: UniversalInstantiationOptions, + payload: DeployMethodPayload = {} +) +``` -Whether to generate a Chonk proof or not +**Parameters:** -**Type:** `boolean` +- `wallet`: `Wallet` +- `contract`: `DeployMethodContract` +- `instantiation`: `UniversalInstantiationOptions` +- `payload` (optional): `DeployMethodPayload` +#### Methods -#### SimulationReturn -**Type:** Type Alias +##### getDeployerAddress -Represents the result type of a simulation. By default, it will just be the return value of the simulated function If `includeMetadata` is set to true in `SimulateInteractionOptions` on the input of `simulate(...)`, it will provide extra information. +Universal deploys are anchored at `AztecAddress.ZERO`; the sender does not enter the preimage. **Signature:** ```typescript -export type SimulationReturn = T extends true - ? { - stats: SimulationStats; - offchainEffects: OffchainEffect[]; - result: any; - estimatedGas: Pick; - } - : any; +public getDeployerAddress(): AztecAddress ``` -#### toSendOptions +**Returns:** -**Type:** Function +`AztecAddress` -Transforms and cleans up the higher level SendInteractionOptions defined by the interaction into SendOptions, which are the ones that can be serialized and forwarded to the wallet +##### lockDeployer + +Universal deploys accept any sender, including `NO_FROM` / `undefined`. **Signature:** ```typescript -export toSendOptions(options: SendInteractionOptions): SendOptions +public lockDeployer(_from: SendInteractionOptionsWithoutWait['from'] | undefined): void ``` **Parameters:** -- `options`: `SendInteractionOptions` +- `_from`: `SendInteractionOptionsWithoutWait['from'] | undefined` + - Ignored. **Returns:** -`SendOptions` - -#### toSimulateOptions +`void` -**Type:** Function +##### cloneInstantiation -Transforms and cleans up the higher level SimulateInteractionOptions defined by the interaction into SimulateOptions, which are the ones that can be serialized and forwarded to the wallet +Re-emits this method's `DeployInstantiationOptions` for `with(...)` to consume. **Signature:** ```typescript -export toSimulateOptions(options: SimulateInteractionOptions): SimulateOptions +public cloneInstantiation(): DeployInstantiationOptions ``` -**Parameters:** +**Returns:** -- `options`: `SimulateInteractionOptions` +`DeployInstantiationOptions` -**Returns:** +#### PendingDeployMethod -`SimulateOptions` +**Type:** Class -#### toProfileOptions +Deploy method whose deployer is not yet decided. The first `send` / `simulate` / `profile` call promotes this into an BoundDeployMethod or UniversalDeployMethod (depending on whether `options.from` is an address or `NO_FROM` / `undefined`); subsequent calls reuse that promotion and reject mismatching `from` values. Reading the address (`getInstance` / `getAddress` / `getPartialAddress`) or building a payload (`request`) before the promotion happens throws — the address would otherwise be ambiguous and could differ from what `send()` ends up deploying. -**Type:** Function +**Extends:** `DeployMethod` -Transforms and cleans up the higher level ProfileInteractionOptions defined by the interaction into ProfileOptions, which are the ones that can be serialized and forwarded to the wallet + +#### Constructor **Signature:** ```typescript -export toProfileOptions(options: ProfileInteractionOptions): ProfileOptions +public constructor( + wallet: Wallet, + contract: DeployMethodContract, + instantiation: PendingInstantiationOptions = {}, + payload: DeployMethodPayload = {} +) ``` **Parameters:** -- `options`: `ProfileInteractionOptions` +- `wallet`: `Wallet` +- `contract`: `DeployMethodContract` +- `instantiation` (optional): `PendingInstantiationOptions` +- `payload` (optional): `DeployMethodPayload` -**Returns:** +#### Properties -`ProfileOptions` ---- +##### #locked -### `contract/protocol_contracts.ts` +The locked sibling created on the first send-side call. Once set, all flavor-specific decisions (sender compatibility, address derivation, clone shape) delegate to it, so a second call with a mismatched `from` is rejected by `BoundDeployMethod.lockDeployer`. +**Type:** `BoundDeployMethod | UniversalDeployMethod` -#### getClassRegistryContract -**Type:** Function +#### Methods + -Returns a Contract wrapper for the contract class registry. +##### getDeployerAddress + +Returns the locked deployer once it has happened. Throws while still pending — the address would otherwise differ from what `send()` ends up deploying. **Signature:** ```typescript -export async getClassRegistryContract(wallet: Wallet) +public getDeployerAddress(): AztecAddress ``` -**Parameters:** - -- `wallet`: `Wallet` - **Returns:** -`Promise` - -#### getInstanceRegistryContract +`AztecAddress` -**Type:** Function +##### lockDeployer -Returns a Contract wrapper for the contract instance registry. +On the first call, promotes this pending method into a locked sibling and remembers it. On subsequent calls, defers to the locked sibling — so a mismatched `from` is rejected by the sibling's own policy, not a duplicate one here. **Signature:** ```typescript -export async getInstanceRegistryContract(wallet: Wallet) +public lockDeployer(from: SendInteractionOptionsWithoutWait['from'] | undefined): void ``` **Parameters:** -- `wallet`: `Wallet` +- `from`: `SendInteractionOptionsWithoutWait['from'] | undefined` + - The send-time `from` value (`AztecAddress`, `NO_FROM`, or `undefined`). **Returns:** -`Promise` +`void` -#### getFeeJuice +##### cloneInstantiation -**Type:** Function +Re-emits this method's `DeployInstantiationOptions` for `with(...)` to consume. + +**Signature:** -Returns a Contract wrapper for the fee juice contract +```typescript +public cloneInstantiation(): DeployInstantiationOptions +``` + +**Returns:** + +`DeployInstantiationOptions` + +##### #promoteFrom + +Builds the locked sibling implied by a send-time `from`: an `AztecAddress` becomes BoundDeployMethod; `NO_FROM` / `undefined` becomes UniversalDeployMethod. **Signature:** ```typescript -export async getFeeJuice(wallet: Wallet) +#promoteFrom(from: SendInteractionOptionsWithoutWait['from'] | undefined): BoundDeployMethod | UniversalDeployMethod ``` **Parameters:** -- `wallet`: `Wallet` +- `from`: `SendInteractionOptionsWithoutWait['from'] | undefined` + - The send-time `from` value. **Returns:** -`Promise` +`BoundDeployMethod | UniversalDeployMethod` --- -### `contract/sent_tx.ts` +### `contract/fastforward_contract_update.ts` -#### WaitOpts +#### fastForwardContractUpdate -**Type:** Type Alias +**Type:** Function -Options related to waiting for a tx. +Builds `SimulationOverrides` that simulate a deployed instance as if it had already been upgraded to a new contract class. Mirrors a real onchain upgrade (scheduling the new class and waiting out the delay): - `publicStorage` rewrites the `ContractInstanceRegistry`'s delayed-public-mutable storage so the AVM's `UpdateCheck` resolves to the new class id. - `contracts` swaps the deployed instance for one whose `currentContractClassId` is bumped to the new class. The new class must already be registered on chain. **Signature:** ```typescript -export type WaitOpts = { - ignoreDroppedReceiptsFor?: number; - timeout?: number; - interval?: number; - dontThrowOnRevert?: boolean; -}; +export async fastForwardContractUpdate(args: { + instanceAddress: AztecAddress; + newClassId: Fr; + node: AztecNode; +}): Promise ``` -**Type Members:** - -##### ignoreDroppedReceiptsFor +**Parameters:** -The amount of time to ignore TxStatus.DROPPED receipts (in seconds) due to the presumption that it is being propagated by the p2p network. Defaults to 5. +- `args`: -**Type:** `number` + ```typescript + { + /** Address of the deployed instance to upgrade. */ + instanceAddress: AztecAddress; + /** ID of the (already-registered) class to upgrade to. */ + newClassId: Fr; + /** Node used to fetch the existing instance and validate the class is registered. */ + node: AztecNode; + } + ``` -##### timeout -The maximum time (in seconds) to wait for the transaction to be mined. Defaults to 60. +**Returns:** -**Type:** `number` +`Promise` -##### interval +--- -The time interval (in seconds) between retries to fetch the transaction receipt. Defaults to 1. +### `contract/interaction_options.ts` -**Type:** `number` -##### dontThrowOnRevert +#### FeePaymentMethodOption -Whether to accept a revert as a status code for the tx when waiting for it. If false, will throw if the tx reverts. +**Type:** Type Alias -**Type:** `boolean` +Interactions allow configuring a custom fee payment method that gets bundled with the transaction before sending it to the wallet +**Signature:** -#### DefaultWaitOpts +```typescript +export type FeePaymentMethodOption = { + paymentMethod?: FeePaymentMethod; +}; +``` -**Type:** Constant +**Type Members:** -**Value Type:** `WaitOpts` +##### paymentMethod +Fee payment method to embed in the interaction -#### SentTx +**Type:** `FeePaymentMethod` -**Type:** Class -The SentTx class represents a sent transaction through the PXE (or directly to a node) providing methods to fetch its hash, receipt, and mining status. +#### GasSettingsOption +**Type:** Type Alias -#### Constructor +User-defined partial gas settings for the interaction. This type is completely optional since the wallet will fill in the missing options **Signature:** ```typescript -constructor( - protected walletOrNode: Wallet | AztecNode, - sendTx: () => Promise -) +export type GasSettingsOption = { + gasSettings?: Partial>; + congestionEstimate?: ManaUsageEstimate; +}; ``` -**Parameters:** - -- `walletOrNode`: `Wallet | AztecNode` -- `sendTx`: `() => Promise` +**Type Members:** -#### Properties +##### gasSettings +The gas settings -##### sendTxPromise +**Type:** `Partial>` -**Type:** `Promise` +##### congestionEstimate +Assumed network congestion level for fee prediction. Controls how aggressively the wallet estimates future fees: None assumes empty blocks, Target assumes steady-state usage, and Limit assumes blocks at maximum capacity. Higher estimates produce higher fee predictions, reducing the risk of underpriced transactions during congestion spikes. Defaults to Limit (worst case) when not specified. -##### sendTxError +**Type:** `ManaUsageEstimate` -**Type:** `Error` +#### InteractionFeeOptions -##### txHash +**Type:** Type Alias -**Type:** `TxHash` +Fee options as set by a user. +**Signature:** -#### Methods +```typescript +export type InteractionFeeOptions = GasSettingsOption & FeePaymentMethodOption; +``` +#### RequestInteractionOptions -##### getTxHash +**Type:** Type Alias -Retrieves the transaction hash of the SentTx instance. The function internally awaits for the 'txHashPromise' to resolve, and then returns the resolved transaction hash. +Represents the options to configure a request from a contract interaction. Allows specifying additional auth witnesses and capsules to use during execution **Signature:** ```typescript -public async getTxHash(): Promise +export type RequestInteractionOptions = { + authWitnesses?: AuthWitness[]; + capsules?: Capsule[]; + fee?: FeePaymentMethodOption; +}; ``` -**Returns:** +**Type Members:** -`Promise` - A promise that resolves to the transaction hash of the SentTx instance. TODO(#7717): Don't throw here. +##### authWitnesses -##### getReceipt +Extra authwits to use during execution -Retrieve the transaction receipt associated with the current SentTx instance. The function fetches the transaction hash using 'getTxHash' and then queries the PXE to get the corresponding transaction receipt. +**Type:** `AuthWitness[]` -**Signature:** +##### capsules -```typescript -public async getReceipt(): Promise -``` +Extra capsules to use during execution -**Returns:** +**Type:** `Capsule[]` -`Promise` - A promise that resolves to a TxReceipt object representing the fetched transaction receipt. +##### fee -##### wait +Fee payment method to embed in the interaction request -Awaits for a tx to be mined and returns the receipt. Throws if tx is not mined. +**Type:** `FeePaymentMethodOption` -**Signature:** -```typescript -public async wait(opts?: WaitOpts): Promise> -``` +#### NO_WAIT -**Parameters:** +**Type:** Constant -- `opts` (optional): `WaitOpts` - - Options for configuring the waiting for the tx to be mined. +Constant for explicitly not waiting for transaction confirmation. We use this instead of false to avoid confusion with falsy checks. -**Returns:** +**Value Type:** `any` + + +#### NoWait -`Promise>` - The transaction receipt. +**Type:** Type Alias -##### waitForReceipt +Type for the NO_WAIT constant. **Signature:** ```typescript -protected async waitForReceipt(opts?: WaitOpts): Promise +export type NoWait = typeof NO_WAIT; ``` -**Parameters:** - -- `opts` (optional): `WaitOpts` - -**Returns:** - -`Promise` - ---- - -### `contract/unsafe_contract.ts` +#### NO_FROM +**Type:** Constant -#### UnsafeContract +Constant for explicitly opting out of account contract mediation. When used as the `from` parameter, the wallet executes the payload directly via the DefaultEntrypoint without wrapping it in an account contract entrypoint. The app is responsible for assembling the complete execution payload, including any entrypoint wrapping (e.g. multicall) if needed. This will result in the first call of the chain receiving msg_sender as Option::none -**Type:** Class +**Value Type:** `any` -Unsafe constructor for ContractBase that bypasses the check that the instance is registered in the wallet. -**Extends:** `ContractBase` +#### NoFrom +**Type:** Type Alias -#### Constructor +Type for the NO_FROM constant. **Signature:** ```typescript -constructor( - instance: ContractInstanceWithAddress, - artifact: ContractArtifact, - wallet: Wallet -) +export type NoFrom = typeof NO_FROM; ``` -**Parameters:** +#### InteractionWaitOptions -- `instance`: `ContractInstanceWithAddress` - - The deployed contract instance definition. -- `artifact`: `ContractArtifact` - - The Application Binary Interface for the contract. -- `wallet`: `Wallet` - - The wallet used for interacting with this contract. +**Type:** Type Alias ---- +Type for wait options in interactions. - NO_WAIT symbol: Don't wait for confirmation, return TxHash immediately - WaitOpts object: Wait with custom options and return receipt/result - undefined: Wait with default options and return receipt/result -### `contract/wait_for_proven.ts` +**Signature:** +```typescript +export type InteractionWaitOptions = NoWait | WaitOpts | undefined; +``` -#### WaitForProvenOpts +#### SendInteractionOptionsWithoutWait **Type:** Type Alias -Options for waiting for a transaction to be proven. +Base options for calling a (constrained) function in a contract, without wait parameter. **Signature:** ```typescript -export type WaitForProvenOpts = { - provenTimeout?: number; - interval?: number; +export type SendInteractionOptionsWithoutWait = RequestInteractionOptions & { + from: AztecAddress | NoFrom; + fee?: InteractionFeeOptions; + additionalScopes?: AztecAddress[]; + sendMessagesAs?: AztecAddress; }; ``` **Type Members:** -##### provenTimeout +##### from -Time to wait for the tx to be proven before timing out +The sender's Aztec address, or NO_FROM to execute without account contract mediation. -**Type:** `number` +**Type:** `AztecAddress | NoFrom` -##### interval +##### fee -Elapsed time between polls to the node +The fee options for the transaction. -**Type:** `number` +**Type:** `InteractionFeeOptions` +##### additionalScopes -#### DefaultWaitForProvenOpts +Additional addresses whose private state and keys should be accessible during execution, beyond the sender's. Required when the transaction needs to access private state or keys belonging to an address other than `from`, e.g. withdrawing from an escrow that holds its own private notes. -**Type:** Constant +**Type:** `AztecAddress[]` -**Value Type:** `WaitForProvenOpts` +##### sendMessagesAs +Overrides the sender address used to derive discovery tags for private messages (notes, events, logs). Recipients use these tags to find messages addressed to them. Defaults to `from`. Typically set when `from === NO_FROM`, since there is no account address to derive tags from. -#### waitForProven +**Type:** `AztecAddress` -**Type:** Function -Wait for a transaction to be proven by polling the node +#### SendInteractionOptions + +**Type:** Type Alias + +Represents options for calling a (constrained) function in a contract. **Signature:** ```typescript -export async waitForProven( - node: AztecNode, - receipt: TxReceipt, - opts?: WaitForProvenOpts -) +export type SendInteractionOptions = SendInteractionOptionsWithoutWait & { + wait?: W; +}; ``` -**Parameters:** - -- `node`: `AztecNode` -- `receipt`: `TxReceipt` -- `opts` (optional): `WaitForProvenOpts` - -**Returns:** - -`Promise` - -## Deployment +**Type Members:** +##### wait ---- +Whether to wait for the transaction to be mined. - undefined (default): wait with default options and return TxReceipt - WaitOpts object: wait with custom options and return TxReceipt - NO_WAIT: return txHash immediately without waiting -### `deployment/broadcast_function.ts` +**Type:** `W` -#### broadcastPrivateFunction +#### SimulateInteractionOptions -**Type:** Function +**Type:** Type Alias -Sets up a call to broadcast a private function's bytecode via the ClassRegistry contract. Note that this is not required for users to call the function, but is rather a convenience to make this code publicly available so dapps or wallets do not need to redistribute it. +Represents the options for simulating a contract function interaction. Allows specifying the address from which the method should be called. Disregarded for simulation of public functions **Signature:** ```typescript -export async broadcastPrivateFunction( - wallet: Wallet, - artifact: ContractArtifact, - selector: FunctionSelector -): Promise +export type SimulateInteractionOptions = Omit & { + fee?: InteractionFeeOptions; + skipTxValidation?: boolean; + skipFeeEnforcement?: boolean; + includeMetadata?: boolean; + overrides?: SimulationOverrides; +}; ``` -**Parameters:** - -- `wallet`: `Wallet` - - Wallet to send the transaction. -- `artifact`: `ContractArtifact` - - Contract artifact that contains the function to be broadcast. -- `selector`: `FunctionSelector` - - Selector of the function to be broadcast. +**Type Members:** -**Returns:** +##### fee -`Promise` - A ContractFunctionInteraction object that can be used to send the transaction. +The fee options for the transaction. -#### broadcastUtilityFunction +**Type:** `InteractionFeeOptions` -**Type:** Function +##### skipTxValidation -Sets up a call to broadcast a utility function's bytecode via the ClassRegistry contract. Note that this is not required for users to call the function, but is rather a convenience to make this code publicly available so dapps or wallets do not need to redistribute it. +Simulate without checking for the validity of the resulting transaction, e.g. whether it emits any existing nullifiers. -**Signature:** +**Type:** `boolean` -```typescript -export async broadcastUtilityFunction( - wallet: Wallet, - artifact: ContractArtifact, - selector: FunctionSelector -): Promise -``` +##### skipFeeEnforcement -**Parameters:** +Whether to ensure the fee payer is not empty and has enough balance to pay for the fee. -- `wallet`: `Wallet` - - Wallet to send the transaction. -- `artifact`: `ContractArtifact` - - Contract artifact that contains the function to be broadcast. -- `selector`: `FunctionSelector` - - Selector of the function to be broadcast. +**Type:** `boolean` -**Returns:** +##### includeMetadata -`Promise` - A ContractFunctionInteraction object that can be used to send the transaction. +Whether to include metadata such as performance statistics (e.g. timing information of the different circuits and oracles) and simulated gas usage in the simulation result, in addition to the return value and offchain effects ---- +**Type:** `boolean` -### `deployment/contract_deployer.ts` +##### overrides +Pre-simulation overrides applied to the ephemeral fork and contract DB (publicStorage writes, contract instance overrides). -#### ContractDeployer +**Type:** `SimulationOverrides` -**Type:** Class -A class for deploying contract. +#### ProfileInteractionOptions +**Type:** Type Alias -#### Constructor +Represents the options for profiling an interaction. **Signature:** ```typescript -constructor( - private artifact: ContractArtifact, - private wallet: Wallet, - private publicKeys?: PublicKeys, - private constructorName?: string -) +export type ProfileInteractionOptions = SimulateInteractionOptions & { + profileMode: 'gates' | 'execution-steps' | 'full'; + skipProofGeneration?: boolean; +}; ``` -**Parameters:** +**Type Members:** -- `artifact`: `ContractArtifact` -- `wallet`: `Wallet` -- `publicKeys` (optional): `PublicKeys` -- `constructorName` (optional): `string` +##### profileMode -#### Methods +Whether to return gates information or the bytecode/witnesses. +**Type:** `'gates' | 'execution-steps' | 'full'` + +##### skipProofGeneration + +Whether to generate a Chonk proof or not + +**Type:** `boolean` -##### deploy -Deploy a contract using the provided ABI and constructor arguments. This function creates a new DeployMethod instance that can be used to send deployment transactions and query deployment status. The method accepts any number of constructor arguments, which will be passed to the contract's constructor during deployment. +#### OffchainMessage + +**Type:** Type Alias + +A message emitted during execution or proving, to be delivered offchain. **Signature:** ```typescript -public deploy(...args: any[]) +export type OffchainMessage = { + recipient: AztecAddress; + payload: Fr[]; + contractAddress: AztecAddress; + anchorBlockTimestamp: bigint; +}; ``` -**Parameters:** +**Type Members:** -- `args`: `any[]` - - The constructor arguments for the contract being deployed. +##### recipient -**Returns:** +The intended recipient of the message. -`DeployMethod` - A DeployMethod instance configured with the ABI, PXE, and constructor arguments. +**Type:** `AztecAddress` ---- +##### payload -### `deployment/publish_class.ts` +The message payload (typically encrypted). +**Type:** `Fr[]` -#### publishContractClass +##### contractAddress -**Type:** Function +The contract that emitted the message. -Sets up a call to publish a contract class given its artifact. +**Type:** `AztecAddress` + +##### anchorBlockTimestamp + +Anchor block timestamp at message emission. + +**Type:** `bigint` + + +#### OffchainOutput + +**Type:** Type Alias + +Groups all unproven outputs from private execution that are returned to the client. **Signature:** ```typescript -export async publishContractClass( - wallet: Wallet, - artifact: ContractArtifact -): Promise +export type OffchainOutput = { + offchainEffects: OffchainEffect[]; + offchainMessages: OffchainMessage[]; +}; ``` -**Parameters:** +**Type Members:** -- `wallet`: `Wallet` -- `artifact`: `ContractArtifact` +##### offchainEffects -**Returns:** +Raw offchain effects emitted during execution. -`Promise` +**Type:** `OffchainEffect[]` ---- +##### offchainMessages -### `deployment/publish_instance.ts` +Messages emitted during execution, to be delivered offchain. +**Type:** `OffchainMessage[]` -#### publishInstance + +#### extractOffchainOutput **Type:** Function -Sets up a call to the canonical contract instance registry to publish a contract instance. +Splits an array of offchain effects into decoded offchain messages and remaining effects. Effects whose data starts with `OFFCHAIN_MESSAGE_IDENTIFIER` are parsed as messages and removed from the effects array. **Signature:** ```typescript -export async publishInstance( - wallet: Wallet, - instance: ContractInstanceWithAddress -): Promise +export extractOffchainOutput( + effects: OffchainEffect[], + anchorBlockTimestamp: bigint +): OffchainOutput ``` **Parameters:** -- `wallet`: `Wallet` - - The wallet to use for the publication (setup) tx. -- `instance`: `ContractInstanceWithAddress` - - The instance to publish. +- `effects`: `OffchainEffect[]` +- `anchorBlockTimestamp`: `bigint` **Returns:** -`Promise` - -## Ethereum - - ---- - -### `ethereum/portal_manager.ts` - +`OffchainOutput` -#### L2Claim +#### SimulationResult **Type:** Type Alias -L1 to L2 message info to claim it on L2. +Represents the result of a simulation. Always includes the return value and offchain output. When `includeMetadata` is set, also includes stats and the simulated gas usage. **Signature:** ```typescript -export type L2Claim = { - claimSecret: Fr; - claimSecretHash: Fr; - messageHash: Hex; - messageLeafIndex: bigint; -}; +export type SimulationResult = { + result: any; + stats?: SimulationStats; + gasUsed?: GasUsed; +} & OffchainOutput; ``` **Type Members:** -##### claimSecret - -Secret for claiming. - -**Type:** `Fr` - -##### claimSecretHash +##### result -Hash of the secret for claiming. +Return value of the function -**Type:** `Fr` +**Type:** `any` -##### messageHash +##### stats -Hash of the message. +Additional stats about the simulation. Present when `includeMetadata` is set. -**Type:** `Hex` +**Type:** `SimulationStats` -##### messageLeafIndex +##### gasUsed -Leaf index in the L1 to L2 message tree. +Raw gas consumed by the simulated transaction. Present when `includeMetadata` is set. Apps that want to declare explicit gas limits should derive their own from this (e.g. pad `totalGas`) and pass them via the fee options; otherwise the wallet fills in the network's per-tx admission limits automatically. -**Type:** `bigint` +**Type:** `GasUsed` -#### L2AmountClaim +#### TxSendResultImmediate **Type:** Type Alias -L1 to L2 message info that corresponds to an amount to claim. +Result of sendTx when not waiting for mining. **Signature:** ```typescript -export type L2AmountClaim = L2Claim & { claimAmount: bigint }; +export type TxSendResultImmediate = { + txHash: TxHash; +} & OffchainOutput; ``` **Type Members:** -##### claimAmount +##### txHash -**Type:** `bigint` +The hash of the sent transaction. + +**Type:** `TxHash` -#### L2AmountClaimWithRecipient +#### TxSendResultMined **Type:** Type Alias -L1 to L2 message info that corresponds to an amount to claim with associated recipient. +Result of sendTx when waiting for mining. **Signature:** ```typescript -export type L2AmountClaimWithRecipient = L2AmountClaim & { - recipient: AztecAddress; -}; +export type TxSendResultMined = { + receipt: TReturn; +} & OffchainOutput; ``` **Type Members:** -##### recipient +##### receipt -Address that will receive the newly minted notes. +The transaction receipt. -**Type:** `AztecAddress` +**Type:** `TReturn` -#### generateClaimSecret +#### SendReturn + +**Type:** Type Alias + +Represents the result type of sending a transaction. If `wait` is NO_WAIT, returns TxSendResultImmediate. Otherwise returns TxSendResultMined. + +**Signature:** + +```typescript +export type SendReturn = T extends NoWait + ? TxSendResultImmediate + : TxSendResultMined; +``` + +#### toSendOptions **Type:** Function -Generates a pair secret and secret hash +Transforms and cleans up the higher level SendInteractionOptions defined by the interaction into SendOptions, which are the ones that can be serialized and forwarded to the wallet **Signature:** ```typescript -export async generateClaimSecret(logger?: Logger): Promise<[ - Fr, - Fr - ]> +export toSendOptions(options: SendInteractionOptions): SendOptions ``` **Parameters:** -- `logger` (optional): `Logger` +- `options`: `SendInteractionOptions` + - The send interaction options with optional wait parameter **Returns:** -`Promise<[Fr, Fr]>` - -#### L1TokenManager - -**Type:** Class +`SendOptions` - The send options to forward to the wallet -Helper for managing an ERC20 on L1. +#### toSimulateOptions +**Type:** Function -#### Constructor +Transforms and cleans up the higher level SimulateInteractionOptions defined by the interaction into SimulateOptions, which are the ones that can be serialized and forwarded to the wallet **Signature:** ```typescript -public constructor( - public readonly tokenAddress: EthAddress, - public readonly handlerAddress: EthAddress | undefined, - private readonly extendedClient: ExtendedViemWalletClient, - private logger: Logger -) +export toSimulateOptions(options: SimulateInteractionOptions): SimulateOptions ``` **Parameters:** -- `tokenAddress`: `EthAddress` - - Address of the ERC20 contract. -- `handlerAddress`: `EthAddress | undefined` - - Address of the handler/faucet contract. -- `extendedClient`: `ExtendedViemWalletClient` -- `logger`: `Logger` +- `options`: `SimulateInteractionOptions` -#### Methods +**Returns:** +`SimulateOptions` -##### getMintAmount +#### toProfileOptions -Returns the amount of tokens available to mint via the handler. +**Type:** Function + +Transforms and cleans up the higher level ProfileInteractionOptions defined by the interaction into ProfileOptions, which are the ones that can be serialized and forwarded to the wallet **Signature:** ```typescript -public async getMintAmount() +export toProfileOptions(options: ProfileInteractionOptions): ProfileOptions ``` +**Parameters:** + +- `options`: `ProfileInteractionOptions` + **Returns:** -`Promise` +`ProfileOptions` -##### getL1TokenBalance +--- -Returns the balance of the given address. +### `contract/wait_for_proven.ts` + + +#### WaitForProvenOpts + +**Type:** Type Alias + +Options for waiting for a transaction to be proven. **Signature:** ```typescript -public async getL1TokenBalance(address: Hex) +export type WaitForProvenOpts = { + provenTimeout?: number; + interval?: number; +}; ``` -**Parameters:** +**Type Members:** -- `address`: `Hex` - - Address to get the balance of. +##### provenTimeout -**Returns:** +Time to wait for the tx to be proven before timing out -`Promise` +**Type:** `number` -##### mint +##### interval -Mints a fixed amount of tokens for the given address. Returns once the tx has been mined. +Elapsed time between polls to the node -**Signature:** +**Type:** `number` -```typescript -public async mint( - address: Hex, - addressName?: string -) -``` -**Parameters:** +#### DefaultWaitForProvenOpts -- `address`: `Hex` - - Address to mint the tokens for. -- `addressName` (optional): `string` - - Optional name of the address for logging. +**Type:** Constant -**Returns:** +**Value Type:** `WaitForProvenOpts` -`Promise` -##### approve +#### waitForProven -Approves tokens for the given address. Returns once the tx has been mined. +**Type:** Function + +Wait for a transaction to be proven by polling the node **Signature:** ```typescript -public async approve( - amount: bigint, - address: Hex, - addressName = '' -) +export async waitForProven( + node: AztecNode, + receipt: TxReceipt, + opts?: WaitForProvenOpts +): Promise ``` **Parameters:** -- `amount`: `bigint` - - Amount to approve. -- `address`: `Hex` - - Address to approve the tokens for. -- `addressName` (optional): `any` - - Optional name of the address for logging. +- `node`: `AztecNode` +- `receipt`: `TxReceipt` +- `opts` (optional): `WaitForProvenOpts` **Returns:** -`Promise` +`Promise` -#### L1FeeJuicePortalManager +--- -**Type:** Class +### `contract/wait_opts.ts` -Helper for interacting with the FeeJuicePortal on L1. +#### WaitOpts -#### Constructor +**Type:** Type Alias + +Options related to waiting for a tx. **Signature:** ```typescript -constructor( - portalAddress: EthAddress, - tokenAddress: EthAddress, - handlerAddress: EthAddress, - private readonly extendedClient: ExtendedViemWalletClient, - private readonly logger: Logger -) +export type WaitOpts = { + ignoreDroppedReceiptsFor?: number; + timeout?: number; + interval?: number; + dontThrowOnRevert?: boolean; + waitForStatus?: TxStatus; + initialDelay?: number; +}; ``` -**Parameters:** +**Type Members:** -- `portalAddress`: `EthAddress` -- `tokenAddress`: `EthAddress` -- `handlerAddress`: `EthAddress` -- `extendedClient`: `ExtendedViemWalletClient` -- `logger`: `Logger` +##### ignoreDroppedReceiptsFor -#### Methods +The amount of time to ignore TxStatus.DROPPED receipts (in seconds) due to the presumption that it is being propagated by the p2p network. Defaults to 5. +**Type:** `number` -##### getTokenManager +##### timeout -Returns the associated token manager for the L1 ERC20. +The maximum time (in seconds) to wait for the transaction to be mined. Defaults to 300 (5 min). -**Signature:** +**Type:** `number` -```typescript -public getTokenManager() -``` +##### interval -**Returns:** +The time interval (in seconds) between retries to fetch the transaction receipt. Defaults to 1. -`L1TokenManager` +**Type:** `number` -##### bridgeTokensPublic +##### dontThrowOnRevert -Bridges fee juice from L1 to L2 publicly. Handles L1 ERC20 approvals. Returns once the tx has been mined. +Whether to accept a revert as a status code for the tx when waiting for it. If false, will throw if the tx reverts. -**Signature:** +**Type:** `boolean` -```typescript -public async bridgeTokensPublic( - to: AztecAddress, - amount: bigint | undefined, - mint = false -): Promise -``` +##### waitForStatus -**Parameters:** +The minimum inclusion status to wait for. If set, waits until the receipt reaches this status or higher. Defaults to CHECKPOINTED. -- `to`: `AztecAddress` - - Address to send the tokens to on L2. -- `amount`: `bigint | undefined` - - Amount of tokens to send. -- `mint` (optional): `any` - - Whether to mint the tokens before sending (only during testing). +**Type:** `TxStatus` -**Returns:** +##### initialDelay -`Promise` +The time (in seconds) to wait before the first receipt poll. Defaults to 0. Used to avoid checking for a receipt right after sending a tx, when we know it cannot have been mined yet. Counts against `timeout`. -##### new +**Type:** `number` -Creates a new instance -**Signature:** +#### DefaultWaitOpts -```typescript -public static async new( - node: AztecNode, - extendedClient: ExtendedViemWalletClient, - logger: Logger -): Promise -``` +**Type:** Constant -**Parameters:** +**Value Type:** `WaitOpts` -- `node`: `AztecNode` - - Aztec node client used for retrieving the L1 contract addresses. -- `extendedClient`: `ExtendedViemWalletClient` - - Wallet client, extended with public actions. -- `logger`: `Logger` - - Logger. -**Returns:** +## Deployment -`Promise` -#### L1ToL2TokenPortalManager +--- + +### `deployment/contract_deployer.ts` + + +#### ContractDeployer **Type:** Class -Helper for interacting with a test TokenPortal on L1 for sending tokens to L2. +A class for deploying contract. #### Constructor @@ -3098,113 +3139,1402 @@ Helper for interacting with a test TokenPortal on L1 for sending tokens to L2. ```typescript constructor( - portalAddress: EthAddress, - tokenAddress: EthAddress, - handlerAddress: EthAddress | undefined, - protected extendedClient: ExtendedViemWalletClient, - protected logger: Logger + private artifact: ContractArtifact, + private wallet: Wallet, + private constructorName?: string ) ``` **Parameters:** -- `portalAddress`: `EthAddress` -- `tokenAddress`: `EthAddress` -- `handlerAddress`: `EthAddress | undefined` -- `extendedClient`: `ExtendedViemWalletClient` -- `logger`: `Logger` - -#### Properties - +- `artifact`: `ContractArtifact` +- `wallet`: `Wallet` +- `constructorName` (optional): `string` -##### portal +#### Methods -**Type:** `ViemContract` +##### deploy -##### tokenManager +Deploy a contract using the provided instantiation parameters and constructor arguments. Creates a new DeployMethod instance that can be used to send the deployment transaction. The first argument is the DeployInstantiationOptions (salt, deployer) — pass `{}` to accept defaults (random salt, deployer = AztecAddress.ZERO). The remaining arguments are the constructor arguments for the contract. -**Type:** `L1TokenManager` +**Signature:** +```typescript +public deploy( + args?: any[], + instantiation?: DeployInstantiationOptions +) +``` -#### Methods +**Parameters:** +- `args` (optional): `any[]` + - The constructor arguments for the contract being deployed. +- `instantiation` (optional): `DeployInstantiationOptions` + - Salt and deployer to mix into the address derivation. -##### getTokenManager +**Returns:** -Returns the token manager for the underlying L1 token. +`DeployMethod` - A DeployMethod instance configured with the ABI, PXE, and constructor arguments. -**Signature:** +--- -```typescript -public getTokenManager() -``` +### `deployment/publish_class.ts` -**Returns:** -`L1TokenManager` +#### publishContractClass -##### bridgeTokensPublic +**Type:** Function -Bridges tokens from L1 to L2. Handles token approvals. Returns once the tx has been mined. +Sets up a call to publish a contract class given its artifact. **Signature:** ```typescript -public async bridgeTokensPublic( - to: AztecAddress, - amount: bigint, - mint = false -): Promise +export async publishContractClass( + wallet: Wallet, + artifact: ContractArtifact +): Promise ``` **Parameters:** -- `to`: `AztecAddress` - - Address to send the tokens to on L2. -- `amount`: `bigint` - - Amount of tokens to send. -- `mint` (optional): `any` - - Whether to mint the tokens before sending (only during testing). +- `wallet`: `Wallet` +- `artifact`: `ContractArtifact` **Returns:** -`Promise` +`Promise` + +--- + +### `deployment/publish_instance.ts` + + +#### publishInstance + +**Type:** Function + +Sets up a call to the canonical contract instance registry to publish a contract instance. + +**Signature:** + +```typescript +export publishInstance( + wallet: Wallet, + instance: ContractInstanceWithAddress +): ContractFunctionInteraction +``` + +**Parameters:** + +- `wallet`: `Wallet` + - The wallet to use for the publication (setup) tx. +- `instance`: `ContractInstanceWithAddress` + - The instance to publish. + +**Returns:** + +`ContractFunctionInteraction` + +## Ethereum + + +--- + +### `ethereum/portal_manager.ts` + + +#### L2Claim + +**Type:** Type Alias + +L1 to L2 message info to claim it on L2. + +**Signature:** + +```typescript +export type L2Claim = { + claimSecret: Fr; + claimSecretHash: Fr; + messageHash: Hex; + messageLeafIndex: bigint; +}; +``` + +**Type Members:** + +##### claimSecret + +Secret for claiming. + +**Type:** `Fr` + +##### claimSecretHash + +Hash of the secret for claiming. + +**Type:** `Fr` + +##### messageHash + +Hash of the message. + +**Type:** `Hex` + +##### messageLeafIndex + +Leaf index in the L1 to L2 message tree. + +**Type:** `bigint` + + +#### L2AmountClaim + +**Type:** Type Alias + +L1 to L2 message info that corresponds to an amount to claim. + +**Signature:** + +```typescript +export type L2AmountClaim = L2Claim & { claimAmount: bigint }; +``` + +**Type Members:** + +##### claimAmount + +**Type:** `bigint` + + +#### L2AmountClaimWithRecipient + +**Type:** Type Alias + +L1 to L2 message info that corresponds to an amount to claim with associated recipient. + +**Signature:** + +```typescript +export type L2AmountClaimWithRecipient = L2AmountClaim & { + recipient: AztecAddress; +}; +``` + +**Type Members:** + +##### recipient + +Address that will receive the newly minted notes. + +**Type:** `AztecAddress` + + +#### generateClaimSecret + +**Type:** Function + +Generates a pair secret and secret hash + +**Signature:** + +```typescript +export async generateClaimSecret(logger?: Logger): Promise<[ + Fr, + Fr + ]> +``` + +**Parameters:** + +- `logger` (optional): `Logger` + +**Returns:** + +`Promise<[Fr, Fr]>` + +#### L1TokenManager + +**Type:** Class + +Helper for managing an ERC20 on L1. + + +#### Constructor + +**Signature:** + +```typescript +public constructor( + public readonly tokenAddress: EthAddress, + public readonly handlerAddress: EthAddress | undefined, + private readonly extendedClient: ExtendedViemWalletClient, + private logger: Logger +) +``` + +**Parameters:** + +- `tokenAddress`: `EthAddress` + - Address of the ERC20 contract. +- `handlerAddress`: `EthAddress | undefined` + - Address of the handler/faucet contract. +- `extendedClient`: `ExtendedViemWalletClient` +- `logger`: `Logger` + +#### Methods + + +##### getMintAmount + +Returns the amount of tokens available to mint via the handler. + +**Signature:** + +```typescript +public async getMintAmount() +``` + +**Returns:** + +`Promise` + +##### getL1TokenBalance + +Returns the balance of the given address. + +**Signature:** + +```typescript +public async getL1TokenBalance(address: Hex) +``` + +**Parameters:** + +- `address`: `Hex` + - Address to get the balance of. + +**Returns:** + +`Promise` + +##### mint + +Mints a fixed amount of tokens for the given address. Returns once the tx has been mined. + +**Signature:** + +```typescript +public async mint( + address: Hex, + addressName?: string +) +``` + +**Parameters:** + +- `address`: `Hex` + - Address to mint the tokens for. +- `addressName` (optional): `string` + - Optional name of the address for logging. + +**Returns:** + +`Promise` + +##### approve + +Approves tokens for the given address. Returns once the tx has been mined. + +**Signature:** + +```typescript +public async approve( + amount: bigint, + address: Hex, + addressName = '' +) +``` + +**Parameters:** + +- `amount`: `bigint` + - Amount to approve. +- `address`: `Hex` + - Address to approve the tokens for. +- `addressName` (optional): `any` + - Optional name of the address for logging. + +**Returns:** + +`Promise` + +#### L1FeeJuicePortalManager + +**Type:** Class + +Helper for interacting with the FeeJuicePortal on L1. + + +#### Constructor + +**Signature:** + +```typescript +constructor( + portalAddress: EthAddress, + tokenAddress: EthAddress, + handlerAddress: EthAddress | undefined, + private readonly extendedClient: ExtendedViemWalletClient, + private readonly logger: Logger +) +``` + +**Parameters:** + +- `portalAddress`: `EthAddress` +- `tokenAddress`: `EthAddress` +- `handlerAddress`: `EthAddress | undefined` +- `extendedClient`: `ExtendedViemWalletClient` +- `logger`: `Logger` + +#### Methods + + +##### getTokenManager + +Returns the associated token manager for the L1 ERC20. + +**Signature:** + +```typescript +public getTokenManager() +``` + +**Returns:** + +`L1TokenManager` + +##### bridgeTokensPublic + +Bridges fee juice from L1 to L2 publicly. Handles L1 ERC20 approvals. Returns once the tx has been mined. + +**Signature:** + +```typescript +public async bridgeTokensPublic( + to: AztecAddress, + amount: bigint | undefined, + mint = false +): Promise +``` + +**Parameters:** + +- `to`: `AztecAddress` + - Address to send the tokens to on L2. +- `amount`: `bigint | undefined` + - Amount of tokens to send. +- `mint` (optional): `any` + - Whether to mint the tokens before sending (only during testing). + +**Returns:** + +`Promise` + +##### new + +Creates a new instance + +**Signature:** + +```typescript +public static async new( + node: AztecNode, + extendedClient: ExtendedViemWalletClient, + logger: Logger +): Promise +``` + +**Parameters:** + +- `node`: `AztecNode` + - Aztec node client used for retrieving the L1 contract addresses. +- `extendedClient`: `ExtendedViemWalletClient` + - Wallet client, extended with public actions. +- `logger`: `Logger` + - Logger. + +**Returns:** + +`Promise` + +#### L1ToL2TokenPortalManager + +**Type:** Class + +Helper for interacting with a test TokenPortal on L1 for sending tokens to L2. + + +#### Constructor + +**Signature:** + +```typescript +constructor( + portalAddress: EthAddress, + tokenAddress: EthAddress, + handlerAddress: EthAddress | undefined, + protected extendedClient: ExtendedViemWalletClient, + protected logger: Logger +) +``` + +**Parameters:** + +- `portalAddress`: `EthAddress` +- `tokenAddress`: `EthAddress` +- `handlerAddress`: `EthAddress | undefined` +- `extendedClient`: `ExtendedViemWalletClient` +- `logger`: `Logger` + +#### Properties + + +##### portal + +**Type:** `ViemContract` + + +##### tokenManager + +**Type:** `L1TokenManager` + + +##### l1TxUtils + +**Type:** `L1TxUtils` + + +#### Methods + + +##### getTokenManager + +Returns the token manager for the underlying L1 token. + +**Signature:** + +```typescript +public getTokenManager() +``` + +**Returns:** + +`L1TokenManager` + +##### bridgeTokensPublic + +Bridges tokens from L1 to L2. Handles token approvals. Returns once the tx has been mined. + +**Signature:** + +```typescript +public async bridgeTokensPublic( + to: AztecAddress, + amount: bigint, + mint = false +): Promise +``` + +**Parameters:** + +- `to`: `AztecAddress` + - Address to send the tokens to on L2. +- `amount`: `bigint` + - Amount of tokens to send. +- `mint` (optional): `any` + - Whether to mint the tokens before sending (only during testing). + +**Returns:** + +`Promise` ##### bridgeTokensPrivate -Bridges tokens from L1 to L2 privately. Handles token approvals. Returns once the tx has been mined. +Bridges tokens from L1 to L2 privately. Handles token approvals. Returns once the tx has been mined. + +**Signature:** + +```typescript +public async bridgeTokensPrivate( + to: AztecAddress, + amount: bigint, + mint = false +): Promise +``` + +**Parameters:** + +- `to`: `AztecAddress` + - Address to send the tokens to on L2. +- `amount`: `bigint` + - Amount of tokens to send. +- `mint` (optional): `any` + - Whether to mint the tokens before sending (only during testing). + +**Returns:** + +`Promise` + +#### L1TokenPortalManager + +**Type:** Class + +Helper for interacting with a test TokenPortal on L1 for both withdrawing from and bridging to L2. + +**Extends:** `L1ToL2TokenPortalManager` + + +#### Constructor + +**Signature:** + +```typescript +constructor( + portalAddress: EthAddress, + tokenAddress: EthAddress, + handlerAddress: EthAddress | undefined, + outboxAddress: EthAddress, + extendedClient: ExtendedViemWalletClient, + logger: Logger +) +``` + +**Parameters:** + +- `portalAddress`: `EthAddress` +- `tokenAddress`: `EthAddress` +- `handlerAddress`: `EthAddress | undefined` +- `outboxAddress`: `EthAddress` +- `extendedClient`: `ExtendedViemWalletClient` +- `logger`: `Logger` + +#### Methods + + +##### withdrawFunds + +Withdraws funds from the portal by consuming an L2 to L1 message. Returns once the tx is mined on L1. + +**Signature:** + +```typescript +public async withdrawFunds( + amount: bigint, + recipient: EthAddress, + epochNumber: EpochNumber, + numCheckpointsInEpoch: number, + messageIndex: bigint, + siblingPath: SiblingPath +) +``` + +**Parameters:** + +- `amount`: `bigint` + - Amount to withdraw. +- `recipient`: `EthAddress` + - Who will receive the funds. +- `epochNumber`: `EpochNumber` + - Epoch number of the message. +- `numCheckpointsInEpoch`: `number` + - The partial-proof depth (1-indexed) the witness was built against. +- `messageIndex`: `bigint` + - Index of the message. +- `siblingPath`: `SiblingPath` + - Sibling path of the message. + +**Returns:** + +`Promise` + +##### getL2ToL1MessageLeaf + +Computes the L2 to L1 message leaf for the given parameters. + +**Signature:** + +```typescript +public async getL2ToL1MessageLeaf( + amount: bigint, + recipient: EthAddress, + l2Bridge: AztecAddress, + callerOnL1: EthAddress = EthAddress.ZERO +): Promise +``` + +**Parameters:** + +- `amount`: `bigint` + - Amount to bridge. +- `recipient`: `EthAddress` + - Recipient on L1. +- `l2Bridge`: `AztecAddress` + - Address of the L2 bridge. +- `callerOnL1` (optional): `EthAddress` + - Caller address on L1. + +**Returns:** + +`Promise` + +## Fee + + +--- + +### `fee/fee_juice_payment_method_with_claim.ts` + + +#### FeeJuicePaymentMethodWithClaim + +**Type:** Class + +Pay fee directly with Fee Juice claimed in the same tx. Claiming consumes an L1 to L2 message that "contains" the fee juice bridged from L1. + +**Implements:** `FeePaymentMethod` + + +#### Constructor + +**Signature:** + +```typescript +constructor( + private sender: AztecAddress, + private claim: Pick +) +``` + +**Parameters:** + +- `sender`: `AztecAddress` +- `claim`: `Pick` + +#### Methods + + +##### getExecutionPayload + +Creates an execution payload to pay the fee in Fee Juice. + +**Signature:** + +```typescript +async getExecutionPayload(): Promise +``` + +**Returns:** + +`Promise` - An execution payload that just contains the `claim_and_end_setup` function call. + +##### getAsset + +**Signature:** + +```typescript +getAsset(): Promise +``` + +**Returns:** + +`Promise` + +##### getFeePayer + +**Signature:** + +```typescript +getFeePayer(): Promise +``` + +**Returns:** + +`Promise` + +##### getGasSettings + +**Signature:** + +```typescript +getGasSettings(): GasSettings | undefined +``` + +**Returns:** + +`GasSettings | undefined` + +--- + +### `fee/fee_payment_method.ts` + + +#### FeePaymentMethod + +**Type:** Interface + +Holds information about how the fee for a transaction is to be paid. + + +#### Methods + + +##### getAsset + +The asset used to pay the fee. + +**Signature:** + +```typescript +getAsset(): Promise +``` + +**Returns:** + +`Promise` + +##### getExecutionPayload + +Returns the data to be added to the final execution request to pay the fee in the given asset + +**Signature:** + +```typescript +getExecutionPayload(): Promise +``` + +**Returns:** + +`Promise` - The function calls to pay the fee. + +##### getFeePayer + +The expected fee payer for this tx. + +**Signature:** + +```typescript +getFeePayer(): Promise +``` + +**Returns:** + +`Promise` + +##### getGasSettings + +The gas settings (if any) used to compute the execution payload of the payment method + +**Signature:** + +```typescript +getGasSettings(): GasSettings | undefined +``` + +**Returns:** + +`GasSettings | undefined` + +--- + +### `fee/private_fee_payment_method.ts` + + +#### PrivateFeePaymentMethod + +**Type:** Class + +**Deprecated:** Is not supported on mainnet. Use FeeJuicePaymentMethodWithClaim or `SponsoredFeePaymentMethod` instead. + +Holds information about how the fee for a transaction is to be paid. + +**Implements:** `FeePaymentMethod` + + +#### Constructor + +**Signature:** + +```typescript +constructor( + private paymentContract: AztecAddress, + private sender: AztecAddress, + private wallet: Wallet, + protected gasSettings: GasSettings, + private setMaxFeeToOne = false +) +``` + +**Parameters:** + +- `paymentContract`: `AztecAddress` + - Address which will hold the fee payment. +- `sender`: `AztecAddress` + - Address of the account that will pay the fee +- `wallet`: `Wallet` + - A wallet to perform the simulation to get the accepted asset +- `gasSettings`: `GasSettings` + - Gas settings used to compute the maximum fee the user is willing to pay +- `setMaxFeeToOne` (optional): `any` + - If true, the max fee will be set to 1. TODO(#7694): Remove this param once the lacking feature in TXE is implemented. + +#### Methods + + +##### getAsset + +The asset used to pay the fee. + +**Signature:** + +```typescript +async getAsset(): Promise +``` + +**Returns:** + +`Promise` - The asset used to pay the fee. + +##### getFeePayer + +**Signature:** + +```typescript +getFeePayer(): Promise +``` + +**Returns:** + +`Promise` + +##### getExecutionPayload + +Creates an execution payload to pay the fee using a private function through an FPC in the desired asset + +**Signature:** + +```typescript +async getExecutionPayload(): Promise +``` + +**Returns:** + +`Promise` - An execution payload that contains the required function calls and auth witnesses. + +##### getGasSettings + +**Signature:** + +```typescript +getGasSettings(): GasSettings | undefined +``` + +**Returns:** + +`GasSettings | undefined` + +--- + +### `fee/public_fee_payment_method.ts` + + +#### PublicFeePaymentMethod + +**Type:** Class + +**Deprecated:** Is not supported on mainnet. Use FeeJuicePaymentMethodWithClaim or `SponsoredFeePaymentMethod` instead. + +Holds information about how the fee for a transaction is to be paid. + +**Implements:** `FeePaymentMethod` + + +#### Constructor + +**Signature:** + +```typescript +constructor( + protected paymentContract: AztecAddress, + protected sender: AztecAddress, + protected wallet: Wallet, + protected gasSettings: GasSettings +) +``` + +**Parameters:** + +- `paymentContract`: `AztecAddress` + - Address which will hold the fee payment. +- `sender`: `AztecAddress` + - An auth witness provider to authorize fee payments +- `wallet`: `Wallet` + - A wallet to perform the simulation to get the accepted asset +- `gasSettings`: `GasSettings` + - Gas settings used to compute the maximum fee the user is willing to pay + +#### Methods + + +##### getAsset + +The asset used to pay the fee. + +**Signature:** + +```typescript +async getAsset(): Promise +``` + +**Returns:** + +`Promise` - The asset used to pay the fee. + +##### getFeePayer + +**Signature:** + +```typescript +getFeePayer(): Promise +``` + +**Returns:** + +`Promise` + +##### getExecutionPayload + +Creates an execution payload to pay the fee using a public function through an FPC in the desired asset + +**Signature:** + +```typescript +async getExecutionPayload(): Promise +``` + +**Returns:** + +`Promise` - An execution payload that contains the required function calls. + +##### getGasSettings + +**Signature:** + +```typescript +getGasSettings(): GasSettings | undefined +``` + +**Returns:** + +`GasSettings | undefined` + +--- + +### `fee/sponsored_fee_payment.ts` + + +#### SponsoredFeePaymentMethod + +**Type:** Class + +A fee payment method that uses a contract that blindly sponsors transactions. This contract is expected to be prefunded in testing environments. + +**Implements:** `FeePaymentMethod` + + +#### Constructor + +**Signature:** + +```typescript +constructor(private paymentContract: AztecAddress) +``` + +**Parameters:** + +- `paymentContract`: `AztecAddress` + +#### Methods + + +##### getAsset + +**Signature:** + +```typescript +getAsset(): Promise +``` + +**Returns:** + +`Promise` + +##### getFeePayer + +**Signature:** + +```typescript +getFeePayer(): Promise +``` + +**Returns:** + +`Promise` + +##### getExecutionPayload + +**Signature:** + +```typescript +async getExecutionPayload(): Promise +``` + +**Returns:** + +`Promise` + +##### getGasSettings + +**Signature:** + +```typescript +getGasSettings(): GasSettings | undefined +``` + +**Returns:** + +`GasSettings | undefined` + +## Utils + + +--- + +### `utils/abi_types.ts` + + +#### FieldLike + +**Type:** Type Alias + +Any type that can be converted into a field for a contract call. + +**Signature:** + +```typescript +export type FieldLike = Fr | Buffer | bigint | number | { toField: () => Fr }; +``` + +#### EthAddressLike + +**Type:** Type Alias + +Any type that can be converted into an EthAddress Aztec.nr struct. + +**Signature:** + +```typescript +export type EthAddressLike = { address: FieldLike } | EthAddress; +``` + +#### AztecAddressLike + +**Type:** Type Alias + +Any type that can be converted into an AztecAddress Aztec.nr struct. + +**Signature:** + +```typescript +export type AztecAddressLike = { address: FieldLike } | AztecAddress; +``` + +#### FunctionSelectorLike + +**Type:** Type Alias + +Any type that can be converted into a FunctionSelector Aztec.nr struct. + +**Signature:** + +```typescript +export type FunctionSelectorLike = FieldLike | FunctionSelector; +``` + +#### EventSelectorLike + +**Type:** Type Alias + +Any type that can be converted into an EventSelector Aztec.nr struct. **Signature:** ```typescript -public async bridgeTokensPrivate( - to: AztecAddress, - amount: bigint, - mint = false -): Promise +export type EventSelectorLike = FieldLike | EventSelector; +``` + +#### U128Like + +**Type:** Type Alias + +Any type that can be converted into a U128. + +**Signature:** + +```typescript +export type U128Like = bigint | number; +``` + +#### WrappedFieldLike + +**Type:** Type Alias + +Any type that can be converted into a struct with a single `inner` field. + +**Signature:** + +```typescript +export type WrappedFieldLike = { inner: FieldLike } | FieldLike; +``` + +#### OptionLike + +**Type:** Type Alias + +Noir `Option` lowered ABI shape, plus ergonomic direct `T | null | undefined` inputs. + +**Signature:** + +```typescript +export type OptionLike = + | T + | null + | undefined + | { _is_some: boolean; _value: T }; +``` + +--- + +### `utils/authwit.ts` + + +#### IntentInnerHash + +**Type:** Type Alias + +Intent with an inner hash + +**Signature:** + +```typescript +export type IntentInnerHash = { + consumer: AztecAddress; + innerHash: Fr; +}; +``` + +**Type Members:** + +##### consumer + +The consumer + +**Type:** `AztecAddress` + +##### innerHash + +The action to approve + +**Type:** `Fr` + + +#### CallIntent + +**Type:** Type Alias + +Intent with a call + +**Signature:** + +```typescript +export type CallIntent = { + caller: AztecAddress; + call: FunctionCall; +}; +``` + +**Type Members:** + +##### caller + +The caller to approve + +**Type:** `AztecAddress` + +##### call + +The call to approve + +**Type:** `FunctionCall` + + +#### ContractFunctionInteractionCallIntent + +**Type:** Type Alias + +Intent with a ContractFunctionInteraction + +**Signature:** + +```typescript +export type ContractFunctionInteractionCallIntent = { + caller: AztecAddress; + action: ContractFunctionInteraction; +}; +``` + +**Type Members:** + +##### caller + +The caller to approve + +**Type:** `AztecAddress` + +##### action + +The action to approve + +**Type:** `ContractFunctionInteraction` + + +#### isContractFunctionInteractionCallIntent + +**Type:** Function + +Identifies ContractFunctionInteractionCallIntents + +**Signature:** + +```typescript +export isContractFunctionInteractionCallIntent(messageHashOrIntent: Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent): messageHashOrIntent is ContractFunctionInteractionCallIntent ``` **Parameters:** -- `to`: `AztecAddress` - - Address to send the tokens to on L2. -- `amount`: `bigint` - - Amount of tokens to send. -- `mint` (optional): `any` - - Whether to mint the tokens before sending (only during testing). +- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` **Returns:** -`Promise` +`messageHashOrIntent is ContractFunctionInteractionCallIntent` -#### L1TokenPortalManager +#### computeAuthWitMessageHash + +**Type:** Constant + +Compute an authentication witness message hash from an intent and metadata If using the `IntentInnerHash`, the consumer is the address that can "consume" the authwit, for token approvals it is the token contract itself. The `innerHash` itself will be the message that a contract is allowed to execute. At the point of "approval checking", the validating contract (account for private and registry for public) will be computing the message hash (`H(consumer, chainid, version, inner_hash)`) where the all but the `inner_hash` is injected from the context (consumer = msg_sender), and use it for the authentication check. Therefore, any allowed `innerHash` will therefore also have information around where it can be spent (version, chainId) and who can spend it (consumer). If using the `CallIntent`, the caller is the address that is making the call, for a token approval from Alice to Bob, this would be Bob. The action is then used along with the `caller` to compute the `innerHash` and the consumer. + +**Value Type:** `any` + + +#### getMessageHashFromIntent + +**Type:** Function + +Compute an authentication witness message hash from an intent and metadata. This is just a wrapper around computeAuthwitMessageHash that allows receiving an already computed messageHash as input + +**Signature:** + +```typescript +export async getMessageHashFromIntent( + messageHashOrIntent: Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, + chainInfo: ChainInfo +) +``` + +**Parameters:** + +- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` + - The precomputed messageHash or intent to approve (consumer and innerHash or caller and call/action) +- `chainInfo`: `ChainInfo` + +**Returns:** + +`Promise` - The message hash for the intent + +#### computeInnerAuthWitHashFromAction + +**Type:** Constant + +Computes the inner authwitness hash for either a function call or an action, for it to later be combined with the metadata required for the outer hash and eventually the full AuthWitness. + +**Value Type:** `any` + + +#### lookupValidity + +**Type:** Function + +Lookup the validity of an authwit in private and public contexts. Uses the chain id and version of the wallet. + +**Signature:** + +```typescript +export async lookupValidity( + wallet: Wallet, + onBehalfOf: AztecAddress, + intent: IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, + witness: AuthWitness +): Promise<{ + isValidInPrivate: boolean; + isValidInPublic: boolean; + }> +``` + +**Parameters:** + +- `wallet`: `Wallet` + - The wallet use to simulate and read the public data +- `onBehalfOf`: `AztecAddress` + - The address of the "approver" +- `intent`: `IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` + - The consumer and inner hash or the caller and action to lookup +- `witness`: `AuthWitness` + - The computed authentication witness to check + +**Returns:** + +```typescript +Promise<{ + /** boolean flag indicating if the authwit is valid in private context */ + isValidInPrivate: boolean; + /** boolean flag indicating if the authwit is valid in public context */ + isValidInPublic: boolean; +}> +``` + +A struct containing the validity of the authwit in private and public contexts. + +#### SetPublicAuthwitContractInteraction **Type:** Class -Helper for interacting with a test TokenPortal on L1 for both withdrawing from and bridging to L2. +Convenience class designed to wrap the very common interaction of setting a public authwit in the AuthRegistry contract -**Extends:** `L1ToL2TokenPortalManager` +**Extends:** `ContractFunctionInteraction` #### Constructor @@ -3212,354 +4542,374 @@ Helper for interacting with a test TokenPortal on L1 for both withdrawing from a **Signature:** ```typescript -constructor( - portalAddress: EthAddress, - tokenAddress: EthAddress, - handlerAddress: EthAddress | undefined, - outboxAddress: EthAddress, - extendedClient: ExtendedViemWalletClient, - logger: Logger +private constructor( + wallet: Wallet, + private from: AztecAddress, + messageHash: Fr, + authorized: boolean ) ``` **Parameters:** -- `portalAddress`: `EthAddress` -- `tokenAddress`: `EthAddress` -- `handlerAddress`: `EthAddress | undefined` -- `outboxAddress`: `EthAddress` -- `extendedClient`: `ExtendedViemWalletClient` -- `logger`: `Logger` +- `wallet`: `Wallet` +- `from`: `AztecAddress` +- `messageHash`: `Fr` +- `authorized`: `boolean` #### Methods -##### withdrawFunds - -Withdraws funds from the portal by consuming an L2 to L1 message. Returns once the tx is mined on L1. +##### create **Signature:** ```typescript -public async withdrawFunds( - amount: bigint, - recipient: EthAddress, - blockNumber: bigint, - messageIndex: bigint, - siblingPath: SiblingPath +static async create( + wallet: Wallet, + from: AztecAddress, + messageHashOrIntent: Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, + authorized: boolean ) ``` **Parameters:** -- `amount`: `bigint` - - Amount to withdraw. -- `recipient`: `EthAddress` - - Who will receive the funds. -- `blockNumber`: `bigint` - - L2 block number of the message. -- `messageIndex`: `bigint` - - Index of the message. -- `siblingPath`: `SiblingPath` - - Sibling path of the message. +- `wallet`: `Wallet` +- `from`: `AztecAddress` +- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` +- `authorized`: `boolean` **Returns:** -`Promise` +`Promise` -##### getL2ToL1MessageLeaf +##### simulate -Computes the L2 to L1 message leaf for the given parameters. +Overrides the simulate method, adding the sender of the authwit (authorizer) as from and preventing misuse **Signature:** ```typescript -public async getL2ToL1MessageLeaf( - amount: bigint, - recipient: EthAddress, - l2Bridge: AztecAddress, - callerOnL1: EthAddress = EthAddress.ZERO -): Promise +public override simulate(options: Omit = {} as Omit): Promise ``` **Parameters:** -- `amount`: `bigint` - - Amount to bridge. -- `recipient`: `EthAddress` - - Recipient on L1. -- `l2Bridge`: `AztecAddress` - - Address of the L2 bridge. -- `callerOnL1` (optional): `EthAddress` - - Caller address on L1. +- `options` (optional): `Omit` + - An optional object containing additional configuration for the transaction. **Returns:** -`Promise` - -## Fee +`Promise` - The result of the transaction as returned by the contract function. +##### profile ---- +Overrides the profile method, adding the sender of the authwit (authorizer) as from and preventing misuse -### `fee/fee_juice_payment_method_with_claim.ts` +**Signature:** +```typescript +public override profile(options: Omit = { profileMode: 'gates' }): Promise +``` -#### FeeJuicePaymentMethodWithClaim +**Parameters:** -**Type:** Class +- `options` (optional): `Omit` + - Same options as `simulate`, plus profiling method -Pay fee directly with Fee Juice claimed in the same tx. Claiming consumes an L1 to L2 message that "contains" the fee juice bridged from L1. +**Returns:** -**Implements:** `FeePaymentMethod` +`Promise` - An object containing the function return value and profile result. +##### send -#### Constructor +Overrides the send method, adding the sender of the authwit (authorizer) as from and preventing misuse **Signature:** ```typescript -constructor( - private sender: AztecAddress, - private claim: Pick -) +public override send(options?: Omit): Promise ``` **Parameters:** -- `sender`: `AztecAddress` -- `claim`: `Pick` - -#### Methods +- `options` (optional): `Omit` + - An optional object containing 'fee' options information +**Returns:** -##### getExecutionPayload +`Promise` - A TxReceipt (if wait is true/undefined) or TxHash (if wait is false) -Creates an execution payload to pay the fee in Fee Juice. +##### send **Signature:** ```typescript -async getExecutionPayload(): Promise +public override send(options?: Omit, 'from'>): Promise> ``` +**Parameters:** + +- `options` (optional): `Omit, 'from'>` + **Returns:** -`Promise` - An execution payload that just contains the `claim_and_end_setup` function call. +`Promise>` -##### getAsset +##### send **Signature:** ```typescript -getAsset() +public override send(options?: Omit, 'from'>): Promise> ``` +**Parameters:** + +- `options` (optional): `Omit, 'from'>` + **Returns:** -`Promise` +`Promise>` -##### getFeePayer +--- -**Signature:** +### `utils/cross_chain.ts` -```typescript -getFeePayer(): Promise -``` -**Returns:** +#### waitForL1ToL2MessageReady -`Promise` +**Type:** Function -##### getGasSettings +Waits for the L1 to L2 message to be ready to be consumed. **Signature:** ```typescript -getGasSettings(): GasSettings | undefined +export waitForL1ToL2MessageReady( + node: Pick, + l1ToL2MessageHash: Fr, + opts: { + timeoutSeconds: number; + chainTip?: BlockTag; +} +): Promise ``` -**Returns:** - -`GasSettings | undefined` - ---- - -### `fee/fee_payment_method.ts` - +**Parameters:** -#### FeePaymentMethod +- `node`: `Pick` + - Aztec node instance used to obtain the information about the message +- `l1ToL2MessageHash`: `Fr` + - Hash of the L1 to L2 message +- `opts`: + - Options -**Type:** Interface + ```typescript + { + /** Timeout for the operation in seconds */ timeoutSeconds: number; + /** + * Chain tip to evaluate readiness against. Defaults to `'latest'`. Set this to the tip the consuming PXE syncs to + * (e.g. `'proven'`) so readiness answers whether the message is present at the same block the transaction + * simulation will anchor to, not at a newer tip. + */ + chainTip?: BlockTag; + } + ``` -Holds information about how the fee for a transaction is to be paid. +**Returns:** -#### Methods +`Promise` +#### isL1ToL2MessageReady -##### getAsset +**Type:** Function -The asset used to pay the fee. +Returns whether the L1 to L2 message is ready to be consumed. **Signature:** ```typescript -getAsset(): Promise +export async isL1ToL2MessageReady( + node: Pick, + l1ToL2MessageHash: Fr, + chainTip: BlockTag = 'latest' +): Promise ``` -**Returns:** +**Parameters:** -`Promise` +- `node`: `Pick` + - Aztec node instance used to obtain the information about the message +- `l1ToL2MessageHash`: `Fr` + - Hash of the L1 to L2 message +- `chainTip` (optional): `BlockTag` + - Chain tip to evaluate readiness against. Defaults to `'latest'`. Pass the tip the consuming PXE syncs to (e.g. `'proven'`) so readiness is checked at the block the transaction simulation will anchor to. -##### getExecutionPayload +**Returns:** -Returns the data to be added to the final execution request to pay the fee in the given asset +`Promise` - True if the message is ready to be consumed, false otherwise -**Signature:** +--- -```typescript -getExecutionPayload(): Promise -``` +### `utils/fee_juice.ts` -**Returns:** -`Promise` - The function calls to pay the fee. +#### getFeeJuiceBalance -##### getFeePayer +**Type:** Function -The expected fee payer for this tx. +Returns the owner's fee juice balance. Note: This is used only e2e_local_network_example test. TODO: Consider nuking. **Signature:** ```typescript -getFeePayer(): Promise +export async getFeeJuiceBalance( + owner: AztecAddress, + node: AztecNode +): Promise ``` +**Parameters:** + +- `owner`: `AztecAddress` +- `node`: `AztecNode` + **Returns:** -`Promise` +`Promise` -##### getGasSettings +--- -The gas settings (if any) used to compute the execution payload of the payment method +### `utils/field_compressed_string.ts` -**Signature:** -```typescript -getGasSettings(): GasSettings | undefined -``` +#### readFieldCompressedString -**Returns:** +**Type:** Constant + +This turns + +**Value Type:** `any` -`GasSettings | undefined` --- -### `fee/private_fee_payment_method.ts` +### `utils/node.ts` -#### PrivateFeePaymentMethod +#### waitForNode -**Type:** Class +**Type:** Constant -Holds information about how the fee for a transaction is to be paid. +Waits for an Aztec node to become reachable, polling AztecNode.getNodeInfo until it succeeds. -**Implements:** `FeePaymentMethod` +**Value Type:** `any` -#### Constructor +#### waitForTx + +**Type:** Function + +Waits for a transaction to be mined and returns its receipt. **Signature:** ```typescript -constructor( - private paymentContract: AztecAddress, - private sender: AztecAddress, - private wallet: Wallet, - protected gasSettings: GasSettings, - private setMaxFeeToOne = false -) +export async waitForTx( + node: AztecNode, + txHash: TxHash, + opts?: WaitOpts +): Promise ``` **Parameters:** -- `paymentContract`: `AztecAddress` - - Address which will hold the fee payment. -- `sender`: `AztecAddress` - - Address of the account that will pay the fee -- `wallet`: `Wallet` - - A wallet to perform the simulation to get the accepted asset -- `gasSettings`: `GasSettings` - - Gas settings used to compute the maximum fee the user is willing to pay -- `setMaxFeeToOne` (optional): `any` - - If true, the max fee will be set to 1. TODO(#7694): Remove this param once the lacking feature in TXE is implemented. +- `node`: `AztecNode` + - The Aztec node to query for transaction status +- `txHash`: `TxHash` + - The hash of the transaction to wait for +- `opts` (optional): `WaitOpts` + - Optional configuration for waiting behavior + +**Returns:** + +`Promise` - The transaction receipt + +#### createAztecNodeClient + +**Type:** Constant -#### Methods +This is re-exported from `@aztec/stdlib/interfaces/client`. See the source module for full documentation. + +**Value Type:** `Re-export` -##### getAsset +#### AztecNode -The asset used to pay the fee. +**Type:** Type Alias + +This is a type re-exported from `@aztec/stdlib/interfaces/client`. See the source module for full type definition and documentation. **Signature:** ```typescript -async getAsset(): Promise +export type { AztecNode } from '@aztec/stdlib/interfaces/client' ``` -**Returns:** +#### AztecNodeClientOptions -`Promise` - The asset used to pay the fee. +**Type:** Type Alias -##### getFeePayer +This is a type re-exported from `@aztec/stdlib/interfaces/client`. See the source module for full type definition and documentation. **Signature:** ```typescript -getFeePayer(): Promise +export type { AztecNodeClientOptions } from '@aztec/stdlib/interfaces/client' ``` -**Returns:** +--- -`Promise` +### `utils/pub_key.ts` -##### getExecutionPayload -Creates an execution payload to pay the fee using a private function through an FPC in the desired asset +#### generatePublicKey + +**Type:** Function + +Method for generating a public grumpkin key from a private key. **Signature:** ```typescript -async getExecutionPayload(): Promise +export generatePublicKey(privateKey: GrumpkinScalar): Promise ``` -**Returns:** - -`Promise` - An execution payload that contains the required function calls and auth witnesses. +**Parameters:** -##### getGasSettings +- `privateKey`: `GrumpkinScalar` + - The private key. -**Signature:** +**Returns:** -```typescript -getGasSettings(): GasSettings | undefined -``` +`Promise` - The generated public key. -**Returns:** +## Wallet -`GasSettings | undefined` --- -### `fee/public_fee_payment_method.ts` +### `wallet/account_entrypoint_meta_payment_method.ts` -#### PublicFeePaymentMethod +#### AccountEntrypointMetaPaymentMethod **Type:** Class -Holds information about how the fee for a transaction is to be paid. +Fee payment method that allows an account contract to pay for its own deployment It works by rerouting the provided fee payment method through the account's entrypoint, which sets itself as fee payer. If no payment method is provided, it is assumed the account will pay with its own fee juice balance. Usually, in order to pay fees it is necessary to obtain an ExecutionPayload that encodes the necessary information that is sent to the user's account entrypoint, that has plumbing to handle it. If there's no account contract yet (it's being deployed) a MultiCallContract is used, which doesn't have a concept of fees or how to handle this payload. HOWEVER, the account contract's entrypoint does, so this method reshapes that fee payload into a call to the account contract entrypoint being deployed with the original fee payload. This class can be seen in action in DeployAccountMethod.ts#getSelfPaymentMethod **Implements:** `FeePaymentMethod` @@ -3570,66 +4920,58 @@ Holds information about how the fee for a transaction is to be paid. ```typescript constructor( - protected paymentContract: AztecAddress, - protected sender: AztecAddress, - protected wallet: Wallet, - protected gasSettings: GasSettings + private account: Account, + private chainInfo: ChainInfo, + private paymentMethod?: FeePaymentMethod, + private feeEntrypointOptions?: any ) ``` **Parameters:** -- `paymentContract`: `AztecAddress` - - Address which will hold the fee payment. -- `sender`: `AztecAddress` - - An auth witness provider to authorize fee payments -- `wallet`: `Wallet` - - A wallet to perform the simulation to get the accepted asset -- `gasSettings`: `GasSettings` - - Gas settings used to compute the maximum fee the user is willing to pay +- `account`: `Account` +- `chainInfo`: `ChainInfo` +- `paymentMethod` (optional): `FeePaymentMethod` +- `feeEntrypointOptions` (optional): `any` #### Methods ##### getAsset -The asset used to pay the fee. - **Signature:** ```typescript -async getAsset(): Promise +getAsset(): Promise ``` **Returns:** -`Promise` - The asset used to pay the fee. +`Promise` -##### getFeePayer +##### getExecutionPayload **Signature:** ```typescript -getFeePayer(): Promise +async getExecutionPayload(): Promise ``` **Returns:** -`Promise` - -##### getExecutionPayload +`Promise` -Creates an execution payload to pay the fee using a public function through an FPC in the desired asset +##### getFeePayer **Signature:** ```typescript -async getExecutionPayload(): Promise +getFeePayer(): Promise ``` **Returns:** -`Promise` - An execution payload that contains the required function calls. +`Promise` ##### getGasSettings @@ -3645,1075 +4987,1044 @@ getGasSettings(): GasSettings | undefined --- -### `fee/sponsored_fee_payment.ts` +### `wallet/account_manager.ts` -#### SponsoredFeePaymentMethod +#### AccountManagerCreateOptions -**Type:** Class +**Type:** Interface -A fee payment method that uses a contract that blindly sponsors transactions. This contract is expected to be prefunded in testing environments. +Optional overrides passed to AccountManager.create. -**Implements:** `FeePaymentMethod` +#### Properties -#### Constructor -**Signature:** +##### salt -```typescript -constructor(private paymentContract: AztecAddress) -``` +Contract instantiation salt. Defaults to a random `Fr`. -**Parameters:** +**Type:** `Salt` -- `paymentContract`: `AztecAddress` -#### Methods +##### immutablesHash +Commitment to the contract's immutable storage values. Folded into the salted initialization hash, so a non-zero value affects the derived address. Defaults to `Fr.ZERO`. -##### getAsset +**Type:** `Fr` -**Signature:** -```typescript -getAsset(): Promise -``` +##### deployer -**Returns:** +Address recorded as the instance deployer. Defaults to `AztecAddress.ZERO`. -`Promise` +**Type:** `AztecAddress` -##### getFeePayer -**Signature:** +#### AccountManager -```typescript -getFeePayer() -``` +**Type:** Class -**Returns:** +Manages a user account. Provides methods for calculating the account's address and other related data, plus a helper to return a preconfigured deploy method. -`Promise` -##### getExecutionPayload +#### Constructor **Signature:** ```typescript -async getExecutionPayload(): Promise +private constructor( + private wallet: Wallet, + private secretKey: Fr, + private accountContract: AccountContract, + private instance: ContractInstanceWithAddress +) ``` -**Returns:** +**Parameters:** -`Promise` +- `wallet`: `Wallet` +- `secretKey`: `Fr` +- `accountContract`: `AccountContract` +- `instance`: `ContractInstanceWithAddress` -##### getGasSettings +#### Methods + + +##### create **Signature:** ```typescript -getGasSettings(): GasSettings | undefined +static async create( + wallet: Wallet, + secretKey: Fr, + accountContract: AccountContract, + opts?: AccountManagerCreateOptions +) ``` -**Returns:** - -`GasSettings | undefined` - -## Utils - - ---- - -### `utils/abi_types.ts` +**Parameters:** +- `wallet`: `Wallet` +- `secretKey`: `Fr` +- `accountContract`: `AccountContract` +- `opts` (optional): `AccountManagerCreateOptions` -#### FieldLike +**Returns:** -**Type:** Type Alias +`Promise` -Any type that can be converted into a field for a contract call. +##### getPublicKeys **Signature:** ```typescript -export type FieldLike = Fr | Buffer | bigint | number | { toField: () => Fr }; +protected getPublicKeys(): PublicKeys ``` -#### EthAddressLike +**Returns:** -**Type:** Type Alias +`PublicKeys` -Any type that can be converted into an EthAddress Aztec.nr struct. +##### getPublicKeysHash **Signature:** ```typescript -export type EthAddressLike = { address: FieldLike } | EthAddress; +protected getPublicKeysHash(): Promise ``` -#### AztecAddressLike +**Returns:** -**Type:** Type Alias +`Promise` -Any type that can be converted into an AztecAddress Aztec.nr struct. +##### getCompleteAddress + +Gets the calculated complete address associated with this account. Does not require the account to have been published for public execution. **Signature:** ```typescript -export type AztecAddressLike = { address: FieldLike } | AztecAddress; +public getCompleteAddress(): Promise ``` -#### FunctionSelectorLike +**Returns:** -**Type:** Type Alias +`Promise` - The address, partial address, and encryption public key. -Any type that can be converted into a FunctionSelector Aztec.nr struct. +##### getSecretKey + +Returns the secret key used to derive the rest of the privacy keys for this contract **Signature:** ```typescript -export type FunctionSelectorLike = FieldLike | FunctionSelector; +public getSecretKey() ``` -#### EventSelectorLike +**Returns:** -**Type:** Type Alias +`Fr` -Any type that can be converted into an EventSelector Aztec.nr struct. +##### getInstance + +Returns the contract instance definition associated with this account. Does not require the account to have been published for public execution. **Signature:** ```typescript -export type EventSelectorLike = FieldLike | EventSelector; +public getInstance(): ContractInstanceWithAddress ``` -#### U128Like +**Returns:** -**Type:** Type Alias +`ContractInstanceWithAddress` - ContractInstance instance. -Any type that can be converted into a U128. +##### getAccount + +Returns the account (the transaction signer) backed by this account contract. Use it to build and authorize transactions from this account. **Signature:** ```typescript -export type U128Like = bigint | number; +public async getAccount(): Promise ``` -#### WrappedFieldLike +**Returns:** -**Type:** Type Alias +`Promise` -Any type that can be converted into a struct with a single `inner` field. +##### getAccountContract + +Returns the account contract that backs this account. **Signature:** ```typescript -export type WrappedFieldLike = { inner: FieldLike } | FieldLike; +getAccountContract(): AccountContract ``` ---- - -### `utils/authwit.ts` - +**Returns:** -#### IntentInnerHash +`AccountContract` - The account contract -**Type:** Type Alias +##### getDeployMethod -Intent with an inner hash +Returns a preconfigured deploy method that contains all the necessary function calls to deploy the account contract. **Signature:** ```typescript -export type IntentInnerHash = { - consumer: AztecAddress; - innerHash: Fr; -}; +public async getDeployMethod(): Promise ``` -**Type Members:** +**Returns:** -##### consumer +`Promise` -The consumer +##### hasInitializer -**Type:** `AztecAddress` +Returns whether this account contract has an initializer function. -##### innerHash +**Signature:** -The action to approve +```typescript +public async hasInitializer() +``` -**Type:** `Fr` +**Returns:** +`Promise` -#### CallIntent +#### Getters -**Type:** Type Alias -Intent with a call +##### address (getter) **Signature:** ```typescript -export type CallIntent = { - caller: AztecAddress; - call: FunctionCall; -}; +get address(): AztecAddress { ``` -**Type Members:** +**Returns:** -##### caller +`AztecAddress` -The caller to approve +--- -**Type:** `AztecAddress` +### `wallet/capabilities.ts` -##### call -The call to approve +#### CAPABILITY_VERSION -**Type:** `FunctionCall` +**Type:** Constant +Current capability manifest version. -#### ContractFunctionInteractionCallIntent +**Value Type:** `any` -**Type:** Type Alias -Intent with a ContractFunctionInteraction +#### ContractFunctionPattern -**Signature:** +**Type:** Interface -```typescript -export type ContractFunctionInteractionCallIntent = { - caller: AztecAddress; - action: ContractFunctionInteraction; -}; -``` +Pattern for matching contract functions with wildcards. Used in simulation and transaction capabilities to specify which contract functions are allowed. -**Type Members:** -##### caller +#### Properties -The caller to approve -**Type:** `AztecAddress` +##### contract -##### action +Contract address or '*' for any contract -The action to approve +**Type:** `AztecAddress | '*'` -**Type:** `ContractFunctionInteraction` +##### function -#### computeAuthWitMessageHash +Function name or '*' for any function -**Type:** Constant +**Type:** `string` -Compute an authentication witness message hash from an intent and metadata If using the `IntentInnerHash`, the consumer is the address that can "consume" the authwit, for token approvals it is the token contract itself. The `innerHash` itself will be the message that a contract is allowed to execute. At the point of "approval checking", the validating contract (account for private and registry for public) will be computing the message hash (`H(consumer, chainid, version, inner_hash)`) where the all but the `inner_hash` is injected from the context (consumer = msg_sender), and use it for the authentication check. Therefore, any allowed `innerHash` will therefore also have information around where it can be spent (version, chainId) and who can spend it (consumer). If using the `CallIntent`, the caller is the address that is making the call, for a token approval from Alice to Bob, this would be Bob. The action is then used along with the `caller` to compute the `innerHash` and the consumer. -**Value Type:** `any` +##### additionalScopes +Additional addresses whose private state and keys are accessible when calling this function, beyond the sender's. - undefined: No additional scopes allowed - AztecAddress[]: Only these specific addresses allowed as additional scopes - '*': All known address allowed as an additional scope -#### getMessageHashFromIntent +**Type:** `AztecAddress[] | '*'` -**Type:** Function -Compute an authentication witness message hash from an intent and metadata. This is just a wrapper around computeAuthwitMessageHash that allows receiving an already computed messageHash as input +#### AccountsCapability -**Signature:** +**Type:** Interface -```typescript -export async getMessageHashFromIntent( - messageHashOrIntent: Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, - chainInfo: ChainInfo -) -``` +Account access capability - grants access to user accounts. Maps to wallet methods: - getAccounts (when canGet: true) - createAuthWit (when canCreateAuthWit: true) The wallet decides which accounts to reveal to the app. Apps don't specify which accounts they want - they just request the capability and the wallet shows them the available accounts. -**Parameters:** -- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` - - The precomputed messageHash or intent to approve (consumer and innerHash or caller and call/action) -- `chainInfo`: `ChainInfo` +#### Properties -**Returns:** -`Promise` - The message hash for the intent +##### type -#### computeInnerAuthWitHashFromAction +Discriminator for capability type -**Type:** Constant +**Type:** `'accounts'` -Computes the inner authwitness hash for either a function call or an action, for it to later be combined with the metadata required for the outer hash and eventually the full AuthWitness. -**Value Type:** `any` +##### canGet +Can get accounts from wallet. Maps to: getAccounts -#### lookupValidity +**Type:** `boolean` -**Type:** Function -Lookup the validity of an authwit in private and public contexts. Uses the chain id and version of the wallet. +##### canCreateAuthWit -**Signature:** +Can create auth witnesses for accounts. Maps to: createAuthWit -```typescript -export async lookupValidity( - wallet: Wallet, - onBehalfOf: AztecAddress, - intent: IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, - witness: AuthWitness -): Promise<{ - isValidInPrivate: boolean; - isValidInPublic: boolean; - }> -``` +**Type:** `boolean` -**Parameters:** -- `wallet`: `Wallet` - - The wallet use to simulate and read the public data -- `onBehalfOf`: `AztecAddress` - - The address of the "approver" -- `intent`: `IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` - - The consumer and inner hash or the caller and action to lookup -- `witness`: `AuthWitness` - - The computed authentication witness to check +#### GrantedAccountsCapability -**Returns:** +**Type:** Interface -```typescript -Promise<{ - /** boolean flag indicating if the authwit is valid in private context */ - isValidInPrivate: boolean; - /** boolean flag indicating if the authwit is valid in public context */ - isValidInPublic: boolean; -}> -``` +Granted account access capability. Extends the request with specific accounts that were granted by the wallet. -A struct containing the validity of the authwit in private and public contexts. +**Extends:** `AccountsCapability` -#### SetPublicAuthwitContractInteraction -**Type:** Class +#### Properties -Convenience class designed to wrap the very common interaction of setting a public authwit in the AuthRegistry contract -**Extends:** `ContractFunctionInteraction` +##### accounts +Specific accounts granted by the wallet with their aliases. The wallet adds this when granting the capability. -#### Constructor +**Type:** `Aliased[]` -**Signature:** -```typescript -private constructor( - wallet: Wallet, - private from: AztecAddress, - messageHash: Fr, - authorized: boolean -) -``` +#### ContractsCapability -**Parameters:** +**Type:** Interface -- `wallet`: `Wallet` -- `from`: `AztecAddress` -- `messageHash`: `Fr` -- `authorized`: `boolean` +Contract interaction capability - for registering and querying contracts. Maps to wallet methods: - registerContract (when canRegister: true) - getContractMetadata (when canGetMetadata: true) Matching is done by contract address, not class ID. This allows updating existing contracts with new artifacts (e.g., when contract is upgraded to a new contractClassId onchain). Note: For querying contract class metadata, use ContractClassesCapability instead. -#### Methods + +#### Properties -##### create +##### type -**Signature:** +Discriminator for capability type -```typescript -static async create( - wallet: Wallet, - from: AztecAddress, - messageHashOrIntent: Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent, - authorized: boolean -) -``` +**Type:** `'contracts'` -**Parameters:** -- `wallet`: `Wallet` -- `from`: `AztecAddress` -- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent | ContractFunctionInteractionCallIntent` -- `authorized`: `boolean` +##### contracts -**Returns:** +Which contracts this applies to: - '*': Any contract address - AztecAddress[]: Specific contract addresses -`Promise` +**Type:** `'*' | AztecAddress[]` -##### simulate -Overrides the simulate method, adding the sender of the authwit (authorizer) as from and preventing misuse +##### canRegister -**Signature:** +Can register contracts and update existing registrations. Maps to: registerContract When true, allows: - Registering new contract instances at specified addresses - Re-registering existing contracts with updated artifacts (e.g., after upgrade) -```typescript -public override simulate(options: Omit): Promise> -``` +**Type:** `boolean` -**Parameters:** -- `options`: `Omit` - - An optional object containing additional configuration for the transaction. +##### canGetMetadata -**Returns:** +Can query contract metadata. Maps to: getContractMetadata -`Promise>` - The result of the transaction as returned by the contract function. +**Type:** `boolean` -##### simulate -**Signature:** +#### GrantedContractsCapability -```typescript -public override simulate(options: Omit = {}): Promise> -``` +**Type:** Interface -**Parameters:** +Granted contract interaction capability. The wallet may reduce the scope (e.g., from '*' to specific addresses). -- `options` (optional): `Omit` +**Extends:** `ContractsCapability` -**Returns:** -`Promise>` +#### ContractClassesCapability -##### profile +**Type:** Interface -Overrides the profile method, adding the sender of the authwit (authorizer) as from and preventing misuse +Contract class capability - for querying contract class metadata and registering contract classes. Maps to wallet methods: - getContractClassMetadata (when canGetMetadata: true) - registerContractClass (when canRegister: true) Contract classes are identified by their class ID (Fr), not by contract address. Multiple contract instances can share the same class. This capability grants permission to query metadata for, and register, specific contract classes. Apps typically acquire this permission automatically when registering a contract with an artifact (the wallet auto-grants permission for that contract's class ID). -**Signature:** -```typescript -public override profile(options: Omit = { profileMode: 'gates' }): Promise -``` +#### Properties -**Parameters:** -- `options` (optional): `Omit` - - Same options as `simulate`, plus profiling method +##### type -**Returns:** +Discriminator for capability type -`Promise` - An object containing the function return value and profile result. +**Type:** `'contractClasses'` -##### send -Overrides the send method, adding the sender of the authwit (authorizer) as from and preventing misuse +##### classes -**Signature:** +Which contract classes this applies to: - '*': Any contract class ID - Fr[]: Specific contract class IDs -```typescript -public override send(options: Omit = {}): SentTx -``` +**Type:** `'*' | Fr[]` -**Parameters:** -- `options` (optional): `Omit` - - An optional object containing 'fee' options information +##### canRegister -**Returns:** +Can register a contract class artifact in the local PXE. Maps to: registerContractClass -`SentTx` - A SentTx instance for tracking the transaction status and information. +**Type:** `boolean` ---- -### `utils/cross_chain.ts` +##### canGetMetadata +Can query contract class metadata. Maps to: getContractClassMetadata -#### waitForL1ToL2MessageReady +**Type:** `boolean` -**Type:** Function -Waits for the L1 to L2 message to be ready to be consumed. +#### GrantedContractClassesCapability -**Signature:** +**Type:** Interface -```typescript -export async waitForL1ToL2MessageReady( - node: Pick, - l1ToL2MessageHash: Fr, - opts: { - timeoutSeconds: number; - forPublicConsumption: boolean; -} -) -``` +Granted contract class capability. The wallet may reduce the scope (e.g., from '*' to specific class IDs). -**Parameters:** +**Extends:** `ContractClassesCapability` -- `node`: `Pick` - - Aztec node instance used to obtain the information about the message -- `l1ToL2MessageHash`: `Fr` - - Hash of the L1 to L2 message -- `opts`: `{ - /** Timeout for the operation in seconds */ timeoutSeconds: number; - /** True if the message is meant to be consumed from a public function */ forPublicConsumption: boolean; - }` - - Options -**Returns:** +#### SimulationCapability -`Promise` +**Type:** Interface -#### isL1ToL2MessageReady +Transaction simulation capability - for simulating transactions and executing utilities. Maps to wallet methods: - simulateTx (when transactions scope specified) - executeUtility (when utilities scope specified) - profileTx (when transactions scope specified) -**Type:** Function -Returns whether the L1 to L2 message is ready to be consumed. +#### Properties -**Signature:** -```typescript -export async isL1ToL2MessageReady( - node: Pick, - l1ToL2MessageHash: Fr, - opts: { - forPublicConsumption: boolean; - messageBlockNumber?: number; -} -): Promise -``` +##### type -**Parameters:** +Discriminator for capability type -- `node`: `Pick` - - Aztec node instance used to obtain the information about the message -- `l1ToL2MessageHash`: `Fr` - - Hash of the L1 to L2 message -- `opts`: `{ - /** True if the message is meant to be consumed from a public function */ forPublicConsumption: boolean; - /** Cached synced block number for the message (will be fetched from PXE otherwise) */ messageBlockNumber?: number; - }` - - Options +**Type:** `'simulation'` -**Returns:** -`Promise` - True if the message is ready to be consumed, false otherwise +##### transactions ---- +Transaction simulation scope. Maps to: simulateTx, profileTx -### `utils/fee_juice.ts` +**Type:** +```typescript +{ + /** + * Which contracts/functions to allow: + * - '*': Any transaction + * - ContractFunctionPattern[]: Specific contract functions + */ + scope: '*' | ContractFunctionPattern[]; + } +``` -#### getFeeJuiceBalance -**Type:** Function +##### utilities -Returns the owner's fee juice balance. Note: This is used only e2e_local_network_example test. TODO: Consider nuking. +Utility execution scope (unconstrained calls). Maps to: executeUtility -**Signature:** +**Type:** ```typescript -export async getFeeJuiceBalance( - owner: AztecAddress, - node: AztecNode -): Promise +{ + /** + * Which contracts/functions to allow: + * - '*': Any utility call + * - ContractFunctionPattern[]: Specific contract functions + */ + scope: '*' | ContractFunctionPattern[]; + } ``` -**Parameters:** -- `owner`: `AztecAddress` -- `node`: `AztecNode` +#### GrantedSimulationCapability -**Returns:** +**Type:** Interface -`Promise` +Granted transaction simulation capability. The wallet may reduce the scope (e.g., from '*' to specific patterns). ---- +**Extends:** `SimulationCapability` + + +#### TransactionCapability + +**Type:** Interface + +Transaction execution capability - for sending transactions. Maps to wallet methods: - sendTx Policy enforcement (rate limits, spending limits) should be handled at the contract level in Aztec, not at the wallet level. + + +#### Properties -### `utils/field_compressed_string.ts` +##### type -#### readFieldCompressedString +Discriminator for capability type -**Type:** Constant +**Type:** `'transaction'` -This turns -**Value Type:** `any` +##### scope +Which contracts/functions to allow: - '*': Any transaction - ContractFunctionPattern[]: Specific patterns ---- +**Type:** `'*' | ContractFunctionPattern[]` -### `utils/node.ts` +#### GrantedTransactionCapability -#### waitForNode +**Type:** Interface -**Type:** Constant +Granted transaction execution capability. The wallet may reduce the scope (e.g., from '*' to specific patterns). -**Value Type:** `any` +**Extends:** `TransactionCapability` -#### createAztecNodeClient +#### DataCapability -**Type:** Constant +**Type:** Interface -This is re-exported from `@aztec/stdlib/interfaces/client`. See the source module for full documentation. +Data access capability - for querying private data. Maps to wallet methods: - getAddressBook (when addressBook: true) - getPrivateEvents (when privateEvents specified) -**Value Type:** `Re-export` +#### Properties -#### AztecNode -**Type:** Type Alias +##### type -This is a type re-exported from `@aztec/stdlib/interfaces/client`. See the source module for full type definition and documentation. +Discriminator for capability type -**Signature:** +**Type:** `'data'` -```typescript -export type { AztecNode } from '@aztec/stdlib/interfaces/client' -``` ---- +##### addressBook -### `utils/pub_key.ts` +Access to address book. Maps to: getAddressBook +**Type:** `boolean` -#### generatePublicKey -**Type:** Function +##### privateEvents -Method for generating a public grumpkin key from a private key. +Access to private events. Maps to: getPrivateEvents -**Signature:** +**Type:** ```typescript -export generatePublicKey(privateKey: GrumpkinScalar): Promise +{ + /** + * Which contracts to allow event queries from: + * - '*': Any contract + * - AztecAddress[]: Specific contracts + */ + contracts: '*' | AztecAddress[]; + } ``` -**Parameters:** - -- `privateKey`: `GrumpkinScalar` - - The private key. -**Returns:** +#### GrantedDataCapability -`Promise` - The generated public key. +**Type:** Interface -## Wallet +Granted data access capability. The wallet may reduce the scope (e.g., from '*' to specific contracts). +**Extends:** `DataCapability` ---- -### `wallet/account_entrypoint_meta_payment_method.ts` +#### Capability +**Type:** Type Alias -#### AccountEntrypointMetaPaymentMethod +Union type of all capability scopes (app request). Capabilities group wallet operations by their security sensitivity and functional cohesion, making permission requests understandable to users. -**Type:** Class +**Signature:** -Fee payment method that allows an account contract to pay for its own deployment It works by rerouting the provided fee payment method through the account's entrypoint, which sets itself as fee payer. If no payment method is provided, it is assumed the account will pay with its own fee juice balance. Usually, in order to pay fees it is necessary to obtain an ExecutionPayload that encodes the necessary information that is sent to the user's account entrypoint, that has plumbing to handle it. If there's no account contract yet (it's being deployed) a MultiCallContract is used, which doesn't have a concept of fees or how to handle this payload. HOWEVER, the account contract's entrypoint does, so this method reshapes that fee payload into a call to the account contract entrypoint being deployed with the original fee payload. This class can be seen in action in DeployAccountMethod.ts#getSelfPaymentMethod +```typescript +export type Capability = + | AccountsCapability + | ContractsCapability + | ContractClassesCapability + | SimulationCapability + | TransactionCapability + | DataCapability; +``` -**Implements:** `FeePaymentMethod` +#### GrantedCapability +**Type:** Type Alias -#### Constructor +Union type of all granted capabilities (wallet response). The wallet may augment capabilities with additional information: - AccountsCapability: adds specific accounts granted - Other capabilities: may reduce scope (e.g., '*' to specific addresses) **Signature:** ```typescript -constructor( - private wallet: Wallet, - private artifact: ContractArtifact, - private feePaymentNameOrArtifact: string | FunctionArtifact, - private accountAddress: AztecAddress, - private paymentMethod?: FeePaymentMethod -) +export type GrantedCapability = + | GrantedAccountsCapability + | GrantedContractsCapability + | GrantedContractClassesCapability + | GrantedSimulationCapability + | GrantedTransactionCapability + | GrantedDataCapability; ``` -**Parameters:** +#### AppCapabilities -- `wallet`: `Wallet` -- `artifact`: `ContractArtifact` -- `feePaymentNameOrArtifact`: `string | FunctionArtifact` -- `accountAddress`: `AztecAddress` -- `paymentMethod` (optional): `FeePaymentMethod` +**Type:** Interface -#### Methods +Application capability manifest. Sent by dApp to declare all operations it needs. This reduces authorization friction from multiple dialogs to a single comprehensive permission request. -##### getAsset +#### Properties -**Signature:** -```typescript -getAsset(): Promise -``` +##### version -**Returns:** +Manifest version for forward compatibility. Currently only '1.0' is supported. -`Promise` +**Type:** `typeof CAPABILITY_VERSION` -##### getExecutionPayload -**Signature:** +##### metadata -```typescript -async getExecutionPayload(): Promise -``` +Application metadata for display in authorization dialogs. -**Returns:** +**Type:** -`Promise` +```typescript +{ + /** Human-readable app name */ + name: string; -##### getFeePayer + /** App version */ + version: string; -**Signature:** + /** Optional description of what the app does */ + description?: string; -```typescript -getFeePayer(): Promise -``` + /** Optional website URL */ + url?: string; -**Returns:** + /** Optional icon URL or data URI */ + icon?: string; + } +``` -`Promise` -##### getGasSettings +##### capabilities -**Signature:** +Requested capabilities grouped by scope. -```typescript -getGasSettings(): GasSettings | undefined -``` +**Type:** `Capability[]` -**Returns:** -`GasSettings | undefined` +#### WalletCapabilities ---- +**Type:** Interface -### `wallet/account_manager.ts` +Wallet capability response. Returned by wallet after user reviews and approves/denies the capability request. The wallet can modify requested capabilities: - Reduce scope (e.g., restrict to specific contracts instead of '*') - Add information (e.g., specify which accounts are granted) - Deny capabilities (by omitting them from the `granted` array) -#### AccountManager +#### Properties -**Type:** Class -Manages a user account. Provides methods for calculating the account's address and other related data, plus a helper to return a preconfigured deploy method. +##### version +Response version for forward compatibility. -#### Constructor +**Type:** `typeof CAPABILITY_VERSION` -**Signature:** -```typescript -private constructor( - private wallet: Wallet, - private secretKey: Fr, - private accountContract: AccountContract, - private instance: ContractInstanceWithAddress, - public readonly salt: Salt -) -``` +##### granted -**Parameters:** +Capabilities granted by the wallet. Capabilities not in this array were implicitly denied. Empty array means the user denied all capabilities. -- `wallet`: `Wallet` -- `secretKey`: `Fr` -- `accountContract`: `AccountContract` -- `instance`: `ContractInstanceWithAddress` -- `salt`: `Salt` - - Contract instantiation salt for the account contract +**Type:** `GrantedCapability[]` -#### Methods +##### wallet -##### create +Wallet implementation details. -**Signature:** +**Type:** ```typescript -static async create( - wallet: Wallet, - secretKey: Fr, - accountContract: AccountContract, - salt?: Salt -) +{ + /** Wallet name/implementation */ + name: string; + + /** Wallet version */ + version: string; + } ``` -**Parameters:** -- `wallet`: `Wallet` -- `secretKey`: `Fr` -- `accountContract`: `AccountContract` -- `salt` (optional): `Salt` +--- -**Returns:** +### `wallet/deploy_account_method.ts` -`Promise` -##### getPublicKeys +#### DeployAccountFeePaymentMethodOption + +**Type:** Type Alias + +Extended fee payment method option for account deployments that includes entrypoint wrapping options **Signature:** ```typescript -protected getPublicKeys() +export type DeployAccountFeePaymentMethodOption = FeePaymentMethodOption & { + feeEntrypointOptions?: unknown; +}; ``` -**Returns:** +**Type Members:** -`any` +##### feeEntrypointOptions -##### getPublicKeysHash +Optional entrypoint-specific options for wrapping execution payloads + +**Type:** `unknown` + + +#### RequestDeployAccountOptions + +**Type:** Type Alias + +The configuration options for the request method. **Signature:** ```typescript -protected getPublicKeysHash() +export type RequestDeployAccountOptions = Omit & { + fee?: DeployAccountFeePaymentMethodOption; + from?: AztecAddress | NoFrom; +}; ``` -**Returns:** +**Type Members:** -`any` +##### fee -##### getAccountInterface +Fee options specific to account deployment -Returns the entrypoint for this account as defined by its account contract. +**Type:** `DeployAccountFeePaymentMethodOption` -**Signature:** +##### from -```typescript -public async getAccountInterface(): Promise -``` +Sender of the request. When NO_FROM, the to-be-deployed account pays for its own deployment (self-paid deploy) and the payload is wrapped through the multicall entrypoint. -**Returns:** +**Type:** `AztecAddress | NoFrom` -`Promise` - An entrypoint. -##### getCompleteAddress +#### DeployAccountOptions -Gets the calculated complete address associated with this account. Does not require the account to have been published for public execution. +**Type:** Type Alias + +The configuration options for the send/prove methods. **Signature:** ```typescript -public getCompleteAddress(): Promise +export type DeployAccountOptions = DeployOptionsWithoutWait & { + wait?: W; +}; ``` -**Returns:** +**Type Members:** -`Promise` - The address, partial address, and encryption public key. +##### wait -##### getSecretKey +Whether to wait for the transaction to be mined. - undefined (default): wait with default options and return TxReceipt - WaitOpts object: wait with custom options and return TxReceipt - false: return txHash immediately without waiting -Returns the secret key used to derive the rest of the privacy keys for this contract +**Type:** `W` + + +#### SimulateDeployAccountOptions + +**Type:** Type Alias + +The configuration options for the simulate method. **Signature:** ```typescript -public getSecretKey() +export type SimulateDeployAccountOptions = SimulateDeployOptions; ``` -**Returns:** +#### DeployAccountMethod -`Fr` +**Type:** Class -##### getInstance +Modified version of the DeployMethod used to deploy account contracts. Supports deploying contracts that can pay for their own fee, plus some preconfigured options to avoid errors. -Returns the contract instance definition associated with this account. Does not require the account to have been published for public execution. +**Extends:** `UniversalDeployMethod` + + +#### Constructor **Signature:** ```typescript -public getInstance(): ContractInstanceWithAddress +constructor( + publicKeys: PublicKeys, + wallet: Wallet, + artifact: ContractArtifact, + postDeployCtor: (instance: ContractInstanceWithAddress, wallet: Wallet) => TContract, + salt: Fr, + immutablesHash: Fr, + private account: Account, + args: any[] = [], + constructorNameOrArtifact?: string | FunctionArtifact, + authWitnesses: AuthWitness[] = [], + capsules: Capsule[] = [], + extraHashedArgs: HashedValues[] = [] +) ``` -**Returns:** +**Parameters:** -`ContractInstanceWithAddress` - ContractInstance instance. +- `publicKeys`: `PublicKeys` +- `wallet`: `Wallet` +- `artifact`: `ContractArtifact` +- `postDeployCtor`: `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` +- `salt`: `Fr` +- `immutablesHash`: `Fr` +- `account`: `Account` +- `args` (optional): `any[]` +- `constructorNameOrArtifact` (optional): `string | FunctionArtifact` +- `authWitnesses` (optional): `AuthWitness[]` +- `capsules` (optional): `Capsule[]` +- `extraHashedArgs` (optional): `HashedValues[]` -##### getAccount +#### Methods + + +##### request -Returns a Wallet instance associated with this account. Use it to create Contract instances to be interacted with from this account. +Returns the execution payload that allows this operation to happen on chain. For self-deployments (from === NO_FROM), the payload is wrapped through the multicall entrypoint on the app side so the wallet can execute it directly. **Signature:** ```typescript -public async getAccount(): Promise +public override async request(opts?: RequestDeployAccountOptions): Promise ``` -**Returns:** +**Parameters:** + +- `opts` (optional): `RequestDeployAccountOptions` + - Configuration options. -`Promise` - A Wallet instance. +**Returns:** -##### getAccountContract +`Promise` - The execution payload for this operation -Returns the account contract that backs this account. +##### convertDeployOptionsToSendOptions **Signature:** ```typescript -getAccountContract(): AccountContract +protected override convertDeployOptionsToSendOptions(options: DeployOptions): SendOptions ``` -**Returns:** +**Parameters:** -`AccountContract` - The account contract +- `options`: `DeployOptions` -##### getDeployMethod +**Returns:** -Returns a preconfigured deploy method that contains all the necessary function calls to deploy the account contract. +`SendOptions` + +##### convertDeployOptionsToSimulateOptions **Signature:** ```typescript -public async getDeployMethod(): Promise +protected override convertDeployOptionsToSimulateOptions(options: SimulateDeployOptions): SimulateOptions ``` -**Returns:** +**Parameters:** -`Promise` +- `options`: `SimulateDeployOptions` -##### hasInitializer +**Returns:** -Returns whether this account contract has an initializer function. +`SimulateOptions` + +##### convertDeployOptionsToProfileOptions **Signature:** ```typescript -public async hasInitializer() +protected override convertDeployOptionsToProfileOptions(options: DeployOptionsWithoutWait & ProfileInteractionOptions): ProfileOptions ``` -**Returns:** +**Parameters:** -`Promise` +- `options`: `DeployOptionsWithoutWait & ProfileInteractionOptions` -#### Getters +**Returns:** + +`ProfileOptions` +##### with -##### address (getter) +Augments this DeployAccountMethod with additional metadata, such as authWitnesses and capsules. **Signature:** ```typescript -get address() { +public override with({ authWitnesses = [], capsules = [], extraHashedArgs = [], }: { + authWitnesses?: AuthWitness[]; + capsules?: Capsule[]; + extraHashedArgs?: HashedValues[]; +}): DeployAccountMethod ``` -**Returns:** `any` - ---- - -### `wallet/deploy_account_method.ts` +**Parameters:** +- `{ authWitnesses = [], capsules = [], extraHashedArgs = [], }`: -#### RequestDeployAccountOptions + ```typescript + { + /** The authWitnesses to add to the deployment */ + authWitnesses?: AuthWitness[]; + /** The capsules to add to the deployment */ + capsules?: Capsule[]; + /** The extra hashed args to add to the deployment */ + extraHashedArgs?: HashedValues[]; + } + ``` -**Type:** Type Alias -The configuration options for the request method. Omits the contractAddressSalt, since for account contracts that is fixed in the constructor +**Returns:** -**Signature:** +`DeployAccountMethod` - A new DeployAccountMethod with the added metadata -```typescript -export type RequestDeployAccountOptions = Omit; -``` +--- -#### DeployAccountOptions +### `wallet/tx_simulation_result_with_app_offset.ts` -**Type:** Type Alias -The configuration options for the send/prove methods. Omits: - The contractAddressSalt, since for account contracts that is fixed in the constructor. - UniversalDeployment flag, since account contracts are always deployed with it set to true +#### TxSimulationResultWithAppOffset -**Signature:** +**Type:** Class -```typescript -export type DeployAccountOptions = Omit; -``` +Extends TxSimulationResult with the app call offset, which tracks where the app's calls begin in the flattened array of calls. Tracking of app call offset is a wallet-level concern: the wallet may wrap the app payload in an entrypoint or may prepend calls (this is typically done for fee payments). -#### SimulateDeployAccountOptions +**Extends:** `TxSimulationResult` -**Type:** Type Alias -The configuration options for the simulate method. Omits the contractAddressSalt, since for account contracts that is fixed in the constructor +#### Constructor **Signature:** ```typescript -export type SimulateDeployAccountOptions = Omit; +constructor( + privateExecutionResult: PrivateExecutionResult, + publicInputs: PrivateKernelTailCircuitPublicInputs, + publicOutput?: PublicSimulationOutput, + stats?: SimulationStats, + public readonly appCallOffset: number | undefined = undefined +) ``` -#### DeployAccountMethod +**Parameters:** -**Type:** Class +- `privateExecutionResult`: `PrivateExecutionResult` +- `publicInputs`: `PrivateKernelTailCircuitPublicInputs` +- `publicOutput` (optional): `PublicSimulationOutput` +- `stats` (optional): `SimulationStats` +- `appCallOffset` (optional): `number | undefined` + - Index of the app's first call in a flattened array of calls. 0 = app call is the root execution itself (DefaultEntrypoint / NO_FROM). 1..N = wallet prepended calls before the app call. undefined = wallet did not send the field; use heuristic fallback. -Modified version of the DeployMethod used to deploy account contracts. Supports deploying contracts that can pay for their own fee, plus some preconfigured options to avoid errors. +#### Methods -**Extends:** `DeployMethod` +##### getPrivateReturnValuesOfAppCall -#### Constructor +Returns the private return values that correspond to the provided app call. **Signature:** ```typescript -constructor( - publicKeys: PublicKeys, - wallet: Wallet, - artifact: ContractArtifact, - postDeployCtor: (instance: ContractInstanceWithAddress, wallet: Wallet) => TContract, - private salt: Fr, - args: any[] = [], - constructorNameOrArtifact?: string | FunctionArtifact -) +getPrivateReturnValuesOfAppCall(appCallIndex: number = 0): NestedProcessReturnValues | undefined ``` **Parameters:** -- `publicKeys`: `PublicKeys` -- `wallet`: `Wallet` -- `artifact`: `ContractArtifact` -- `postDeployCtor`: `(instance: ContractInstanceWithAddress, wallet: Wallet) => TContract` -- `salt`: `Fr` -- `args` (optional): `any[]` -- `constructorNameOrArtifact` (optional): `string | FunctionArtifact` +- `appCallIndex` (optional): `number` + - Index of the app call within the app calls. -#### Methods +**Returns:** +`NestedProcessReturnValues | undefined` -##### request +##### fromResultAndOffset -Returns the execution payload that allows this operation to happen on chain. +Creates a TxSimulationResultWithAppOffset from an existing TxSimulationResult, attaching the app call offset computed by the wallet (i.e. how many calls precede the first app call in the flattened execution tree). **Signature:** ```typescript -public override async request(opts?: RequestDeployAccountOptions): Promise +static fromResultAndOffset( + result: TxSimulationResult, + appCallOffset: number +): TxSimulationResultWithAppOffset ``` **Parameters:** -- `opts` (optional): `RequestDeployAccountOptions` - - Configuration options. +- `result`: `TxSimulationResult` + - The simulation result to wrap. +- `appCallOffset`: `number` + - The index of the app's first call in the flattened execution tree. **Returns:** -`Promise` - The execution payload for this operation +`TxSimulationResultWithAppOffset` -##### convertDeployOptionsToRequestOptions +##### random **Signature:** ```typescript -override convertDeployOptionsToRequestOptions(options: DeployOptions): RequestDeployOptions +static override async random() ``` -**Parameters:** +**Returns:** + +`Promise` + +#### Getters + + +##### schema (getter) -- `options`: `DeployOptions` +**Signature:** + +```typescript +static override get schema(): ZodFor { +``` **Returns:** -`RequestDeployOptions` +`ZodFor` --- @@ -4754,13 +6065,13 @@ The item being aliased. **Type:** Type Alias -Options for simulating interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet wether the interaction contains a fee payment method or not +Options for simulating interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet whether the interaction contains a fee payment method or not **Signature:** ```typescript export type SimulateOptions = Omit & { - fee?: GasSettingsOption & FeeEstimationOptions; + fee?: GasSettingsOption; }; ``` @@ -4770,14 +6081,14 @@ export type SimulateOptions = Omit & { The fee options -**Type:** `GasSettingsOption & FeeEstimationOptions` +**Type:** `GasSettingsOption` #### ProfileOptions **Type:** Type Alias -Options for profiling interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet wether the interaction contains a fee payment method or not +Options for profiling interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet whether the interaction contains a fee payment method or not **Signature:** @@ -4800,13 +6111,17 @@ The fee options **Type:** Type Alias -Options for sending/proving interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet wether the interaction contains a fee payment method or not +Options for sending/proving interactions with the wallet. Overrides the fee settings of an interaction with a simplified version that only hints at the wallet whether the interaction contains a fee payment method or not **Signature:** ```typescript -export type SendOptions = Omit & { +export type SendOptions = Omit< + SendInteractionOptionsWithoutWait, + 'fee' +> & { fee?: GasSettingsOption; + wait?: W; }; ``` @@ -4818,52 +6133,39 @@ The fee options **Type:** `GasSettingsOption` +##### wait + +Whether to wait for the transaction to be mined + +**Type:** `W` + #### BatchableMethods **Type:** Type Alias -Helper type that represents all methods that can be batched. +Helper type that represents all methods that can be batched (all methods except batch itself). **Signature:** ```typescript -export type BatchableMethods = Pick< - Wallet, - 'registerContract' | 'sendTx' | 'registerSender' | 'simulateUtility' | 'simulateTx' ->; +export type BatchableMethods = Omit; ``` #### BatchedMethod **Type:** Type Alias -From the batchable methods, we create a type that represents a method call with its name and arguments. This is what the wallet will accept as arguments to the `batch` method. +Union of all possible batched method calls. This ensures type safety: the `args` must match the specific `name`. **Signature:** ```typescript -export type BatchedMethod = { - name: T; - args: Parameters; -}; +export type BatchedMethod = { + [K in keyof BatchableMethods]: BatchedMethodInternal; +}[keyof BatchableMethods]; ``` -**Type Members:** - -##### name - -The method name - -**Type:** `T` - -##### args - -The method arguments - -**Type:** `Parameters` - - #### BatchedMethodResult **Type:** Type Alias @@ -4874,7 +6176,7 @@ Helper type to extract the return type of a batched method ```typescript export type BatchedMethodResult = - T extends BatchedMethod ? Awaited> : never; + T extends BatchedMethodInternal ? Awaited> : never; ``` #### BatchedMethodResultWrapper @@ -4886,7 +6188,7 @@ Wrapper type for batch results that includes the method name for discriminated u **Signature:** ```typescript -export type BatchedMethodResultWrapper> = { +export type BatchedMethodResultWrapper = { name: T['name']; result: BatchedMethodResult; }; @@ -4916,101 +6218,287 @@ Maps a tuple of BatchedMethod to a tuple of their wrapped return types **Signature:** ```typescript -export type BatchResults[]> = { +export type BatchResults = { [K in keyof T]: BatchedMethodResultWrapper; }; ``` -**Type Members:** +**Type Members:** + +##### [K in keyof T] + +**Signature:** `[K in keyof T]: BatchedMethodResultWrapper` + +**Key Type:** `keyof T` + +**Value Type:** `BatchedMethodResultWrapper` + + +#### EventFilterBase + +**Type:** Type Alias + +Base filter options for event queries. + +**Signature:** + +```typescript +export type EventFilterBase = { + txHash?: TxHash; + fromBlock?: BlockNumber; + toBlock?: BlockNumber; +}; +``` + +**Type Members:** + +##### txHash + +Transaction in which the events were emitted. + +**Type:** `TxHash` + +##### fromBlock + +The block number from which to start fetching events (inclusive). Optional. If provided, it must be greater or equal than 1. Defaults to the initial L2 block number (INITIAL_L2_BLOCK_NUM). + +**Type:** `BlockNumber` + +##### toBlock + +The block number until which to fetch logs (not inclusive). Optional. If provided, it must be greater than fromBlock. + +**Type:** `BlockNumber` + + +#### PrivateEventFilter + +**Type:** Type Alias + +Filter options when querying private events. + +**Signature:** + +```typescript +export type PrivateEventFilter = EventFilterBase & { + contractAddress: AztecAddress; + scopes: AztecAddress[]; +}; +``` + +**Type Members:** + +##### contractAddress + +The address of the contract that emitted the events. + +**Type:** `AztecAddress` + +##### scopes + +Addresses of accounts that are in scope for this filter. + +**Type:** `AztecAddress[]` + + +#### PublicEventFilter + +**Type:** Type Alias + +Filter options when querying public events. The contract address is required because the public log index is keyed on `(contract, tag)`; tag-only queries are not supported. + +**Signature:** + +```typescript +export type PublicEventFilter = EventFilterBase & { + contractAddress: AztecAddress; + afterEvent?: EventCursor; +}; +``` + +**Type Members:** + +##### contractAddress + +The address of the contract that emitted the events. Required. + +**Type:** `AztecAddress` + +##### afterEvent + +Cursor to resume strictly after, for pagination. Pass GetPublicEventsResult.nextCursor from a previous page here to fetch the next one. Omit to start from the beginning of the range. + +**Type:** `EventCursor` + + +#### Event + +**Type:** Type Alias + +An ABI decoded event with associated metadata. + +**Signature:** + +```typescript +export type Event = { + event: T; + metadata: InTx & M; +}; +``` + +**Type Members:** + +##### event + +The ABI decoded event + +**Type:** `T` + +##### metadata + +Metadata describing event context information such as tx and block + +**Type:** `InTx & M` + + +#### PrivateEvent + +**Type:** Type Alias + +An ABI decoded private event with associated metadata. + +**Signature:** + +```typescript +export type PrivateEvent = Event; +``` + +#### PublicEvent + +**Type:** Type Alias + +An ABI decoded public event with associated metadata (includes contract address). + +**Signature:** + +```typescript +export type PublicEvent = Event< + T, + { + contractAddress: AztecAddress; + } +>; +``` + +#### ContractMetadata + +**Type:** Type Alias + +Contract metadata including deployment and registration status. + +**Signature:** + +```typescript +export type ContractMetadata = { + instance?: ContractInstancePreimageWithAddress; + initializationStatus: ContractInitializationStatus; + isContractPublished: boolean; + isContractUpdated: boolean; + updatedContractClassId?: Fr | undefined; +}; +``` + +**Type Members:** + +##### instance + +The contract instance preimage and address. + +**Type:** `ContractInstancePreimageWithAddress` + +##### initializationStatus + +Whether the contract has been initialized. + +**Type:** `ContractInitializationStatus` + +##### isContractPublished + +Whether the contract instance is publicly deployed onchain + +**Type:** `boolean` + +##### isContractUpdated + +Whether the contract has been updated to a different class -##### [K in keyof T] +**Type:** `boolean` -**Signature:** `[K in keyof T]: BatchedMethodResultWrapper` +##### updatedContractClassId -**Key Type:** `keyof T` +The updated contract class ID if the contract has been updated -**Value Type:** `BatchedMethodResultWrapper` +**Type:** `Fr | undefined` -#### PrivateEventFilter +#### ContractClassMetadata **Type:** Type Alias -Filter options when querying private events. +Contract class metadata. **Signature:** ```typescript -export type PrivateEventFilter = { - contractAddress: AztecAddress; - scopes: AztecAddress[]; - txHash?: TxHash; - fromBlock?: BlockNumber; - toBlock?: BlockNumber; +export type ContractClassMetadata = { + isArtifactRegistered: boolean; + isContractClassPubliclyRegistered: boolean; }; ``` **Type Members:** -##### contractAddress - -The address of the contract that emitted the events. - -**Type:** `AztecAddress` - -##### scopes - -Addresses of accounts that are in scope for this filter. - -**Type:** `AztecAddress[]` - -##### txHash - -Transaction in which the events were emitted. - -**Type:** `TxHash` - -##### fromBlock +##### isArtifactRegistered -The block number from which to start fetching events (inclusive). Optional. If provided, it must be greater or equal than 1. Defaults to the initial L2 block number (INITIAL_L2_BLOCK_NUM). +Whether the artifact is registered in the wallet -**Type:** `BlockNumber` +**Type:** `boolean` -##### toBlock +##### isContractClassPubliclyRegistered -The block number until which to fetch logs (not inclusive). Optional. If provided, it must be greater than fromBlock. Defaults to the latest known block to PXE + 1. +Whether the contract class is publicly registered onchain -**Type:** `BlockNumber` +**Type:** `boolean` -#### PrivateEvent +#### ExecuteUtilityOptions **Type:** Type Alias -An ABI decoded private event with associated metadata. +Options for executing a utility function call. **Signature:** ```typescript -export type PrivateEvent = { - event: T; - metadata: InTx; +export type ExecuteUtilityOptions = { + scopes: AztecAddress[]; + authWitnesses?: AuthWitness[]; }; ``` **Type Members:** -##### event +##### scopes -The ABI decoded event +The scopes for the utility execution (determines which notes and keys are visible). -**Type:** `T` +**Type:** `AztecAddress[]` -##### metadata +##### authWitnesses -Metadata describing event context information such as tx and block +Optional auth witnesses to use during execution. -**Type:** `InTx` +**Type:** `AuthWitness[]` #### Wallet @@ -5023,67 +6511,37 @@ The wallet interface. ```typescript export type Wallet = { - getContractClassMetadata(id: Fr, includeArtifact?: boolean): Promise; - getContractMetadata(address: AztecAddress): Promise; getPrivateEvents( eventMetadata: EventMetadataDefinition, eventFilter: PrivateEventFilter, ): Promise[]>; getChainInfo(): Promise; - getTxReceipt(txHash: TxHash): Promise; + getContractMetadata(address: AztecAddress): Promise; + getContractClassMetadata(id: Fr): Promise; registerSender(address: AztecAddress, alias?: string): Promise; getAddressBook(): Promise[]>; getAccounts(): Promise[]>; registerContract( - instance: ContractInstanceWithAddress, + instance: ContractInstancePreimage, artifact?: ContractArtifact, - secretKey?: Fr, - ): Promise; - simulateTx(exec: ExecutionPayload, opts: SimulateOptions): Promise; - simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise; + secretKeyOrKeys?: Fr | MasterSecretKeys, + ): Promise; + registerContractClass(artifact: ContractArtifact): Promise; + simulateTx(exec: ExecutionPayload, opts: SimulateOptions): Promise; + executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise; profileTx(exec: ExecutionPayload, opts: ProfileOptions): Promise; - sendTx(exec: ExecutionPayload, opts: SendOptions): Promise; - createAuthWit(from: AztecAddress, messageHashOrIntent: Fr | IntentInnerHash | CallIntent): Promise; - batch[]>(methods: T): Promise>; + sendTx( + exec: ExecutionPayload, + opts: SendOptions, + ): Promise>; + createAuthWit(from: AztecAddress, messageHashOrIntent: IntentInnerHash | CallIntent): Promise; + requestCapabilities(manifest: AppCapabilities): Promise; + batch(methods: T): Promise>; }; ``` **Type Members:** -##### getContractClassMetadata - -**Signature:** - -```typescript -getContractClassMetadata( - id: Fr, - includeArtifact?: boolean -): Promise -``` - -**Parameters:** - -- `id`: `Fr` -- `includeArtifact` (optional): `boolean` - -**Returns:** - -`Promise` -##### getContractMetadata - -**Signature:** - -```typescript -getContractMetadata(address: AztecAddress): Promise -``` - -**Parameters:** - -- `address`: `AztecAddress` - -**Returns:** - -`Promise` ##### getPrivateEvents **Signature:** @@ -5114,21 +6572,36 @@ getChainInfo(): Promise **Returns:** `Promise` -##### getTxReceipt +##### getContractMetadata **Signature:** ```typescript -getTxReceipt(txHash: TxHash): Promise +getContractMetadata(address: AztecAddress): Promise ``` **Parameters:** -- `txHash`: `TxHash` +- `address`: `AztecAddress` + +**Returns:** + +`Promise` +##### getContractClassMetadata + +**Signature:** + +```typescript +getContractClassMetadata(id: Fr): Promise +``` + +**Parameters:** + +- `id`: `Fr` **Returns:** -`Promise` +`Promise` ##### registerSender **Signature:** @@ -5176,21 +6649,38 @@ getAccounts(): Promise[]> ```typescript registerContract( - instance: ContractInstanceWithAddress, + instance: ContractInstancePreimage, artifact?: ContractArtifact, - secretKey?: Fr -): Promise + secretKeyOrKeys?: Fr | MasterSecretKeys +): Promise ``` **Parameters:** -- `instance`: `ContractInstanceWithAddress` +- `instance`: `ContractInstancePreimage` - `artifact` (optional): `ContractArtifact` -- `secretKey` (optional): `Fr` +- `secretKeyOrKeys` (optional): `Fr | MasterSecretKeys` + +**Returns:** + +`Promise` +##### registerContractClass + +Registers a contract class artifact in the local PXE without binding it to any instance. Useful for simulation flows that need the artifact available locally before any onchain upgrade has taken effect. No chain check. + +**Signature:** + +```typescript +registerContractClass(artifact: ContractArtifact): Promise +``` + +**Parameters:** + +- `artifact`: `ContractArtifact` **Returns:** -`Promise` +`Promise` ##### simulateTx **Signature:** @@ -5199,7 +6689,7 @@ registerContract( simulateTx( exec: ExecutionPayload, opts: SimulateOptions -): Promise +): Promise ``` **Parameters:** @@ -5209,26 +6699,26 @@ simulateTx( **Returns:** -`Promise` -##### simulateUtility +`Promise` +##### executeUtility **Signature:** ```typescript -simulateUtility( +executeUtility( call: FunctionCall, - authwits?: AuthWitness[] -): Promise + opts: ExecuteUtilityOptions +): Promise ``` **Parameters:** - `call`: `FunctionCall` -- `authwits` (optional): `AuthWitness[]` +- `opts`: `ExecuteUtilityOptions` **Returns:** -`Promise` +`Promise` ##### profileTx **Signature:** @@ -5253,20 +6743,20 @@ profileTx( **Signature:** ```typescript -sendTx( +sendTx( exec: ExecutionPayload, - opts: SendOptions -): Promise + opts: SendOptions +): Promise> ``` **Parameters:** - `exec`: `ExecutionPayload` -- `opts`: `SendOptions` +- `opts`: `SendOptions` **Returns:** -`Promise` +`Promise>` ##### createAuthWit **Signature:** @@ -5274,40 +6764,48 @@ sendTx( ```typescript createAuthWit( from: AztecAddress, - messageHashOrIntent: Fr | IntentInnerHash | CallIntent + messageHashOrIntent: IntentInnerHash | CallIntent ): Promise ``` **Parameters:** - `from`: `AztecAddress` -- `messageHashOrIntent`: `Fr | IntentInnerHash | CallIntent` +- `messageHashOrIntent`: `IntentInnerHash | CallIntent` **Returns:** `Promise` -##### batch +##### requestCapabilities **Signature:** ```typescript -batch[]>(methods: T): Promise> +requestCapabilities(manifest: AppCapabilities): Promise ``` **Parameters:** -- `methods`: `T` +- `manifest`: `AppCapabilities` **Returns:** -`Promise>` +`Promise` +##### batch -#### FunctionCallSchema +**Signature:** -**Type:** Constant +```typescript +batch(methods: T): Promise> +``` -**Value Type:** `any` +**Parameters:** +- `methods`: `T` + +**Returns:** + +`Promise>` #### ExecutionPayloadSchema @@ -5323,7 +6821,7 @@ batch[]>(methods: **Value Type:** `any` -#### WalletSimulationFeeOptionSchema +#### WaitOptsSchema **Type:** Constant @@ -5358,13 +6856,41 @@ batch[]>(methods: **Value Type:** `any` -#### BatchedMethodSchema +#### EventMetadataDefinitionSchema + +**Type:** Constant + +**Value Type:** `any` + + +#### PrivateEventFilterSchema + +**Type:** Constant + +**Value Type:** `any` + + +#### PublicEventFilterSchema **Type:** Constant **Value Type:** `any` +#### PrivateEventSchema + +**Type:** Constant + +**Value Type:** `z.ZodType` + + +#### PublicEventSchema + +**Type:** Constant + +**Value Type:** `z.ZodType>` + + #### ContractMetadataSchema **Type:** Constant @@ -5379,27 +6905,135 @@ batch[]>(methods: **Value Type:** `any` -#### EventMetadataDefinitionSchema +#### ContractFunctionPatternSchema **Type:** Constant **Value Type:** `any` -#### PrivateEventSchema +#### AccountsCapabilitySchema **Type:** Constant -**Value Type:** `ZodFor>` +**Value Type:** `any` + +#### GrantedAccountsCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### ContractsCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedContractsCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### ContractClassesCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedContractClassesCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` -#### PrivateEventFilterSchema + +#### SimulationCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedSimulationCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### TransactionCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedTransactionCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### DataCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedDataCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### CapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### GrantedCapabilitySchema + +**Type:** Constant + +**Value Type:** `any` + + +#### AppCapabilitiesSchema + +**Type:** Constant + +**Value Type:** `any` + + +#### WalletCapabilitiesSchema **Type:** Constant **Value Type:** `any` +#### BatchedMethodSchema + +**Type:** Constant + + +#### BatchedResultSchema + +**Type:** Constant + + #### WalletSchema **Type:** Constant diff --git a/docs/docs-words.txt b/docs/docs-words.txt index 65c95b9276c3..4f6dab3df23a 100644 --- a/docs/docs-words.txt +++ b/docs/docs-words.txt @@ -141,6 +141,7 @@ excalidraw existant explicity faceid +fastforward favo FDIV fdiv diff --git a/docs/scripts/aztecjs_reference_generation/README.md b/docs/scripts/aztecjs_reference_generation/README.md index 2789362c16b0..7d4a7b84b6ad 100644 --- a/docs/scripts/aztecjs_reference_generation/README.md +++ b/docs/scripts/aztecjs_reference_generation/README.md @@ -60,14 +60,21 @@ The generated documentation follows this hierarchy: ```markdown ## Account # H2: Folder/Module --- -### File: `account/account.ts` # H3: File +### `account/account.ts` # H3: File #### AccountContract # H4: Export (Class/Interface/Type) **Type:** Class -##### constructor # H5: Member (Method/Property) -##### Methods # H5: Subsection -###### deploy # H6: Specific method +#### Methods # H4: Member group +##### createAuthWit # H5: Member (Method/Property/Getter) ``` +Docusaurus derives a heading's anchor from every heading before it, so the table of contents can +only be written once the body is known. `transform_to_markdown.py` renders every heading through +`MarkdownGenerator.heading()`, which claims the anchor as the heading is emitted; one written as a +plain string instead would misdirect table of contents links rather than break them: the link still +resolves, just to the wrong section, so nothing downstream reports it. `generate()` re-reads the page +it just rendered and raises unless its headings are exactly the ones `heading()` emitted, so a +heading added any other way fails the build instead. + ## Configuration ### Customization diff --git a/docs/scripts/aztecjs_reference_generation/parse_typescript.js b/docs/scripts/aztecjs_reference_generation/parse_typescript.js index 60a5109feeb3..a4e870ebe2c0 100644 --- a/docs/scripts/aztecjs_reference_generation/parse_typescript.js +++ b/docs/scripts/aztecjs_reference_generation/parse_typescript.js @@ -17,6 +17,26 @@ const ts = require('typescript'); const fs = require('fs'); const path = require('path'); +// readdirSync returns entries in filesystem order, and localeCompare depends on the runtime's +// locale data, so either one can order the reference differently on another machine. Comparing +// code units keeps the generated page identical everywhere the same sources are parsed. +const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + +// The reference documents aztec.js on its own, so the checker resolves relative imports only. +// Resolving @aztec/* would make every inferred return type depend on which sibling packages the +// environment has built, and a page generated against one build state silently differs from a page +// generated against another. Types that cross a package boundary have to be annotated in the source. +function relativeImportsOnlyHost(compilerOptions) { + const host = ts.createCompilerHost(compilerOptions, true); + host.resolveModuleNameLiterals = (literals, containingFile) => + literals.map(literal => + literal.text.startsWith('.') + ? ts.resolveModuleName(literal.text, containingFile, compilerOptions, host) + : { resolvedModule: undefined } + ); + return host; +} + /** * JSDoc Validator - validates JSDoc completeness and correctness */ @@ -162,7 +182,10 @@ class TypeScriptParser { constructor(sourcePath, options = {}) { this.sourcePath = path.resolve(sourcePath); this.options = { - excludeDirs: ['api', 'node_modules', '__tests__', 'test'], + // protocol_contracts is gitignored build output, generated from the compiled Noir protocol + // contracts. Documenting it would make this page unverifiable from a checkout and would tie + // it to noir-projects, so a Noir contract change would leave the committed page stale. + excludeDirs: ['api', 'node_modules', '__tests__', 'test', 'protocol_contracts'], excludeFiles: ['.test.ts', '.test.tsx', 'index.ts'], validate: false, // Enable validation ...options @@ -227,7 +250,7 @@ class TypeScriptParser { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); // Get directories first - const dirs = entries.filter(e => e.isDirectory()); + const dirs = entries.filter(e => e.isDirectory()).sort(byName); for (const dir of dirs) { const dirName = dir.name; @@ -289,7 +312,7 @@ class TypeScriptParser { } } - return files.sort((a, b) => a.name.localeCompare(b.name)); + return files.sort(byName); } /** @@ -329,7 +352,7 @@ class TypeScriptParser { } } - program = ts.createProgram([filePath], compilerOptions); + program = ts.createProgram([filePath], compilerOptions, relativeImportsOnlyHost(compilerOptions)); this.typeChecker = program.getTypeChecker(); // Use the source file from the program (required for type checking) sourceFile = program.getSourceFile(filePath); @@ -589,7 +612,22 @@ class TypeScriptParser { for (const element of node.exportClause.elements) { const name = element.name.getText(sourceFile); const isTypeOnly = element.isTypeOnly || node.isTypeOnly; - const moduleSpecifier = node.moduleSpecifier ? node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, '') : ''; + + // `export { foo }` with no `from` publishes a local declaration rather than re-exporting + // one, so there is no source module to send a reader to. Documenting it as a re-export + // would name an empty module and claim a type of `Re-export`. + if (!node.moduleSpecifier) { + exports.push({ + kind: isTypeOnly ? 'type' : 'const', + name: name, + signature: isTypeOnly ? `export type { ${name} }` : `export { ${name} }`, + jsdoc: { description: '', tags: [] }, + type: '', + }); + continue; + } + + const moduleSpecifier = node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, ''); // Create a simple re-export entry with improved documentation const description = isTypeOnly diff --git a/docs/scripts/aztecjs_reference_generation/transform_to_markdown.py b/docs/scripts/aztecjs_reference_generation/transform_to_markdown.py index 1a43cebbe635..84990cf498f2 100644 --- a/docs/scripts/aztecjs_reference_generation/transform_to_markdown.py +++ b/docs/scripts/aztecjs_reference_generation/transform_to_markdown.py @@ -9,6 +9,8 @@ import json import argparse +import re +from textwrap import indent from typing import Dict, Any, List from pathlib import Path @@ -19,11 +21,57 @@ YAML_AVAILABLE = False +class HeadingSlugger: + """ + Assigns the anchors Docusaurus generates for a document's headings. + + Docusaurus slugs headings with github-slugger: lowercase, drop punctuation, turn spaces into + hyphens, then keep the result unique by appending `-1`, `-2` and so on. The suffix search walks + the anchors already taken rather than counting repeats of the same text, so a heading that + literally reads `wallet-1` takes that anchor away from the second `Wallet`. An anchor therefore + depends on every heading before it, including ones nothing links to. + """ + + # Punctuation github-slugger drops. Its own table also covers non-ASCII punctuation, which no + # heading generated from TypeScript sources has needed so far. + PUNCTUATION = set("\\'!\"#$%&()*+,./:;<=>?@[]^`{|}~") + + def __init__(self): + self.occurrences = {} + + def slug(self, heading_text: str) -> str: + """ + Claim and return the anchor for the next heading, without its leading `#`. + + Examples, for a document whose earlier headings took none of these: + `## Account` -> `account` + `#### CAPABILITY_VERSION` -> `capability_version` + `## Contract / Protocol_Contracts` -> `contract--protocol_contracts` + """ + base = self.base_slug(heading_text) + slug = base + while slug in self.occurrences: + self.occurrences[base] += 1 + slug = f"{base}-{self.occurrences[base]}" + self.occurrences[slug] = 0 + return slug + + @classmethod + def base_slug(cls, heading_text: str) -> str: + """Slug a heading without regard for the anchors already taken.""" + slug = heading_text.lower().strip() + slug = ''.join(c for c in slug if c not in cls.PUNCTUATION) + return slug.replace(' ', '-') + + class MarkdownGenerator: """Generates markdown documentation from structured API data.""" def __init__(self, data: Dict[str, Any], config: Dict[str, Any] = None): self.data = data + self.slugger = HeadingSlugger() + self.headings: List[str] = [] + self.toc_entries: List[Dict[str, str]] = [] # Merge provided config with defaults to ensure all config keys exist default_config = self.get_default_config() if config: @@ -44,7 +92,7 @@ def generate(self) -> str: # Title if self.config.get("title"): - sections.append(f"# {self.config['title']}\n") + sections.append(f"{self.heading(1, self.config['title'])}\n") # Metadata if self.config.get("include_metadata"): @@ -57,19 +105,26 @@ def generate(self) -> str: # Introduction sections.append(self.generate_introduction()) - # Table of Contents - if self.config.get("include_toc"): - toc = self.generate_main_toc() - if toc: - sections.append("## Table of Contents\n") - sections.append(toc) - sections.append("\n---\n") + # The table of contents links to anchors the body claims, so the body has to be generated + # first. Its own heading still precedes the body in the document, and so claims its anchor + # before any of them. + folders = self.data.get("folders", []) + toc_heading = "" + if self.config.get("include_toc") and folders: + toc_heading = f"{self.heading(2, 'Table of Contents')}\n" - # Main content - iterate through folders - for folder in self.data.get("folders", []): - sections.append(self.generate_folder_section(folder)) + body = [self.generate_folder_section(folder) for folder in folders] - return "\n".join(sections) + if toc_heading: + sections.append(toc_heading) + sections.append(self.generate_main_toc()) + sections.append("\n---\n") + + sections.extend(body) + + markdown = "\n".join(sections) + self.verify_headings(markdown) + return markdown def generate_introduction(self) -> str: """Generate introduction text.""" @@ -79,44 +134,99 @@ def generate_introduction(self) -> str: """ def generate_main_toc(self) -> str: - """Generate the main table of contents.""" + """Generate the main table of contents from the anchors the body claimed.""" lines = [] - for folder in self.data.get("folders", []): - folder_name = folder.get("name", "") - folder_path = folder.get("path", folder_name) # Full path for nested folders - # For folder header like "## Account", Docusaurus generates anchor "#account" - folder_slug = folder_path.lower().replace('/', '').replace('_', '') - folder_display = folder_path.replace('/', ' / ').title() - lines.append(f"- [{folder_display}](#{folder_slug})") - - # Add files as sub-items - for file in folder.get("files", []): - file_path = file.get("path", "") - - # For file header like "### `account/account_contract.ts`" - # Docusaurus removes backticks and special chars: "#accountaccount_contractts" - file_slug = file_path.lower().replace('/', '').replace('.', '').replace('_', '').replace('-', '') - - # List the exports for this file - for export in file.get("exports", []): - export_name = export.get("name", "") - # For export header like "#### AccountContract", Docusaurus generates "#accountcontract" - export_slug = export_name.lower().replace('_', '').replace('-', '') - lines.append(f" - [{export_name}](#{export_slug})") + for entry in self.toc_entries: + indent = "" if entry["kind"] == "folder" else " " + lines.append(f"{indent}- [{entry['text']}](#{entry['anchor']})") return "\n".join(lines) + def heading(self, level: int, text: str, toc_kind: str = "") -> str: + """ + Render a heading and claim its anchor. + + Every heading in the document has to be rendered through here, in the order it appears, + because each anchor depends on the ones already taken. Pass `toc_kind` to also list the + heading in the table of contents. + + Args: + level: Heading level, as a count of `#`s + text: The heading text, as it is rendered + toc_kind: "folder" or "export" to list this heading in the table of contents + + Returns: + The rendered heading line + """ + anchor = self.slugger.slug(text) + self.headings.append(text) + if toc_kind: + self.toc_entries.append({"kind": toc_kind, "text": text, "anchor": anchor}) + return f"{'#' * level} {text}" + + def verify_headings(self, markdown: str) -> None: + """ + Check that the document's headings are exactly the ones that claimed an anchor. + + A heading written as a plain string never reaches the slugger, so it takes an anchor the + generator does not know about and silently shifts the suffix of every later duplicate. That + misdirects table of contents links rather than breaking them, which nothing downstream + detects: the links still resolve, just to the wrong section. + """ + rendered = [] + in_code_block = False + for line in markdown.split("\n"): + if line.lstrip().startswith("```"): + in_code_block = not in_code_block + continue + if in_code_block: + continue + match = re.match(r'^(#{1,6}) (.*)$', line) + if match: + rendered.append(match.group(2)) + + if rendered != self.headings: + for claimed, found in zip(self.headings, rendered): + if claimed != found: + raise ValueError( + f"Heading {found!r} did not claim an anchor; expected {claimed!r}. " + "Render every heading through MarkdownGenerator.heading()." + ) + missing = self.headings[len(rendered):] or rendered[len(self.headings):] + raise ValueError( + f"The document and the claimed anchors disagree on {len(missing)} trailing " + f"heading(s), starting at {missing[0]!r}." + ) + + def format_description(self, jsdoc: Dict[str, Any]) -> List[str]: + """ + Render an entry's description, behind a deprecation notice when it carries one. + + A doc comment that is only a `@deprecated` tag leaves the description empty, so without + this the entry reads as though nothing were wrong with it. + """ + sections = [] + + deprecated = next((tag for tag in jsdoc.get("tags", []) if tag.get("name") == "deprecated"), None) + if deprecated is not None: + note = deprecated.get("text", "").strip() + sections.append(f"**Deprecated:** {note}\n" if note else "**Deprecated**\n") + + if jsdoc.get("description"): + sections.append(f"{jsdoc['description']}\n") + + return sections + def generate_folder_section(self, folder: Dict[str, Any]) -> str: """Generate documentation for a folder.""" folder_name = folder.get("name", "") folder_path = folder.get("path", folder_name) # Full path for nested folders - folder_slug = self.slugify(folder_path) sections = [] # Use full path for nested directories, capitalize just the display folder_display = folder_path.replace('/', ' / ').title() - sections.append(f"\n## {folder_display}\n") + sections.append(f"\n{self.heading(2, folder_display, toc_kind='folder')}\n") # Folder description if available if "description" in folder: @@ -124,13 +234,12 @@ def generate_folder_section(self, folder: Dict[str, Any]) -> str: # Generate documentation for each file for file in folder.get("files", []): - sections.append(self.generate_file_section(file, folder_path)) + sections.append(self.generate_file_section(file)) return "\n".join(sections) - def generate_file_section(self, file: Dict[str, Any], folder_name: str) -> str: + def generate_file_section(self, file: Dict[str, Any]) -> str: """Generate documentation for a file.""" - file_name = file.get("name", "") file_path = file.get("path", "") exports = file.get("exports", []) @@ -142,46 +251,43 @@ def generate_file_section(self, file: Dict[str, Any], folder_name: str) -> str: # Add file-level separator and header (only if there are exports) sections.append("\n---\n") - sections.append(f"### `{file_path}`\n") + sections.append(f"{self.heading(3, f'`{file_path}`')}\n") # Generate documentation for each export for export in exports: - sections.append(self.generate_export_section(export, folder_name, file_name, file_path)) + sections.append(self.generate_export_section(export)) return "\n".join(sections) - def generate_export_section(self, export: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_export_section(self, export: Dict[str, Any]) -> str: """Generate documentation for an export (class, interface, type, function).""" kind = export.get("kind", "") name = export.get("name", "") if kind == "class": - return self.generate_class_docs(export, folder_name, file_name, file_path) + return self.generate_class_docs(export) elif kind == "interface": - return self.generate_interface_docs(export, folder_name, file_name, file_path) + return self.generate_interface_docs(export) elif kind == "type": - return self.generate_type_docs(export, folder_name, file_name, file_path) + return self.generate_type_docs(export) elif kind == "function": - return self.generate_function_docs(export, folder_name, file_name, file_path) + return self.generate_function_docs(export) elif kind == "const": - return self.generate_const_docs(export, folder_name, file_name, file_path) + return self.generate_const_docs(export) else: return "" - def generate_class_docs(self, cls: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_class_docs(self, cls: Dict[str, Any]) -> str: """Generate documentation for a class.""" name = cls.get("name", "") - file_name_no_ext = file_name.replace(".ts", "") - slug = self.slugify(f"{folder_name}-{file_name_no_ext}-{name}") sections = [] - sections.append(f"\n#### {name}\n") + sections.append(f"\n{self.heading(4, name, toc_kind='export')}\n") sections.append(f"**Type:** Class\n") # Description jsdoc = cls.get("jsdoc", {}) - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) # Heritage extends = cls.get("extends", []) @@ -204,50 +310,47 @@ def generate_class_docs(self, cls: Dict[str, Any], folder_name: str, file_name: # Constructor if constructors: - sections.append("\n#### Constructor\n") + sections.append(f"\n{self.heading(4, 'Constructor')}\n") for constructor in constructors: sections.append(self.generate_constructor_docs(constructor)) # Properties if properties: - sections.append("\n#### Properties\n") + sections.append(f"\n{self.heading(4, 'Properties')}\n") for prop in properties: sections.append(self.generate_property_docs(prop)) # Methods if methods: - sections.append("\n#### Methods\n") + sections.append(f"\n{self.heading(4, 'Methods')}\n") for method in methods: sections.append(self.generate_method_docs(method)) # Getters if getters: - sections.append("\n#### Getters\n") + sections.append(f"\n{self.heading(4, 'Getters')}\n") for getter in getters: sections.append(self.generate_accessor_docs(getter)) # Setters if setters: - sections.append("\n#### Setters\n") + sections.append(f"\n{self.heading(4, 'Setters')}\n") for setter in setters: sections.append(self.generate_accessor_docs(setter)) return "\n".join(sections) - def generate_interface_docs(self, iface: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_interface_docs(self, iface: Dict[str, Any]) -> str: """Generate documentation for an interface.""" name = iface.get("name", "") - file_name_no_ext = file_name.replace(".ts", "") - slug = self.slugify(f"{folder_name}-{file_name_no_ext}-{name}") sections = [] - sections.append(f"\n#### {name}\n") + sections.append(f"\n{self.heading(4, name, toc_kind='export')}\n") sections.append(f"**Type:** Interface\n") # Description jsdoc = iface.get("jsdoc", {}) - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) # Extends extends = iface.get("extends", []) @@ -264,25 +367,25 @@ def generate_interface_docs(self, iface: Dict[str, Any], folder_name: str, file_ # Properties if properties: - sections.append("\n#### Properties\n") + sections.append(f"\n{self.heading(4, 'Properties')}\n") for prop in properties: sections.append(self.generate_property_docs(prop)) # Methods if methods: - sections.append("\n#### Methods\n") + sections.append(f"\n{self.heading(4, 'Methods')}\n") for method in methods: sections.append(self.generate_method_docs(method)) # Call signatures if call_sigs: - sections.append("\n#### Call Signatures\n") + sections.append(f"\n{self.heading(4, 'Call Signatures')}\n") for sig in call_sigs: sections.append(self.generate_call_signature_docs(sig)) return "\n".join(sections) - def generate_type_docs(self, type_alias: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_type_docs(self, type_alias: Dict[str, Any]) -> str: """Generate documentation for a type alias.""" name = type_alias.get("name", "") signature = type_alias.get("signature", "") @@ -290,11 +393,10 @@ def generate_type_docs(self, type_alias: Dict[str, Any], folder_name: str, file_ members = type_alias.get("members", []) sections = [] - sections.append(f"\n#### {name}\n") + sections.append(f"\n{self.heading(4, name, toc_kind='export')}\n") sections.append(f"**Type:** Type Alias\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -350,7 +452,7 @@ def generate_type_docs(self, type_alias: Dict[str, Any], folder_name: str, file_ return "\n".join(sections) - def generate_function_docs(self, func: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_function_docs(self, func: Dict[str, Any]) -> str: """Generate documentation for a function.""" name = func.get("name", "") signature = func.get("signature", "") @@ -360,11 +462,10 @@ def generate_function_docs(self, func: Dict[str, Any], folder_name: str, file_na return_description = func.get("returnDescription", "") sections = [] - sections.append(f"\n#### {name}\n") + sections.append(f"\n{self.heading(4, name, toc_kind='export')}\n") sections.append(f"**Type:** Function\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -379,7 +480,7 @@ def generate_function_docs(self, func: Dict[str, Any], folder_name: str, file_na return "\n".join(sections) - def generate_const_docs(self, const: Dict[str, Any], folder_name: str, file_name: str, file_path: str) -> str: + def generate_const_docs(self, const: Dict[str, Any]) -> str: """Generate documentation for a const.""" name = const.get("name", "") signature = const.get("signature", "") @@ -387,14 +488,13 @@ def generate_const_docs(self, const: Dict[str, Any], folder_name: str, file_name const_type = const.get("type", "") sections = [] - sections.append(f"\n#### {name}\n") + sections.append(f"\n{self.heading(4, name, toc_kind='export')}\n") sections.append(f"**Type:** Constant\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) if const_type: - sections.append(f"**Value Type:** `{const_type}`\n") + sections.append(self.format_labeled_type("Value Type", const_type)) return "\n".join(sections) @@ -406,8 +506,7 @@ def generate_constructor_docs(self, constructor: Dict[str, Any]) -> str: sections = [] - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -428,12 +527,11 @@ def generate_property_docs(self, prop: Dict[str, Any]) -> str: is_optional = prop.get("optional", False) sections = [] - sections.append(f"\n##### {name}\n") + sections.append(f"\n{self.heading(5, name)}\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) - sections.append(f"**Type:** `{prop_type}`\n") + sections.append(self.format_labeled_type("Type", prop_type)) return "\n".join(sections) @@ -449,10 +547,9 @@ def generate_method_docs(self, method: Dict[str, Any]) -> str: is_async = method.get("async", False) sections = [] - sections.append(f"\n##### {name}\n") + sections.append(f"\n{self.heading(5, name)}\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -477,10 +574,9 @@ def generate_accessor_docs(self, accessor: Dict[str, Any]) -> str: return_type = accessor.get("returnType", "") sections = [] - sections.append(f"\n##### {name} ({kind})\n") + sections.append(f"\n{self.heading(5, f'{name} ({kind})')}\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -489,7 +585,7 @@ def generate_accessor_docs(self, accessor: Dict[str, Any]) -> str: sections.append(self.generate_parameters_table(parameters)) if return_type and kind == "getter": - sections.append(f"\n**Returns:** `{return_type}`") + sections.append(self.format_return_type(return_type)) return "\n".join(sections) @@ -503,8 +599,7 @@ def generate_call_signature_docs(self, sig: Dict[str, Any]) -> str: sections = [] - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) sections.append("**Signature:**\n") sections.append(f"```typescript\n{signature}\n```") @@ -525,13 +620,12 @@ def generate_index_signature_docs(self, sig: Dict[str, Any]) -> str: value_type = sig.get("type", "any") sections = [] - sections.append(f"\n##### {name}\n") + sections.append(f"\n{self.heading(5, name)}\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) - sections.append(f"**Signature:** `{signature}`\n") - sections.append(f"**Value Type:** `{value_type}`\n") + sections.append(self.format_labeled_type("Signature", signature)) + sections.append(self.format_labeled_type("Value Type", value_type)) return "\n".join(sections) @@ -544,14 +638,13 @@ def generate_mapped_type_docs(self, mapped: Dict[str, Any]) -> str: key_type = mapped.get("keyType", "any") sections = [] - sections.append(f"\n##### {name}\n") + sections.append(f"\n{self.heading(5, name)}\n") - if jsdoc.get("description"): - sections.append(f"{jsdoc['description']}\n") + sections.extend(self.format_description(jsdoc)) - sections.append(f"**Signature:** `{signature}`\n") - sections.append(f"**Key Type:** `{key_type}`\n") - sections.append(f"**Value Type:** `{value_type}`\n") + sections.append(self.format_labeled_type("Signature", signature)) + sections.append(self.format_labeled_type("Key Type", key_type)) + sections.append(self.format_labeled_type("Value Type", value_type)) return "\n".join(sections) @@ -564,7 +657,9 @@ def generate_parameters_table(self, parameters: List[Dict[str, Any]]) -> str: sections.append("\n**Parameters:**\n") for param in parameters: - name = param.get("name", "") + # Destructured parameters are declared over several lines; collapse them so the name + # stays inside a single-line inline code span. + name = " ".join(param.get("name", "").split()) param_type = param.get("type", "") is_optional = param.get("optional", False) description = param.get("description", "") @@ -573,12 +668,38 @@ def generate_parameters_table(self, parameters: List[Dict[str, Any]]) -> str: if is_optional: param_name += " (optional)" - sections.append(f"- {param_name}: `{param_type}`") - if description: - sections.append(f" - {description}") + if '\n' in param_type: + sections.append(f"- {param_name}:") + if description: + sections.append(f" - {description}") + sections.append("") + sections.append(indent(f"```typescript\n{param_type}\n```", " ")) + sections.append("") + else: + sections.append(f"- {param_name}: `{param_type}`") + if description: + sections.append(f" - {description}") return "\n".join(sections) + def format_labeled_type(self, label: str, type_str: str) -> str: + """ + Format a `**Label:** ` line, using a code block when the type spans several lines. + + A multi-line type can contain blank lines, which terminate an inline code span and leave + the type's braces and angle brackets to be parsed as MDX expressions and JSX tags. + + Args: + label: The bold label preceding the type (e.g. "Type", "Value Type") + type_str: The type string + + Returns: + Formatted markdown string for the labeled type + """ + if '\n' in type_str: + return f"**{label}:**\n\n```typescript\n{type_str}\n```\n" + return f"**{label}:** `{type_str}`\n" + def format_return_type(self, return_type: str, return_description: str = "") -> str: """ Format a return type for markdown documentation. @@ -610,21 +731,6 @@ def format_return_type(self, return_type: str, return_description: str = "") -> return "\n".join(sections) - def slugify(self, text: str) -> str: - """Convert text to a markdown-friendly anchor.""" - # Convert to lowercase and replace spaces/special chars with hyphens - slug = text.lower() - slug = slug.replace(" ", "-") - slug = slug.replace("/", "-") - slug = slug.replace(".", "-") - slug = slug.replace("_", "-") - # Remove any other special characters - slug = ''.join(c for c in slug if c.isalnum() or c == '-') - # Remove consecutive hyphens - while '--' in slug: - slug = slug.replace('--', '-') - return slug.strip('-') - def load_input_file(file_path: str) -> Dict[str, Any]: """Load JSON or YAML input file.""" diff --git a/docs/scripts/aztecjs_reference_generation/verify_docs.py b/docs/scripts/aztecjs_reference_generation/verify_docs.py index ac34d4c7002f..00420ba7e6b6 100644 --- a/docs/scripts/aztecjs_reference_generation/verify_docs.py +++ b/docs/scripts/aztecjs_reference_generation/verify_docs.py @@ -85,40 +85,69 @@ def check_heading_hierarchy(self): previous_level = current_level + # Headings the generator emits to group a class or interface's members. They sit at the same + # level as the export headings but describe no export of their own. + MEMBER_GROUP_HEADINGS = {'Constructor', 'Properties', 'Methods', 'Getters', 'Setters', 'Call Signatures'} + + # Only these kinds are documented with a signature; a class, interface or constant has none. + KINDS_WITH_SIGNATURE = {'Function', 'Type Alias'} + def check_section_structure(self): """Check that Type/Interface/Class sections have required subsections.""" section_pattern = re.compile(r'^####\s+(.+)$') - type_label_pattern = re.compile(r'^\*\*Type:\*\*\s+(.+)$') + type_label_pattern = re.compile(r'^\*\*Type:\*\*\s*(.*)$') signature_pattern = re.compile(r'^\*\*Signature:\*\*') current_section = None current_line = 0 + section_kind = '' has_type_label = False has_signature = False + in_code_block = False + + def check_finished_section(): + if not current_section: + return + if not has_type_label: + self.issues.append((current_line, 'WARNING', f'Section "{current_section}" missing **Type:** label')) + if section_kind in self.KINDS_WITH_SIGNATURE and not has_signature: + self.issues.append((current_line, 'INFO', f'Section "{current_section}" missing **Signature:**')) for i, line in enumerate(self.lines, start=1): + # A multi-line type is rendered inside a fence, so its contents are not labels. + if line.strip().startswith('```'): + in_code_block = not in_code_block + continue + if in_code_block: + continue # New H4 section (export) if section_pattern.match(line): - # Check previous section - if current_section: - if not has_type_label: - self.issues.append((current_line, 'WARNING', f'Section "{current_section}" missing **Type:** label')) - if not has_signature: - self.issues.append((current_line, 'INFO', f'Section "{current_section}" missing **Signature:**')) - - current_section = section_pattern.match(line).group(1).strip() + check_finished_section() + + heading = section_pattern.match(line).group(1).strip() + if heading in self.MEMBER_GROUP_HEADINGS: + current_section = None + continue + + current_section = heading current_line = i + section_kind = '' has_type_label = False has_signature = False # Check for type label - if type_label_pattern.match(line): + type_label_match = type_label_pattern.match(line) + if type_label_match: + if not has_type_label: + section_kind = type_label_match.group(1).strip() has_type_label = True # Check for signature if signature_pattern.match(line): has_signature = True + check_finished_section() + def check_empty_sections(self): """Check for empty parameter/returns sections.""" param_pattern = re.compile(r'^\*\*Parameters:\*\*\s*$') diff --git a/yarn-project/aztec.js/src/account/account_contract.ts b/yarn-project/aztec.js/src/account/account_contract.ts index f75c501ad8ba..2e88300686ca 100644 --- a/yarn-project/aztec.js/src/account/account_contract.ts +++ b/yarn-project/aztec.js/src/account/account_contract.ts @@ -1,6 +1,7 @@ import type { AuthWitnessProvider } from '@aztec/entrypoints/interfaces'; import { Fr } from '@aztec/foundation/curves/bn254'; import type { ContractArtifact } from '@aztec/stdlib/abi'; +import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import type { CompleteAddress } from '@aztec/stdlib/contract'; import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract'; import { deriveKeys } from '@aztec/stdlib/keys'; @@ -32,7 +33,7 @@ export interface AccountContract { /** * The hash of this account's immutable instantiation params, committed into its address. Returns - * undefined for accounts that have no immutables (these are instead deployed via an on-chain + * undefined for accounts that have no immutables (these are instead deployed via an onchain * initializer, which contributes to the address through its initialization hash). */ getImmutablesHash(): Promise; @@ -61,7 +62,7 @@ export async function getAccountContractAddress( secret: Fr, salt: Fr, immutablesHash?: Fr, -) { +): Promise { const { publicKeys } = await deriveKeys(secret); const { constructorName, constructorArgs } = (await accountContract.getInitializationFunctionAndArgs()) ?? { constructorName: undefined, 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 df3a45f518be..b868ddaa7f45 100644 --- a/yarn-project/aztec.js/src/contract/contract_function_interaction.ts +++ b/yarn-project/aztec.js/src/contract/contract_function_interaction.ts @@ -75,7 +75,7 @@ export class ContractFunctionInteraction extends BaseContractInteraction { * Useful when generating authwits * @returns An encoded function call */ - public async getFunctionCall() { + public async getFunctionCall(): Promise { const args = encodeArguments(this.functionDao, this.args); return FunctionCall.from({ name: this.functionDao.name, diff --git a/yarn-project/aztec.js/src/contract/fastforward_contract_update.ts b/yarn-project/aztec.js/src/contract/fastforward_contract_update.ts index f3b2186c9690..fd45936741c9 100644 --- a/yarn-project/aztec.js/src/contract/fastforward_contract_update.ts +++ b/yarn-project/aztec.js/src/contract/fastforward_contract_update.ts @@ -11,7 +11,7 @@ import { SimulationOverrides } from '@aztec/stdlib/tx'; /** * Builds `SimulationOverrides` that simulate a deployed instance as if it had already been upgraded to a - * new contract class. Mirrors a real on-chain upgrade (scheduling the new class and waiting out the delay): + * new contract class. Mirrors a real onchain upgrade (scheduling the new class and waiting out the delay): * * - `publicStorage` rewrites the `ContractInstanceRegistry`'s delayed-public-mutable storage so the AVM's * `UpdateCheck` resolves to the new class id. diff --git a/yarn-project/aztec.js/src/contract/wait_for_proven.ts b/yarn-project/aztec.js/src/contract/wait_for_proven.ts index 6ae9534ee0d8..95f15b14583c 100644 --- a/yarn-project/aztec.js/src/contract/wait_for_proven.ts +++ b/yarn-project/aztec.js/src/contract/wait_for_proven.ts @@ -1,3 +1,4 @@ +import type { BlockNumber } from '@aztec/foundation/branded-types'; import { retryUntil } from '@aztec/foundation/retry'; import type { AztecNode } from '@aztec/stdlib/interfaces/client'; import type { TxReceipt } from '@aztec/stdlib/tx'; @@ -22,7 +23,11 @@ export const DefaultWaitForProvenOpts: WaitForProvenOpts = { /** * Wait for a transaction to be proven by polling the node */ -export async function waitForProven(node: AztecNode, receipt: TxReceipt, opts?: WaitForProvenOpts) { +export async function waitForProven( + node: AztecNode, + receipt: TxReceipt, + opts?: WaitForProvenOpts, +): Promise { if (!receipt.blockNumber) { throw new Error(`Cannot wait for proven: receipt of tx ${receipt.txHash} does not have a block number`); } diff --git a/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts b/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts index c386d98f301b..6e791ed0e1ae 100644 --- a/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts +++ b/yarn-project/aztec.js/src/fee/fee_juice_payment_method_with_claim.ts @@ -49,7 +49,7 @@ export class FeeJuicePaymentMethodWithClaim implements FeePaymentMethod { ); } - getAsset() { + getAsset(): Promise { return Promise.resolve(ProtocolContractAddress.FeeJuice); } diff --git a/yarn-project/aztec.js/src/fee/sponsored_fee_payment.ts b/yarn-project/aztec.js/src/fee/sponsored_fee_payment.ts index 4b060dfb2cf4..e7d1b8e3178d 100644 --- a/yarn-project/aztec.js/src/fee/sponsored_fee_payment.ts +++ b/yarn-project/aztec.js/src/fee/sponsored_fee_payment.ts @@ -15,7 +15,7 @@ export class SponsoredFeePaymentMethod implements FeePaymentMethod { throw new Error('Asset is not required for sponsored fpc.'); } - getFeePayer() { + getFeePayer(): Promise { return Promise.resolve(this.paymentContract); } diff --git a/yarn-project/aztec.js/src/utils/cross_chain.ts b/yarn-project/aztec.js/src/utils/cross_chain.ts index 3010e6eab40a..947c11cc55b0 100644 --- a/yarn-project/aztec.js/src/utils/cross_chain.ts +++ b/yarn-project/aztec.js/src/utils/cross_chain.ts @@ -21,7 +21,7 @@ export function waitForL1ToL2MessageReady( */ chainTip?: BlockTag; }, -) { +): Promise { return retryUntil( () => isL1ToL2MessageReady(node, l1ToL2MessageHash, opts.chainTip), `L1 to L2 message ${l1ToL2MessageHash.toString()} ready`, diff --git a/yarn-project/aztec.js/src/wallet/account_manager.ts b/yarn-project/aztec.js/src/wallet/account_manager.ts index 6fd9cf425117..064159fe661a 100644 --- a/yarn-project/aztec.js/src/wallet/account_manager.ts +++ b/yarn-project/aztec.js/src/wallet/account_manager.ts @@ -5,6 +5,7 @@ import { type ContractInstanceWithAddress, getContractInstanceFromInstantiationParams, } from '@aztec/stdlib/contract'; +import type { PublicKeys } from '@aztec/stdlib/keys'; import { deriveKeys } from '@aztec/stdlib/keys'; import type { AccountContract } from '../account/account_contract.js'; @@ -67,11 +68,11 @@ export class AccountManager { return new AccountManager(wallet, secretKey, accountContract, instance); } - protected getPublicKeys() { + protected getPublicKeys(): PublicKeys { return this.instance.publicKeys; } - protected getPublicKeysHash() { + protected getPublicKeysHash(): Promise { return this.getPublicKeys().hash(); } @@ -91,7 +92,7 @@ export class AccountManager { return this.secretKey; } - get address() { + get address(): AztecAddress { return this.instance.address; } diff --git a/yarn-project/aztec.js/src/wallet/capabilities.ts b/yarn-project/aztec.js/src/wallet/capabilities.ts index f8643faab6e3..b9b2f3e63b7e 100644 --- a/yarn-project/aztec.js/src/wallet/capabilities.ts +++ b/yarn-project/aztec.js/src/wallet/capabilities.ts @@ -84,7 +84,7 @@ export interface GrantedAccountsCapability extends AccountsCapability { * * Matching is done by contract address, not class ID. This allows updating * existing contracts with new artifacts (e.g., when contract is upgraded - * to a new contractClassId on-chain). + * to a new contractClassId onchain). * * Note: For querying contract class metadata, use ContractClassesCapability instead. * @@ -138,7 +138,7 @@ export interface ContractsCapability { export interface GrantedContractsCapability extends ContractsCapability {} /** - * Contract class capability - for querying contract class meatadata and registering contract classes. + * Contract class capability - for querying contract class metadata and registering contract classes. * * Maps to wallet methods: * - getContractClassMetadata (when canGetMetadata: true) diff --git a/yarn-project/aztec.js/src/wallet/wallet.ts b/yarn-project/aztec.js/src/wallet/wallet.ts index 0337d2a24a79..9b4ca2511533 100644 --- a/yarn-project/aztec.js/src/wallet/wallet.ts +++ b/yarn-project/aztec.js/src/wallet/wallet.ts @@ -243,7 +243,7 @@ export type ContractMetadata = { instance?: ContractInstancePreimageWithAddress; /** Whether the contract has been initialized. */ initializationStatus: ContractInitializationStatus; - /** Whether the contract instance is publicly deployed on-chain */ + /** Whether the contract instance is publicly deployed onchain */ isContractPublished: boolean; /** Whether the contract has been updated to a different class */ isContractUpdated: boolean; @@ -257,7 +257,7 @@ export type ContractMetadata = { export type ContractClassMetadata = { /** Whether the artifact is registered in the wallet */ isArtifactRegistered: boolean; - /** Whether the contract class is publicly registered on-chain */ + /** Whether the contract class is publicly registered onchain */ isContractClassPubliclyRegistered: boolean; }; @@ -292,7 +292,7 @@ export type Wallet = { ): Promise; /** * Registers a contract class artifact in the local PXE without binding it to any instance. - * Useful for simulation flows that need the artifact available locally before any on-chain + * Useful for simulation flows that need the artifact available locally before any onchain * upgrade has taken effect. No chain check. */ registerContractClass(artifact: ContractArtifact): Promise;