bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 35쪽
et: GAME_ADDRESS, method: "play_card" },
{ target: STAKING_ADDRESS, method: "enter_delegation_pool" },
],
});
// New session is registered with expanded policies
// All matching transactions are automatically paymastered
```
### Policy Best Practices
1. **Be specific**: Only allow the methods users actually need
2. **Start minimal**: Begin with basic policies, add more as needed
3. **Explain policies**: Let users know what they're approving and that matching transactions will be gasless
4. **Group related operations**: Put related game actions in the same policy set
5. **Review regularly**: Update policies based on user feedback and game features
## Error Handling
```typescript theme={null}
try {
const wallet = await sdk.connectCartridge({ policies });
} catch (error) {
if (error.message.includes("popup")) {
console.error("User blocked popup or closed window");
} else if (error.message.includes("authentication")) {
console.error("Authentication failed");
} else {
console.error("Connection failed:", error);
}
}
```
## Resources
* [Cartridge Controller Documentation](https://docs.cartridge.gg/controller/overview)
* [Cartridge Website](https://cartridge.gg)
* [Policy Documentation](https://docs.cartridge.gg/controller/policies)
## Best Practices
1. **Request minimal permissions** - Only ask for what users need
2. **Handle popup blockers** - Guide users if popups are blocked
3. **Provide clear instructions** - Explain the connection process
4. **Test on multiple browsers** - Ensure compatibility
5. **Monitor user experience** - Track connection success rates
# Privy Integration
Source: https://docs.starknet.io/build/starkzap/integrations/privy
Server-side key management and wallet infrastructure for Starknet applications
<img alt="Privy integration hero" />
## Overview
[Privy](https://privy.io) provides secure, server-side key management for Starknet wallets. With Privy, you can:
* Create and manage Starknet wallets for users
* Sign transactions server-side without exposing private keys
* Support social login and email-based authentication
* Integrate with existing Privy authentication flows
Privy supports Starknet as a [Tier 2 chain](https://docs.privy.io/recipes/use-tier-2#starknet), allowing you to use Privy's raw sign functionality for transaction signing.
## Why Use Privy?
* ✅ **Security**: Private keys never leave Privy's secure infrastructure
* ✅ **User Experience**: Social login and email-based authentication
* ✅ **Server-Side Signing**: Sign transactions on your backend
* ✅ **Multi-Chain**: Same infrastructure for multiple blockchains
* ✅ **Gasless Transactions**: Configure AVNU Paymaster for sponsored transactions (see [AVNU Paymaster Integration](/build/starkzap/integrations/avnu-paymaster))
## Wallet ownership model
Privy supports two ways to use wallets. Choosing the wrong one can lead to JWT or auth errors, so use this as a guide:
| Wallet type | Requires user JWT? | Best for |
| - | - | - |
| **Server-managed** | No | Backend signing, custodial flows |
| **User-owned** | Yes | End-user auth, user-linked wallets |
* **Server-managed**: Create wallets without an owner (omit `owner`). Your backend signs with `PrivyClient` (app credentials) and no end-user JWT is required. Create with just `{ chain_type: "starknet" }`. Best for custodial / backend-only flows.
* **User-owned**: Create wallets with `owner: { user_id }` (the user's DID) so the wallet is tied to a Privy user; access and signing then require that user's JWT. **This is the model the examples below use** — the client authenticates with a Privy client SDK, and the backend verifies the token before creating/using the wallet.
Note: `owner: { user_id }` takes the user's DID (`did:privy:...`). The separate `owner_id` field expects a **cuid2 key-quorum id**, not a user DID — passing a DID there fails with an `Invalid cuid2` error.
## Setup
### 1. Install Privy
```bash theme={null}
npm install @privy-io/node
```
### 2. Initialize Privy Client
```typescript theme={null}
import { PrivyClient } from "@privy-io/node";
const privy = new PrivyClient({
appId: process.env.PRIVY_APP_ID!,
appSecret: process.env.PRIVY_APP_SECRET!,
});
```
### 3. Create a Starknet Wallet
```typescript theme={null}
// Server-managed wallet (app-owned) — no end-user JWT required to sign.
const wallet = await privy.wallets().create({ chain_type: "starknet" });
// Or tie the wallet to a Privy user (user-owned). Note: it's `owner: { user_id }`
// with the user's DID — not a top-level `user_id`, and not `owner_id` (that field
// is a cuid2 key-quorum id, not a user DID). Signing then requires the user's JWT.
// const wallet = await privy.wallets().create({
// chain_type: "starknet",
// owner: { user_id: "did:privy:..." },
// });
console.log("Wallet ID:", wallet.id);
console.log("Wallet Address:", wallet.address);
console.log("Public Key:", wallet.public_key);
```
## Integration with Starkzap
### Server-Side Signing Endpoint
Create an endpoint that signs transaction hashes using Privy:
```typescript theme={null}
import express from "express";
app.post("/api/wallet/sign", async (req, res) => {
const { walletId, hash } = req.body;
if (!walletId || !hash) {
return res.status(400).json({ error: "walletId and hash required" });
}
try {
const result = await privy.wallets().rawSign(walletId, {
params: { hash },
});
res.json({ signature: result.signature });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
```
### Client-Side Integration
> The access token comes from a Privy **client** SDK — `@privy-io/js-sdk-core`
> (vanilla JS/Svelte/Vue), `@privy-io/react-auth` (React), or `@privy-io/expo`
> (React Native) — after the user logs in. The `@privy-io/node` `PrivyClient`
> shown above is **server-only** and has no `getAccessToken()`. Below, `privy`
> refers to the initialized client SDK instance.
Use Privy with Starkzap:
```typescript theme={null}
import { StarkZap, PrivySigner, OnboardStrategy, accountPresets } from "starkzap";
const sdk = new StarkZap({ network: "sepolia" });
// `privy` here is your Privy client SDK instance (see note above).
const accessToken = await privy.getAccessToken();
// Option 1: Using onboard API (recommended)
const onboard = await sdk.onboard({
strategy: OnboardStrategy.Privy,
accountPreset: accountPresets.argentXV050,
privy: {
resolve: async () => {
// Get Privy signer context (walletId + publicKey) from your backend
const walletRes = await fetch("https://your-api.example/api/wallet/starknet", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
const walletData = await walletRes.json();
return {
walletId: walletData.wallet.id,
publicKey: walletData.wallet.publicKey,
serverUrl: "https://your-api.example/api/wallet/sign",
};
},
},
deploy: "if_needed",
});
const wallet = onboard.wallet;
// Option 2: Using PrivySigner directly (reuse accessToken)
const walletRes = await fetch("https://your-api.example/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-api.example/api/wallet/sign",
});
const walletFromSigner = await sdk.connectWallet({
account: { signer, accountClass: accountPresets.argentXV050 },
});
```
## Complete Example
### Backend (Express.js)
```typescript theme={null}
import express from "express";
import { PrivyClient } from "@privy-io/node";
import cors from "cors";
const privy = new PrivyClient({
appId: process.env.PRIVY_APP_ID!,
appSecret: process.env.PRIVY_APP_SECRET!,
});
const app = express();
app.use(cors());
app.use(express.json());
// Verify the Privy access token → the authenticated user's DID.
async function auth(req, res, next) {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).json({ error: "Missing token" });
try {
const claims = await privy.utils().auth().verifyAccessToken(token);
req.userId = claims.user_id; // e.g. "did:privy:..."
next();
} catch {
res.status(401).json({ error: "Invalid token" });
}
}
// Create or get the user's Starknet wallet.
// In production, cache the wallet per user (e.g. in a database) so you don't
// create a new one on every call.
app.post("/api/wallet/starknet", auth, async (req, res) => {
try {
const wallet = await privy.wallets().create({
chain_type: "starknet",
owner: { user_id: req.userId }, // user's DID from the verified token
});
res.json({
wallet: {
id: wallet.id,
address: wallet.address,
publicKey: wallet.public_key,
},
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Sign transaction hash
app.post("/api/wallet/sign", async (req, res) => {
const { walletId, hash } = req.body;
try {
const result = await privy.wallets().rawSign(walletId, {
params: { hash },
});
res.json({ signature: result.signature });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3001);
```
### Frontend
```typescript theme={null}
import { StarkZap, OnboardStrategy, accountPresets } from "starkzap";
const sdk = new StarkZap({ network: "sepolia" });
// `privy` is your Privy client SDK instance (js-sdk-core / react-auth / expo),
// not the server-only @privy-io/node PrivyClient.
const accessToken = await privy.getAccessToken();
// Connect with SDK
const onboard = await sdk.onboard({
strategy: OnboardStrategy.Privy,
accountPreset: accountPresets.argentXV050,
privy: {
resolve: async () => {
const walletRes = await fetch("http://localhost:3001/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: "http://localhost:3001/api/wallet/sign",
};
},
},
deploy: "if_needed",
});
const connectedWallet = onboard.wallet;
// Use the wallet
const balance = await connectedWallet.balanceOf(STRK);
console.log(balance.toFormatted());
```
## React Native Integration
For React Native applications, use `@privy-io/expo`:
```typescript theme={null}
import { PrivyProvider } from "@privy-io/expo";
import { StarkZap, OnboardStrategy } from "starkzap";
// Wrap your app with PrivyProvider (expo needs both appId and clientId)
<PrivyProvider appId={PRIVY_APP_ID} clientId={PRIVY_CLIENT_ID}>
<App />
</PrivyProvider>
// In your component
const privyClient = usePrivy();
const accessToken = await privyClient.getAccessToken();
const walletRes = await fetch("https://your-api.example/api/wallet/starknet", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
const { wallet: walletData } = await walletRes.json();
const onboard = await sdk.onboard({
strategy: OnboardStrategy.Privy,
deploy: "never",
privy: {
resolve: async () => ({
walletId: walletData.id,
publicKey: walletData.publicKey,
serverUrl: "https://your-api.example/api/wallet/sign",
}),
},
});
```
## Resources
* [Privy Documentation](https://docs.privy.io)
* [Starknet Tier 2 Support](https://docs.privy.io/recipes/use-tier-2#starknet)
* [Privy Node SDK](https://docs.privy.io/reference/server-sdk-node)
* [Privy Expo SDK](https://docs.privy.io/reference/react-native-sdk)
## Best Practices
1. **Never expose private keys** - Always use server-side signing
2. **Authenticate requests** - Verify user identity before signing
3. **Use HTTPS** - Always use secure connections for signing endpoints
4. **Handle errors gracefully** - Provide user-friendly error messages
5. **Monitor usage** - Track wallet creation and signing operations
# Lending & Borrowing
Source: https://docs.starknet.io/build/starkzap/lending
Supply, borrow, withdraw, and repay with Vesu—discover markets, manage positions, and check collateral health
## Overview
Starkzap supports lending and borrowing through [**Vesu**](https://vesu.xyz/lite/markets). Users can supply assets (deposit), borrow against collateral, repay debt, and withdraw supplied assets.
**What users can do with lending:**
* 💰 **Supply assets** - Deposit tokens into lending pools and earn interest (supply APY)
* 💳 **Borrow** - Use supplied collateral to borrow other assets
* 💵 **Repay** - Pay down debt; optionally withdraw collateral in the same flow
* 📤 **Withdraw** - Withdraw supplied tokens (or max withdraw in one call)
* 📊 **Monitor positions** - Query position size, debt, and collateralization health
<Info>
The default lending provider is [Vesu](https://vesu.xyz/lite/markets). It is registered automatically when the wallet is created. You can register additional providers or set a different default via `wallet.lending().registerProvider()` and `setDefaultProvider()`.
</Info>
## Configuration
No extra configuration is required for [Vesu](https://vesu.xyz/lite/markets) on mainnet or Sepolia. The wallet's `lending()` client uses the connected chain:
```typescript theme={null}
import { StarkZap } from "starkzap";
const sdk = new StarkZap({ network: "mainnet" });
const wallet = await sdk.connectWallet({ account: { signer, accountClass } });
// Lending client uses wallet chain and address
const lending = wallet.lending();
```
Optional: register another provider or set default:
```typescript theme={null}
lending.registerProvider(myLendingProvider, true); // true = make default
lending.setDefaultProvider("vesu");
```
## Discovering markets
Fetch available lending markets for the wallet's chain:
```typescript theme={null}
const markets = await wallet.lending().getMarkets();
for (const market of markets) {
console.log(market.asset.symbol, market.poolAddress, market.vTokenAddress);
console.log("Can be borrowed:", market.canBeBorrowed);
}
```
### LendingMarket shape
```typescript theme={null}
interface LendingMarket {
protocol: string;
poolAddress: Address;
poolName?: string;
asset: Token;
vTokenAddress: Address;
vTokenSymbol?: string;
canBeBorrowed?: boolean;
stats?: LendingMarketStats;
}
```
Use these markets (and their `poolAddress` / `asset` / `vTokenAddress`) when calling deposit, withdraw, borrow, and repay with the same token/pool.
## Depositing
Supply tokens into a lending pool. The provider includes the approval call when building the transaction.
```typescript theme={null}
const tx = await wallet.lending().deposit({
token: USDC,
amount: Amount.parse("1000", USDC),
// receiver?: Address — defaults to wallet address
});
await tx.wait();
```
With execution options (e.g. sponsored fees):
```typescript theme={null}
const tx = await wallet.lending().deposit(
{ token: USDC, amount: Amount.parse("1000", USDC) },
{ feeMode: { type: "paymaster" } }
);
await tx.wait();
```
## Withdrawing
Withdraw a specific amount of supplied tokens:
```typescript theme={null}
const tx = await wallet.lending().withdraw({
token: USDC,
amount: Amount.parse("200", USDC),
receiver: wallet.address, // optional
});
await tx.wait();
```
Withdraw the maximum allowed (e.g. full supplied balance) in one call:
```typescript theme={null}
const tx = await wallet.lending().withdrawMax({
token: USDC,
receiver: wallet.address,
});
await tx.wait();
```
<Note>
Max withdraw may not be supported by all providers. [Vesu](https://vesu.xyz/lite/markets) supports `withdrawMax`. Check `provider.prepareWithdrawMax` or catch the error if you need to support multiple providers.
</Note>
## Borrowing
Borrow against collateral. You specify the collateral pair (collateral token + debt token) and the amount to borrow (or collateral amount, depending on denomination).
```typescript theme={null}
const tx = await wallet.lending().borrow({
collateralToken: ETH,
debtToken: USDC,
amount: Amount.parse("500", USDC), // amount of debt to borrow
});
await tx.wait();
```
Optional: pass `poolAddress` if you have a specific pool, or `provider: "vesu"` to force the provider. `user` defaults to the wallet address.
## Repaying
Repay borrowed debt. You can optionally withdraw collateral in the same action (provider-dependent).
```typescript theme={null}
const tx = await wallet.lending().repay({
collateralToken: ETH,
debtToken: USDC,
amount: Amount.parse("100", USDC),
// withdrawCollateral?: boolean
});
await tx.wait();
```
## Position and health
### Get position
Retrieve the user's lending position for a collateral/debt pair:
```typescript theme={null}
const position = await wallet.lending().getPosition({
collateralToken: ETH,
debtToken: USDC,
});
console.log(position.collateralShares);
console.log(position.nominalDebt);
console.log(position.collateralAmount, position.debtAmount);
console.log("Collateralized:", position.isCollateralized);
console.log("Collateral value:", position.collateralValue, "Debt value:", position.debtValue);
```
### LendingPosition shape
```typescript theme={null}
interface LendingPosition {
collateralShares: bigint;
nominalDebt: bigint;
collateralAmount?: bigint;
debtAmount?: bigint;
collateralValue: bigint; // USD value [SCALE]
debtValue: bigint; // USD value [SCALE]
isCollateralized: boolean;
}
```
### Get health
Check if the position is collateralized (above liquidation threshold):
```typescript theme={null}
const health = await wallet.lending().getHealth({
collateralToken: ETH,
debtToken: USDC,
});
console.log("Collateralized:", health.isCollateralized);
console.log("Collateral value:", health.collateralValue, "Debt value:", health.debtValue);
```
### Quote projected health
Simulate an action (e.g. borrow or repay) and get the projected health after the action, plus the prepared calls and fee simulation:
```typescript theme={null}
const quote = await wallet.lending().quoteHealth({
action: { action: "borrow", request: { collateralToken: ETH, debtToken: USDC, amount } },
health: { collateralToken: ETH, debtToken: USDC },
feeMode: { type: "paymaster" },
});
console.log("Current health:", quote.current);
console.log("Projected health after action:", quote.projected);
console.log("Prepared calls:", quote.prepared.calls);
console.log("Simulation:", quote.simulation);
```
Use this to show users how a borrow or repay would affect their collateralization before they confirm.
## Using the transaction builder
Batch lending actions with transfers, staking, or other operations using the tx builder. Methods are prefixed with `lend`:
* `.lendDeposit(request)` — add a deposit
* `.lendWithdraw(request)` — add a withdraw
* `.lendWithdrawMax(request)` — add a max withdraw
* `.lendBorrow(request)` — add a borrow
* `.lendRepay(request)` — add a repay
**Example: deposit and then transfer in one tx**
```typescript theme={null}
const tx = await wallet
.tx()
.lendDeposit({ token: USDC, amount: Amount.parse("500", USDC) })
.transfer(USDC, [{ to: recipient, amount: Amount.parse("100", USDC) }])
.send();
await tx.wait();
```
**Example: repay and withdraw collateral**
```typescript theme={null}
const tx = await wallet
.tx()
.lendRepay({
collateralToken: ETH,
debtToken: USDC,
amount: Amount.parse("200", USDC),
withdrawCollateral: true,
})
.send();
await tx.wait();
```
See [Tx Builder](/build/starkzap/tx-builder) for the full list of builder methods.
## Best practices
1. **Check health before and after** borrow/repay so users understand liquidation risk.
2. **`Use quoteHealth()`** to show projected health after an action before the user confirms.
3. **Discover markets once** (e.g. on load) and cache `getMarkets()` if you list markets in the UI.
4. **Use token presets** for `token`, `collateralToken`, and `debtToken` so addresses match the chain.
## Troubleshooting
### "Lending provider returned no calls"
The provider could not build calls for the given request (e.g. wro프로젝트로 돌아가기