Starknet 백서

Starknet

원문

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

o> <AccordionGroup> <Accordion title="Network"> The simplest way to configure the SDK is using network presets. Think of networks like environments: * **mainnet** = Production (real money, real transactions) * **sepolia** = Staging/Testnet (fake money for testing) * **devnet** = Local development (your own test blockchain) ```typescript theme={null} import { StarkZap } from "starkzap"; // Mainnet const sdk = new StarkZap({ network: "mainnet" }); // Sepolia testnet const sdk = new StarkZap({ network: "sepolia" }); // Local devnet (starknet-devnet-rs) const sdk = new StarkZap({ network: "devnet" }); ``` ### Available Presets | Preset | Chain ID | RPC | Explorer | | - | - | - | - | | `mainnet` | `SN_MAIN` | `https://api.cartridge.gg/x/starknet/mainnet` | `https://voyager.online` | | `sepolia` | `SN_SEPOLIA` | `https://api.cartridge.gg/x/starknet/sepolia` | `https://sepolia.voyager.online` | | `devnet` | `SN_SEPOLIA` | `http://localhost:5050` | — | ### Using Network Objects You can also pass a custom `NetworkPreset` object: ```typescript theme={null} import { StarkZap, networks } from "starkzap"; const sdk = new StarkZap({ network: networks.mainnet }); ``` </Accordion> <Accordion title="RPC"> If you run your own blockchain node or use a different RPC provider (like using a different API endpoint): <Info> An **RPC provider** is like choosing which API server to use. Just like you might use AWS, Google Cloud, or your own servers, you can use different RPC providers to connect to the blockchain. </Info> ```typescript theme={null} import { StarkZap, ChainId } from "starkzap"; const sdk = new StarkZap({ rpcUrl: "https://starknet-mainnet.infura.io/v3/YOUR_KEY", chainId: ChainId.MAINNET, }); ``` <Note> `rpcUrl` and `chainId` override values from `network` if both are provided. </Note> <Note> Plain `http://` is accepted only for loopback hosts (`localhost`, `127.0.0.1`, `[::1]`), which is what the `devnet` preset uses. Any other plain-http host is refused. If a device or emulator reaches a devnet or proxy over your LAN, set `allowInsecureHttp: true` on the SDK config. It applies to `rpcUrl`, the Cartridge URLs and the Privy `serverUrl`; the privacy module has its own flag. Never set it in a production build. </Note> </Accordion> <Accordion title="Staking"> Enable staking functionality to let users earn passive income by staking their tokens. When configured, users can: * 💰 **Stake tokens** in validator pools and earn rewards over time (like earning interest on a savings account) * 📈 **Grow their holdings** as rewards accumulate automatically * 🔄 **Manage their positions** by adding more tokens, claiming rewards, or exiting pools * 🏦 **Support network security** while earning passive income Staking works out of the box using chain-aware staking contract presets: ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", }); ``` If needed, you can override the default preset: ```typescript theme={null} import { StarkZap, fromAddress } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", staking: { contract: fromAddress( "0x00ca1702e64c81d9a07b86bd2c540188d92a2c73cf5cc0e508d949015e7e84a7" ), }, }); ``` <Info> **Ready to implement staking?** See the [Staking & Delegation Guide](/build/starkzap/staking) for complete instructions on how users can stake tokens, claim rewards, and manage their positions. </Info> </Accordion> <Accordion title="Bridging"> Configure optional cross-chain bridge settings when depositing assets from Ethereum or Solana into Starknet. ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", bridging: { ethereumRpcUrl: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", solanaRpcUrl: "https://solana-mainnet.g.alchemy.com/v2/YOUR_KEY", layerZeroApiKey: "YOUR_LAYERZERO_API_KEY", // for OFT routes layerswapApiKey: "YOUR_LAYERSWAP_API_KEY", // for Layerswap routes + token discovery }, }); ``` * `ethereumRpcUrl`: Custom Ethereum RPC for bridge fee/balance operations * `solanaRpcUrl`: Custom Solana RPC (falls back to cluster URL if omitted) * `layerZeroApiKey`: Required for OFT/OFT-migrated routes * `layerswapApiKey`: Required for Layerswap routes and Layerswap token discovery * `layerswapBaseUrl`: Optional Layerswap API base URL (defaults to `https://api.layerswap.io`) * `layerswapAllowedContracts`: Starknet contracts Layerswap may call in a withdrawal besides the bridge token. Unset, only the token transfer is signed. See [Bridging](/build/starkzap/bridging) before listing anything. <Warning> OFT routes require `bridging.layerZeroApiKey` and are supported on mainnet bridge routes only. </Warning> <Warning> Layerswap routes and Layerswap token discovery require `bridging.layerswapApiKey`. Keys are environment-scoped — use a Mainnet key with Starknet Mainnet and a Testnet key with Starknet Sepolia. </Warning> <Info> For the full deposit flow (`getBridgingTokens`, external wallet adapters, fee estimate, deposit), see the [Bridging Guide](/build/starkzap/bridging). </Info> </Accordion> <Accordion title="Logging"> Configure optional SDK diagnostics when you need visibility into wallet, bridge, and transaction flows during development or debugging. Logging is opt-in and the SDK stays silent by default. ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet", logging: { logger: console, }, }); ``` StarkZap accepts any console-compatible logger with `debug`, `info`, `warn`, and `error` methods. You can also filter logs inside the SDK with `logLevel`: ```typescript theme={null} import { StarkZap } from "starkzap"; import pino from "pino"; const sdk = new StarkZap({ network: "mainnet", logging: { logger: pino(), logLevel: "warn", }, }); ``` * Omit `logging` to keep the SDK completely silent * Omit `logLevel` to forward all log levels to your logger * Supported levels are `trace`, `debug`, `info`, `warn`, `error`, `fatal`, and `silent` </Accordion> </AccordionGroup> ## Complete Configuration Example Here's an example with all optional features configured: ### Using Network Preset ```typescript theme={null} import { StarkZap, fromAddress } from "starkzap"; const sdk = new StarkZap({ // Network configuration network: "mainnet", // Optional: SDK diagnostics logging: { logger: console, logLevel: "info", }, // Optional: override staking contract preset staking: { contract: fromAddress( "0x00ca1702e64c81d9a07b86bd2c540188d92a2c73cf5cc0e508d949015e7e84a7" ), }, bridging: { ethereumRpcUrl: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", layerZeroApiKey: "YOUR_LAYERZERO_API_KEY", }, }); ``` ### Using Custom RPC ```typescript theme={null} import { StarkZap, ChainId, fromAddress } from "starkzap"; const sdk = new StarkZap({ // Custom RPC configuration rpcUrl: "https://starknet-mainnet.infura.io/v3/YOUR_KEY", chainId: ChainId.MAINNET, // Optional: SDK diagnostics logging: { logger: console, }, // Optional: override staking contract preset staking: { contract: fromAddress( "0x00ca1702e64c81d9a07b86bd2c540188d92a2c73cf5cc0e508d949015e7e84a7" ), }, bridging: { solanaRpcUrl: "https://solana-mainnet.g.alchemy.com/v2/YOUR_KEY", }, }); ``` <Note> For paymaster configuration, see the [Paymasters Guide](/build/starkzap/paymasters) for detailed setup instructions for AVNU Paymaster or Cartridge's built-in paymaster. </Note> ## Configuration Type Reference ```typescript theme={null} interface SDKConfig { // Network (choose one) network?: NetworkName | NetworkPreset; rpcUrl?: string; chainId?: ChainId; allowInsecureHttp?: boolean; // accept plain http:// off loopback; dev only // Optional features paymaster?: PaymasterOptions; // { nodeUrl?: string; default?: boolean; headers?: object } explorer?: ExplorerConfig; staking?: StakingConfig; bridging?: BridgingConfig; logging?: LoggerConfig; } interface StakingConfig { contract: Address; // optional override } interface BridgingConfig { layerZeroApiKey?: string; // OFT/OFT-migrated routes layerswapApiKey?: string; // Layerswap routes + token discovery layerswapBaseUrl?: string; // defaults to https://api.layerswap.io layerswapAllowedContracts?: readonly Address[]; // extra contracts Layerswap may call; unset = transfer only ethereumRpcUrl?: string; solanaRpcUrl?: string; } interface LoggerConfig { logger: { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; }; logLevel?: "trace" | "debug" | "info" | "warn" | "error" | "fatal" | "silent"; } ``` <Note> For paymaster configuration details, see the [Paymasters Guide](/build/starkzap/paymasters). </Note> ## Next Steps * Set up [Paymasters](/build/starkzap/paymasters) for gasless transactions * Enable [Staking & Delegation](/build/starkzap/staking) so users can earn passive income * Configure [Bridging](/build/starkzap/bridging) for Ethereum/Solana deposits into and withdrawals out of Starknet * Learn about [Connecting Wallets](/build/starkzap/connecting-wallets) with different signers * Configure [Account Presets](/build/starkzap/connecting-wallets#account-presets) for your use case # Wallets Source: https://docs.starknet.io/build/starkzap/connecting-wallets Connect wallets using different signer strategies: private keys, Privy, Cartridge, and custom signers <img alt="Wallets hero" /> ## Overview Starkzap supports multiple ways to connect wallets, each suited for different use cases and security requirements. This guide covers all available connection methods. <Info> **New to wallets?** A **wallet** is like a bank account on the blockchain—it has an address (like an account number) and uses a **signer** (like authentication) to authorize transactions. A **signer** is what proves you own the wallet, similar to how OAuth tokens prove you're logged in. See the [Glossary](/build/starkzap/glossary) for more details. </Info> ## Connection Methods Comparison Choose the right method for your use case: | Method | Best For | User Experience | Gas Fees | Setup Complexity | | - | - | - | - | - | | **Private Key** | Server-side apps, development | Manual key entry | ⚠️ User pays (or configure AVNU Paymaster) | ⭐ Simple | | **Privy** | Consumer apps, mobile/web | Email/social login | ⚠️ User pays (or configure AVNU Paymaster) | ⭐⭐ Moderate | | **Cartridge** | Gaming applications | Social login, Face ID/Touch ID (web popup or native session) | ✅ **Policy-matching calls can be sponsored** | ⭐⭐ Moderate (RN: Metro + adapter) | ### Quick Decision Guide * **Building a game?** → Use **Cartridge** (web: `@cartridge/controller`; React Native: `starkzap-native` + [React Native Integration](/build/starkzap/react-native)) * **Building a consumer app?** → Use **Privy** (email/social login, configure AVNU Paymaster for gasless) * **Building a server-side service?** → Use **Private Key** (with proper security, configure AVNU Paymaster for gasless) * **Need gasless-style UX for approved game calls?** → Use **Cartridge** with policies that match your contract calls * **Need email-based auth?** → Use **Privy** * **Just testing?** → Use **Private Key** for quick setup ## Connection Methods ### 1. Local Private Key (StarkSigner) The simplest approach — sign transactions locally using a private key (like storing a password locally). Best for: * Server-side applications * Trusted environments * Development and testing <Info> A **private key** is like a password—it proves you own the wallet. Unlike a password, you should **never** expose it in client-side code. Only use this method on secure servers or for development. **For gasless transactions:** Configure [AVNU Paymaster](/build/starkzap/integrations/avnu-paymaster) separately to sponsor transaction fees. </Info> ```typescript theme={null} import { StarkZap, StarkSigner, OpenZeppelinPreset, ArgentPreset } from "starkzap"; const sdk = new StarkZap({ network: "sepolia" }); const signer = new StarkSigner("0xYOUR_PRIVATE_KEY"); // Default account type: OpenZeppelin const wallet = await sdk.connectWallet({ account: { signer }, }); // Or specify an account preset const wallet = await sdk.connectWallet({ account: { signer, accountClass: ArgentPreset }, }); ``` <Warning> Never expose private keys in client-side code. Use this method only in secure server environments or for development. </Warning> ### 2. Privy Signer (Server-Side Key Management) [Privy](https://privy.io) manages private keys securely on their infrastructure (like how OAuth providers manage authentication). The signing happens through your backend. Best for: * Consumer applications * Mobile and web apps * Applications requiring secure key management <Info> Think of Privy like **OAuth for wallets**—they manage the keys (like Google manages your login), and you just call their API to sign transactions (like calling Google's API to verify a token). **For gasless transactions:** Configure [AVNU Paymaster](/build/starkzap/integrations/avnu-paymaster) separately to sponsor transaction fees. </Info> <Info> For detailed Privy integration instructions, see the [Privy Integration Guide](/build/starkzap/integrations/privy). </Info> **Option A: Provide your backend URL (recommended for mobile/web clients)** ```typescript theme={null} import { StarkZap, PrivySigner, ArgentXV050Preset } from "starkzap"; const accessToken = await privy.getAccessToken(); const walletRes = await fetch("https://your-backend.com/api/wallet/starknet", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, }); const { wallet: privyWallet } = await walletRes.json(); const signer = new PrivySigner({ walletId: privyWallet.id, publicKey: privyWallet.publicKey, serverUrl: "https://your-backend.com/api/wallet/sign", }); const wallet = await sdk.connectWallet({ account: { signer, accountClass: ArgentXV050Preset }, }); ``` Your backend endpoint receives `{ walletId, hash }` and must return `{ signature }`. **Option B: Custom signing function (for server-side Node.js)** ```typescript theme={null} import { PrivySigner } from "starkzap"; // Use the wallet identity returned by your /api/wallet/starknet endpoint const walletId = "wallet-id-from-backend"; const publicKey = "0xPUBLIC_KEY_FROM_BACKEND"; const signer = new PrivySigner({ walletId, publicKey, rawSign: async (walletId, messageHash) => { const response = await privyClient.wallets().rawSign(walletId, { params: { hash: messageHash }, }); return response.signature; }, }); ``` ### 3. Cartridge (web Controller or native session) [Cartridge](https://cartridge.gg) is specialized for gaming applications and provides social login and passkey authentication. * **Web:** opens a Controller popup (install `@cartridge/controller`). * **React Native / Expo:** in-app browser / deep-link **session** flow via `starkzap-native` — register the native Cartridge adapter before connecting; see [React Native Integration](/build/starkzap/react-native). Best for: * Gaming applications * Social login integration * Passkey-based authentication * Policy-approved, paymastered execution (not every arbitrary call) <Info> **Key advantage:** Cartridge can sponsor **policy-matching** transactions through its paymaster/session stack after users approve policies. Other calls may still require user fees or extra steps. See the [Cartridge Controller Integration Guide](/build/starkzap/integrations/cartridge-controller). </Info> ```typescript theme={null} import { StarkZap } from "starkzap"; const sdk = new StarkZap({ network: "mainnet" }); const wallet = await sdk.connectCartridge({ policies: [ { target: "0xTOKEN_CONTRACT", method: "transfer" }, { target: "0xPOOL_CONTRACT", method: "enter_delegation_pool" }, ], }); // Use just like any other wallet const tx = await wallet.execute([...]); // Access Cartridge-specific features const controller = wallet.getController(); controller.openProfile(); ``` ### 4. Custom Signer Implement `SignerInterface` to integrate any key management solution (hardware wallets, MPC, HSMs, etc.): ```typescript theme={null} import type { SignerInterface } from "starkzap"; import type { Signature } from "starknet"; class MySigner implements SignerInterface { async getPubKey(): Promise<string> { return "0xMY_PUBLIC_KEY"; } async signRaw(hash: string): Promise<Signature> { // Sign the hash using your key management solution // Return [r, s] tuple return ["0x...", "0x..."]; } } const wallet = await sdk.connectWallet({ account: { signer: new MySigner() }, }); ``` ## Account Presets Account presets define what type of wallet account to create. Think of it like choosing between "Personal" vs "Business" account types—different presets have different features and security models. <Info> An **account preset** is like selecting a user role or account type. Each preset (OpenZeppelin, Argent, Braavos) has different capabilities, just like how different user roles have different permissions in your app. </Info> ### Built-in Presets ```typescript theme={null} import { OpenZeppelinPreset, // Default — OpenZeppelin account ArgentPreset, // Argent v0.4.0 ArgentXV050Preset, // Argent v0.5.0 (used by Privy) BraavosPreset, // Braavos v1.2.0 DevnetPreset, // Local devnet accounts } from "starkzap"; // Use when connecting a wallet const wallet = await sdk.connectWallet({ account: { signer: new StarkSigner(privateKey), accountClass: ArgentPreset, }, }); ``` ### Custom Account Class ```typescript theme={null} import type { AccountClassConfig } from "starkzap"; import { CallData } from "starknet"; const MyAccountPreset: AccountClassConfig = { classHash: "0xYOUR_CLASS_HASH", buildConstructorCalldata: (publicKey) => { return CallData.compile({ owner: publicKey }); }, // Optional: custom salt derivation (default uses publicKey) getSalt: (publicKey) => publicKey, }; ``` ## Wallet Lifecycle ### Deployment Starknet accounts are smart contracts that need to be "deployed" (created on the blockchain) before they can execute transactions. Think of it like creating a new user account in your database—it needs to exist before you can use it. <Info> **Deployment** is like provisioning a new service or creating a new account. The SDK handles this automatically, but you can control when it happens with the `deploy` option. </Info> ```typescript theme={null} // Check if deployed const deployed = await wallet.isDeployed(); // Deploy explicitly if (!deployed) { const tx = await wallet.deploy(); await tx.wait(); } // Deploy with sponsored fees (gasless) const tx = await wallet.deploy({ feeMode: { type: "paymaster" } }); await tx.wait(); ``` <Note> For sponsored wallets, `execute()` automatically deploys the account in the same transaction if needed — no separate deploy step required. </Note> ### Ensure Ready A convenience method that checks deployment and optionally deploys: ```typescript theme={null} // Deploy if needed (default behavior) await wallet.ensureReady(); // Explicit options await wallet.ensureReady({ deploy: "if_needed", // "never" | "if_needed" | "always" feeMode: { type: "paymaster" }, onProgress: (event) => { console.log(event.step); // "CONNECTED" → "CHECK_DEPLOYED" → "DEPLOYING" → "READY" }, }); ``` ### Deployment Policy Options * `"never"` - Fail if account is undeployed * `"if_needed"` - Deploy undeployed accounts automatically * `"always"` - Force deployment flow even if already deployed ## Using the Onboarding API The onboarding API simplifies wallet connection by handling strategy selection, signer construction, and account readiness: ```typescript them
프로젝트로 돌아가기