Starknet 백서

Starknet

원문

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

}, }); res.json({ signature }); }); ``` ### Cartridge Connection Fails **Problem:** Cartridge wallet connection doesn't work or popup doesn't appear. **Solution:** 1. Ensure `@cartridge/controller` is installed 2. Check that you're calling `connectCartridge` in a browser environment 3. Verify network configuration matches Cartridge's supported networks 4. Check browser console for Cartridge-specific errors ### Bridge Token Loading Fails **Problem:** `sdk.getBridgingTokens()` throws an error or returns no tokens. **Solution:** 1. Verify the SDK chain config is correct (`SN_MAIN` vs `SN_SEPOLIA`) and matches your intended environment 2. Confirm network access to the token API endpoint used by the SDK 3. Install required optional deps for the chains you use: * Ethereum routes: `ethers` * Solana routes: `@solana/web3.js` (and Hyperlane packages for Solana bridge operations) ```bash theme={null} npm install ethers @solana/web3.js @hyperlane-xyz/sdk @hyperlane-xyz/registry @hyperlane-xyz/utils ``` ### OFT Bridge Fails with LayerZero API Key Error **Problem:** You see an error like: `OFT bridging requires a LayerZero API key. Set "bridging.layerZeroApiKey"...` **Solution:** 1. Set `bridging.layerZeroApiKey` in `new StarkZap({ ... })` 2. Use a mainnet route for OFT/OFT-migrated bridge flows ```typescript theme={null} const sdk = new StarkZap({ network: "mainnet", bridging: { layerZeroApiKey: "YOUR_LAYERZERO_API_KEY", }, }); ``` ### Bridge Deposit Fails with Chain Mismatch **Problem:** Deposit fails with errors indicating token chain and external wallet chain do not match. **Solution:** 1. Ensure the selected `BridgeToken.chain` matches the connected external wallet type 2. Ensure external wallet network and Starknet network pairing is valid (mainnet with mainnet, testnet with testnet) 3. Recreate connected external wallets with `ConnectedEthereumWallet.from(...)` / `ConnectedSolanaWallet.from(...)` after network switch ### Amount Arithmetic Errors **Problem:** Getting errors when performing arithmetic on amounts. **Solution:** Ensure amounts have compatible decimals and symbols: ```typescript theme={null} // ❌ This will throw const a = Amount.parse("10", STRK); // 18 decimals const b = Amount.parse("5", USDC); // 6 decimals const c = a.add(b); // Error: incompatible amounts // ✅ Use amounts with same token const a = Amount.parse("10", STRK); const b = Amount.parse("5", STRK); const c = a.add(b); // Works! ``` ### Transaction Fails in Preflight but Not in Execution **Problem:** Preflight simulation shows errors, but transaction would succeed. **Solution:** Preflight uses the current state, which may differ from execution time. This is normal - preflight is a best-effort check. Always handle transaction failures gracefully: ```typescript theme={null} try { const tx = await wallet.execute(calls); await tx.wait(); } catch (error) { // Handle error appropriately console.error("Transaction failed:", error); } ``` ### TypeScript Type Errors **Problem:** TypeScript complains about type mismatches. **Solution:** Ensure you're using the correct types: ```typescript theme={null} import { Address, Amount, ChainId } from "starkzap"; // Use fromAddress for addresses const addr: Address = fromAddress("0x..."); // Use Amount.parse for amounts const amount: Amount = Amount.parse("10", STRK); // Use ChainId constants const chainId = ChainId.MAINNET; ``` ### Network Configuration Issues **Problem:** SDK can't connect to the network or wrong network is used. **Solution:** Verify your network configuration: ```typescript theme={null} // Check current chain ID const chainId = wallet.getChainId(); console.log(chainId.toLiteral()); // "SN_MAIN" or "SN_SEPOLIA" // Verify RPC URL const provider = sdk.getProvider(); const chainIdFromProvider = await provider.getChainId(); ``` ### Fee Estimation Fails **Problem:** `estimateFee()` throws errors. **Solution:** 1. Ensure the account is deployed 2. Verify the calls are valid 3. Check that you have sufficient balance for fees 4. Try using `preflight()` first to catch call errors ## Getting More Help If you're still experiencing issues: 1. Check the [API Reference](/build/starkzap/api-reference) for detailed method signatures 2. Review the [Examples](/build/starkzap/examples) for working code samples 3. Ask for help in the [Starknet Discord community](https://discord.gg/starknet-community) 4. Browse the [Starknet community forum](https://community.starknet.io/) ## Reporting Issues If you find a bug or have a feature request: 1. Check if the issue is already reported 2. Create a detailed issue report with: * SDK version * Runtime environment (Node.js, browser, React Native) * Steps to reproduce * Expected vs actual behavior * Error messages and stack traces # Troves Source: https://docs.starknet.io/build/starkzap/troves Discover Troves strategies, inspect positions, and deposit or withdraw through Starkzap ## Overview Starkzap supports [Troves](https://app.troves.fi) strategies through `wallet.troves()`. Troves combines off-chain strategy discovery with on-chain execution: * 📊 **Discover strategies** - Fetch the currently available Troves strategies and protocol-level stats * 🧾 **Inspect positions** - Read the wallet's share balance and the current underlying asset amounts for a strategy * 💸 **Deposit** - Build and execute the Troves deposit flow from typed `Amount` inputs * 📤 **Withdraw** - Build and execute the Troves withdraw flow with the same typed API * 📦 **Batch with other actions** - Compose Troves deposits or withdrawals inside `wallet.tx()` <Info> Troves uses the Troves HTTP API to discover strategies and build the required calls, then executes those calls through the connected Starknet wallet. </Info> ## Configuration Troves is available from the wallet: ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet" }); const wallet = await sdk.connectWallet({ account: { signer, accountClass }, }); const troves = wallet.troves(); ``` By default, Troves is **mainnet-only**. If the wallet is not on Starknet Mainnet, `wallet.troves()` throws unless you explicitly override the API base: ```typescript theme={null} const troves = wallet.troves({ apiBase: "https://your-custom-troves-backend.example.com", timeoutMs: 15000, }); ``` Use `apiBase` only when you intentionally want to point the SDK at a custom Troves-compatible backend. ## Discovering strategies Fetch the current strategy catalog: ```typescript theme={null} const { strategies, lastUpdated } = await wallet.troves().getStrategies(); console.log("Updated at:", lastUpdated); for (const strategy of strategies) { console.log(strategy.id, strategy.name); console.log("APY:", strategy.apy); console.log("TVL (USD):", strategy.tvlUsd); console.log( "Deposit tokens:", strategy.depositTokens.map((token) => token.symbol).join(", ") ); } ``` You can force a fresh fetch instead of using the default cached endpoint: ```typescript theme={null} const data = await wallet.troves().getStrategies({ noCache: true }); ``` ### Strategy shape ```typescript theme={null} interface TrovesStrategyAPIResult { id: string; name: string; apy: number | string; apySplit: { baseApy: number; rewardsApy: number; }; depositTokens: TrovesDepositToken[]; leverage: number; contracts: TrovesContract[]; tvlUsd: number; status: { number: number; value: string }; liveStatus?: string; isAudited: boolean; isRetired: boolean; assets: string[]; protocols: string[]; } ``` ### Protocol-level stats ```typescript theme={null} const stats = await wallet.troves().getStats(); console.log(stats.tvl); console.log(stats.lastUpdated); ``` ## Querying a position Read the wallet's position in a strategy by id: ```typescript theme={null} const position = await wallet.troves().getPosition("ekubo_cl_strketh"); if (position) { console.log("Shares:", position.shares); position.amounts.forEach((amount) => { console.log(amount.toFormatted()); }); } ``` `getPosition()` returns `null` when the wallet holds no shares, or when the strategy does not expose a readable vault contract for this flow. ### Position shape ```typescript theme={null} interface TrovesPosition { strategyId: string; vaultAddress: Address; shares: bigint; amounts: Amount[]; } ``` For single-asset strategies, `amounts` contains one `Amount`. For dual-asset strategies, it contains two entries in the same order as the strategy's `depositTokens`. ## Depositing Deposit into a Troves strategy with typed `Amount` inputs: ```typescript theme={null} const tx = await wallet.troves().deposit({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("10", STRK), }); await tx.wait(); ``` Dual-asset strategies can provide `amount2`: ```typescript theme={null} const tx = await wallet.troves().deposit({ strategyId: "some_dual_asset_strategy", amount: Amount.parse("10", TOKEN_A), amount2: Amount.parse("0.5", TOKEN_B), }); await tx.wait(); ``` With execution options: ```typescript theme={null} const tx = await wallet.troves().deposit( { strategyId: "ekubo_cl_strketh", amount: Amount.parse("10", STRK), }, { feeMode: { type: "paymaster" } } ); await tx.wait(); ``` ## Withdrawing Withdraw from a Troves strategy using the same typed shape: ```typescript theme={null} const tx = await wallet.troves().withdraw({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("5", STRK), }); await tx.wait(); ``` For dual-asset strategies: ```typescript theme={null} const tx = await wallet.troves().withdraw({ strategyId: "some_dual_asset_strategy", amount: Amount.parse("5", TOKEN_A), amount2: Amount.parse("0.25", TOKEN_B), }); await tx.wait(); ``` ## Using the transaction builder Troves can be composed into a larger atomic transaction through the tx builder: ```typescript theme={null} const tx = await wallet .tx() .trovesDeposit({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("10", STRK), }) .transfer(STRK, [{ to: recipient, amount: Amount.parse("1", STRK) }]) .send(); await tx.wait(); ``` Withdraw through the builder: ```typescript theme={null} const tx = await wallet .tx() .trovesWithdraw({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("5", STRK), }) .send(); await tx.wait(); ``` ## Low-level call preparation If you need to inspect or batch Troves calls manually, use the populate helpers: ```typescript theme={null} const depositCalls = await wallet.troves().populateDeposit({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("10", STRK), }); const withdrawCalls = await wallet.troves().populateWithdraw({ strategyId: "ekubo_cl_strketh", amount: Amount.parse("5", STRK), }); ``` These return Starknet `Call[]` values without executing them. ## Best Practices 1. Use `getStrategies()` to drive the strategy picker instead of hard-coding ids. 2. Treat Troves as mainnet-only unless you are explicitly using a custom compatible backend. 3. Use typed `Amount` values from the strategy's deposit tokens to avoid decimals mismatches. 4. Prefer `wallet.tx().trovesDeposit(...)` and `wallet.tx().trovesWithdraw(...)` when Troves actions should be atomic with other wallet operations. 5. Expect some strategies to return `apy` as a string label rather than a numeric yield; use `apySplit` when you need structured numeric values. ## Next Steps * [Tx Builder](/build/starkzap/tx-builder) — Batch Troves actions with transfers, staking, swaps, and more * [Transactions](/build/starkzap/transactions) — Direct execution, fee modes, and preflight * [Bitcoin, Stablecoins, and Tokens](/build/starkzap/erc20) — Token presets and typed `Amount` handling * [API Reference](/build/starkzap/api-reference) — Full method and type signatures # Tx Builder Source: https://docs.starknet.io/build/starkzap/tx-builder Batch multiple operations into a single atomic transaction using the fluent TxBuilder API <img alt="Tx Builder hero" /> ## Overview The `TxBuilder` provides a fluent API for batching multiple operations into a single atomic transaction. This saves gas and guarantees all-or-nothing execution—either all operations succeed together, or none of them execute. ## Basic Usage ```typescript theme={null} const tx = await wallet .tx() .enterPool(poolAddress, Amount.parse("100", STRK)) .send(); await tx.wait(); ``` ## Mixing Operations Combine transfers, staking, approvals, and raw calls: ```typescript theme={null} const tx = await wallet .tx() // Transfer tokens to multiple recipients .transfer(USDC, [ { to: alice, amount: Amount.parse("50", USDC) }, { to: bob, amount: Amount.parse("25", USDC) }, ]) // Stake in a pool (auto-detects enter vs. add) .stake(poolAddress, Amount.parse("100", STRK)) // Claim rewards .claimPoolRewards(anotherPoolAddress) // Add raw contract calls .add({ contractAddress: "0xDEX_CONTRACT", entrypoint: "swap", calldata: [/* ... */], }) .send(); await tx.wait(); ``` The `.stake()` method is smart — it automatically calls `enter_delegation_pool` for new members or `add_to_delegation_pool` for existing members. ## Preflight with Builder ```typescript theme={null} const builder = wallet .tx() .stake(poolAddress, amount) .transfer(USDC, { to: alice, amount: usdcAmount }); const result = await builder.preflight(); if (!result.ok) { console.error("Transaction would fail:", result.reason); } else { const tx = await builder.send(); await tx.wait(); } ``` ## Fee Estimation ```typescript theme={null} const fee = await wallet .tx() .transfer(USDC, { to: alice, amount }) .stake(poolAddress, stakeAmount) .estimateFee(); console.log("Estimated fee:", fee.overall_fee); ``` ## Extracting Calls You can also extract the raw calls for inspection: ```typescript theme={null} const calls = await wallet .tx() .transfer(USDC, { to: alice, amount }) .enterPool(poolAddress, stakeAmount) .calls(); console.log(`${calls.length} calls in this transaction`); ``` ## Available Builder Methods | Method | Description | | - | - | | `.add(...calls)` | Add raw `Call` objects | | `.approve(token, spender, amount)` | ERC20 approval | | `.transfer(token, transfers)` | ERC20 transfer(s) | | `.stake(pool, amount)` | Smart stake (enter or add based on membership) | | `.enterPool(pool, amount)` | Enter pool as new member | | `.addToPool(pool, amount)` | Add to existing pool position | | `.claimPoolRewards(pool)` | Claim staking rewards | | `.exitPoolIntent(pool, amount)` | Start exit process | | `.exitPool(pool)` | Complete exit after window | | `.swap(request)` | Provider-driven token swap — see [Swaps](/build/starkzap/swap) | | `.lendDeposit(request)` | Lending deposit (supply) — see [Lending](/build/starkzap/lending) | | `.lendWithdraw(request)` | Lending withdraw | | `.lendWithdrawMax(request)` | Lending max withdraw | | `.lendBorrow(request)` | Lending borrow | | `.lendRepay(request)` | Lending repay | | `.trovesDeposit(params)` | Troves strategy deposit — see [Troves](/build/starkzap/troves) | | `.trovesWithdraw(params)` | Troves strategy withdraw — see [Troves](/build/starkzap/troves) | | `.dcaCreate(request)` | Create a DCA (recurring buy) order — see [DCA](/build/starkzap/dollar-cost-average) | | `.dcaCancel(request)` | Cancel a DCA order | | `.confidentialFund(confidential, details)` | Fund confidential account — see [Tongo](/build/starkzap/privacy/tongo) | | `.confidentialTransfer(confidential, details)` | Confidential transfer | | `.confidentialWithdraw(confidential, details)` | Withdraw from confidential to public address | | `.calls()` | Resolve all calls without sending | | `.estimateFee()` | Estimate gas cost | | `.preflight()` | Simulate the transaction | | `.send(options?)` | Execute all calls atomically | ## Best Practices 1. **Use the transaction builder** for complex operations to save gas 2. **Always preflight** non-trivial batches before submitting 3. **Combine related operations** into a single transaction when possible 4. **Use `.estimateFee()`** to show users the cost before executing ## Next Steps * Learn about [Transaction Execution](/build/starkzap/transactions) for direct execution methods * Explore [Staking and Delegation](/build/starkzap/staking) for staking operations * Check the [Bitcoin, Stablecoins, and Token](/build/starkzap/erc20) module for token operations * [Lending](/build/starkzap/lending) — Batch deposit, withdraw, borrow, and repay with Vesu * [Troves](/build/starkzap/troves) — Batch Troves deposits and withdrawals with other wallet operations * [Tongo confidential transfers](/build/starkzap/privacy/tongo) — Fund, transfer, and withdraw with Tongo <Note> Only Tongo batches. [STRK20 privacy pool](/build/starkzap/privacy/strk20) operations cannot go through the builder: the proof belongs to the transaction rather than to a call, so a privacy operation can never share a transaction with other calls. </Note> # AI-Powered Development Source: https://docs.starknet.io/build/starkzap/using-llms Configure Cursor IDE and MCP using Starkzap's internal standards for smarter coding. ## Overview Maximize development speed by providing Cursor and LLMs with the full context of the Starkzap codebase using our built-in AI configuration files. ## 1. Cursor IDE Setup ### Add Project Rules For the best experience, Cursor needs to understand our coding standards (ESM, Strict TS, and Path Aliases). 1. Copy the contents of `CLAUDE.md` from the root of the [repository](https://github.com/keep-starknet-strange/starkzap). 2. Paste them into a `.cursorrules` file in your project root. 3. This allows Cursor to automatically use the correct commands (like `npm run typecheck`) and follow our internal `<conventions>`. ### Add External Documentation Add the Starkzap API reference to Cursor's indexed docs: 1. **Settings > Features > Docs** 2. **Add new doc** 3. URL: `https://docs.starkzap.com/llms-full.txt` (or your local `docs/export/` path) *** ## 2. Using the Agent Model (MCP) If you are using the **Model Context Protocol (MCP)** with Claude or Cursor: * **Context Loading:** Point your filesystem MCP to `CLAUDE.md` and `AGENTS.md`. * **Workflow Alignment:** The AI will now understand the `Coordinator -> Executor -> Reviewer` workflow defined in our repo, making it better at planning complex features. *** ## 3. Common AI Commands Inside Cursor Chat (Cmd+L or Ctrl+L), you can now use specific context: * **"Check my types"**: The AI will know to run `npm run typecheck` based on `CLAUDE.md`. * **"Generate a new token preset"**: The AI will point you to `npm run generate:tokens` instead of suggesting manual edits. * **"@docs Starkzap how to batch transactions"**: Uses the indexed documentation for accurate SDK syntax. ## Next Steps * Review the **Development Workflow** in [CLAUDE.md](https://github.com/keep-starknet-strange/starkzap/blob/main/CLAUDE.md) * Learn about **Multi-agent coordination** in [AGENTS.md](https://github.com/keep-starknet-strange/starkzap/blob/main/AGENTS.md) # Source: https://docs.starknet.io/index The ultimate guide to building on Starknet - Cairo smart contracts, ZK technology, and scaling Ethereum & Bitcoin. <div> <div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg> </div> <div> <svg> <path /> </svg>
프로젝트로 돌아가기