@aztec/aztec.js 0.23.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dest/account/index.d.ts +1 -1
  2. package/dest/account/index.d.ts.map +1 -1
  3. package/dest/account/interface.d.ts +12 -2
  4. package/dest/account/interface.d.ts.map +1 -1
  5. package/dest/account/interface.js +1 -1
  6. package/dest/account_manager/index.d.ts +4 -2
  7. package/dest/account_manager/index.d.ts.map +1 -1
  8. package/dest/account_manager/index.js +15 -6
  9. package/dest/api/account.d.ts +1 -1
  10. package/dest/api/account.d.ts.map +1 -1
  11. package/dest/api/account.js +1 -1
  12. package/dest/api/deployment.d.ts +4 -0
  13. package/dest/api/deployment.d.ts.map +1 -0
  14. package/dest/api/deployment.js +4 -0
  15. package/dest/api/fee.d.ts +5 -0
  16. package/dest/api/fee.d.ts.map +1 -0
  17. package/dest/api/fee.js +4 -0
  18. package/dest/contract/base_contract_interaction.d.ts +5 -0
  19. package/dest/contract/base_contract_interaction.d.ts.map +1 -1
  20. package/dest/contract/base_contract_interaction.js +1 -1
  21. package/dest/contract/batch_call.d.ts +3 -2
  22. package/dest/contract/batch_call.d.ts.map +1 -1
  23. package/dest/contract/batch_call.js +4 -3
  24. package/dest/contract/contract.d.ts +4 -2
  25. package/dest/contract/contract.d.ts.map +1 -1
  26. package/dest/contract/contract.js +7 -5
  27. package/dest/contract/contract_function_interaction.d.ts +2 -2
  28. package/dest/contract/contract_function_interaction.d.ts.map +1 -1
  29. package/dest/contract/contract_function_interaction.js +4 -4
  30. package/dest/contract/deploy_method.d.ts +37 -12
  31. package/dest/contract/deploy_method.d.ts.map +1 -1
  32. package/dest/contract/deploy_method.js +79 -35
  33. package/dest/contract/deploy_sent_tx.d.ts +3 -3
  34. package/dest/contract/deploy_sent_tx.d.ts.map +1 -1
  35. package/dest/contract/deploy_sent_tx.js +4 -7
  36. package/dest/contract/sent_tx.d.ts.map +1 -1
  37. package/dest/contract/sent_tx.js +10 -10
  38. package/dest/contract/unsafe_contract.d.ts +15 -0
  39. package/dest/contract/unsafe_contract.d.ts.map +1 -0
  40. package/dest/contract/unsafe_contract.js +14 -0
  41. package/dest/deployment/broadcast_function.d.ts +24 -0
  42. package/dest/deployment/broadcast_function.d.ts.map +1 -0
  43. package/dest/deployment/broadcast_function.js +67 -0
  44. package/dest/{contract_deployer → deployment}/contract_deployer.d.ts +4 -3
  45. package/dest/deployment/contract_deployer.d.ts.map +1 -0
  46. package/dest/{contract_deployer → deployment}/contract_deployer.js +5 -4
  47. package/dest/deployment/deploy_instance.d.ts +13 -0
  48. package/dest/deployment/deploy_instance.d.ts.map +1 -0
  49. package/dest/deployment/deploy_instance.js +13 -0
  50. package/dest/deployment/index.d.ts.map +1 -0
  51. package/dest/{contract_deployer → deployment}/index.js +1 -1
  52. package/dest/deployment/protocol_contracts.d.ts +7 -0
  53. package/dest/deployment/protocol_contracts.d.ts.map +1 -0
  54. package/dest/deployment/protocol_contracts.js +14 -0
  55. package/dest/deployment/register_class.d.ts +6 -0
  56. package/dest/deployment/register_class.d.ts.map +1 -0
  57. package/dest/deployment/register_class.js +12 -0
  58. package/dest/fee/fee_payment_method.d.ts +24 -0
  59. package/dest/fee/fee_payment_method.d.ts.map +1 -0
  60. package/dest/fee/fee_payment_method.js +2 -0
  61. package/dest/fee/native_fee_payment_method.d.ts +32 -0
  62. package/dest/fee/native_fee_payment_method.d.ts.map +1 -0
  63. package/dest/fee/native_fee_payment_method.js +54 -0
  64. package/dest/fee/private_fee_payment_method.d.ts +52 -0
  65. package/dest/fee/private_fee_payment_method.d.ts.map +1 -0
  66. package/dest/fee/private_fee_payment_method.js +62 -0
  67. package/dest/fee/public_fee_payment_method.d.ts +52 -0
  68. package/dest/fee/public_fee_payment_method.d.ts.map +1 -0
  69. package/dest/fee/public_fee_payment_method.js +62 -0
  70. package/dest/index.d.ts +6 -4
  71. package/dest/index.d.ts.map +1 -1
  72. package/dest/index.js +7 -5
  73. package/dest/rpc_clients/pxe_client.d.ts.map +1 -1
  74. package/dest/rpc_clients/pxe_client.js +15 -15
  75. package/dest/utils/authwit.d.ts +30 -4
  76. package/dest/utils/authwit.d.ts.map +1 -1
  77. package/dest/utils/authwit.js +35 -5
  78. package/dest/utils/cheat_codes.js +3 -3
  79. package/dest/utils/index.d.ts +0 -1
  80. package/dest/utils/index.d.ts.map +1 -1
  81. package/dest/utils/index.js +1 -2
  82. package/dest/utils/l2_contracts.js +2 -2
  83. package/dest/wallet/account_wallet.d.ts +10 -3
  84. package/dest/wallet/account_wallet.d.ts.map +1 -1
  85. package/dest/wallet/account_wallet.js +34 -10
  86. package/dest/wallet/base_wallet.d.ts +7 -4
  87. package/dest/wallet/base_wallet.d.ts.map +1 -1
  88. package/dest/wallet/base_wallet.js +9 -3
  89. package/dest/wallet/signerless_wallet.js +2 -2
  90. package/package.json +9 -6
  91. package/src/account/contract.ts +33 -0
  92. package/src/account/index.ts +16 -0
  93. package/src/account/interface.ts +47 -0
  94. package/src/account/wallet.ts +8 -0
  95. package/src/account_manager/deploy_account_sent_tx.ts +42 -0
  96. package/src/account_manager/index.ts +188 -0
  97. package/src/api/README.md +7 -0
  98. package/src/api/abi.ts +3 -0
  99. package/src/api/account.ts +13 -0
  100. package/src/api/aztec_address.ts +1 -0
  101. package/src/api/deployment.ts +3 -0
  102. package/src/api/eth_address.ts +1 -0
  103. package/src/api/ethereum.ts +6 -0
  104. package/src/api/fee.ts +4 -0
  105. package/src/api/fields.ts +1 -0
  106. package/src/api/init.ts +10 -0
  107. package/src/api/interfaces/pxe.ts +1 -0
  108. package/src/api/log_id.ts +1 -0
  109. package/src/api/tx_hash.ts +1 -0
  110. package/src/api/wallet.ts +1 -0
  111. package/src/contract/base_contract_interaction.ts +67 -0
  112. package/src/contract/batch_call.ts +24 -0
  113. package/src/contract/checker.ts +117 -0
  114. package/src/contract/contract.ts +64 -0
  115. package/src/contract/contract_base.ts +72 -0
  116. package/src/contract/contract_function_interaction.ts +80 -0
  117. package/src/contract/deploy_method.ts +192 -0
  118. package/src/contract/deploy_sent_tx.ts +66 -0
  119. package/src/contract/index.ts +44 -0
  120. package/src/contract/sent_tx.ts +135 -0
  121. package/src/contract/unsafe_contract.ts +19 -0
  122. package/src/deployment/broadcast_function.ts +118 -0
  123. package/src/deployment/contract_deployer.ts +42 -0
  124. package/src/deployment/deploy_instance.ts +28 -0
  125. package/src/deployment/index.ts +1 -0
  126. package/src/deployment/protocol_contracts.ts +17 -0
  127. package/src/deployment/register_class.ts +19 -0
  128. package/src/fee/fee_payment_method.ts +25 -0
  129. package/src/fee/native_fee_payment_method.ts +60 -0
  130. package/src/fee/private_fee_payment_method.ts +79 -0
  131. package/src/fee/public_fee_payment_method.ts +79 -0
  132. package/src/index.ts +150 -0
  133. package/src/rpc_clients/index.ts +1 -0
  134. package/src/rpc_clients/pxe_client.ts +63 -0
  135. package/src/utils/abi_types.ts +16 -0
  136. package/src/utils/account.ts +32 -0
  137. package/src/utils/authwit.ts +62 -0
  138. package/src/utils/cheat_codes.ts +297 -0
  139. package/src/utils/index.ts +8 -0
  140. package/src/utils/l1_contracts.ts +21 -0
  141. package/src/utils/l2_contracts.ts +12 -0
  142. package/src/utils/pub_key.ts +12 -0
  143. package/src/utils/pxe.ts +16 -0
  144. package/src/wallet/account_wallet.ts +94 -0
  145. package/src/wallet/account_wallet_with_private_key.ts +28 -0
  146. package/src/wallet/base_wallet.ts +129 -0
  147. package/src/wallet/create_recipient.ts +13 -0
  148. package/src/wallet/index.ts +31 -0
  149. package/src/wallet/signerless_wallet.ts +37 -0
  150. package/dest/contract_deployer/contract_deployer.d.ts.map +0 -1
  151. package/dest/contract_deployer/index.d.ts.map +0 -1
  152. package/dest/utils/secrets.d.ts +0 -8
  153. package/dest/utils/secrets.d.ts.map +0 -1
  154. package/dest/utils/secrets.js +0 -10
  155. /package/dest/{contract_deployer → deployment}/index.d.ts +0 -0
