Starknet 백서

Starknet

원문

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

e={null} import { StarkZap, OnboardStrategy } from "starkzap"; const sdk = new StarkZap({ network: "sepolia" }); const accessToken = await privy.getAccessToken(); const onboard = await sdk.onboard({ strategy: OnboardStrategy.Privy, privy: { resolve: async () => { const walletRes = await fetch("https://your-api.example/api/wallet/starknet", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, }); const { wallet } = await walletRes.json(); return { walletId: wallet.id, publicKey: wallet.publicKey, serverUrl: "https://your-api.example/api/wallet/sign", }; }, }, accountPreset: "argentXV050", deploy: "if_needed", }); const wallet = onboard.wallet; ``` ## Production Guidance * **Prefer signer separation by trust boundary**: * Server-only keys on backend * Privy for managed end-user keys * Cartridge for delegated UX * **Always call `ensureReady()`** before user actions * **Use appropriate account presets** for your use case * **Handle deployment errors gracefully** in production ## Next Steps * Learn about [Executing Transactions](/build/starkzap/transactions) * Explore [ERC20 Token Operations](/build/starkzap/erc20) * Set up [Staking & Delegation](/build/starkzap/staking) # Dollar-Cost Averaging Source: https://docs.starknet.io/build/starkzap/dollar-cost-average Schedule recurring buys with AVNU or Ekubo—create orders, preview cycles, and cancel via wallet.dca() ## Overview Starkzap supports **Dollar-Cost Averaging (DCA)** through **[AVNU](https://app.avnu.fi/en)** and **[Ekubo](https://ekubo.org/starknet/swap)**. Users can create recurring buy orders (sell token X, buy token Y on a schedule), preview the expected swap per cycle, and cancel orders. DCA providers handle order creation, execution, and cancellation independently. Swap providers are only used for `previewCycle` quoting. **What users can do with DCA:** * 📅 **Create recurring orders** - Set token pair, amount per cycle, and frequency (e.g. daily); optional min/max bounds with AVNU * 📊 **Preview a cycle** - See the expected buy amount for the next cycle before creating or on existing orders * 📋 **List orders** - Fetch active (and optionally past) DCA orders for the wallet * ❌ **Cancel orders** - Cancel by order id or order address * 📦 **Batch with other actions** - Use the transaction builder to combine DCA create/cancel with transfers or swaps <Info> DCA providers (AVNU, Ekubo) handle cycle execution on their own backend — swap providers are **not** involved in execution. However, `previewCycle` uses the wallet's default (or specified) swap provider to quote the next cycle. Register [swap providers](/build/starkzap/swap#registering-swap-providers) if you want to use `previewCycle`. </Info> ## Configuration ### Registering DCA providers Register DCA providers when connecting the wallet (or at runtime). The wallet's `dca()` client uses these providers for create/cancel and for cycle preview (which uses the swap provider to quote the next cycle). <Info> `AvnuDcaProvider` (and `AvnuSwapProvider`, used by `previewCycle`) require the optional peer dependency `@avnu/avnu-sdk` (`npm install @avnu/avnu-sdk`). It is loaded lazily on first use, so the first AVNU DCA call throws an install hint if the package is missing. Ekubo providers need no extra dependency. See [Installation](/build/starkzap/installation#peer-dependencies-by-feature). </Info> ```typescript theme={null} import { StarkZap, AvnuSwapProvider, EkuboSwapProvider, AvnuDcaProvider, EkuboDcaProvider, 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", dcaProviders: [ new AvnuDcaProvider(), new EkuboDcaProvider(), ], defaultDcaProviderId: "avnu", }); ``` At runtime (e.g. after Cartridge onboard), register DCA providers and set the default the same way you do for [swap providers](/build/starkzap/swap#registering-swap-providers): `wallet.dca().registerProvider(provider)`, `wallet.dca().setDefaultProvider(providerId)`. <Note> Register swap providers and a default swap provider if you want to use `previewCycle`. Cycle execution is handled by the DCA provider backend and does not require swap providers. </Note> ## Creating a DCA order Create a recurring order with token pair, amount per cycle, frequency, and optional bounds (AVNU supports min/max buy amount per cycle; Ekubo uses TWAMM-style continuous execution). ```typescript theme={null} const tx = await wallet.dca().create({ sellToken: STRK, buyToken: USDC, sellAmount: Amount.parse("100", STRK), // total amount to sell across all cycles sellAmountPerCycle: Amount.parse("10", STRK), frequency: "P1D", // ISO 8601 duration, e.g. daily // Optional (AVNU): pricingStrategy with min/max bounds // Optional: provider, startTime, endTime }); await tx.wait(); ``` To batch DCA create with other operations, use the [Tx Builder](/build/starkzap/tx-builder) (e.g. `.dcaCreate(...)`). ## Previewing a cycle Show users the expected outcome of the next DCA cycle (quote from the swap provider) before they create the order or to display on an existing order: ```typescript theme={null} const quote = await wallet.dca().previewCycle({ sellToken: STRK, buyToken: USDC, sellAmountPerCycle: Amount.parse("10", STRK), // optional: swapProvider, slippageBps }); console.log(quote.amountOutBase); // expected buy amount for one cycle ``` ## Listing and cancelling orders List active (and optionally past) DCA orders for the wallet, then cancel by order id or order address: ```typescript theme={null} const page = await wallet.dca().getOrders({ provider: "avnu" }); for (const order of page.content) { console.log(order.id, order.sellTokenAddress, order.buyTokenAddress, order.frequency); } // Cancel by order id (provider-specific string) or by order address const tx = await wallet.dca().cancel({ orderId: page.content[0].id }); await tx.wait(); ``` ## Using the transaction builder Batch DCA create or cancel with other actions: ```typescript theme={null} const tx = await wallet .tx() .dcaCreate({ sellToken: STRK, buyToken: USDC, sellAmount: Amount.parse("100", STRK), sellAmountPerCycle: Amount.parse("10", STRK), frequency: "P1D", }) .transfer(USDC, [{ to: recipient, amount: Amount.parse("5", USDC) }]) .send(); await tx.wait(); ``` Cancel via the builder: ```typescript theme={null} const tx = await wallet.tx().dcaCancel({ orderId: myOrderId }).send(); await tx.wait(); ``` See [Tx Builder](/build/starkzap/tx-builder) for the full list of builder methods. ## DCA providers | Provider | Id | Description | | - | - | - | | **[AVNU](https://app.avnu.fi/en)** | `avnu` | Recurring orders with optional min/max buy amount per cycle; uses AVNU swap routing for execution. | | **[Ekubo](https://ekubo.org/starknet/swap)** | `ekubo` | TWAMM-style continuous DCA; no discrete per-cycle amount (continuous flow). Supports order list and cancel. | Provider-specific options (e.g. AVNU bounds, Ekubo time alignment) are documented in the SDK types. Use `wallet.dca().listProviders()` to see registered DCA provider ids and `setDefaultProvider(providerId)` to change the default. ## Best practices 1. **Register swap providers** if you want `previewCycle` to have a quote source (not required for DCA execution itself). 2. **Use token presets** from `getPresets(chainId)` or `mainnetTokens` / `sepoliaTokens` for `tokenIn` and `tokenOut` so addresses and decimals match the chain. 3. **Preview before create** — call `previewCycle` and show users the expected buy amount per cycle before they confirm the order. 4. **Handle provider differences** — AVNU supports discrete cycles and optional min/max bounds; Ekubo is continuous (TWAMM). Validate inputs per provider when building forms. ## Troubleshooting ### "No default DCA provider configured" Register at least one DCA provider and call `setDefaultProvider(providerId)` (or pass `defaultDcaProviderId` when connecting). Alternatively, pass `provider: "avnu"` or `provider: "ekubo"` on each DCA request. ### "requires optional peer dependency "@avnu/avnu-sdk"" An AVNU provider is selected but `@avnu/avnu-sdk` is not installed. Run `npm install @avnu/avnu-sdk`, or use the Ekubo providers (no extra dependency) instead. ### DCA relies on swap providers If `previewCycle` fails, ensure swap providers are registered and a default swap provider is set. Swap providers are only used for cycle quoting — actual cycle execution is handled by the DCA provider backend (AVNU/Ekubo). ### Chain or provider mismatch Ensure the wallet is on a chain supported by the chosen DCA provider (AVNU and Ekubo support mainnet and Sepolia). Align the SDK network config with the RPC/wallet chain. ## Next steps * [Swaps](/build/starkzap/swap) — One-off quotes and swaps (used by `previewCycle` for quoting) * [Bitcoin, Stablecoins, and Tokens](/build/starkzap/erc20) — Token presets and amounts * [Tx Builder](/build/starkzap/tx-builder) — Batching DCA with other operations * [API Reference](/build/starkzap/api-reference) — Full method signatures # Stablecoins & Token Source: https://docs.starknet.io/build/starkzap/erc20 Check balances, transfer tokens, and work with amounts using type-safe primitives <img alt="Bitcoin, Stablecoins, and Token hero" /> ## Overview Starkzap provides comprehensive support for ERC20 token operations, including balance queries, transfers, and type-safe amount handling. This module allows you to work with: * **Bitcoin wrappers on Starknet** - wBTC, lBTC, tBTC (wrapped Bitcoin tokens that represent Bitcoin on Starknet) * **Stablecoins** - USDC, USDT, and other stablecoins * **Other ERC20 tokens** - Any ERC20-compatible token on Starknet This guide covers all token-related functionality for these different token types. ## Token Presets The SDK ships with pre-configured token definitions for mainnet and Sepolia: ```typescript theme={null} import { mainnetTokens, sepoliaTokens } from "starkzap"; // Access specific tokens const STRK = mainnetTokens.STRK; const USDC = mainnetTokens.USDC; const ETH = mainnetTokens.ETH; ``` ### Token Shape ```typescript theme={null} interface Token { name: string; // "Starknet Token" address: Address; // "0x04718f5a0..." decimals: number; // 18 symbol: string; // "STRK" metadata?: { logoUrl?: URL }; } ``` ### Getting Tokens for Current Network ```typescript theme={null} import { getPresets } from "starkzap"; const tokens = getPresets(wallet.getChainId()); // Record<string, Token> ``` ### Resolving Unknown Tokens Resolve tokens from on-chain contract addresses: ```typescript theme={null} import { getTokensFromAddresses } from "starkzap"; const tokens = await getTokensFromAddresses( [fromAddress("0xTOKEN_CONTRACT")], provider ); ``` ## Checking Balances ```typescript theme={null} const balance = await wallet.balanceOf(STRK); console.log(balance.toUnit()); // "150.25" console.log(balance.toFormatted()); // "STRK 150.25" console.log(balance.toFormatted(true)); // "STRK 150.25" (compressed, max 4 decimals) console.log(balance.toBase()); // 150250000000000000000n (raw) console.log(balance.isZero()); // false ``` ## Transferring Tokens ### Single Transfer ```typescript theme={null} const tx = await wallet.transfer(USDC, [ { to: fromAddress("0xRECIPIENT"), amount: Amount.parse("100", USDC) }, ]); await tx.wait(); ``` ### Batch Transfer (Multiple Recipients) Send to multiple recipients in a single transaction: ```typescript theme={null} const tx = await wallet.transfer(USDC, [ { to: fromAddress("0xALICE"), amount: Amount.parse("50", USDC) }, { to: fromAddress("0xBOB"), amount: Amount.parse("25", USDC) }, { to: fromAddress("0xCHARLIE"), amount: Amount.parse("10", USDC) }, ]); await tx.wait(); ``` ### With Paymaster Fees ```typescript theme={null} const tx = await wallet.transfer( USDC, [{ to: recipient, amount: Amount.parse("100", USDC) }], { feeMode: { type: "paymaster" } } ); ``` ## Working with Amounts The `Amount` class provides precision-safe handling of token amounts, preventing common errors when converting between human-readable values and raw blockchain values. ### Creating Amounts ```typescript theme={null} import { Amount } from "starkzap"; // From human-readable values (what users type) const amount = Amount.parse("1.5", STRK); // 1.5 STRK const amount = Amount.parse("100", USDC); // 100 USDC const amount = Amount.parse("0.001", 18, "ETH"); // With explicit decimals // From raw blockchain values (from contract calls, balance queries) const amount = Amount.fromRaw(1500000000000000000n, STRK); // 1.5 STRK const amount = Amount.fromRaw(100000000n, 6, "USDC"); // 100 USDC const amount = Amount.fromRaw(balance, STRK); // From balance query ``` ### Converting and Displaying ```typescript theme={null} const amount = Amount.parse("1500.50", 18, "ETH"); amount.toUnit(); // "1500.5" — human-readable string amount.toBase(); // 1500500000...0n — raw bigint for contracts amount.toFormatted(); // "ETH 1,500.5" — locale-formatted with symbol amount.toFormatted(true); // "ETH 1,500.5" — compressed (max 4 decimals) amount.getDecimals(); // 18 amount.getSymbol(); // "ETH" ``` ### Arithmetic All arithmetic operations return new `Amount` instances (immutable): ```typescript theme={null} const a = Amount.parse("10", STRK); const b = Amount.parse("3", STRK); a.add(b).toUnit(); // "13" a.subtract(b).toUnit(); // "7" a.multiply(2).toUnit(); // "20" a.multiply("0.5").toUnit(); // "5" a.divide(4).toUnit(); // "2.5" ``` <Warning> Arithmetic between incompatible amounts (different decimals or symbols) throws an error. </Warning> ### Comparisons ```typescript theme={null} const a = Amount.parse("10", STRK); const b = Amount.parse("5", STRK); a.eq(b); // false — equal a.gt(b); // true — greater than a.gte(b); // true — greater than or equal a.lt(b); // false — less than a.lte(b); // false — less than or equal a.isZero(); // false a.isPositive(); // true ``` <Note> Comparisons between incompatible amounts return `false` (never throw). </Note> ## Using Amounts in Transactions Amounts work seamlessly with all SDK methods: ```typescript theme={null} // Transfer const tx = await wallet.transfer(STRK, [ { to: recipient, amount: Amount.parse("10", STRK) }, ]); // Staking await wallet.enterPool(poolAddress, Amount.parse("100", STRK)); // Transaction builder await wallet .tx() .transfer(USDC, { to: alice, amount: Amount.parse("50", USDC) }) .send(); ``` ## Token Approval For operations that require spending tokens (like staking), you may need to approve first: ```typescript theme={null} // Using transaction builder await wallet .tx() .approve(STRK, spenderAddress, Amount.parse("1000", STRK)) .send(); // Or direct approval (if supported by your token) const tx = await wallet.execute([{ contractAddress: STRK.address, entrypoint: "approve", calldata: [spenderAddress, Amount.parse("1000", STRK).toBase(), "0"], }]); ``` ## Best Practices 1. **Always use Amount.parse()** for user input to avoid precision errors 2. **Use token presets** instead of hardcoding addresses 3. **Check balances before transfers** to provide better UX 4. **Use batch transfers** when sending to multiple recipients to save gas 5. **Format amounts for display** using `toFormatted()` for better UX ## Common Patterns ### Checking if User Has Enough Balance ```typescript theme={null} const balance = await wallet.balanceOf(STRK); const transferAmount = Amount.parse("100", STRK); if (balance.lt(transferAmount)) { throw new Error("Insufficient balance"); } const tx = await wallet.transfer(STRK, [ { to: recipient, amount: transferAmount }, ]); ``` ### Checking Balance Covers Transfer + Fee ```typescript theme={null} const balance = await wallet.balanceOf(STRK); const transferAmount = Amount.parse("100", STRK); const estimatedFee = await wallet.estimateFee([/* transfer call */]); // Fee is paid in the fee token (ETH or STRK depending on fee mode). // Compare transfer amount and fee separately against their respective balances. if (balance.lt(transferAmount)) { throw new Error("Insufficient STRK balance for transfer"); } // Check fee token balance separately const feeBalance = await wallet.balanceOf(ETH); const feeAmount = Amount.fromRaw(estimatedFee.overall_fee, ETH); if (feeBalance.lt(feeAmount)) { throw new Error("Insufficient ETH balance for fees"); } ``` ## Next Steps * Learn about [Staking & Delegation](/build/starkzap/staking) * Explore [Transaction Builder](/build/starkzap/transactions#transaction-builder) for complex operations * Check the [API Reference](/build/starkzap/api-reference) for detailed method signatures # Examples Source: https://docs.starknet.io/build/starkzap/examples Complete example applications demonstrating Starkzap in action ## Overview The repository includes three example applications in the [examples/](https://github.com/keep-starknet-strange/starkzap/tree/main/examples) directory: 1. **Web Example** — Svelte + Vite, with three wallet connection methods (Cartridge, Privy, private key) and panels for every SDK module. 2. **Mobile Example** — React Native + Expo, mirroring the web example across eight feature tabs. 3. **Server Example** — Express backend providing Privy wallet operations and a paymaster proxy for the other two. The web and mobile examples cover the same ground and consume the SDK straight from the repo (`file:../..` and `file:../../packages/native`), so a change to `src/` is picked up on the next build. <Tabs> <Tab title="Web App"> The web example is a **Svelte + Vite** app demonstrating wallet integration in the browser. Its panels are organised by SDK module, one directory per feature under `examples/web/src/features/`. ### Features * ✅ Three wallet connection methods: * Cartridge Controller (social login / passkey) * Privy (server-managed keys) * Private Key (local signing) * ✅ Account deployment and status checking, across account presets (OpenZeppelin, Argent, Braavos, and others) * ✅ Balances, transfers, staking, and yield * ✅ Swaps and DCA (AVNU and Ekubo) * ✅ Lending (Vesu) * ✅ Bridging from Ethereum and Solana, and withdrawals out of Starknet * ✅ Privacy — both the [STRK20 pool](/build/starkzap/privacy/strk20) and [Tongo](/build/starkzap/privacy/tongo) ### Getting Started ```bash theme={null} cd examples/web npm install npm run dev ``` The app will be available at `http://localhost:5173` (or the port Vite assigns). `npm install` also builds the SDK from the repo root, since the example depends on it as `starkzap: file:../..`. ### Running with Privy Server Privy and the paymaster proxy both come from the server example. Run both at once from `examples/web`: ```bash theme={null} npm run dev:all ``` Or start them separately — Vite on 5173, Express on 3001: ```bash theme={null} npm run dev # terminal 1 npm run dev:server # terminal 2 ``` Then point the app at the server with `VITE_PRIVY_SERVER_URL` in `examples/web/.env`. ### Bridge Setup (Web Example) The web example can also demonstrate bridge flows from Ethereum/Solana into Starknet, as well as withdrawals out of Starknet. Set optional environment variables in `examples/web/.env`: ```bash theme={null} VITE_ALCHEMY_API_KEY=<key> # external RPCs for Ethereum/Solana bridge operations VITE_OFT_PUBLIC_KEY=<key> # LayerZero API key for OFT routes VITE_LAYERSWAP_API_KEY=<key> # Layerswap API key for Layerswap routes + token discovery ``` <Note> Layerswap keys are environment-scoped. The web example also reads `VITE_LAYERSWAP_API_KEY_MAINNET` / `VITE_LAYERSWAP_API_KEY_TESTNET` (falling back to `VITE_LAYERSWAP_API_KEY`), plus an optional `VITE_LAYERSWAP_BASE_URL` override. </Note> SDK setup in `examples/web/src/main.t
프로젝트로 돌아가기