### React Native Quickstart
Source: https://docs.privy.io/basics/react-native/quickstart
This snippet outlines the basic steps to get started with Privy in a React Native project. It covers installation and initialization.
```APIDOC
## Installation
To get started, install the Privy React Native SDK:
```bash
npm install privy-react-native
# or
yarn add privy-react-native
```
## Initialization
Initialize Privy in your application's entry point (e.g., `App.js` or `index.js`).
```javascript
import React from 'react';
import { PrivyW3Modal } from '@privy-io/react-native';
function App() {
return (
{/* Your app content */}
);
}
export default App;
```
Replace `YOUR_PRIVY_APP_ID` with your actual Privy App ID. You can find this in your Privy dashboard.
```
--------------------------------
### Ruby Quickstart Example
Source: https://docs.privy.io/basics/ruby/quickstart
This snippet demonstrates basic user and wallet creation, and transaction signing using the Privy Ruby SDK. Ensure you have the Privy SDK installed and configured with your API key.
```ruby
require "privy"
# Initialize the Privy client with your API key
client = Privy::Client.new(api_key: ENV["PRIVY_API_KEY"])
# Create a new user
user = client.users.create
puts "Created user: #{user.id}"
# Create an embedded wallet for the user
wallet = client.wallets.create(user_id: user.id, embedded: true)
puts "Created embedded wallet: #{wallet.address}"
# Example of signing a transaction (replace with actual transaction data)
# This is a simplified example; actual transaction signing requires more context
# For example, you might need to construct a transaction object specific to the blockchain
# and potentially use a different method depending on the operation.
# The following is a conceptual representation:
#
# transaction_data = {
# to: "0xRecipientAddress",
# value: "0x0",
# data: "0x",
# nonce: "0x0",
# gas_price: "0x12345",
# gas_limit: "0x12345"
# }
#
# signed_transaction = client.wallets.sign_transaction(
# wallet_address: wallet.address,
# transaction: transaction_data
# )
# puts "Signed transaction: #{signed_transaction.signed_transaction}"
# To send a transaction, you would typically use a blockchain client (e.g., eth-ruby)
# with the signed transaction and broadcast it to the network.
# Example of getting user details
retrieved_user = client.users.get(user.id)
puts "Retrieved user: #{retrieved_user.id}"
# Example of getting wallet details
retrieved_wallet = client.wallets.get(wallet.address)
puts "Retrieved wallet: #{retrieved_wallet.address}"
```
--------------------------------
### Android Quickstart - Initial Setup
Source: https://docs.privy.io/basics/android/quickstart
This snippet shows the initial setup for Privy in an Android application. It includes necessary imports and basic configuration.
```kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.privy.wallet.Privy
import com.privy.wallet.PrivyClient
import com.privy.wallet.PrivyClient.Companion.create
import com.privy.wallet.PrivyClient.Companion.get
@Composable
fun PrivyQuickstart(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
var privyClient by remember { mutableStateOf(null) }
var authenticatedUser by remember { mutableStateOf(null) }
LaunchedEffect(Unit) {
val privy = Privy.Builder(context)
.withAndroidConfig(
Privy.AndroidConfig(
appId = "YOUR_APP_ID",
embeddedWalletOnly = true
)
)
.build()
privyClient = privy.client
}
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Privy Quickstart")
Button(
onClick = {
privyClient?.let {
// TODO: Implement authentication logic
}
}
) {
Text("Authenticate")
}
if (authenticatedUser != null) {
Text("Authenticated as: $authenticatedUser")
}
}
}
@Preview
@Composable
fun PrivyQuickstartPreview() {
PrivyQuickstart()
}
```
--------------------------------
### Ruby Quickstart: Get Wallet by ID
Source: https://docs.privy.io/basics/ruby/quickstart
Demonstrates how to retrieve an existing wallet using its unique ID.
```ruby
wallet = client.wallets.get(id: wallet.id)
puts wallet.address
```
--------------------------------
### Rust Quickstart
Source: https://docs.privy.io/basics/rust/quickstart
This snippet demonstrates the basic setup and usage of the Privy Rust SDK for creating and interacting with wallets.
```APIDOC
## Initialize Privy SDK
### Description
Initializes the Privy SDK with your API key.
### Method
`privy::init(api_key: &str)`
### Parameters
- **api_key** (string) - Required - Your Privy API key.
### Request Example
```rust
privy::init("YOUR_PRIVY_API_KEY");
```
## Create Wallet
### Description
Creates a new Privy wallet.
### Method
`privy::create_wallet()`
### Response
#### Success Response (200)
- **wallet_address** (string) - The address of the newly created wallet.
### Request Example
```rust
let wallet = privy::create_wallet().await.expect("Failed to create wallet");
println!("Created wallet: {}", wallet.wallet_address);
```
## Get Wallet
### Description
Retrieves an existing Privy wallet by its address.
### Method
`privy::get_wallet(address: &str)`
### Parameters
- **address** (string) - Required - The address of the wallet to retrieve.
### Response
#### Success Response (200)
- **wallet_address** (string) - The address of the retrieved wallet.
### Request Example
```rust
let wallet = privy::get_wallet("0x...").await.expect("Failed to get wallet");
println!("Retrieved wallet: {}", wallet.wallet_address);
```
```
--------------------------------
### Ruby Quickstart: Create Wallet
Source: https://docs.privy.io/basics/ruby/quickstart
Example of creating a new wallet using the Privy client. This is a fundamental step for user onboarding.
```ruby
wallet = client.wallets.create
puts wallet.id
puts wallet.address
puts wallet.private_key
```
--------------------------------
### Complete Example with WagmiProvider
Source: https://docs.privy.io/wallets/connectors/ethereum/integrations/wagmi
This is a complete example demonstrating how to integrate Privy with Wagmi, including the necessary imports and provider setup. It shows the structure for wrapping your application with `PrivyProvider`, `QueryClientProvider`, and `WagmiProvider`.
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { PrivyProvider } from '@privy-io/react-auth';
import { WagmiProvider, cookieToInitialState } from 'wagmi';
import { config, cookieName } from './config';
const queryClient = new QueryClient();
function App({
cookies
}: {
cookies?: string;
}) {
const initialState = cookieToInitialState(config, cookies);
return (
{/* Your app components */}
);
}
```
--------------------------------
### Import Wallet via Private Key (CLI Example)
Source: https://docs.privy.io/wallets/wallets/import-a-wallet/private-key
This example demonstrates how to import a wallet using its private key via a command-line interface. Ensure you have your app credentials, app ID, and the wallet's encrypted private key and encapsulated key ready.
```bash
curl \
--request POST \
--url https://api.privy.io/v1/wallets/import/submit \
--header 'Authorization: Basic ' \
--header 'Content-Type: application/json' \
--header 'privy-app-id: ' \
--data '{
"wallet": {
"address": "",
"chain_type": "solana",
"entropy_type": "private-key",
"encryption_type": "HPKE",
"ciphertext": "",
"encapsulated_key": ""
},
'
```
--------------------------------
### React Project Setup with Vite
Source: https://docs.privy.io/recipes/react/eip-7702
Create a new React project using Vite and install necessary dependencies for Privy, Wagmi, and Biconomy.
```bash
bun create vite biconomy-mee-embedded-example --template react-ts
cd biconomy-mee-embedded-example
```
```json
"dependencies": {
"@biconomy/abstractjs": "^1.0.17",
"@privy-io/react-auth": "^2.14.2",
"@privy-io/wagmi": "^1.0.4",
"@tanstack/react-query": "^5.80.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"viem": "^2.31.3",
"wagmi": "^2.15.6"
}
```
```bash
bun install
```
--------------------------------
### Import Wallet with Private Key (Python)
Source: https://docs.privy.io/wallets/wallets/import-a-wallet/private-key
This example demonstrates importing a wallet using a private key in Python. Ensure you have the 'web3.py' library installed.
```python
from web3 import Web3
private_key = "0x..." # Replace with your actual private key
account = Web3().eth.account.from_key(private_key)
print(f"Imported wallet address: {account.address}")
```
--------------------------------
### Send SOL Recipe Example
Source: https://docs.privy.io/wallets/using-wallets/solana/send-a-transaction
This is a link to a recipe for sending SOL transactions. It provides a complete example for this specific use case.
```markdown
[sending a\\nSOL transaction recipe](/recipes/solana/send-sol)
```
--------------------------------
### REST API Example
Source: https://docs.privy.io/wallets/wallets/import-a-wallet/private-key
Example of initializing a wallet import flow via the REST API.
```APIDOC
## Initialize Wallet Import (REST API)
### Description
Initialize a key import flow by calling the `/v1/wallets/import/init` endpoint with your wallet address and chain type. See "authentication" for how to encode your app credentials.
### Method
`POST`
### Endpoint
`/v1/wallets/import/init`
### Parameters
#### Request Body
- **address** (string) - Required - The wallet address.
- **chain_type** (string) - Required - The chain type (e.g., `evm`, `solana`).
### Request Example
```bash
curl -X POST \
'https://api.privy.io/v1/wallets/import/init' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic YOUR_APP_CREDENTIALS_BASE64'
-d '{
"address": "",
"chain_type": "evm"
}'
```
### Response
#### Success Response (200)
- **wallet_id** (string) - The ID of the wallet to be imported.
- **proof** (string) - A proof that must be signed by the wallet to confirm ownership.
#### Response Example
```json
{
"wallet_id": "wallet_abc123",
"proof": "0xabcdef12345..."
}
```
```
--------------------------------
### EVM Smart Wallet Initialization (C#)
Source: https://docs.privy.io/wallets/wallets/create/create-a-wallet
Example of initializing an EVM smart wallet using the Privy SDK in C#.
```csharp
Task \
}),
}),
_jsx(CodeBlock, {
filename: "",
numberOfLines: "1",
language: "csharp",
children: _jsx(_components.pre, {
className: "shiki shiki-themes github-light-default dark-plus",
style: {
backgroundColor: "#ffffff",
"--shiki-dark-bg": "#0B0C0E",
color: "#1F2328",
"--shiki-dark": "#D4D4D4"
},
language: "csharp",
children: _jsxs(_components.code, {
language: "csharp",
numberOfLines: "1",
children: [
_jsxs(_components.span, {
className: "line",
children: [
_jsx(_components.span, {
style: {
color: "#953800",
"--shiki-dark": "#4EC9B0"
},
children: "Task"
}),
_jsx(_components.span, {
style: {
color: "#1F2328",
"--shiki-dark": "#D4D4D4"
},
children: "<"
}),
_jsx(_components.span, {
style: {
color: "#953800",
"--shiki-dark": "#4EC9B0"
},
children: "IEmbeddedSolanaWallet"
}),
_jsx(_components.span, {
style: {
color: "#1F2328",
"--shiki-dark": "#D4D4D4"
},
children: "> "
})
]
})
]
})
})
})
```
--------------------------------
### JavaScript SDK Example
Source: https://docs.privy.io/wallets/wallets/import-a-wallet/private-key
Example of importing a wallet using a private key via the Privy JavaScript SDK.
```APIDOC
## Import Wallet with Private Key (JavaScript SDK)
### Description
Use the Privy SDK to import an existing wallet by providing its private key, address, and chain type.
### Method
`privy.importWallet()`
### Parameters
#### Request Body
- **wallet** (object) - Required - The wallet details.
- **entropy_type** (string) - Required - Must be `'private-key'`.
- **chain_type** (string) - Required - The blockchain the wallet is on (e.g., `'evm'`, `'solana'`).
- **address** (string) - Required - The wallet's public address.
- **private_key** (Uint8Array) - Required - The wallet's private key as a Uint8Array.
### Request Example
```javascript
import { privy } from '@privy/sdk';
const wallet = await privy.importWallet({
entropy_type: 'private-key',
chain_type: 'evm',
address: '',
private_key: '',
});
```
### Response
#### Success Response (200)
- **wallet** (object) - The imported wallet object.
- **id** (string) - The unique identifier for the wallet.
- **address** (string) - The wallet's public address.
- **chain_type** (string) - The blockchain type.
- **owner_id** (string) - The ID of the user who owns the wallet.
- **created_at** (string) - Timestamp of wallet creation.
- **updated_at** (string) - Timestamp of last wallet update.
#### Response Example
```json
{
"wallet": {
"id": "wallet_abc123",
"address": "0x123...",
"chain_type": "evm",
"owner_id": "user_xyz789",
"created_at": "2023-10-27T10:00:00Z",
"updated_at": "2023-10-27T10:00:00Z"
}
}
```
**Note:** The returned wallet is of type `Wallet`. See "get wallet by ID" for type definition.
```
--------------------------------
### Create EVM Smart Wallet Request Example
Source: https://docs.privy.io/wallets/wallets/create/create-a-wallet
This is an example of a request to create an EVM smart wallet. It includes common parameters like idempotency key, external ID, and display name.
```shellscript
curl -X POST \"https://api.privy.io/v1/wallets\" \\\n --header \"Authorization: Bearer YOUR_PRIVY_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{ \\\n \"idempotency_key\": \"your-unique-idempotency-key\", \\\n \"external_id\": \"your-external-wallet-id\", \\\n \"display_name\": \"My Awesome Wallet\" \\\n }'
```
--------------------------------
### Send SPL Tokens Recipe Example
Source: https://docs.privy.io/wallets/using-wallets/solana/send-a-transaction
This is a link to a recipe for sending SPL tokens. It provides a complete example for this specific use case.
```markdown
[sending SPL tokens\\nrecipe](/recipes/solana/send-spl-tokens)
```
--------------------------------
### React Setup with Privy and Aave Providers
Source: https://docs.privy.io/recipes/yield/aave-guide
Minimal setup for Privy provider with Aave provider. Customize your Privy provider by following the Privy Quickstart guide.
```tsx
import { PrivyProvider } from "@privy-io/react-auth";
import { AaveProvider } from "@aave/react";
function App() {
return (
{/* Your application components */}
);
}
export default App;
```
--------------------------------
### Create Wallet with Callbacks (EVM)
Source: https://docs.privy.io/wallets/wallets/create/create-a-wallet
Example of using `useCreateWallet` with `onSuccess` and `onError` callbacks for Ethereum wallet creation.
```tsx
const {createWallet} = useCreateWallet({
onSuccess: ({wallet}) => {
console.log('Created wallet ', wallet);
},
onError: (error) => {
console.error('Failed to create wallet with error ', e)
}
})
```
--------------------------------
### React Setup with Privy and Aave Providers
Source: https://docs.privy.io/recipes/yield/aave-guide
Minimal setup for PrivyProvider with Aave provider configuration in a React application. Customize your Privy provider by following the Privy Quickstart guide.
```tsx
// App.tsx
import { PrivyProvider } from '@privy-io/react-auth';
import { AaveProvider } from '@aave/react';
function App() {
return (
{/* Your application components */}
);
}
export default App;
```
--------------------------------
### Get Started with Signers
Source: https://docs.privy.io/wallets/using-wallets/signers/overview
This snippet shows the basic setup for using signers with Privy. Ensure you have initialized Privy and obtained a user object before proceeding.
```javascript
import { PrivyClient, WalletClient } from "@privy/sdk";
const client = new PrivyClient("YOUR_PRIVY_APP_ID");
// Assuming you have an authenticated user object
const user = await client.login("YOUR_USER_EMAIL");
const signer = user.walletClient.getSigner();
// Now you can use the signer to sign transactions or messages
```
--------------------------------
### Basic Viem Setup
Source: https://docs.privy.io/wallets/connectors/ethereum/integrations/viem
Demonstrates how to set up Viem with Privy to interact with Ethereum. This involves creating a Privy client and then initializing Viem with the Privy provider.
```APIDOC
## Initialize Viem with Privy
### Description
This example shows how to initialize Viem using the Privy provider, enabling your application to leverage Viem's utilities with Privy's managed wallets.
### Method
```javascript
import { create } from '@privy-sh/privy'
import { createPublicClient, http } from 'viem'
async function setupViem() {
// Initialize Privy client
const privy = await create({
// your Privy configuration
})
// Get the Viem provider from Privy
const viemProvider = privy.getViemProvider()
// Create a Viem public client using the Privy provider
const publicClient = createPublicClient({
transport: http(viemProvider.transport.url),
// chain: viemProvider.chain // Optionally specify the chain if needed
})
console.log('Viem public client initialized:', publicClient)
// You can now use publicClient for read-only operations
// For example: const blockNumber = await publicClient.getBlockNumber()
}
setupViem()
```
### Usage
This snippet is intended to be run in a JavaScript environment where `@privy-sh/privy` and `viem` are installed. It demonstrates the core steps to bridge Privy's wallet management with Viem's client functionalities.
```
--------------------------------
### Send SOL Transaction Example
Source: https://docs.privy.io/recipes/solana/send-sol
This snippet shows how to send SOL from a Privy embedded wallet. It utilizes the `useSignAndSendTransaction` hook and the `getTransferSolInstruction` function from `@solana/kit`. Ensure you have the necessary wallet setup and dependencies installed.
```javascript
import { useSignAndSendTransaction } from "@privy-io/react-auth";
import { getTransferSolInstruction } from "@solana/kit";
function SendSolButton() {
const { signAndSendTransaction, isLoading } = useSignAndSendTransaction({
// The transaction to send
transaction: {
// The instruction to send SOL
instruction: getTransferSolInstruction({
// The amount to send in lamports (1 SOL = 1,000,000,000 lamports)
amount: 1000000000,
// The recipient's public key
to: "",
// The sender's public key (usually the embedded wallet address)
from: "",
}),
// Optional: recent blockhash for the transaction
blockhash: "",
// Optional: fee payer for the transaction
feePayer: "",
},
// Callback function to execute after the transaction is sent
onSuccess: (txHash) => console.log(`Transaction sent: ${txHash}`),
// Callback function to execute if there is an error
onError: (error) => console.error(`Transaction failed: ${error.message}`),
});
return (
);
}
export default SendSolButton;
```
--------------------------------
### Solana Integration Example
Source: https://docs.privy.io/basics/go/quickstart
An example demonstrating integration with Solana. This snippet is part of the Solana-specific setup or usage instructions.
```go
package main
import (
"fmt"
"log"
"privy-go/privy"
)
func main() {
// Replace with your actual Privy API key
privyClient := privy.NewClient("YOUR_PRIVY_API_KEY")
// Example: Get user by ID
userID := "some-user-id"
user, err := privyClient.GetUser(userID)
if err != nil {
log.Fatalf("Failed to get user: %v", err)
}
fmt.Printf("User: %+v\n", user)
// Example: Create a new linked account
// This is a simplified example; actual linking involves more steps
// For instance, you'd typically generate a nonce and have the user sign it
// See Privy's documentation for detailed linking flows.
// For demonstration, we'll simulate a successful link response.
fmt.Println("Simulating linked account creation...")
// In a real scenario, you would call a method like:
// linkResponse, err := privyClient.Link("some-wallet-address", "some-signature", "some-nonce")
// For now, we'll just print a success message.
fmt.Println("Linked account creation simulated successfully.")
}
```
--------------------------------
### Usage Example: Creating a Wallet
Source: https://docs.privy.io/wallets/wallets/create/create-a-wallet
This snippet demonstrates the import and basic usage of the `createWallet` function. Ensure you have the necessary imports from `@privy-io/expo/extended-chains`.
```tsx
import { createWallet } from "@privy-io/expo/extended-chains";
```
--------------------------------
### Get Wallets Example
Source: https://docs.privy.io/api-reference/introduction
This example demonstrates how to fetch wallet information using the Privy API via JavaScript and cURL.
```APIDOC
## GET /v1/wallets
### Description
Fetches a list of wallets.
### Method
GET
### Endpoint
https://api.privy.io/v1/wallets
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
**JavaScript**
```javascript
fetch('https://api.privy.io/v1/wallets', {
method: 'GET',
headers: {
'Authorization': `Basic ${btoa('insert-your-app-id' + ':' + 'insert-your-app-secret')}`,
'privy-app-id': 'insert-your-app-id',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data));
```
**cURL**
```bash
curl -X GET "https://api.privy.io/v1/wallets" \
--user "insert-your-app-id:insert-your-app-secret" \
-H "privy-app-id: insert-your-app-id" \
-H "Content-Type: application/json"
```
### Response
#### Success Response (200)
(Response structure not detailed in source)
#### Response Example
(Response example not detailed in source)
```
--------------------------------
### Basic Java Setup
Source: https://docs.privy.io/basics/java/quickstart
This snippet shows the basic setup for initializing the Privy client in a Java application. Ensure you have the necessary dependencies.
```java
import io.privy.privy.Privy;
public class Main {
public static void main(String[] args) {
// Initialize the Privy client with your API key
Privy privy = new Privy("YOUR_PRIVY_API_KEY");
// Now you can use the privy client for various operations
System.out.println("Privy client initialized successfully.");
}
}
```
--------------------------------
### C# Example: Get User and Check Authentication
Source: https://docs.privy.io/authentication/user-authentication/authentication-state
Demonstrates how to get the current user from the Privy instance and check if a user is authenticated in C#.
```csharp
var privyUser = await PrivyManager.Instance.GetUser();
if (privyUser != null)
{
var linkedAccounts = privyUser.LinkedAccounts;
}
```
--------------------------------
### Swift Quickstart Example
Source: https://docs.privy.io/basics/swift/quickstart
This is a generated Swift code snippet, likely part of a larger MDX content structure. It defines MDX content rendering functions.
```swift
function MDXCreateElement(type, props, ...children) {
return { type, props: props || {}, children: children.flat() };
}
function MDXContent(props = {}) {
const {wrapper: MDXLayout} = {
..._provideComponents(),
...props.components
};
return MDXLayout ? _jsx(MDXLayout, {
...props,
children: _createMdxContent({
...props
})
}) : _createMdxContent(props);
}
return {
default: MDXContent
};
function _missingMdxReference(id, component) {
throw new Error("Expected " + (component ? "component" : "object") + " `" + id + "` to be defined: you likely forgot to import, pass, or provide it.");
}
```
--------------------------------
### React x402 Fetch Example
Source: https://docs.privy.io/recipes/agent-integrations/x402
Example of using the `useX402Fetch` hook in a React application to make an x402 payment-authorized request. Ensure you have `@privy-io/react-auth` installed.
```tsx
import { useX402Fetch } from "@privy-io/react-auth";
function MyComponent() {
const x402Fetch = useX402Fetch();
const handleClick = async () => {
try {
const response = await x402Fetch("/protected-resource", {
method: "POST",
body: JSON.stringify({ data: "some data" }),
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
const result = await response.json();
console.log("Success:", result);
} else {
console.error("Error:", response.status, await response.text());
}
} catch (error) {
console.error("Network error:", error);
}
};
return ;
}
export default MyComponent;
```
--------------------------------
### Project Setup with Vite
Source: https://docs.privy.io/recipes/react/eip-7702
This command initializes a new project using Vite, a modern frontend build tool. It's the first step in setting up the development environment for integrating Privy with smart accounts.
```shellscript
npm create vite@latest
```
--------------------------------
### Create Authorization Key with Node.js
Source: https://docs.privy.io/controls/authorization-keys/keys/create/key
This Node.js example demonstrates creating an authorization key. Ensure you have the Privy SDK installed (`npm install privy-node`).
```javascript
const { PrivyClient } = require('privy-node');
const privy = new PrivyClient(process.env.PRIVY_API_KEY);
async function createKey() {
const key = await privy.keys.create({
"description": "My Node.js key",
"permissions": [
"read:user"
],
"expiresAt": "2024-12-31T23:59:59Z"
});
console.log(key);
}
createKey();
```
--------------------------------
### Install Passkey Dependencies
Source: https://docs.privy.io/recipes/passkey-server-wallets
Install the necessary server and browser SDKs for simple passkey integration.
```bash
sh npm install @simplewebauthn/server @simplewebauthn/browser
```
--------------------------------
### Import Wallet with Private Key (Go)
Source: https://docs.privy.io/wallets/wallets/import-a-wallet/private-key
This Go example shows how to import a wallet using a private key. Ensure you have the 'go-ethereum' library imported.
```go
import (
"fmt"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
privateKey := "0x..." // Replace with your actual private key
key, err := crypto.HexToECDSA(privateKey[2:]) // Remove "0x" prefix
if err != nil {
panic(err)
}
address := crypto.PubkeyToAddress(key.PublicKey)
fmt.Printf("Imported wallet address: %s\n", address.Hex())
}
```
--------------------------------
### Allow Transfers After Start Date
Source: https://docs.privy.io/controls/policies/example-policies/ethereum
This example shows how to create a policy that only allows transfers after a specified start date. It's useful for time-gated operations.
```typescript
{
"contract": "0x1234567890abcdef1234567890abcdef12345678",
"method": "transfer",
"operator": "gt",
"value": "1678886400"
}
```
--------------------------------
### Create React App Setup with Privy
Source: https://docs.privy.io/basics/react/setup
This example demonstrates the necessary imports and basic structure for setting up Privy within a Create React App project. It includes importing React, ReactDOM, and the PrivyProvider.
```tsx
import React from 'react';
import ReactDOM from 'react';
import { PrivyProvider } from '@privy-council/react';
// ... rest of your app setup
```
--------------------------------
### Complete Fiat Onramp Example
Source: https://docs.privy.io/wallets/funding/fiat-onramp
A full example demonstrating how to use the `useFiatOnramp` hook to start a purchase flow, including handling the button click and initiating the process.
```javascript
import { usePrivy, useFiatOnramp } from "@privy-io/react-auth";
function FiatOnrampComponent() {
const { ready, user } = usePrivy();
const { startPurchase } = useFiatOnramp();
const handlePurchase = async () => {
if (!ready || !user) {
// Handle cases where Privy is not ready or user is not logged in
return;
}
try {
await startPurchase({
purchase: {
amount: 50,
currency: 'EUR',
},
});
} catch (error) {
console.error("Failed to start purchase:", error);
// Handle error display to the user
}
};
return (
);
}
```
--------------------------------
### Import Dependencies and Initialize Clients
Source: https://docs.privy.io/recipes/yield/kamino-guide
Import necessary libraries for Privy, Solana, and Kamino SDK. Configure Privy credentials and establish RPC connections.
```javascript
import {PrivyClient} from '@privy-io/node';
import {
createSolanaRpc,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
createNoopSigner,
getBase64EncodedWireTransaction,
compileTransaction
} from '@solana/kit';
import {KaminoVault} from '@kamino-finance/klend-sdk';
import {Decimal} from 'decimal.js';
const PRIVY_APP_ID = 'put-your-privy-app-id-here';
const PRIVY_APP_SECRET = 'put-your-privy-app-secret-here';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const VAULT_ADDRESS = 'put-your-vault-address-here';
const AUTH_KEY_ID = 'put-your-auth-key-id-here';
const AUTH_KEY_PRIVATE = 'put-your-auth-key-private-here';
const USER_EMAIL = 'put-your-email-here';
const privy = new PrivyClient({
appId: PRIVY_APP_ID,
appSecret: PRIVY_APP_SECRET
});
const rpc = createSolanaRpc(RPC_ENDPOINT);
```
--------------------------------
### Unlink Email Example
Source: https://docs.privy.io/user-management/users/unlinking-accounts
This example demonstrates how to use the `useUnlinkEmail` hook to unlink an email address from a user's account. It requires the `usePrivy` hook to get the user object.
```javascript
function UnlinkOptions() {
const { user } = usePrivy();
const { unlink: unlinkEmail } = useUnlinkEmail();
return (
);
}
```
--------------------------------
### Fetch Asset Balance Example
Source: https://docs.privy.io/wallets/gas-and-asset-management/assets/fetch-balance
This example demonstrates how to fetch the balance of an asset for a wallet. It prints the raw value, the value in decimals, and the chain information.
```javascript
System.out.println("Balance (raw): " + rawValue);
System.out.println("Balance (decimals): " + rawValueDecimals);
System.out.println("Chain: " + balance.chain());
System.out.println("Asset: " + balance.asset());
```
--------------------------------
### Verify Access Token on Backend
Source: https://docs.privy.io/authentication/user-authentication/access-tokens
This snippet shows a basic example of how to verify an access token on your backend using the `privy-node` SDK. Ensure you have installed it: `npm install privy-node`.
```javascript
import { verifyAccessToken } from 'privy-node';
// Assuming you have the token from the request header
const token = req.headers.authorization.split(' ')[1];
try {
const decodedToken = await verifyAccessToken(token, 'YOUR_PRIVY_API_KEY');
console.log('Decoded Token:', decodedToken);
// Use decodedToken.userId to identify the user
} catch (error) {
console.error('Invalid token:', error);
// Handle invalid token error
}
```
--------------------------------
### Ethena Initialization and Configuration
Source: https://docs.privy.io/recipes/yield/ethena-guide
This snippet shows how to initialize and configure the Ethena SDK. It includes setting up the Ethena client with specific configurations.
```javascript
import { Ethena } from "@ethereal/ethana";
const ethana = new Ethena({
// Configuration options
// e.g., apiKey: "YOUR_API_KEY",
// baseUrl: "https://api.ethana.com",
});
```