@@ -0,0 +1,80 @@
1
+ import { FunctionCall, TxExecutionRequest } from '@aztec/circuit-types';
2
+ import { AztecAddress, FunctionData } from '@aztec/circuits.js';
3
+ import { FunctionAbi, FunctionType, encodeArguments } from '@aztec/foundation/abi';
4
+
5
+ import { Wallet } from '../account/wallet.js';
6
+ import { BaseContractInteraction, SendMethodOptions } from './base_contract_interaction.js';
7
+
8
+ export { SendMethodOptions };
9
+
10
+ /**
11
+ * Represents the options for a view method in a contract function interaction.
12
+ * Allows specifying the address from which the view method should be called.
13
+ */
14
+ export type ViewMethodOptions = {
15
+ /**
16
+ * The sender's Aztec address.
17
+ */
18
+ from?: AztecAddress;
19
+ };
20
+
21
+ /**
22
+ * This is the class that is returned when calling e.g. `contract.methods.myMethod(arg0, arg1)`.
23
+ * It contains available interactions one can call on a method, including view.
24
+ */
25
+ export class ContractFunctionInteraction extends BaseContractInteraction {
26
+ constructor(
27
+ protected wallet: Wallet,
28
+ protected contractAddress: AztecAddress,
29
+ protected functionDao: FunctionAbi,
30
+ protected args: any[],
31
+ ) {
32
+ super(wallet);
33
+ if (args.some(arg => arg === undefined || arg === null)) {
34
+ throw new Error('All function interaction arguments must be defined and not null. Received: ' + args);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Create a transaction execution request that represents this call, encoded and authenticated by the
40
+ * user's wallet, ready to be simulated.
41
+ * @param opts - An optional object containing additional configuration for the transaction.
42
+ * @returns A Promise that resolves to a transaction instance.
43
+ */
44
+ public async create(opts?: SendMethodOptions): Promise<TxExecutionRequest> {
45
+ if (this.functionDao.functionType === FunctionType.UNCONSTRAINED) {
46
+ throw new Error("Can't call `create` on an unconstrained function.");
47
+ }
48
+ if (!this.txRequest) {
49
+ this.txRequest = await this.wallet.createTxExecutionRequest([this.request()], opts?.fee);
50
+ }
51
+ return this.txRequest;
52
+ }
53
+
54
+ /**
55
+ * Returns an execution request that represents this operation. Useful as a building
56
+ * block for constructing batch requests.
57
+ * @returns An execution request wrapped in promise.
58
+ */
59
+ public request(): FunctionCall {
60
+ const args = encodeArguments(this.functionDao, this.args);
61
+ const functionData = FunctionData.fromAbi(this.functionDao);
62
+ return { args, functionData, to: this.contractAddress };
63
+ }
64
+
65
+ /**
66
+ * Execute a view (read-only) transaction on an unconstrained function.
67
+ * This method is used to call functions that do not modify the contract state and only return data.
68
+ * Throws an error if called on a non-unconstrained function.
69
+ * @param options - An optional object containing additional configuration for the transaction.
70
+ * @returns The result of the view transaction as returned by the contract function.
71
+ */
72
+ public view(options: ViewMethodOptions = {}) {
73
+ if (this.functionDao.functionType !== FunctionType.UNCONSTRAINED) {
74
+ throw new Error('Can only call `view` on an unconstrained function.');
75
+ }
76
+
77
+ const { from } = options;
78
+ return this.wallet.viewTx(this.functionDao.name, this.args, this.contractAddress, from);
79
+ }
80
+ }
@@ -0,0 +1,192 @@
1
+ import { FunctionCall, PublicKey, Tx, TxExecutionRequest } from '@aztec/circuit-types';
2
+ import {
3
+ AztecAddress,
4
+ computePartialAddress,
5
+ getContractClassFromArtifact,
6
+ getContractInstanceFromDeployParams,
7
+ } from '@aztec/circuits.js';
8
+ import { ContractArtifact, FunctionArtifact } from '@aztec/foundation/abi';
9
+ import { EthAddress } from '@aztec/foundation/eth-address';
10
+ import { Fr } from '@aztec/foundation/fields';
11
+ import { createDebugLogger } from '@aztec/foundation/log';
12
+ import { ContractInstanceWithAddress } from '@aztec/types/contracts';
13
+
14
+ import { Wallet } from '../account/index.js';
15
+ import { deployInstance } from '../deployment/deploy_instance.js';
16
+ import { registerContractClass } from '../deployment/register_class.js';
17
+ import { BaseContractInteraction, SendMethodOptions } from './base_contract_interaction.js';
18
+ import { type Contract } from './contract.js';
19
+ import { ContractBase } from './contract_base.js';
20
+ import { ContractFunctionInteraction } from './contract_function_interaction.js';
21
+ import { DeploySentTx } from './deploy_sent_tx.js';
22
+
23
+ /**
24
+ * Options for deploying a contract on the Aztec network.
25
+ * Allows specifying a portal contract, contract address salt, and additional send method options.
26
+ */
27
+ export type DeployOptions = {
28
+ /** The Ethereum address of the Portal contract. */
29
+ portalContract?: EthAddress;
30
+ /** An optional salt value used to deterministically calculate the contract address. */
31
+ contractAddressSalt?: Fr;
32
+ /** Set to true to *not* include the sender in the address computation. */
33
+ universalDeploy?: boolean;
34
+ /** Skip contract class registration. */
35
+ skipClassRegistration?: boolean;
36
+ /** Skip public deployment and only initialize the contract. */
37
+ skipPublicDeployment?: boolean;
38
+ } & SendMethodOptions;
39
+
40
+ // TODO(@spalladino): Add unit tests for this class!
41
+
42
+ /**
43
+ * Contract interaction for deployment. Handles class registration, public instance deployment,
44
+ * and initialization of the contract. Extends the BaseContractInteraction class.
45
+ */
46
+ export class DeployMethod<TContract extends ContractBase = Contract> extends BaseContractInteraction {
47
+ /** The contract instance to be deployed. */
48
+ private instance?: ContractInstanceWithAddress = undefined;
49
+
50
+ /** Constructor function to call. */
51
+ private constructorArtifact: FunctionArtifact;
52
+
53
+ private log = createDebugLogger('aztec:js:deploy_method');
54
+
55
+ constructor(
56
+ private publicKey: PublicKey,
57
+ protected wallet: Wallet,
58
+ private artifact: ContractArtifact,
59
+ private postDeployCtor: (address: AztecAddress, wallet: Wallet) => Promise<TContract>,
60
+ private args: any[] = [],
61
+ constructorName: string = 'constructor',
62
+ ) {
63
+ super(wallet);
64
+ const constructorArtifact = artifact.functions.find(f => f.name === constructorName);
65
+ if (!constructorArtifact) {
66
+ throw new Error('Cannot find constructor in the artifact.');
67
+ }
68
+ this.constructorArtifact = constructorArtifact;
69
+ }
70
+
71
+ /**
72
+ * Create a contract deployment transaction, given the deployment options.
73
+ * This function internally calls `request()` and `sign()` methods to prepare
74
+ * the transaction for deployment. The resulting signed transaction can be
75
+ * later sent using the `send()` method.
76
+ *
77
+ * @param options - An object containing optional deployment settings, including portalContract, contractAddressSalt, and from.
78
+ * @returns A Promise resolving to an object containing the signed transaction data and other relevant information.
79
+ */
80
+ public async create(options: DeployOptions = {}): Promise<TxExecutionRequest> {
81
+ if (!this.txRequest) {
82
+ this.txRequest = await this.wallet.createTxExecutionRequest(await this.request(options));
83
+ // TODO: Should we add the contracts to the DB here, or once the tx has been sent or mined?
84
+ await this.pxe.addContracts([{ artifact: this.artifact, instance: this.instance! }]);
85
+ }
86
+ return this.txRequest;
87
+ }
88
+
89
+ /**
90
+ * Returns an array of function calls that represent this operation. Useful as a building
91
+ * block for constructing batch requests.
92
+ * @param options - Deployment options.
93
+ * @returns An array of function calls.
94
+ * @remarks This method does not have the same return type as the `request` in the ContractInteraction object,
95
+ * it returns a promise for an array instead of a function call directly.
96
+ */
97
+ public async request(options: DeployOptions = {}): Promise<FunctionCall[]> {
98
+ const { address } = this.getInstance(options);
99
+ const constructorCall = new ContractFunctionInteraction(this.wallet, address, this.constructorArtifact, this.args);
100
+ return [...(await this.getDeploymentFunctionCalls(options)), constructorCall.request()];
101
+ }
102
+
103
+ /**
104
+ * Returns calls for registration of the class and deployment of the instance, depending on the provided options.
105
+ * @param options - Deployment options.
106
+ * @returns A function call array with potentially requests to the class registerer and instance deployer.
107
+ */
108
+ protected async getDeploymentFunctionCalls(options: DeployOptions = {}): Promise<FunctionCall[]> {
109
+ const calls: FunctionCall[] = [];
110
+
111
+ // Set contract instance object so it's available for populating the DeploySendTx object
112
+ const instance = this.getInstance(options);
113
+
114
+ // Obtain contract class from artifact and check it matches the reported one by the instance.
115
+ // TODO(@spalladino): We're unnecessarily calculating the contract class multiple times here.
116
+ const contractClass = getContractClassFromArtifact(this.artifact);
117
+ if (!instance.contractClassId.equals(contractClass.id)) {
118
+ throw new Error(
119
+ `Contract class mismatch when deploying contract: got ${instance.contractClassId.toString()} from instance and ${contractClass.id.toString()} from artifact`,
120
+ );
121
+ }
122
+
123
+ // Register the contract class if it hasn't been published already.
124
+ if (!options.skipClassRegistration) {
125
+ if (await this.pxe.isContractClassPubliclyRegistered(contractClass.id)) {
126
+ this.log(
127
+ `Skipping registration of already registered contract class ${contractClass.id.toString()} for ${instance.address.toString()}`,
128
+ );
129
+ } else {
130
+ this.log(
131
+ `Creating request for registering contract class ${contractClass.id.toString()} as part of deployment for ${instance.address.toString()}`,
132
+ );
133
+ calls.push((await registerContractClass(this.wallet, this.artifact)).request());
134
+ }
135
+ }
136
+
137
+ // Deploy the contract via the instance deployer.
138
+ if (!options.skipPublicDeployment) {
139
+ calls.push(deployInstance(this.wallet, instance, { universalDeploy: options.universalDeploy }).request());
140
+ }
141
+
142
+ return calls;
143
+ }
144
+
145
+ /**
146
+ * Send the contract deployment transaction using the provided options.
147
+ * This function extends the 'send' method from the ContractFunctionInteraction class,
148
+ * allowing us to send a transaction specifically for contract deployment.
149
+ *
150
+ * @param options - An object containing various deployment options such as portalContract, contractAddressSalt, and from.
151
+ * @returns A SentTx object that returns the receipt and the deployed contract instance.
152
+ */
153
+ public send(options: DeployOptions = {}): DeploySentTx<TContract> {
154
+ const txHashPromise = super.send(options).getTxHash();
155
+ return new DeploySentTx(this.pxe, txHashPromise, this.postDeployCtor, this.getInstance(options));
156
+ }
157
+
158
+ /**
159
+ * Builds the contract instance to be deployed and returns it.
160
+ *
161
+ * @param options - An object containing various deployment options.
162
+ * @returns An instance object.
163
+ */
164
+ public getInstance(options: DeployOptions = {}): ContractInstanceWithAddress {
165
+ if (!this.instance) {
166
+ const portalContract = options.portalContract ?? EthAddress.ZERO;
167
+ const contractAddressSalt = options.contractAddressSalt ?? Fr.random();
168
+ const deployParams = [this.artifact, this.args, contractAddressSalt, this.publicKey, portalContract] as const;
169
+ this.instance = getContractInstanceFromDeployParams(...deployParams);
170
+ }
171
+ return this.instance;
172
+ }
173
+
174
+ /**
175
+ * Simulate the request.
176
+ * @param options - Deployment options.
177
+ * @returns The simulated tx.
178
+ */
179
+ public simulate(options: DeployOptions): Promise<Tx> {
180
+ return super.simulate(options);
181
+ }
182
+
183
+ /** Return this deployment address. */
184
+ public get address() {
185
+ return this.instance?.address;
186
+ }
187
+
188
+ /** Returns the partial address for this deployment. */
189
+ public get partialAddress() {
190
+ return this.instance && computePartialAddress(this.instance);
191
+ }
192
+ }
@@ -0,0 +1,66 @@
1
+ import { PXE, TxHash, TxReceipt } from '@aztec/circuit-types';
2
+ import { AztecAddress } from '@aztec/circuits.js';
3
+ import { FieldsOf } from '@aztec/foundation/types';
4
+ import { ContractInstanceWithAddress } from '@aztec/types/contracts';
5
+
6
+ import { Wallet } from '../account/index.js';
7
+ import { type Contract } from './contract.js';
8
+ import { ContractBase } from './contract_base.js';
9
+ import { SentTx, WaitOpts } from './sent_tx.js';
10
+
11
+ /** Options related to waiting for a deployment tx. */
12
+ export type DeployedWaitOpts = WaitOpts & {
13
+ /** Wallet to use for creating a contract instance. Uses the one set in the deployer constructor if not set. */
14
+ wallet?: Wallet;
15
+ };
16
+
17
+ /** Extends a transaction receipt with a contract instance that represents the newly deployed contract. */
18
+ export type DeployTxReceipt<TContract extends ContractBase = Contract> = FieldsOf<TxReceipt> & {
19
+ /** Instance of the newly deployed contract. */
20
+ contract: TContract;
21
+ };
22
+
23
+ /**
24
+ * A contract deployment transaction sent to the network, extending SentTx with methods to create a contract instance.
25
+ */
26
+ export class DeploySentTx<TContract extends Contract = Contract> extends SentTx {
27
+ constructor(
28
+ wallet: PXE | Wallet,
29
+ txHashPromise: Promise<TxHash>,
30
+ private postDeployCtor: (address: AztecAddress, wallet: Wallet) => Promise<TContract>,
31
+ /** The deployed contract instance */
32
+ public instance: ContractInstanceWithAddress,
33
+ ) {
34
+ super(wallet, txHashPromise);
35
+ }
36
+
37
+ /**
38
+ * Awaits for the tx to be mined and returns the contract instance. Throws if tx is not mined.
39
+ * @param opts - Options for configuring the waiting for the tx to be mined.
40
+ * @returns The deployed contract instance.
41
+ */
42
+ public async deployed(opts?: DeployedWaitOpts): Promise<TContract> {
43
+ const receipt = await this.wait(opts);
44
+ return receipt.contract;
45
+ }
46
+
47
+ /**
48
+ * Awaits for the tx to be mined and returns the receipt along with a contract instance. Throws if tx is not mined.
49
+ * @param opts - Options for configuring the waiting for the tx to be mined.
50
+ * @returns The transaction receipt with the deployed contract instance.
51
+ */
52
+ public async wait(opts?: DeployedWaitOpts): Promise<DeployTxReceipt<TContract>> {
53
+ const receipt = await super.wait(opts);
54
+ const contract = await this.getContractObject(opts?.wallet);
55
+ return { ...receipt, contract };
56
+ }
57
+
58
+ protected getContractObject(wallet?: Wallet): Promise<TContract> {
59
+ const isWallet = (pxe: PXE | Wallet): pxe is Wallet => !!(pxe as Wallet).createTxExecutionRequest;
60
+ const contractWallet = wallet ?? (isWallet(this.pxe) && this.pxe);
61
+ if (!contractWallet) {
62
+ throw new Error(`A wallet is required for creating a contract instance`);
63
+ }
64
+ return this.postDeployCtor(this.instance.address, contractWallet) as Promise<TContract>;
65
+ }
66
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The `contract` module provides utilities for deploying and interacting with contracts, based on a
3
+ * `Wallet` instance and a compiled artifact. Refer to the {@link account} module for how to obtain a valid
4
+ * `Wallet` instance, and to the {@link https://docs.aztec.network/developers/contracts/compiling | Compiling contracts}
5
+ * section of the documentation for how to generate an artifact out of your Noir source code.
6
+ *
7
+ * The {@link Contract} class is the main class in this module, and provides static methods for deploying
8
+ * a contract or interacting with an already deployed one. The `methods` property of the contract instance
9
+ * provides access to private, public, and view methods, that can be invoked in a transaction via `send()`,
10
+ * or can be queried via `view()`.
11
+ *
12
+ * ```ts
13
+ * const contract = await Contract.deploy(wallet, MyContractArtifact, [...constructorArgs]).send().deployed();
14
+ * console.log(`Contract deployed at ${contract.address}`);
15
+ * ```
16
+ *
17
+ * ```ts
18
+ * const contract = await Contract.at(address, MyContractArtifact, wallet);
19
+ * await contract.methods.mint(1000, owner).send().wait();
20
+ * console.log(`Total supply is now ${await contract.methods.totalSupply().view()}`);
21
+ * ```
22
+ *
23
+ * The result of calling a method in a contract instance, such as `contract.methods.mint(1000, owner)`
24
+ * in the example, is a {@link ContractFunctionInteraction} instance. Usually this will be just sent as
25
+ * a transaction to the network via the `send` method, but you can also `simulate` it without sending,
26
+ * or obtaining the `request` for aggregating into a {@link BatchCall}.
27
+ *
28
+ * The result of `send`ing a transaction is a {@link SentTx} object, from which you can get the
29
+ * transaction hash, or simply `wait` until the transaction is mined and the local PXE Service
30
+ * has synchronized its changes.
31
+ *
32
+ * @remarks If you are using typescript, consider using the
33
+ * {@link https://docs.aztec.network/developers/contracts/compiling#typescript-interfaces | autogenerated type-safe interfaces}
34
+ * for interacting with your contracts.
35
+ *
36
+ * @packageDocumentation
37
+ */
38
+ export * from './contract.js';
39
+ export * from './contract_function_interaction.js';
40
+ export * from './sent_tx.js';
41
+ export * from './contract_base.js';
42
+ export * from './batch_call.js';
43
+ export * from './deploy_method.js';
44
+ export * from './deploy_sent_tx.js';
@@ -0,0 +1,135 @@
1
+ import { ExtendedNote, GetUnencryptedLogsResponse, PXE, TxHash, TxReceipt, TxStatus } from '@aztec/circuit-types';
2
+ import { retryUntil } from '@aztec/foundation/retry';
3
+ import { FieldsOf } from '@aztec/foundation/types';
4
+
5
+ /** Options related to waiting for a tx. */
6
+ export type WaitOpts = {
7
+ /** The maximum time (in seconds) to wait for the transaction to be mined. Defaults to 60. */
8
+ timeout?: number;
9
+ /** The time interval (in seconds) between retries to fetch the transaction receipt. Defaults to 1. */
10
+ interval?: number;
11
+ /**
12
+ * Whether to wait for the PXE Service to sync all notes up to the block in which this tx was mined.
13
+ * If false, then any queries that depend on state set by this transaction may return stale data. Defaults to true.
14
+ **/
15
+ waitForNotesSync?: boolean;
16
+ /** Whether to include information useful for debugging/testing in the receipt. */
17
+ debug?: boolean;
18
+ };
19
+
20
+ export const DefaultWaitOpts: WaitOpts = {
21
+ timeout: 60,
22
+ interval: 1,
23
+ waitForNotesSync: true,
24
+ debug: false,
25
+ };
26
+
27
+ /**
28
+ * The SentTx class represents a sent transaction through the PXE, providing methods to fetch
29
+ * its hash, receipt, and mining status.
30
+ */
31
+ export class SentTx {
32
+ constructor(protected pxe: PXE, protected txHashPromise: Promise<TxHash>) {}
33
+
34
+ /**
35
+ * Retrieves the transaction hash of the SentTx instance.
36
+ * The function internally awaits for the 'txHashPromise' to resolve, and then returns the resolved transaction hash.
37
+ *
38
+ * @returns A promise that resolves to the transaction hash of the SentTx instance.
39
+ */
40
+ public getTxHash(): Promise<TxHash> {
41
+ return this.txHashPromise;
42
+ }
43
+
44
+ /**
45
+ * Retrieve the transaction receipt associated with the current SentTx instance.
46
+ * The function fetches the transaction hash using 'getTxHash' and then queries
47
+ * the PXE to get the corresponding transaction receipt.
48
+ *
49
+ * @returns A promise that resolves to a TxReceipt object representing the fetched transaction receipt.
50
+ */
51
+ public async getReceipt(): Promise<TxReceipt> {
52
+ const txHash = await this.getTxHash();
53
+ return await this.pxe.getTxReceipt(txHash);
54
+ }
55
+
56
+ /**
57
+ * Awaits for a tx to be mined and returns the receipt. Throws if tx is not mined.
58
+ * @param opts - Options for configuring the waiting for the tx to be mined.
59
+ * @returns The transaction receipt.
60
+ */
61
+ public async wait(opts?: WaitOpts): Promise<FieldsOf<TxReceipt>> {
62
+ if (opts?.debug && opts.waitForNotesSync === false) {
63
+ throw new Error('Cannot set getNotes to true if waitForNotesSync is false');
64
+ }
65
+ const receipt = await this.waitForReceipt(opts);
66
+ if (receipt.status !== TxStatus.MINED) {
67
+ throw new Error(`Transaction ${await this.getTxHash()} was ${receipt.status}`);
68
+ }
69
+ if (opts?.debug) {
70
+ const txHash = await this.getTxHash();
71
+ const tx = (await this.pxe.getTxEffect(txHash))!;
72
+ const visibleNotes = await this.pxe.getNotes({ txHash });
73
+ receipt.debugInfo = {
74
+ noteHashes: tx.noteHashes.filter(n => !n.isZero()),
75
+ nullifiers: tx.nullifiers.filter(n => !n.isZero()),
76
+ publicDataWrites: tx.publicDataWrites.filter(p => !p.isEmpty()),
77
+ l2ToL1Msgs: tx.l2ToL1Msgs.filter(l => !l.isZero()),
78
+ contractsLeaves: tx.contractLeaves.filter(c => !c.isZero()),
79
+ contractData: tx.contractData.filter(c => !c.isEmpty()),
80
+ visibleNotes,
81
+ };
82
+ }
83
+ return receipt;
84
+ }
85
+
86
+ /**
87
+ * Gets unencrypted logs emitted by this tx.
88
+ * @remarks This function will wait for the tx to be mined if it hasn't been already.
89
+ * @returns The requested logs.
90
+ */
91
+ public async getUnencryptedLogs(): Promise<GetUnencryptedLogsResponse> {
92
+ await this.wait();
93
+ return this.pxe.getUnencryptedLogs({ txHash: await this.getTxHash() });
94
+ }
95
+
96
+ /**
97
+ * Get notes of accounts registered in the provided PXE/Wallet created in this tx.
98
+ * @remarks This function will wait for the tx to be mined if it hasn't been already.
99
+ * @returns The requested notes.
100
+ */
101
+ public async getVisibleNotes(): Promise<ExtendedNote[]> {
102
+ await this.wait();
103
+ return this.pxe.getNotes({ txHash: await this.getTxHash() });
104
+ }
105
+
106
+ protected async waitForReceipt(opts?: WaitOpts): Promise<TxReceipt> {
107
+ const txHash = await this.getTxHash();
108
+ return await retryUntil(
109
+ async () => {
110
+ const txReceipt = await this.pxe.getTxReceipt(txHash);
111
+ // If receipt is not yet available, try again
112
+ if (txReceipt.status === TxStatus.PENDING) {
113
+ return undefined;
114
+ }
115
+ // If the tx was dropped, return it
116
+ if (txReceipt.status === TxStatus.DROPPED) {
117
+ return txReceipt;
118
+ }
119
+ // If we don't care about waiting for notes to be synced, return the receipt
120
+ const waitForNotesSync = opts?.waitForNotesSync ?? DefaultWaitOpts.waitForNotesSync;
121
+ if (!waitForNotesSync) {
122
+ return txReceipt;
123
+ }
124
+ // Check if all sync blocks on the PXE Service are greater or equal than the block in which the tx was mined
125
+ const { blocks, notes } = await this.pxe.getSyncStatus();
126
+ const targetBlock = txReceipt.blockNumber!;
127
+ const areNotesSynced = blocks >= targetBlock && Object.values(notes).every(block => block >= targetBlock);
128
+ return areNotesSynced ? txReceipt : undefined;
129
+ },
130
+ 'isMined',
131
+ opts?.timeout ?? DefaultWaitOpts.timeout,
132
+ opts?.interval ?? DefaultWaitOpts.interval,
133
+ );
134
+ }
135
+ }
@@ -0,0 +1,19 @@
1
+ import { ContractArtifact } from '@aztec/foundation/abi';
2
+ import { ContractInstanceWithAddress } from '@aztec/types/contracts';
3
+
4
+ import { Wallet } from '../wallet/index.js';
5
+ import { ContractBase } from './contract_base.js';
6
+
7
+ /** Unsafe constructor for ContractBase that bypasses the check that the instance is registered in the wallet. */
8
+ export class UnsafeContract extends ContractBase {
9
+ constructor(
10
+ /** The deployed contract instance definition. */
11
+ instance: ContractInstanceWithAddress,
12
+ /** The Application Binary Interface for the contract. */
13
+ artifact: ContractArtifact,
14
+ /** The wallet used for interacting with this contract. */
15
+ wallet: Wallet,
16
+ ) {
17
+ super(instance, artifact, wallet);
18
+ }
19
+ }
@@ -0,0 +1,118 @@
1
+ import {
2
+ ARTIFACT_FUNCTION_TREE_MAX_HEIGHT,
3
+ MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS,
4
+ computeArtifactFunctionTree,
5
+ computeArtifactFunctionTreeRoot,
6
+ computeArtifactMetadataHash,
7
+ computeFunctionArtifactHash,
8
+ computePrivateFunctionsTree,
9
+ getContractClassFromArtifact,
10
+ } from '@aztec/circuits.js';
11
+ import { ContractArtifact, FunctionSelector, FunctionType, bufferAsFields } from '@aztec/foundation/abi';
12
+ import { padArrayEnd } from '@aztec/foundation/collection';
13
+ import { Fr } from '@aztec/foundation/fields';
14
+
15
+ import { ContractFunctionInteraction } from '../contract/contract_function_interaction.js';
16
+ import { Wallet } from '../wallet/index.js';
17
+ import { getRegistererContract } from './protocol_contracts.js';
18
+
19
+ /**
20
+ * Sets up a call to broadcast a private function's bytecode via the ClassRegisterer contract.
21
+ * Note that this is not required for users to call the function, but is rather a convenience to make
22
+ * this code publicly available so dapps or wallets do not need to redistribute it.
23
+ * @param wallet - Wallet to send the transaction.
24
+ * @param artifact - Contract artifact that contains the function to be broadcast.
25
+ * @param selector - Selector of the function to be broadcast.
26
+ * @returns A ContractFunctionInteraction object that can be used to send the transaction.
27
+ */
28
+ export function broadcastPrivateFunction(
29
+ wallet: Wallet,
30
+ artifact: ContractArtifact,
31
+ selector: FunctionSelector,
32
+ ): ContractFunctionInteraction {
33
+ const contractClass = getContractClassFromArtifact(artifact);
34
+ const privateFunction = contractClass.privateFunctions.find(fn => fn.selector.equals(selector));
35
+ if (!privateFunction) {
36
+ throw new Error(`Private function with selector ${selector.toString()} not found`);
37
+ }
38
+ const privateFunctionArtifact = artifact.functions.find(fn =>
39
+ FunctionSelector.fromNameAndParameters(fn).equals(selector),
40
+ )!;
41
+
42
+ // TODO(@spalladino): The following is computing the unconstrained root hash twice.
43
+ // Feels like we need a nicer API for returning a hash along with all its preimages,
44
+ // since it's common to provide all hash preimages to a function that verifies them.
45
+ const artifactMetadataHash = computeArtifactMetadataHash(artifact);
46
+ const unconstrainedArtifactFunctionTreeRoot = computeArtifactFunctionTreeRoot(artifact, FunctionType.OPEN);
47
+
48
+ // We need two sibling paths because private function information is split across two trees:
49
+ // The "private function tree" captures the selectors and verification keys, and is used in the kernel circuit for verifying the proof generated by the app circuit.
50
+ // The "artifact tree" captures function bytecode and metadata, and is used by the pxe to check that its executing the code it's supposed to be executing, but it never goes into circuits.
51
+ const privateFunctionTreePath = computePrivateFunctionsTree(contractClass.privateFunctions).getSiblingPath(0);
52
+ const artifactFunctionTreePath = computeArtifactFunctionTree(artifact, FunctionType.SECRET)!.getSiblingPath(0);
53
+
54
+ const vkHash = privateFunction.vkHash;
55
+ const metadataHash = computeFunctionArtifactHash(privateFunctionArtifact);
56
+ const bytecode = bufferAsFields(
57
+ Buffer.from(privateFunctionArtifact.bytecode, 'hex'),
58
+ MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS,
59
+ );
60
+
61
+ const registerer = getRegistererContract(wallet);
62
+ return registerer.methods.broadcast_private_function(
63
+ contractClass.id,
64
+ Fr.fromBufferReduce(artifactMetadataHash),
65
+ Fr.fromBufferReduce(unconstrainedArtifactFunctionTreeRoot),
66
+ privateFunctionTreePath.map(Fr.fromBufferReduce),
67
+ padArrayEnd(artifactFunctionTreePath.map(Fr.fromBufferReduce), Fr.ZERO, ARTIFACT_FUNCTION_TREE_MAX_HEIGHT),
68
+ // eslint-disable-next-line camelcase
69
+ { selector, metadata_hash: Fr.fromBufferReduce(metadataHash), bytecode, vk_hash: vkHash },
70
+ );
71
+ }
72
+
73
+ /**
74
+ * Sets up a call to broadcast an unconstrained function's bytecode via the ClassRegisterer contract.
75
+ * Note that this is not required for users to call the function, but is rather a convenience to make
76
+ * this code publicly available so dapps or wallets do not need to redistribute it.
77
+ * @param wallet - Wallet to send the transaction.
78
+ * @param artifact - Contract artifact that contains the function to be broadcast.
79
+ * @param selector - Selector of the function to be broadcast.
80
+ * @returns A ContractFunctionInteraction object that can be used to send the transaction.
81
+ */
82
+ export function broadcastUnconstrainedFunction(
83
+ wallet: Wallet,
84
+ artifact: ContractArtifact,
85
+ selector: FunctionSelector,
86
+ ): ContractFunctionInteraction {
87
+ const functionArtifactIndex = artifact.functions.findIndex(
88
+ fn => fn.functionType === FunctionType.UNCONSTRAINED && FunctionSelector.fromNameAndParameters(fn).equals(selector),
89
+ );
90
+ if (functionArtifactIndex < 0) {
91
+ throw new Error(`Unconstrained function with selector ${selector.toString()} not found`);
92
+ }
93
+ const functionArtifact = artifact.functions[functionArtifactIndex];
94
+
95
+ // TODO(@spalladino): Same comment as above on computing duplicated hashes.
96
+ const artifactMetadataHash = computeArtifactMetadataHash(artifact);
97
+ const privateArtifactFunctionTreeRoot = computeArtifactFunctionTreeRoot(artifact, FunctionType.SECRET);
98
+ const functionTreePath = computeArtifactFunctionTree(artifact, FunctionType.UNCONSTRAINED)!.getSiblingPath(
99
+ functionArtifactIndex,
100
+ );
101
+
102
+ const contractClassId = getContractClassFromArtifact(artifact).id;
103
+ const metadataHash = computeFunctionArtifactHash(functionArtifact);
104
+ const bytecode = bufferAsFields(
105
+ Buffer.from(functionArtifact.bytecode, 'hex'),
106
+ MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS,
107
+ );
108
+
109
+ const registerer = getRegistererContract(wallet);
110
+ return registerer.methods.broadcast_unconstrained_function(
111
+ contractClassId,
112
+ Fr.fromBufferReduce(artifactMetadataHash),
113
+ Fr.fromBufferReduce(privateArtifactFunctionTreeRoot),
114
+ padArrayEnd(functionTreePath.map(Fr.fromBufferReduce), Fr.ZERO, ARTIFACT_FUNCTION_TREE_MAX_HEIGHT),
115
+ // eslint-disable-next-line camelcase
116
+ { selector, metadata_hash: Fr.fromBufferReduce(metadataHash), bytecode },
117
+ );
118
+ }