Aztec 백서

Aztec

원문

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

ou can scope this to a single transaction (by locating its block and matching its tx hash) or to a block range (by reading each block's tx effects): read\_logs\_by\_filter ``` // Get raw public logs for a specific transaction by locating its block and tx effect. const txReceiptForLogs = await node.getTxReceipt(gsReceipt.txHash); const txBlock = await node.getBlock(txReceiptForLogs.blockNumber!, { includeTransactions: true, }); const txLogs = txBlock?.body.txEffects .filter((tx) => tx.txHash.equals(gsReceipt.txHash)) .flatMap((tx) => tx.publicLogs) ?? []; // Get raw public logs for a block range by reading each block's tx effects. const tipBlockNumber = await node.getBlockNumber(); const rangeLogs = ( await Promise.all( Array.from({ length: tipBlockNumber }, (_, i) => BlockNumber(i + 1)).map( async (blockNumber) => { const rangeBlock = await node.getBlock(blockNumber, { includeTransactions: true, }); return rangeBlock?.body.txEffects.flatMap((tx) => tx.publicLogs) ?? []; }, ), ) ).flat(); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L447-L472](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L447-L472) ## Reading events[​](#reading-events "Direct link to Reading events") Events provide typed access to contract emissions. The event metadata from your contract artifact (`Contract.events.EventName`) contains the ABI type information needed for decoding. ### Reading public events[​](#reading-public-events "Direct link to Reading public events") Use the `getPublicEvents` helper to retrieve typed public events: import\_get\_public\_events ``` import { getPublicEvents as _importCheck } from "@aztec-labs/aztec.js/events"; ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L483-L485](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L483-L485) get\_public\_events ``` const publicEventFilter: PublicEventFilter = { contractAddress: testLogContract.address, fromBlock: BlockNumber(firstTx.blockNumber!), toBlock: BlockNumber(lastTx.blockNumber! + 1), }; const { events: collectedEvent0s } = await getPublicEvents<ExampleEvent0>( aztecNode, TestLogContract.events.ExampleEvent0, publicEventFilter, ); const { events: collectedEvent1s } = await getPublicEvents<ExampleEvent1>( aztecNode, TestLogContract.events.ExampleEvent1, publicEventFilter, ); ``` > [Source code: yarn-project/end-to-end/src/automine/effects/event\_logs.test.ts#L147-L165](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/yarn-project/end-to-end/src/automine/effects/event_logs.test.ts#L147-L165) The function parameters are: * `aztecNode` - The node to query * `Contract.events.EventName` - Event metadata from the contract artifact (contains the event selector) * `filter` - An object with optional fields: <!-- --> * `fromBlock` - Starting block number (inclusive) * `toBlock` - Ending block number (exclusive) * `contractAddress` - Filter to a specific contract * `txHash` - Filter to a specific transaction Each returned event includes both the decoded `event` data and `metadata` (block number, block hash, tx hash, contract address). ### Reading private events[​](#reading-private-events "Direct link to Reading private events") Private events are stored in the PXE with privacy scoping. Use `wallet.getPrivateEvents()` to retrieve them: import\_private\_event\_types ``` import type { PrivateEventFilter } from "@aztec-labs/aztec.js/wallet"; import { BlockNumber } from "@aztec-labs/aztec.js/fields"; ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L487-L490](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L487-L490) The `BlockNumber` type is a branded type that wraps raw numbers for type safety. Use it when setting `fromBlock` and `toBlock` in filters. get\_private\_events ``` const eventFilter: PrivateEventFilter = { contractAddress: testLogContract.address, fromBlock: BlockNumber(firstBlockNumber), toBlock: BlockNumber(lastBlockNumber + 1), scopes: [account1Address, account2Address], }; // Each emit_encrypted_events call emits 2 ExampleEvent0s and 1 ExampleEvent1 // So with 5 calls we expect 10 ExampleEvent0s and 5 ExampleEvent1s const collectedEvent0s = await wallet.getPrivateEvents<ExampleEvent0>( TestLogContract.events.ExampleEvent0, eventFilter, ); const collectedEvent1s = await wallet.getPrivateEvents<ExampleEvent1>( TestLogContract.events.ExampleEvent1, eventFilter, ); ``` > [Source code: yarn-project/end-to-end/src/automine/effects/event\_logs.test.ts#L76-L95](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/yarn-project/end-to-end/src/automine/effects/event_logs.test.ts#L76-L95) The `PrivateEventFilter` includes: * `contractAddress` - The contract that emitted the events * `fromBlock` / `toBlock` - Block range to search * `scopes` - Array of account addresses whose private state is being queried * `txHash` (optional) - Filter to a specific transaction Private events return objects with an `event` property containing the decoded data: ``` collectedEvents.forEach((ev) => { console.log(ev.event.value0); // Access event fields via .event }); ``` ## Polling for events[​](#polling-for-events "Direct link to Polling for events") To continuously monitor for new events, poll at regular intervals while tracking the last processed block: poll\_for\_events ``` // Poll for new events at regular intervals let lastProcessedBlock = await node.getBlockNumber(); async function pollForTransferEvents() { const currentBlock = await node.getBlockNumber(); if (currentBlock > lastProcessedBlock) { const { events } = await getPublicEvents<Transfer>( node, TokenContract.events.Transfer, { contractAddress: token.address, fromBlock: BlockNumber(lastProcessedBlock + 1), toBlock: BlockNumber(currentBlock + 1), // toBlock is exclusive }, ); for (const { event, metadata } of events) { // Process each transfer event console.log( `Transfer: ${event.amount} from ${event.from} to ${event.to}`, ); console.log( ` in block ${metadata.l2BlockNumber}, tx ${metadata.txHash}`, ); } lastProcessedBlock = currentBlock; } } // Example: poll once (in production, use setInterval) await pollForTransferEvents(); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L297-L331](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L297-L331) For private events, use the same pattern with `wallet.getPrivateEvents()` and update the `fromBlock` in your filter accordingly. ## Next steps[​](#next-steps "Direct link to Next steps") * [Send transactions](/developers/testnet/docs/aztec-js/how_to_send_transaction.md) to modify contract state * Learn about [call types](/developers/testnet/docs/foundational-topics/call_types.md) and when to use simulation vs transactions * Explore [testing patterns](/developers/testnet/docs/aztec-js/how_to_test.md) that use simulation --- # Sending Transactions This guide shows you how to send transactions to smart contracts on Aztec. ## Overview[​](#overview "Direct link to Overview") Transactions on Aztec execute contract functions that modify state. Unlike simple reads, transactions go through private execution on your device, proving, and then submission to the network for inclusion in a block. You can send single transactions, batch multiple calls atomically, and query transaction status after submission. <!-- --> ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * [Connected to a network](how_to_connect_to_local_network) with an <!-- --> `EmbeddedWallet` instance and funded accounts <!-- --> * Deployed contract with its address and ABI (see [How to Deploy](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md)) * Understanding of [contract interactions](/developers/testnet/docs/aztec-nr/framework-description/calling_contracts.md) ## Send a transaction[​](#send-a-transaction "Direct link to Send a transaction") After connecting to a contract: connect\_to\_contract ``` // wallet is from the connection guide; token is the contract deployed in the deploy guide const contract = await Contract.at( token.address, TokenContract.artifact, wallet, ); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L333-L340](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L333-L340) Call a function and wait for it to be mined: basic\_send\_transaction ``` // contract is from the step above; aliceAddress is from the connection guide const { receipt: sendReceipt } = await contract.methods .transfer_in_public(aliceAddress, bobAddress, 100n, 0n) .send({ from: aliceAddress }); console.log(`Transaction mined in block ${sendReceipt.blockNumber}`); console.log(`Transaction fee: ${sendReceipt.transactionFee}`); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L342-L349](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L342-L349) The `from` field specifies which account sends the transaction. If that account has Fee Juice, it pays for the transaction automatically. For other fee payment options, see [paying fees](/developers/testnet/docs/aztec-js/how_to_pay_fees.md). ### What happens behind the scenes[​](#what-happens-behind-the-scenes "Direct link to What happens behind the scenes") When using `EmbeddedWallet`, calling `send()` triggers a **simulation** step before the transaction is actually sent. This simulation: 1. **Estimates gas limits** based on actual execution, with a configurable padding (default 10%) to avoid reverts. If you provide explicit gas limits via `fee.gasSettings`, they take precedence. 2. **Generates private authwits automatically**. If the contract you're calling requires a private [authentication witness](/developers/testnet/docs/aztec-js/how_to_use_authwit.md) (e.g., a token transfer on behalf of the sender), the wallet detects this during simulation and creates the authwit on the fly — no manual setup needed. 3. **Delays the first receipt poll.** After the transaction is sent, `.wait()` holds off one poll interval before its first `getTxReceipt` call, since the transaction cannot have been mined yet. Environments where receipts are available immediately (for example automine) can pass `initialDelay: 0` to `.wait()`. This means a simple `.send()` is all most apps need. You can adjust the gas padding if desired: set\_gas\_padding ``` wallet.setEstimatedGasPadding(0.2); // 20% padding instead of the default 10% ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L351-L353](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L351-L353) note Public authwits still need to be set explicitly before the transaction, as they require a separate onchain transaction. See [Using Authentication Witnesses](/developers/testnet/docs/aztec-js/how_to_use_authwit.md) for details. ### Send without waiting[​](#send-without-waiting "Direct link to Send without waiting") Use the `NO_WAIT` option to get the transaction hash immediately without waiting for inclusion: no\_wait\_transaction ``` // Use NO_WAIT for regular transactions too const { txHash: transferTxHash } = await token.methods .transfer(bobAddress, 100n) .send({ from: aliceAddress, wait: NO_WAIT }); console.log(`Transaction sent: ${transferTxHash.toString()}`); // Wait for inclusion later using the node const transferReceipt = await waitForTx(node, transferTxHash); console.log(`Transaction mined in block ${transferReceipt.blockNumber}`); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L167-L178](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L167-L178) ## Send batch transactions[​](#send-batch-transactions "Direct link to Send batch transactions") Execute multiple calls atomically using `BatchCall`: batch\_call ``` // Execute multiple calls atomically using BatchCall const batch = new BatchCall(wallet, [ token.methods.mint_to_public(aliceAddress, 500n), token.methods.transfer(bobAddress, 200n), ]); const { receipt: batchReceipt } = await batch.send({ from: aliceAddress }); console.log(`Batch executed in block ${batchReceipt.blockNumber}`); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L180-L189](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L180-L189) warning All calls in a batch must succeed or the entire batch reverts. Use batch transactions when you need atomic execution of multiple operations. ## Query transaction status[​](#query-transaction-status "Direct link to Query transaction status") After sending a transaction without waiting, you can query its receipt using the node: query\_tx\_status ``` // Query transaction status after sending without waiting const { txHash: statusTxHash } = await token.methods .transfer(bobAddress, 10n) .send({ from: aliceAddress, wait: NO_WAIT }); // Check status using the node const txReceipt = await node.getTxReceipt(statusTxHash); console.log(`Status: ${txReceipt.status}`); console.log(`Block number: ${txReceipt.blockNumber}`); console.log(`Transaction fee: ${txReceipt.transactionFee}`); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L212-L224](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L212-L224) `getTxReceipt` always resolves to one of three lifecycle variants of the `TxReceipt` union, depending on where the transaction is in its lifecycle: * `PendingTxReceipt` - still in the mempool. Exposes `status` (`pending`) and, when requested, the pending `tx`. * `DroppedTxReceipt` - dropped by the node. Exposes `status` (`dropped`) and an optional `error` message. * `MinedTxReceipt` - included in a block. Exposes `status` (`proposed`, `checkpointed`, `proven`, or `finalized`), `blockNumber`, `blockHash`, `txIndexInBlock`, `transactionFee`, and the execution result. The `status`, `blockNumber`, and `transactionFee` fields are readable on the bare union, but block and fee details are only populated once the transaction is mined. Use the `isMined()`, `isPending()`, and `isDropped()` type guards to narrow to a specific variant before reading its fields: ``` const receipt = await node.getTxReceipt(txHash); if (receipt.isMined()) { console.log(`Mined in block ${receipt.blockNumber}, fee ${receipt.transactionFee}`); } ``` You can pass a second `options` argument to attach extra data to the receipt: * `includeTxEffect` - attaches the full `TxEffect` (note hashes, nullifiers, logs, and messages) to a mined receipt, available as `receipt.txEffect`. * `includePendingTx` - attaches the pending `Tx` to a pending receipt, available as `receipt.tx`. * `includeProof` - keeps the proof on that attached pending tx (only meaningful together with `includePendingTx`; the proof is stripped by default to avoid shipping large payloads over RPC). For example, to read a mined transaction's effects, request them with `includeTxEffect` and read `receipt.txEffect` after narrowing with `isMined()`: ``` const receipt = await node.getTxReceipt(txHash, { includeTxEffect: true }); if (receipt.isMined() && receipt.txEffect) { console.log(`Nullifiers: ${receipt.txEffect.nullifiers.length}`); } ``` ## Next steps[​](#next-steps "Direct link to Next steps") * Learn to [read contract data](/developers/testnet/docs/aztec-js/how_to_read_data.md) including simulating functions before sending * Understand [authentication witnesses](/developers/testnet/docs/aztec-js/how_to_use_authwit.md) for delegated transactions * Configure [gas and fees](/developers/testnet/docs/aztec-js/how_to_pay_fees.md) for transaction costs * Set up [transaction testing](/developers/testnet/docs/aztec-js/how_to_test.md) in your development workflow --- # Simulate without signing prompts You want to call `.simulate()` from an app and not have the user's wallet pop up a signing prompt. This page covers the symptoms that lead to that prompt, why the obvious workarounds do not work, and the right fix. For the conceptual model of what kernelless simulation is, see [Kernelless simulations](/developers/testnet/docs/foundational-topics/pxe/kernelless_simulations.md). ## Symptoms[​](#symptoms "Direct link to Symptoms") You are probably here because of one of these: * The wallet prompts the user for a signature on every `.simulate()` call, including reads of view-style functions. * `.simulate()` fails with one of: <!-- --> * `Account "0x0000…0000" does not exist on this wallet.` (from `EmbeddedWallet`) * `Account not found in wallet for address: 0x0000…0000` (from other wallets built on `BaseWallet`) * `Circuit execution failed: min_revertible_side_effect_counter must not be 0 for tail_to_public` (from a custom wallet that does not intercept the zero address, where the call reaches the kernel) All three are the same root cause: passing `from: AztecAddress.ZERO`. * A custom fee payment method breaks during simulation because `from` is `AztecAddress.ZERO`. * Simulations take long enough that you want to skip the kernel circuits entirely. ## The wrong fix[​](#the-wrong-fix "Direct link to The wrong fix") Do not pass `from: AztecAddress.ZERO`. That value was the old way to express "no account context," and it is no longer a supported input for `.simulate()`. The replacement is `NO_FROM` (from `@aztec-labs/aztec.js/account`), which tells the wallet to execute the payload through the default entrypoint with no account contract mediation. `NO_FROM` is still only appropriate for calls that genuinely have no sender; use a real account address for everything else. ## The right fix[​](#the-right-fix "Direct link to The right fix") A simulation uses a **stub account contract override**: the wallet provides a `SimulationOverrides` payload whose `contracts` map swaps the caller's account contract for a stub whose `is_valid` always returns true, and the PXE applies that override during the kernelless simulation. With the stub in place, authwit validity checks pass without a signature, and the wallet collects any `CallAuthorizationRequest` offchain effects emitted during the run to turn them into real authentication witnesses for the eventual `.send()`. `EmbeddedWallet` installs this override automatically on every `.simulate()` call, so most apps do not need to construct overrides themselves. The two ways to wire this up below correspond to "use the default" and "implement it in your own wallet." ### Calling .simulate() from an app[​](#calling-simulate-from-an-app "Direct link to Calling .simulate() from an app") For a normal `.simulate()` you do not need to pass overrides yourself. The default simulation path is already kernelless, and wallets such as `EmbeddedWallet` install the stub-account override internally for you. Three things to remember: * Pass a real account address as `from`, or `NO_FROM` if the call genuinely has no sender. Do not use `AztecAddress.ZERO`. * For simple reads, you can omit the `fee` block. * For a transaction whose real fee path uses a fee payment contract (FPC) with private side effects (the FPC emits notes during fee payment), include that FPC in the simulation's fee options so gas estimation accounts for the FPC's side effects. Kernelless still applies; the gas number stays accurate. * If you have a stale call site that uses `from: AztecAddress.ZERO` plus a no-op fee payment method as a workaround, replace it with a real `from` (or `NO_FROM`) and drop the no-op fee contract. simulate-view-without-signing ``` // Reading a private view functio
프로젝트로 돌아가기