Starknet 백서

Starknet

원문

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

itional rewards * **Long-term holding** - Encourage users to hold tokens by offering staking rewards ## Best Practices 1. **Always check pool membership** before calling `addToPool` 2. **Monitor rewards regularly** and show users their earnings 3. **Help users understand exit windows** before initiating exit 4. **Use transaction builder** to batch staking with other operations 5. **Override staking contract only if needed** (custom deployments, forks, or private environments) 6. **Display earnings clearly** - Show users their staked amount, earned rewards, and total position value ## Troubleshooting ### "No staking contract configured for chain ..." The SDK has no staking contract for the current chain, or you set a custom `staking.contract` that doesn't match. Remove the override to use the built-in preset, or set the correct contract for your network. ### Pool Not Found Ensure you're using the correct pool contract address. Use `getStakerPools()` to discover available pools. ## Next Steps * Learn about [Transaction Builder](/build/starkzap/transactions#transaction-builder) for batching operations * Explore [LST Staking](/build/starkzap/lst-staking) for liquid staking flows with `wallet.lstStaking(asset)` * Explore [ERC20 Token Operations](/build/starkzap/erc20) * Check the [API Reference](/build/starkzap/api-reference) for detailed method signatures # Swaps Source: https://docs.starknet.io/build/starkzap/swap Exchange one token for another using AVNU or Ekubo swap providers—get quotes, set slippage, and execute swaps ## Overview Starkzap lets users swap one token for another through pluggable **swap providers**. The SDK supports **[AVNU](https://app.avnu.fi/en)** (DEX aggregator) and **[Ekubo](https://ekubo.org/starknet/swap)** (concentrated liquidity AMM). You get a quote, optionally set slippage tolerance, and execute the swap in one call. **What users can do with swaps:** * 📊 **Get quotes** - See how much they will receive before swapping (amount out, price impact) * 🔄 **Execute swaps** - Exchange tokens in a single transaction with optional slippage protection * 🏪 **Choose providers** - Use [AVNU](https://app.avnu.fi/en) for aggregated routes or [Ekubo](https://ekubo.org/starknet/swap) for concentrated liquidity * 📦 **Batch with other actions** - Run a swap then use the transaction builder for follow-up operations For **recurring buys (Dollar-Cost Averaging)**, see [DCA](/build/starkzap/dollar-cost-average). <Info> The wallet fills `chainId` and `takerAddress` from the connected wallet when you call `getQuote()` or `swap()`. You only need to pass `tokenIn`, `tokenOut`, and `amountIn` (and optionally `slippageBps` or `provider`). </Info> ## Configuration ### Registering swap providers Register one or more swap providers when connecting the wallet (or at runtime). If you register multiple providers, set a default so `getQuote()` and `swap()` work without specifying `provider` on each request. <Info> `AvnuSwapProvider` requires the optional peer dependency `@avnu/avnu-sdk` (`npm install @avnu/avnu-sdk`). It is loaded lazily on the first quote/swap, so the first call throws an install hint if the package is missing. `EkuboSwapProvider` needs no extra dependency. See [Installation](/build/starkzap/installation#peer-dependencies-by-feature). </Info> **At connect / onboard:** ```typescript theme={null} import { StarkZap, AvnuSwapProvider, EkuboSwapProvider, ArgentPreset } from "starkzap"; const sdk = new StarkZap({ network: "mainnet" }); const wallet = await sdk.connectWallet({ account: { signer, accountClass: ArgentPreset }, swapProviders: [ new AvnuSwapProvider(), new EkuboSwapProvider(), ], defaultSwapProviderId: "avnu", }); ``` **At runtime (e.g. after Cartridge onboard):** ```typescript theme={null} wallet.registerSwapProvider(new AvnuSwapProvider()); wallet.registerSwapProvider(new EkuboSwapProvider()); wallet.setDefaultSwapProvider("avnu"); ``` ### Token presets Use the SDK token presets for `tokenIn` and `tokenOut` so addresses and decimals match the chain: ```typescript theme={null} import { getPresets, mainnetTokens } from "starkzap"; const tokens = getPresets(wallet.getChainId()); const STRK = tokens.STRK ?? mainnetTokens.STRK; const USDC = tokens.USDC ?? mainnetTokens.USDC; ``` See [Bitcoin, Stablecoins, and Tokens](/build/starkzap/erc20#token-presets) for more on token presets. ## Getting a quote Call `wallet.getQuote()` with the swap input. The wallet uses the default swap provider unless you pass `provider`: ```typescript theme={null} import { Amount } from "starkzap"; const quote = await wallet.getQuote({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), }); console.log(quote.amountInBase); // input in base units console.log(quote.amountOutBase); // expected output in base units console.log(quote.priceImpactBps); // optional price impact (basis points) console.log(quote.provider); // e.g. "avnu" ``` **With slippage and a specific provider:** ```typescript theme={null} const quote = await wallet.getQuote({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), slippageBps: 50n, // 0.5% provider: "ekubo", }); ``` ### Quote shape ```typescript theme={null} interface SwapQuote { amountInBase: bigint; amountOutBase: bigint; routeCallCount?: number; priceImpactBps?: bigint | null; provider?: string; } ``` ## Executing a swap Use the same request shape as the quote. The wallet resolves the provider and builds the swap calls, then executes them. **Minimal swap:** ```typescript theme={null} const tx = await wallet.swap({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), }); await tx.wait(); ``` **With slippage:** ```typescript theme={null} const tx = await wallet.swap( { tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), slippageBps: 100n, // 1% }, { feeMode: { type: "paymaster" } } // optional execution options ); await tx.wait(); ``` ## Providers | Provider | Id | Description | | - | - | - | | **[AVNU](https://app.avnu.fi/en)** | `avnu` | DEX aggregator; finds best route across liquidity sources | | **[Ekubo](https://ekubo.org/starknet/swap)** | `ekubo` | Concentrated liquidity AMM; single-protocol routes | **List and switch providers:** ```typescript theme={null} const ids = wallet.listSwapProviders(); console.log(ids); // ["avnu", "ekubo"] // Use a specific provider for one request const quote = await wallet.getQuote({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), provider: "ekubo", }); ``` ## Batching with other operations Use the transaction builder's `.swap()` method to batch a swap with other operations in a single atomic transaction: ```typescript theme={null} const tx = await wallet .tx() .swap({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), }) .transfer(USDC, [{ to: recipient, amount: Amount.parse("50", USDC) }]) .send(); await tx.wait(); ``` You can also execute a swap standalone via `wallet.swap()`: ```typescript theme={null} const tx = await wallet.swap({ tokenIn: STRK, tokenOut: USDC, amountIn: Amount.parse("100", STRK), }); await tx.wait(); ``` For **Dollar-Cost Averaging (recurring buys)** with AVNU or Ekubo, see [DCA](/build/starkzap/dollar-cost-average). ## Best practices 1. **Always get a quote first** and show users the expected amount out and price impact before executing. 2. **Set slippage** (`slippageBps`) for volatile pairs or large sizes to avoid failed transactions. 3. **Use token presets** from `getPresets(chainId)` or `mainnetTokens` / `sepoliaTokens` so token addresses and decimals match the chain. 4. **Handle chain mismatch** — ensure the wallet's chain matches the swap provider's supported chains (AVNU and Ekubo support mainnet and Sepolia). ## Troubleshooting ### "No default swap provider configured" Register at least one swap provider and call `setDefaultSwapProvider(providerId)` (or pass `defaultSwapProviderId` when connecting). Alternatively, pass `provider: "avnu"` or `provider: "ekubo"` on every `getQuote()` / `swap()` call. ### "requires optional peer dependency "@avnu/avnu-sdk"" The AVNU provider is selected but `@avnu/avnu-sdk` is not installed. Run `npm install @avnu/avnu-sdk`, or use `EkuboSwapProvider` (no extra dependency) instead. ### Chain or provider mismatch Ensure the wallet is on a chain supported by the chosen provider (e.g. `SN_MAIN` or `SN_SEPOLIA`). If you see a chain mismatch error, align the SDK network config with the RPC/wallet chain. ### Swap returned no calls The provider could not build a route for the pair or amount. Try a different provider, a smaller amount, or another token pair. ## Next steps * [DCA](/build/starkzap/dollar-cost-average) — Recurring buys (Dollar-Cost Averaging) with AVNU or Ekubo * [Bitcoin, Stablecoins, and Tokens](/build/starkzap/erc20) — Token presets and amounts * [Transactions](/build/starkzap/transactions) — Execution options and fee modes * [Tx Builder](/build/starkzap/tx-builder) — Batching transfers and other operations * [API Reference](/build/starkzap/api-reference) — Full method signatures # Executing Transactions Source: https://docs.starknet.io/build/starkzap/transactions Send transactions, batch operations, simulate transactions, and handle fees ## Overview Transaction execution is the process of sending operations to the Starknet blockchain. Starkzap provides multiple ways to execute transactions, from simple contract calls to complex batched operations. **What is a transaction?** A transaction is a request to execute a function on a smart contract deployed on Starknet. Think of it like calling an API endpoint—you're invoking a function on a deployed contract that performs some action (like transferring tokens, updating state, or executing business logic). **Requirements:** * A smart contract must be deployed on Starknet before you can execute transactions against it * Your wallet account must be deployed (the SDK handles this automatically with `deploy: "if_needed"`) * Sufficient balance to pay for gas fees (unless using a paymaster for sponsored transactions) <Info> **Want to deploy your own smart contracts?** This guide focuses on executing transactions against existing contracts. If you need to create and deploy your own smart contracts, check out the [Starknet Quickstart Guide](https://docs.starknet.io/build/quickstart/overview) for comprehensive tutorials on smart contract development with Cairo. </Info> This guide covers all transaction execution patterns for interacting with deployed smart contracts. ## Direct Execution Use `wallet.execute()` for arbitrary contract calls: ```typescript theme={null} import type { Call } from "starknet"; const call: Call = { contractAddress: "0xCONTRACT_ADDRESS", entrypoint: "transfer", calldata: ["0xRECIPIENT", "1000000", "0"], }; const tx = await wallet.execute([call]); await tx.wait(); ``` ### Multiple Calls (Atomic Batching) Multiple calls execute atomically in a single transaction: ```typescript theme={null} const tx = await wallet.execute([approveCall, swapCall, transferCall]); await tx.wait(); ``` All calls succeed or fail together — no partial execution. ## Transaction Tracking Every `execute()`, `deploy()`, or `transfer()` call returns a `Tx` object: ```typescript theme={null} const tx = await wallet.execute(calls); // Transaction hash console.log(tx.hash); // "0x..." // Block explorer link console.log(tx.explorerUrl); // "https://voyager.online/tx/0x..." // Wait for confirmation (L2 acceptance) await tx.wait(); // Wait for L1 finality await tx.wait({ successStates: [TransactionFinalityStatus.ACCEPTED_ON_L1], }); // Get full receipt const receipt = await tx.receipt(); console.log(receipt.actual_fee); // Watch status changes in real-time const unsubscribe = tx.watch(({ finality, execution }) => { console.log(`Status: ${finality} (${execution})`); // "RECEIVED" → "ACCEPTED_ON_L2" → "ACCEPTED_ON_L1" }); // Stop watching early if needed unsubscribe(); ``` ## Paymaster Transactions (Sponsored / Gasless) If the SDK is configured with a paymaster, use `feeMode: { type: "paymaster" }`: ```typescript theme={null} // Per-transaction sponsorship const tx = await wallet.execute([call], { feeMode: { type: "paymaster" } }); // Or set as default when connecting const wallet = await sdk.connectWallet({ account: { signer }, feeMode: { type: "paymaster" }, }); // Now all transactions are sponsored by default const tx = await wallet.execute([call]); // sponsored automatically ``` <Info> The SDK works seamlessly with [AVNU Paymaster](https://docs.avnu.fi/docs/paymaster/index) for sponsored transactions. See the [AVNU Paymaster Integration](/build/starkzap/integrations/avnu-paymaster) guide for setup instructions. </Info> <Note> **Cartridge:** On **web** Controller and **native** session flows, matching calls can be paymastered per Cartridge's session / SNIP-9 rules after users approve **policies**. You typically do **not** configure AVNU for those paths. Arbitrary calls outside approved policies are not guaranteed to be sponsored. On React Native, sponsored execution is commonly tied to **`feeMode: { type: "paymaster" }`** on the session wallet. See [Cartridge Controller](/build/starkzap/integrations/cartridge-controller) and [React Native Integration](/build/starkzap/react-native). </Note> <Note> `feeMode: "sponsored"` is still supported as a deprecated alias for backward compatibility. </Note> ## Preflight Simulation Simulate transactions before sending to check for errors: ```typescript theme={null} const result = await wallet.preflight({ calls }); if (!result.ok) { console.error(result.reason); } else { const tx = await wallet.execute(calls); await tx.wait(); } ``` <Note> Always preflight non-trivial batches before submitting to catch errors early. </Note> ## Transaction Builder For batching multiple operations into a single atomic transaction, use the `TxBuilder`. This is especially useful for complex operations that need to execute together. <Info> **For detailed TxBuilder documentation**, see the [Tx Builder](/build/starkzap/tx-builder) guide which covers all builder methods, preflight simulation, fee estimation, and best practices. </Info> Quick example: ```typescript theme={null} const tx = await wallet .tx() .transfer(USDC, { to: alice, amount }) .stake(poolAddress, stakeAmount) .send(); await tx.wait(); ``` ## Fee Modes ### User Pays (Default) ```typescript theme={null} const tx = await wallet.execute(calls, { feeMode: "user_pays" }); ``` The user's account pays for transaction fees. ### Paymaster (Sponsored / Gasless) ```typescript theme={null} const tx = await wallet.execute(calls, { feeMode: { type: "paymaster" } }); ``` The paymaster path covers transaction fees (sponsored) or lets users pay with a supported gas token. ```typescript theme={null} import { fromAddress } from "starkzap"; const tx = await wallet.execute(calls, { feeMode: { type: "paymaster", gasToken: fromAddress("0x053c91253bc96bfed3be381a97265e250ed0a2e2cbf1a54898ad0d2f7982f78f"), }, }); ``` <Note> **Cartridge:** Policy-matching calls can be paymastered per Cartridge session rules; arbitrary calls are not guaranteed sponsored. You typically do not configure AVNU for Cartridge paths. See [Cartridge Controller](/build/starkzap/integrations/cartridge-controller) and [React Native Integration](/build/starkzap/react-native). </Note> ## Transaction Status Transactions go through several states: 1. **RECEIVED** - Transaction received by the sequencer 2. **ACCEPTED\_ON\_L2** - Transaction accepted on L2 (most common success state) 3. **ACCEPTED\_ON\_L1** - Transaction finalized on L1 ```typescript theme={null} // Wait for L2 acceptance (default) await tx.wait(); // Wait for L1 finality await tx.wait({ successStates: [TransactionFinalityStatus.ACCEPTED_ON_L1], }); ``` ## Error Handling Always handle transaction errors: ```typescript theme={null} try { const tx = await wallet.execute(calls); await tx.wait(); console.log("Transaction successful!"); } catch (error) { console.error("Transaction failed:", error); } ``` ## Best Practices 1. **Always preflight** non-trivial batches before submitting 2. **Use the transaction builder** for complex operations to save gas 3. **Handle errors gracefully** and provide user feedback 4. **Standardize fee behavior** (`user_pays` vs `paymaster`) per flow 5. **Wait for appropriate confirmation** based on your use case ## Next Steps * Learn about [ERC20 Token Operations](/build/starkzap/erc20) * Explore [Staking & Delegation](/build/starkzap/staking) * Check the [API Reference](/build/starkzap/api-reference) for detailed method signatures # Troubleshooting Source: https://docs.starknet.io/build/starkzap/troubleshooting Common issues and solutions when using Starkzap ## Common Issues ### "No staking contract configured for chain ..." **Problem:** The SDK has no staking contract for the current chain, or you set a custom `staking.contract` that doesn't match. **Solution:** Remove the custom override to use chain-aware defaults, or set the correct contract for your network: ```typescript theme={null} import { StarkZap } from "starkzap"; // Recommended: use built-in chain-aware staking preset const sdk = new StarkZap({ network: "mainnet" }); ``` ### Transaction Submits but Explorer URL Points to Wrong Explorer **Problem:** Transactions execute successfully but `tx.explorerUrl` points to the default explorer (Voyager) instead of your preferred one. **Solution:** Configure the `explorer` in your SDK config to use your preferred provider: ```typescript theme={null} const sdk = new StarkZap({ network: "mainnet", explorer: { provider: "starkscan" }, // or "voyager" (default) }); ``` ### React Native Random Values/Text Encoding Issues **Problem:** Errors related to random value generation or text encoding in React Native. **Solution:** Use the React Native setup guide and Metro wrapper, which handles required polyfills and resolver compatibility. 1. Follow [React Native Integration](/build/starkzap/react-native) 2. Ensure your `metro.config.js` is wrapped with `withStarkzap(...)` 3. Clear Metro cache after dependency changes (`npx expo start -c`) If you still need manual installation checks, make sure these packages are present: ```bash theme={null} npm install react-native-get-random-values fast-text-encoding buffer @ethersproject/shims ``` If not using `withStarkzap`, import polyfills in your entrypoint (e.g. `index.js` or `App.tsx`): ```typescript theme={null} import "react-native-get-random-values"; import "fast-text-encoding"; import "@ethersproject/shims"; ``` ### Account Not Deployed Error **Problem:** Getting errors about account not being deployed when trying to execute transactions. **Solution:** Ensure the account is deployed before executing transactions: ```typescript theme={null} // Option 1: Use ensureReady await wallet.ensureReady({ deploy: "if_needed" }); // Option 2: Deploy explicitly if (!(await wallet.isDeployed())) { await wallet.deploy(); } // Option 3: Use onboard API which handles this automatically const onboard = await sdk.onboard({ strategy: OnboardStrategy.Signer, account: { signer }, deploy: "if_needed", }); ``` ### Privy Signer Backend Not Responding **Problem:** Privy signer fails with network errors or timeouts. **Solution:** 1. Verify your backend endpoint is accessible 2. Ensure the endpoint accepts POST requests with `{ walletId, hash }` 3. Check that the endpoint returns `{ signature }` in the correct format 4. Verify CORS settings if calling from a browser Example backend endpoint: ```typescript theme={null} // Express.js example app.post("/api/wallet/sign", async (req, res) => { const { walletId, hash } = req.body; const signature = await privyClient.wallets().rawSign(walletId, { params: { hash
프로젝트로 돌아가기