Starknet 백서

Starknet

원문

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

eact Native Integration](/build/starkzap/react-native) and [Cartridge Controller](/build/starkzap/integrations/cartridge-controller). Cartridge can sponsor **policy-matching** calls via its paymaster/session stack; arbitrary transactions are not guaranteed to be gasless. ```typescript theme={null} import { OnboardStrategy } from "starkzap"; const onboard = await sdk.onboard({ strategy: OnboardStrategy.Cartridge, cartridge: { policies: [{ target: "0xCONTRACT", method: "transfer" }], }, // On native Cartridge, you may want deploy: "never" (default in some flows) or "if_needed" explicitly // deploy: "if_needed", }); ``` </Tab> </Tabs> ## What the Onboarding API Handles The `sdk.onboard()` method automatically handles everything needed to get a wallet ready: * ✅ Chooses the right authentication method based on your strategy * ✅ Sets up the signer (the thing that proves ownership) * ✅ Connects and initializes the wallet * ✅ Creates the wallet on the blockchain if it doesn't exist yet * ✅ Configures network settings * ✅ Sets up fee payment options (user pays or paymaster) ## Next Steps Now that you have a basic example working: 1. Learn about [Configuration](/build/starkzap/configuration) options 2. Explore different [Wallet Connection](/build/starkzap/connecting-wallets) methods 3. See how to [Execute Transactions](/build/starkzap/transactions) 4. Explore [Bridging](/build/starkzap/bridging) for Ethereum/Solana deposits into Starknet # React Native Integration Source: https://docs.starknet.io/build/starkzap/react-native Set up StarkZap in React Native/Expo projects with starkzap-native and Metro configuration ## Overview Use `starkzap-native` when integrating StarkZap in React Native/Expo apps. It re-exports the SDK API and adds a Metro helper (`starkzap-native/metro`) that handles ESM/CJS resolver compatibility for `starknet` and its dependencies, and hoists your polyfills to run before the app entry. ## 1) Install Packages Install the React Native package and the one polyfill every StarkZap flow needs: ```bash theme={null} npm install starkzap-native npm install fast-text-encoding ``` Install the rest **only for the features you actually use** — each is reached by a specific code path, not by every flow: ```bash theme={null} # Cartridge sessions, paymaster / outside-execution (SNIP-9), random key generation npm install react-native-get-random-values # Ethereum bridge routes — pulls in ethers, which needs Buffer + crypto shims npm install ethers buffer @ethersproject/shims # Solana bridging — required for any Solana route npm install @solana/web3.js # Additionally, only if you use the Hyperlane Solana routes npm install @hyperlane-xyz/sdk @hyperlane-xyz/registry @hyperlane-xyz/utils # STRK20 privacy pool with OHTTP on. Supplies the `crypto.subtle` Hermes lacks npm install react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 ``` ## 2) Configure Metro Set up Metro once and wrap your config with `withStarkzap`: ```javascript theme={null} // metro.config.js const { getDefaultConfig } = require("expo/metro-config"); const { withStarkzap } = require("starkzap-native/metro"); const config = getDefaultConfig(__dirname); // Optional: add your own resolver overrides before wrapping. module.exports = withStarkzap(config); ``` <Info> `withStarkzap` handles resolver compatibility for StarkZap dependencies and hoists your polyfills to run first. It does **not** import the polyfills for you — do that at your app entry (next step). </Info> ## 3) Load polyfills at your app entry `withStarkzap` can only run polyfills that are in Metro's module graph — it reorders them so they run first, but it cannot import them for you. Import the ones your app needs **once**, at your entry point (e.g. `index.js` or your root layout), before any StarkZap code runs. Each polyfill exists for a specific reason, so import only what your app actually uses: | Polyfill | Provides | Needed by | | - | - | - | | `fast-text-encoding` | `TextEncoder` / `TextDecoder` | **Every flow** — `starknet` hashes an entrypoint selector via `TextEncoder` on every contract read/write (`getSelectorFromName`), and decodes returned strings/byte-arrays | | `react-native-get-random-values` | `crypto.getRandomValues` | **Cartridge** sessions, **paymaster / outside-execution** (SNIP-9) nonces, and random key generation. Deterministic signing and read calls do **not** need it | | `buffer` (+ set the global) | `Buffer` | **Bridge only** — `ethers` and the Solana bridge code | | `@ethersproject/shims` | ethers crypto/random shims | **Bridge only** — `ethers` (v6) used by the Ethereum bridge. The shims package is itself v5-era, but it is what supplies the missing React Native crypto globals | | `react-native-quick-crypto` | `crypto.subtle` | **STRK20 privacy with OHTTP only.** The OHTTP transport needs WebCrypto. Hermes has none, and `react-native-get-random-values` supplies only `getRandomValues` | Required for every app: ```typescript theme={null} // polyfills.ts — imported first at your app entry import "fast-text-encoding"; ``` Add if you use Cartridge, the paymaster, or generate keys: ```typescript theme={null} import "react-native-get-random-values"; ``` Add if you use the bridge features: ```typescript theme={null} import { Buffer } from "buffer"; import "@ethersproject/shims"; if (!globalThis.Buffer) globalThis.Buffer = Buffer; ``` Add this if you use the [STRK20 privacy pool](/build/starkzap/privacy/strk20) with OHTTP on. Take only `subtle`. The package's own `install()` replaces the whole `crypto` global, including the `getRandomValues` installed above for `starknet`: ```typescript theme={null} if (!globalThis.crypto.subtle) { const { subtle } = require("react-native-quick-crypto"); Object.defineProperty(globalThis.crypto, "subtle", { value: subtle, configurable: true, }); } ``` <Note> Use `require` inside the guard, not a top-level `import`. The package loads native modules at import time, so an unconditional import crashes where those modules are absent, such as Expo Go. It needs a dev build (`npx expo run:android`). In an existing native project, run `npx expo prebuild` again so the C++ module is linked. </Note> Then import that file as the very first line of your entry: ```typescript theme={null} // app entry (e.g. app/_layout.tsx) import "./polyfills"; ``` If you skip `fast-text-encoding`, `starknet` crashes on the first contract call (`TextEncoder is not defined`) — `starkzap-native` warns in the console when it's absent. Skipping `react-native-get-random-values` surfaces a clear `crypto.getRandomValues must be defined` only when a Cartridge/paymaster/keygen path runs. ## 4) Initialize the SDK Import from `starkzap-native` and use the same onboarding APIs as web: ```typescript theme={null} import { StarkZap, OnboardStrategy, StarkSigner } from "starkzap-native"; const sdk = new StarkZap({ network: "sepolia" }); const { wallet } = await sdk.onboard({ strategy: OnboardStrategy.Signer, account: { signer: new StarkSigner("0xYOUR_PRIVATE_KEY") }, deploy: "if_needed", }); ``` For Privy-based onboarding, see [Privy Integration](/build/starkzap/integrations/privy). ## 5) Cartridge (native session) When your `starkzap-native` version supports it, you can onboard with **Cartridge** using an in-app browser / deep-link **session** flow (not the web `@cartridge/controller` popup). 1. **Register** the native Cartridge adapter **once** at app startup, before `connectCartridge()` or `onboard({ strategy: OnboardStrategy.Cartridge })`. Exact export names depend on your SDK version (for example `registerCartridgeTsAdapter` / `registerCartridgeNativeAdapter`). 2. Pass **policies** and/or a Cartridge **preset** that resolves policies for your chain (same concepts as [Cartridge Controller](/build/starkzap/integrations/cartridge-controller)). 3. Align `rpcUrl` / `chainId` (or `network`) on `new StarkZap({ ... })` with the session and paymaster you target. 4. **Deploy:** native Cartridge flows often default to **`deploy: "never"`** or recommend it when deployment semantics differ from the browser Controller. Pass **`deploy: "if_needed"`** explicitly if you need core-style deployment checks. 5. **Fees:** sponsored execution on native is tied to the session wallet (commonly **`feeMode: { type: "paymaster" }`** only for matching policy paths, without `gasToken`). See [Cartridge Controller](/build/starkzap/integrations/cartridge-controller) for policy and paymaster behavior, and the `examples/tic-tac-toe` app in the [Starkzap repository](https://github.com/keep-starknet-strange/starkzap) when available for a full Expo reference. ## 6) External Wallet Providers (Optional) If your app uses WalletConnect/Reown for external wallets, initialize its RN compatibility layer at app startup: ```typescript theme={null} import "@walletconnect/react-native-compat"; ``` Then pass the resulting providers into StarkZap external wallet adapters as described in [Bridging](/build/starkzap/bridging#connect-external-wallets). <Warning> If `connectCartridge` or Cartridge onboarding throws **not implemented**, your installed `starkzap-native` build does not ship the native adapter yet — upgrade to a version that documents native Cartridge, or use **Signer** / **Privy** until then. </Warning> ## Next Steps * [Quick Start](/build/starkzap/quick-start) * [Connecting Wallets](/build/starkzap/connecting-wallets) * [Bridging](/build/starkzap/bridging) * [Troubleshooting](/build/starkzap/troubleshooting) * [Examples](/build/starkzap/examples) # Staking & Delegation Source: https://docs.starknet.io/build/starkzap/staking Stake in Starknet delegation pools, claim rewards, and manage exits with the native two-step staking flow <img alt="Staking and Delegation hero" /> ## Overview This page covers Starkzap support for Starknet's native delegation staking protocol. Validators run pools where delegators can stake tokens and earn rewards. <Info> Looking for liquid staking (LST) via Endur? See [LST Staking](/build/starkzap/lst-staking). </Info> **What users can do with staking:** * 💰 **Earn passive income** - Stake tokens (like STRK) and earn rewards over time, similar to a savings account with interest * 🏦 **Support network security** - Stake tokens to help secure the Starknet network while earning rewards * 📈 **Grow their holdings** - Rewards compound over time, allowing users to increase their token holdings without additional purchases * ⏰ **Flexible participation** - Add more tokens anytime, claim rewards when ready, and exit when needed (with a cooldown period) **Real-world analogy:** Think of staking like putting money in a high-yield savings account or certificate of deposit (CD). You lock up your tokens for a period, and in return, you earn interest (rewards). The longer you stake, the more you can potentially earn. <Info> Staking contract is selected automatically from chain-aware presets. You only need `staking.contract` if you want to override the default. </Info> ## Configuration Staking works out of the box when using a supported chain preset: ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", }); ``` Optional override: ```typescript theme={null} import { StarkZap, fromAddress } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", staking: { contract: fromAddress( "0x00ca1702e64c81d9a07b86bd2c540188d92a2c73cf5cc0e508d949015e7e84a7" ), }, }); ``` ## Discovering Validators and Pools ### Using Validator Presets ```typescript theme={null} import { mainnetValidators, sepoliaValidators } from "starkzap"; // Use built-in validator presets for (const validator of Object.values(mainnetValidators)) { console.log(`${validator.name}: ${validator.stakerAddress}`); } // Also available: sepoliaValidators ``` ### Getting Stakeable Tokens ```typescript theme={null} const tokens = await sdk.stakingTokens(); console.log(tokens.map((t) => t.symbol)); // ["STRK", ...] ``` ### Getting Pools for a Validator ```typescript theme={null} const pools = await sdk.getStakerPools(validator.stakerAddress); for (const pool of pools) { console.log(`${pool.token.symbol}: ${pool.amount.toFormatted()} delegated`); console.log(`Pool contract: ${pool.poolContract}`); } ``` ## Entering a Pool Stake tokens for the first time in a validator's pool. The SDK handles the token approval automatically. ```typescript theme={null} const tx = await wallet.enterPool(poolAddress, Amount.parse("100", STRK)); await tx.wait(); ``` This will: 1. Approve the staking contract to spend your tokens (if needed) 2. Call `enter_delegation_pool` on the staking contract 3. Return a transaction you can track ## Smart Stake (Recommended) Use `wallet.stake()` when you don't want to branch on membership manually: ```typescript theme={null} const tx = await wallet.stake(poolAddress, Amount.parse("100", STRK)); await tx.wait(); ``` `wallet.stake()` automatically: * calls `enter_delegation_pool` for first-time stakers * calls `add_to_delegation_pool` for existing members ## Adding to an Existing Stake If you're already a pool member, add more tokens: ```typescript theme={null} const tx = await wallet.addToPool(poolAddress, Amount.parse("50", STRK)); await tx.wait(); ``` ## Claiming Rewards Users earn rewards continuously while their tokens are staked. Rewards accumulate over time and can be claimed at any time: ```typescript theme={null} const position = await wallet.getPoolPosition(poolAddress); if (position && !position.rewards.isZero()) { const tx = await wallet.claimPoolRewards(poolAddress); await tx.wait(); console.log(`Claimed ${position.rewards.toFormatted()}`); } ``` **What users get:** Rewards are paid in the same token they staked (e.g., if you stake STRK, you earn STRK rewards). Users can claim rewards and either: * Withdraw them to their wallet * Re-stake them to compound earnings (add them back to the pool) ## Exiting a Pool (Two-Step Process) Exiting a pool is a two-step process with an exit window: ### Step 1: Declare Exit Intent Tokens stop earning rewards immediately: ```typescript theme={null} const tx = await wallet.exitPoolIntent( poolAddress, Amount.parse("50", STRK) ); await tx.wait(); ``` ### Step 2: Complete Withdrawal Wait for the exit window, then complete the withdrawal: ```typescript theme={null} const position = await wallet.getPoolPosition(poolAddress); if (position?.unpoolTime && new Date() >= position.unpoolTime) { const tx = await wallet.exitPool(poolAddress); await tx.wait(); console.log("Tokens returned to wallet"); } ``` ## Querying Position Get detailed information about your staking position to show users their earnings: ```typescript theme={null} const position = await wallet.getPoolPosition(poolAddress); if (position) { console.log(`Staked: ${position.staked.toFormatted()}`); // Original amount staked console.log(`Rewards: ${position.rewards.toFormatted()}`); // Earned rewards (can claim) console.log(`Total: ${position.total.toFormatted()}`); // Staked + rewards combined console.log(`Commission: ${position.commissionPercent}%`); // Validator's fee console.log(`Unpooling: ${position.unpooling.toFormatted()}`); // Amount being withdrawn console.log(`Unpool at: ${position.unpoolTime}`); // When withdrawal completes } ``` **What this shows users:** * How much they've staked (their original investment) * How much they've earned in rewards (their passive income) * Their total position value (staked + rewards) * When they can withdraw if they've initiated an exit ### Position Interface ```typescript theme={null} interface PoolMember { staked: Amount; rewards: Amount; total: Amount; unpooling: Amount; unpoolTime: Date | null; commissionPercent: number; rewardAddress: Address; } ``` ### Checking Membership ```typescript theme={null} const isMember = await wallet.isPoolMember(poolAddress); ``` ### Getting Commission Rate ```typescript theme={null} const commission = await wallet.getPoolCommission(poolAddress); console.log(`Commission: ${commission}%`); ``` ## Using Transaction Builder The transaction builder makes it easy to combine staking operations with other actions: ```typescript theme={null} const tx = await wallet .tx() // Transfer some tokens .transfer(STRK, [{ to: recipient, amount: Amount.parse("10", STRK) }]) // Stake in a pool (auto-detects enter vs. add) .stake(poolAddress, Amount.parse("100", STRK)) // Claim rewards from another pool .claimPoolRewards(anotherPoolAddress) .send(); await tx.wait(); ``` The `.stake()` method automatically: * Calls `enter_delegation_pool` for new members * Calls `add_to_delegation_pool` for existing members ## Staking Flow Examples ### Complete Staking Flow Here's a complete example showing how users can stake, earn, and manage their position: ```typescript theme={null} // 1. Discover pools const pools = await sdk.getStakerPools(validator.stakerAddress); const strkPool = pools.find((p) => p.token.symbol === "STRK"); // 2. Enter pool - User stakes 100 STRK and starts earning immediately await wallet.enterPool(strkPool.poolContract, Amount.parse("100", STRK)); // User's tokens are now earning rewards in the background // 3. Check position - Show user their earnings const position = await wallet.getPoolPosition(strkPool.poolContract); console.log(`Staked: ${position.staked.toFormatted()}`); // "STRK 100" console.log(`Rewards earned: ${position.rewards.toFormatted()}`); // "STRK 2.5" (example) // 4. Add more later - User can increase their stake anytime await wallet.addToPool(strkPool.poolContract, Amount.parse("50", STRK)); // Now staking 150 STRK total, earning more rewards // 5. Claim rewards - User withdraws their earned rewards await wallet.claimPoolRewards(strkPool.poolContract); // Rewards are sent to user's wallet, can be spent or re-staked // 6. Exit (two-step) - User wants to withdraw some tokens await wallet.exitPoolIntent(strkPool.poolContract, Amount.parse("25", STRK)); // ... wait for exit window (cooldown period) ... await wallet.exitPool(strkPool.poolContract); // 25 STRK returned to user's wallet ``` ### Monitoring Rewards Show users their earnings and help them claim rewards: ```typescript theme={null} async function checkRewards(wallet, poolAddress) { const position = await wallet.getPoolPosition(poolAddress); if (!position) { console.log("Not a member of this pool"); return; } if (position.rewards.isZero()) { console.log("No rewards available yet"); return; } // Show user their earnings console.log(`Available rewards: ${position.rewards.toFormatted()}`); console.log(`Total position: ${position.total.toFormatted()}`); // Staked + rewards // Auto-claim if above threshold (optional) if (position.rewards.gt(Amount.parse("1", STRK))) { await wallet.claimPoolRewards(poolAddress); console.log("Rewards claimed! Tokens sent to your wallet."); } } ``` **User experience:** Users can see their earnings growing in real-time, claim rewards whenever they want, and watch their total position value increase over time. ## User Benefits Summary **What users can do with staking in your app:** * 💰 **Earn passive income** - Stake tokens and earn rewards automatically, like interest on a savings account * 📈 **Grow their holdings** - Rewards accumulate over time, increasing their total token balance * 🔄 **Flexible management** - Add more tokens anytime, claim rewards when ready, exit when needed * 🏦 **Support the network** - Help secure Starknet while earning rewards * ⏱️ **Set and forget** - Once staked, tokens earn rewards in the background without daily management **Real-world use cases:** * **Savings feature** - Let users "save" their tokens and earn interest * **Investment tool** - Enable users to grow their crypto holdings over time * **Rewards program** - Users can stake tokens to earn add
프로젝트로 돌아가기