Aztec 백서

Aztec

원문

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

esign, routing fee payments through private notes rather than public function calls. note The SDK includes `PrivateFeePaymentMethod` and `PublicFeePaymentMethod` classes for the built-in reference FPC, but these are **deprecated** and do not work on mainnet alpha. For custom-token fee payment, use a third-party FPC with its own SDK (see [below](#third-party-fpcs-on-testnet-and-mainnet)). ### Sponsored FPC[​](#sponsored-fpc "Direct link to Sponsored FPC") The Sponsored FPC pays fees unconditionally, enabling free transactions. It is available on testnet, devnet, and local network. You can derive the Sponsored FPC address from its deployment parameters, register it with your wallet, and use it to pay for transactions: deploy\_sponsored\_fpc\_contract ``` // Set up the Sponsored FPC (see fees guide for full setup) const sponsoredFPCInstance = await getContractInstanceFromInstantiationParams( SponsoredFPCContract.artifact, { salt: new Fr(0) }, ); await wallet.registerContract( sponsoredFPCInstance, SponsoredFPCContract.artifact, ); const sponsoredPaymentMethod = new SponsoredFeePaymentMethod( sponsoredFPCInstance.address, ); // wallet is from the connection guide; sponsoredPaymentMethod is from the fees guide const { contract: sponsoredContract } = await TokenContract.deploy( wallet, aliceAddress, "SponsoredToken", "SPT", 18, ).send({ from: aliceAddress, fee: { paymentMethod: sponsoredPaymentMethod } }); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L50-L72](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L50-L72) Here's a simpler example from the test suite: sponsored\_fpc\_simple ``` const bananasToSendToBob = 10n; const { receipt: tx } = await bananaCoin.methods .transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0) .send({ from: aliceAddress, fee: { gasSettings, paymentMethod: new SponsoredFeePaymentMethod(sponsoredFPC.address), }, }); ``` > [Source code: yarn-project/end-to-end/src/single-node/fees/private\_payments.parallel.test.ts#L422-L433](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/yarn-project/end-to-end/src/single-node/fees/private_payments.parallel.test.ts#L422-L433) ### Private fee payment[​](#private-fee-payment "Direct link to Private fee payment") For transactions where the fee payment itself should be private, you can use a fully private FPC, one that holds Fee Juice claimed from L1 as an internal private balance, works on every network, and never needs an onchain deployment. See [Pay Fees Privately](/developers/testnet/docs/aztec-js/how_to_use_private_fee_juice.md) for how this pattern works and a walkthrough using a community-built example. Shared salt for privacy When multiple apps derive the same private FPC address (using the same artifact and salt), every private fee payment joins a single, larger privacy set. See [recommended salt](/developers/testnet/docs/aztec-js/how_to_use_private_fee_juice.md#recommended-salt-0) for details. ### Third-party FPCs on testnet and mainnet[​](#third-party-fpcs-on-testnet-and-mainnet "Direct link to Third-party FPCs on testnet and mainnet") On networks where the Sponsored FPC is unavailable, third-party FPCs deployed by ecosystem teams let you pay fees in tokens other than Fee Juice. Each FPC provider typically offers an SDK or API that handles payment method construction on the client side. This may include quote fetching and authwit creation, though the exact flow depends on the FPC design. For background on how FPCs work at the protocol level, see [how FPCs work](/developers/testnet/docs/foundational-topics/fees.md#how-fpcs-work). #### Example: Nethermind Private Multi Asset FPC[​](#example-nethermind-private-multi-asset-fpc "Direct link to Example: Nethermind Private Multi Asset FPC") To illustrate how a third-party FPC integration works, the following walkthrough uses Nethermind's [Private Multi Asset FPC](https://github.com/NethermindEth/aztec-fpc) as a reference. This is one implementation, other FPCs may differ in design and API. This FPC is quote-based and operates privately: * A single deployment accepts many tokens. The asset is selected per quote rather than hard-coded at deploy time. * Fee payments are transferred as private notes, so fee activity is not visible onchain. * An operator-run attestation service signs per-user quotes binding the FPC address, accepted asset, amounts, expiry, and user. * A cold-start entrypoint allows a brand-new account to bridge tokens from L1, claim on L2, and pay the fee in a single transaction. Note that the cold-start path calls `Token::mint_to_private`, which enqueues a public call to update the token's total supply, so the minted amount is visible onchain even though the user's identity and balances remain private. Third-party software This FPC is developed and maintained by Nethermind, not by Aztec Labs. The SDK (`@nethermindeth/aztec-fpc-sdk`) may not yet be published to npm; check the [repository README](https://github.com/NethermindEth/aztec-fpc/blob/main/sdk/README.md) for current install instructions. Review the [protocol spec](https://github.com/NethermindEth/aztec-fpc/blob/main/docs/spec/protocol-spec.md) and evaluate independently before integrating. The SDK wraps the quote-and-pay flow into a single call. The snippet below shows the general shape of the integration (illustrative; verify against the current SDK API before using): ``` import { FpcClient } from "@nethermindeth/aztec-fpc-sdk"; // Point the client at the FPC's attestation service const fpcClient = new FpcClient({ fpcAddress, // the deployed FPC contract address operator, // operator's Aztec address node, // PXE or node connection attestationBaseUrl: "https://...", // attestation service URL from the FPC provider }); // Estimate gas, fetch a signed quote, and build the payment method const payment = await fpcClient.createPaymentMethod({ wallet, user: aliceAddress, // the account paying the fee tokenAddress, // the token you want to pay in estimatedGas, // gas limits derived from a prior simulation's gasUsed }); // Use it like any other payment method const tx = await myContract.methods.myMethod(args).send({ fee: payment.fee }); await tx.wait(); ``` For the cold-start flow, deployment addresses, and the full API, see the [`aztec-fpc` repository](https://github.com/NethermindEth/aztec-fpc). ## Bridge Fee Juice from L1[​](#bridge-fee-juice-from-l1 "Direct link to Bridge Fee Juice from L1") Fee Juice is non-transferable on L2, but you can bridge it from L1, claim it on L2, and use it. This involves a few components that are part of a running network's infrastructure: * An L1 fee juice contract * An L1 fee juice portal * An L2 fee juice portal * An L2 fee juice contract `aztec.js` provides helpers to simplify the process: bridge\_fee\_juice\_setup ``` import { createExtendedL1Client } from "@aztec-labs/ethereum/client"; import { L1FeeJuicePortalManager } from "@aztec-labs/aztec.js/ethereum"; import { createLogger } from "@aztec-labs/aztec.js/log"; // Create an L1 client (accepts a mnemonic or 0x-prefixed private key) const l1RpcUrl = process.env.ETHEREUM_HOST ?? "http://localhost:8545"; const l1Mnemonic = "test test test test test test test test test test test junk"; const l1Client = createExtendedL1Client([l1RpcUrl], l1Mnemonic); // Create a portal manager to interact with the L1 fee juice portal const logger = createLogger("docs:fee-juice-bridge"); const portalManager = await L1FeeJuicePortalManager.new(node, l1Client, logger); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L99-L113](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L99-L113) Under the hood, `L1FeeJuicePortalManager` gets the L1 addresses from the node `aztec_getNodeInfo` endpoint. It then exposes an easy method `bridgeTokensPublic` which mints fee juice on L1 and sends it to an L2 address via the L1 portal: bridge\_fee\_juice\_execute ``` // portalManager is from the L1FeeJuicePortalManager setup above // feeJuiceAccount.address is an Aztec address from createSchnorrAccount const claim = await portalManager.bridgeTokensPublic( feeJuiceAccount.address, // the L2 address 1000000000000000000000n, // the amount to send to the L1 portal true, // whether to mint or not (set to false if your L1 account already has fee juice!) ); console.log("Claim secret:", claim.claimSecret); console.log("Claim amount:", claim.claimAmount); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L115-L126](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L115-L126) After this transaction is minted on L1 and a few blocks pass, you can claim the message on L2 and use it directly to pay for fees: bridge\_fee\_juice\_claim ``` import { FeeJuicePaymentMethodWithClaim } from "@aztec-labs/aztec.js/fee"; // claim is from the bridgeTokensPublic step above // Create a payment method that claims the bridged Fee Juice and uses it to pay const bridgePaymentMethod = new FeeJuicePaymentMethodWithClaim( feeJuiceAccount.address, claim, ); // Use it to pay for any transaction; here we deploy the account in one step const deployMethodBridged = await feeJuiceAccount.getDeployMethod(); await deployMethodBridged.send({ from: NO_FROM, fee: { paymentMethod: bridgePaymentMethod }, }); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L166-L182](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L166-L182) ## Configure gas settings[​](#configure-gas-settings "Direct link to Configure gas settings") ### Understanding gas dimensions[​](#understanding-gas-dimensions "Direct link to Understanding gas dimensions") Gas settings specify limits and fees for both DA and L2 dimensions: * **gasLimits**: Maximum mana the transaction may consume in total, across all phases including teardown * **teardownGasLimits**: Portion of `gasLimits` reserved for the teardown phase (used by FPCs for refunds) * **maxFeesPerGas**: Maximum price you're willing to pay per mana unit * **maxPriorityFeesPerGas**: Priority fee for faster inclusion Teardown gas is not added on top of `gasLimits`: it is a reservation carved out of the total, so the mana available to the rest of the transaction is `gasLimits - teardownGasLimits`. A transaction with a teardown call is billed the full `teardownGasLimits`, regardless of how much teardown actually consumes. The fee limit is calculated as `gasLimits × maxFeesPerGas` for each dimension. ### Set custom gas limits[​](#set-custom-gas-limits "Direct link to Set custom gas limits") Set custom gas limits by importing from `stdlib`: custom\_gas\_settings ``` // Query current network fees to set realistic limits const networkFees = await node.getCurrentMinFees(); // Declare at most what the network admits per tx; these limits vary by network geometry, // so read them from the node rather than hardcoding values that may exceed a given network's maximum. const { txsLimits } = await node.getNodeInfo(); const gasLimits = Gas.from(txsLimits.gas); const gasSettings = GasSettings.from({ gasLimits, // Teardown must be strictly less than the total limits so app logic has gas to run. teardownGasLimits: { daGas: Math.floor(gasLimits.daGas / 2), l2Gas: Math.floor(gasLimits.l2Gas / 8), }, maxFeesPerGas: { feePerDaGas: networkFees.feePerDaGas * 2n, feePerL2Gas: networkFees.feePerL2Gas * 2n, }, maxPriorityFeesPerGas: { feePerDaGas: 0n, feePerL2Gas: 0n }, }); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L416-L436](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L416-L436) Then pass the settings when sending: send\_with\_gas\_settings ``` const { receipt: gsReceipt } = await token.methods .mint_to_public(aliceAddress, 1n) .send({ from: aliceAddress, fee: { gasSettings }, }); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L438-L445](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L438-L445) Note that `gasLimits` and `teardownGasLimits` use `daGas`/`l2Gas` field names, while `maxFeesPerGas` and `maxPriorityFeesPerGas` use `feePerDaGas`/`feePerL2Gas`. ### Use automatic gas estimation[​](#use-automatic-gas-estimation "Direct link to Use automatic gas estimation") note When using `EmbeddedWallet`, gas estimation happens automatically on every `send()`; you don't need to declare gas limits at all. Reading `gasUsed` from a `simulate({ includeMetadata: true })` result is useful when you want to preview costs before sending, or to set explicit limits with a custom wallet implementation. auto\_gas\_estimation ``` // Read the gas a transaction would consume before sending, and pad it yourself. const { gasUsed: autoGasUsed } = await token.methods .mint_to_public(aliceAddress, 1n) .simulate({ from: aliceAddress, includeMetadata: true }); const autoEstimate = autoGasUsed!.totalGas.mul(1.2); // 20% padding console.log("Auto-estimated L2 gas:", autoEstimate.l2Gas); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L474-L481](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L474-L481) tip Gas estimation runs a simulation first to determine actual gas usage, then adds padding for safety. This works with all payment methods, including FPCs. ## Next steps[​](#next-steps "Direct link to Next steps") * Learn about [fee concepts](/developers/testnet/docs/foundational-topics/fees.md) in detail * Explore [authentication witnesses](/developers/testnet/docs/aztec-js/how_to_use_authwit.md) for delegated payments * See [testing guide](/developers/testnet/docs/aztec-js/how_to_test.md) for fee testing strategies --- # Reading Contract Data This guide shows you how to read data from Aztec contracts in TypeScript, including simulating function calls, reading raw logs, and retrieving typed events. <!-- --> ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * [Connected to a network](how_to_connect_to_local_network) with an <!-- --> `EmbeddedWallet` instance and funded accounts <!-- --> * A deployed contract instance (see [How to Deploy a Contract](/developers/testnet/docs/aztec-js/how_to_deploy_contract.md)) ## Simulating functions[​](#simulating-functions "Direct link to Simulating functions") The `simulate` method executes a contract function locally and returns its result. It works with private, public, and utility functions. No transaction is created and no gas is spent. simulate\_function ``` const { result: balance } = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress }); console.log(`Alice's token balance: ${balance}`); ``` > [Source code: docs/examples/ts/aztecjs\_connection/index.ts#L151-L157](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_connection/index.ts#L151-L157) The `from` option specifies which account context to use for the simulation. This is required for all simulations. For private functions, it determines which account's private state is accessed. For public functions, it sets the `msg_sender` context. ### Handling return values[​](#handling-return-values "Direct link to Handling return values") For functions returning multiple values, destructure the result: ``` // contract and callerAddress are from the example above const { result: [value1, value2] } = await contract.methods .get_multiple_values() .simulate({ from: callerAddress }); ``` ### Including metadata[​](#including-metadata "Direct link to Including metadata") Set `includeMetadata: true` to get additional information about the simulation: simulate\_with\_metadata ``` const metaResult = await token.methods .balance_of_public(aliceAddress) .simulate({ from: aliceAddress, includeMetadata: true }); console.log("Balance:", metaResult.result); // `gasUsed` is the raw gas the simulation consumed; derive your own limits from it (see below). console.log("L2 gas used:", metaResult.gasUsed!.totalGas.l2Gas); console.log("DA gas used:", metaResult.gasUsed!.totalGas.daGas); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L355-L363](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L355-L363) The result includes `result` (the function return value), `stats` (execution statistics), `offchainEffects`, and `gasUsed` (the raw gas the simulation consumed, with `totalGas` and `teardownGas`). Derive your own gas limits from `gasUsed` if you want to declare them explicitly; otherwise the wallet fills in the network's per-tx admission limits. ### Private function considerations[​](#private-function-considerations "Direct link to Private function considerations") When simulating private functions, the caller must have access to any private state being read. The PXE only has visibility into notes belonging to registered accounts. simulate\_private\_access ``` // This works if aliceAddress owns the notes const { result: privateBalance } = await token.methods .balance_of_private(aliceAddress) .simulate({ from: aliceAddress }); ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L492-L497](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L492-L497) If the caller doesn't have access to another address's notes, the simulation will fail with an error. tip If `.simulate()` is prompting the user to sign every call, or failing with `min_revertible_side_effect_counter must not be 0` when you pass `from: AztecAddress.ZERO`, see [Simulate without signing prompts](/developers/testnet/docs/aztec-js/how_to_simulate_without_signing.md). warning Simulation runs locally without generating proofs. No correctness guarantees are provided on the result. See [Call Types](/developers/testnet/docs/foundational-topics/call_types.md#simulate) for more details. ## Reading logs vs events[​](#reading-logs-vs-events "Direct link to Reading logs vs events") Contracts emit data in two forms you can read: | Aspect | Logs | Events | | ------------------ | --------------------------------- | -------------------------------------------------- | | **What** | Raw field arrays (untyped) | Decoded domain objects with type info | | **Storage** | Archiver (node-level) | PXE (client-level) for private events | | **API** | `aztecNode.getBlock()` tx effects | `wallet.getPrivateEvents()` or `getPublicEvents()` | | **Type awareness** | None - raw `Fr[]` data | Requires ABI metadata to decode | **Logs** are the low-level transport layer, while **events** are the semantic application layer decoded using ABI metadata from your contract. ## Reading raw public logs[​](#reading-raw-public-logs "Direct link to Reading raw public logs") Raw public logs are carried on each block's transaction effects. Fetch a block with `includeTransactions: true` and read `body.txEffects[*].publicLogs`: read\_public\_logs ``` // Raw public logs are carried on each block's transaction effects. const latestBlockNumber = await node.getBlockNumber(); const block = await node.getBlock(latestBlockNumber, { includeTransactions: true, }); const publicLogs = block?.body.txEffects.flatMap((tx) => tx.publicLogs) ?? []; if (publicLogs.length > 0) { const rawFields = publicLogs[0].getEmittedFields(); // Fr[] console.log("Raw log fields:", rawFields.length); } ``` > [Source code: docs/examples/ts/aztecjs\_advanced/index.ts#L365-L376](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/ts/aztecjs_advanced/index.ts#L365-L376) Y
프로젝트로 돌아가기