# AI-Optimized Docs
Source: https://docs.b3.fun/ai-optimized
Learn how B3's documentation is optimized for AI tools and how to leverage these features for better development experience
### Contextual Menu Integration
Every page in our documentation includes a contextual menu that provides one-click access to AI tools. Look for the menu icon on any page to access these features:
Copies the current page as optimized Markdown that you can paste directly into any AI tool as context.
Opens the current page in Markdown format, perfect for understanding the raw structure or copying specific sections.
Creates a new ChatGPT conversation with the current page already loaded as context.
Starts a Claude conversation with the documentation page pre-loaded for immediate assistance.
Opens Perplexity with the current page as context for research and fact-checking.
Provides Model Context Protocol (MCP) server URLs for advanced AI tool integrations.
Direct integration with Cursor and VSCode through MCP for seamless coding assistance.
### Automatic LLM Indexing
Our documentation automatically generates and maintains industry-standard files that help AI tools understand and index our content:
#### llms.txt
* **Automatic Generation**: Available at [/llms.txt](/llms.txt)
* **Structured Content**: Lists all pages with descriptions for efficient AI navigation
* **Always Up-to-Date**: Automatically updated when content changes
* **Zero Maintenance**: No manual updates required
#### llms-full.txt
* **Complete Context**: Available at [/llms-full.txt](/llms-full.txt)
* **Single File**: Combines entire documentation into one file
* **AI-Ready Format**: Optimized for use as context in AI conversations
* **Comprehensive**: Includes all content from across the documentation
## How to Use These Features
### For Quick Questions
1. **Navigate** to any relevant documentation page
2. **Click** the contextual menu icon
3. **Select** "Open in ChatGPT" or "Open in Claude"
4. **Ask** your question - the AI already has the page context
### For Code Development
1. **Open** your preferred code editor (Cursor or VSCode)
2. **Use** the MCP integration from our contextual menu
3. **Access** B3 documentation directly within your coding environment
4. **Get** contextual help while writing code
### For Deep Research
1. **Copy** the relevant page using "Copy Page" feature
2. **Paste** into your preferred AI tool
3. **Combine** with additional context or questions
4. **Get** comprehensive answers with full documentation context
## AI-Optimized Content Structure
Our documentation is structured to work exceptionally well with AI tools:
### Clear Hierarchies
* **Logical organization** that AI tools can easily parse
* **Consistent formatting** across all pages
* **Descriptive headings** that provide context
### Rich Metadata
* **Comprehensive titles** and descriptions
* **Structured frontmatter** for better AI understanding
* **Semantic markup** that enhances AI comprehension
### Code Examples
* **Complete, runnable examples** that AI can explain and modify
* **Well-commented code** for better AI interpretation
* **Multiple implementation approaches** for different use cases
## Benefits for Developers
Get instant access to relevant documentation within your AI conversation, eliminating the need to switch between tools and manually copy content.
AI tools receive properly formatted, comprehensive context about B3 features, leading to more accurate and helpful responses.
Direct integration with development tools like Cursor and VSCode means you can get help without leaving your coding environment.
Our AI-optimized files are automatically updated, ensuring AI tools always have access to the latest information.
## Example Use Cases
### Smart Contract Development
```
1. Open the AnySpend SDK documentation
2. Use "Open in Cursor" to load context into your editor
3. Ask questions about implementation while coding
4. Get contextual code suggestions and explanations
```
### Integration Planning
```
1. Navigate to the relevant protocol documentation
2. Use "Copy Page" to get formatted content
3. Paste into Claude or ChatGPT
4. Ask for integration strategies and best practices
```
### Debugging and Troubleshooting
```
1. Find the error handling documentation
2. Use contextual menu to open in your preferred AI tool
3. Describe your specific issue
4. Get targeted solutions with documentation context
```
## Technical Implementation
Our AI optimization is powered by:
* **Mintlify's AI features**: Built-in contextual menu and LLM file generation
* **Structured content**: Consistent markdown formatting optimized for AI parsing
* **Model Context Protocol (MCP)**: Standard for AI tool integration
* **Automatic updates**: CI/CD pipeline ensures AI files stay current
## Get Started
Ready to leverage these AI features? Here's how:
1. **Browse** to any page in our documentation
2. **Look** for the contextual menu icon (usually in the top-right area)
3. **Try** copying a page or opening it in your favorite AI tool
4. **Experience** the enhanced development workflow
The AI optimization features are available on every page of our documentation and require no setup - they're ready to use immediately.
***
These AI features are designed to enhance your development experience with B3. They work best when combined with a clear understanding of your specific use case and goals.
# Get Account Abstraction Indexing Status
Source: https://docs.b3.fun/data/api-reference/blockscout/get-account-abstraction-indexing-status
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/proxy/account-abstraction/status
# Get Address Coin Balance History
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-coin-balance-history
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/coin-balance-history
# Get Address Coin Balance History by Day
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-coin-balance-history-by-day
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/coin-balance-history-by-day
# Get Address Counters
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-counters
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/counters
# Get Address Info
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-info
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}
# Get Address Logs
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-logs
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/logs
# Get Address Transactions
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/transactions
# Get Address Withdrawals
Source: https://docs.b3.fun/data/api-reference/blockscout/get-address-withdrawals
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/withdrawals
# Get blockscoutapiv1celestiablob
Source: https://docs.b3.fun/data/api-reference/blockscout/get-blockscoutapiv1celestiablob
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/api/v1/celestia/blob
# Get blockscoutapiv1celestial2batchmetadata
Source: https://docs.b3.fun/data/api-reference/blockscout/get-blockscoutapiv1celestial2batchmetadata
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/api/v1/celestia/l2BatchMetadata
# Get JSON RPC URL
Source: https://docs.b3.fun/data/api-reference/blockscout/get-json-rpc-url
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/config/json-rpc-url
# Get List of NFT Owned by Address
Source: https://docs.b3.fun/data/api-reference/blockscout/get-list-of-nft-owned-by-address
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/nft
# Get List of NFT Owned by Address, Grouped by Collection
Source: https://docs.b3.fun/data/api-reference/blockscout/get-list-of-nft-owned-by-address-grouped-by-collection
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/nft/collections
# Get Native Coin Holders List
Source: https://docs.b3.fun/data/api-reference/blockscout/get-native-coin-holders-list
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses
# Get Smart Contract
Source: https://docs.b3.fun/data/api-reference/blockscout/get-smart-contract
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/smart-contracts/{address_hash}
# Get Stats Counters
Source: https://docs.b3.fun/data/api-reference/blockscout/get-stats-counters
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/stats
# Get Transactions
Source: https://docs.b3.fun/data/api-reference/blockscout/get-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions
# Get Verified Smart Contracts
Source: https://docs.b3.fun/data/api-reference/blockscout/get-verified-smart-contracts
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/smart-contracts
# Get Verified Smart Contracts Counters
Source: https://docs.b3.fun/data/api-reference/blockscout/get-verified-smart-contracts-counters
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/smart-contracts/counters
# Get Withdrawals
Source: https://docs.b3.fun/data/api-reference/blockscout/get-withdrawals
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/withdrawals
# If the requested service is unknown, the call will fail with status
NOT_FOUND.
Source: https://docs.b3.fun/data/api-reference/blockscout/if-the-requested-service-is-unknown-the-call-will-fail-with-statusnot_found
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/health
# Get Block Info
Source: https://docs.b3.fun/data/api-reference/blockscoutblocks/get-block-info
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/blocks/{block_number_or_hash}
# Get Block Transactions
Source: https://docs.b3.fun/data/api-reference/blockscoutblocks/get-block-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/blocks/{block_number_or_hash}/transactions
# Get Block Withdrawals
Source: https://docs.b3.fun/data/api-reference/blockscoutblocks/get-block-withdrawals
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/blocks/{block_number_or_hash}/withdrawals
# Get Blocks
Source: https://docs.b3.fun/data/api-reference/blockscoutblocks/get-blocks
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/blocks
# Get Blocks Validated by Address
Source: https://docs.b3.fun/data/api-reference/blockscoutblocks/get-blocks-validated-by-address
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/blocks-validated
# Get Indexing Status
Source: https://docs.b3.fun/data/api-reference/blockscoutmain-page/get-indexing-status
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/main-page/indexing-status
# Get Main Page Blocks
Source: https://docs.b3.fun/data/api-reference/blockscoutmain-page/get-main-page-blocks
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/main-page/blocks
# Get Main Page Transactions
Source: https://docs.b3.fun/data/api-reference/blockscoutmain-page/get-main-page-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/main-page/transactions
# Search
Source: https://docs.b3.fun/data/api-reference/blockscoutsearch/search
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/search
# Search Redirect
Source: https://docs.b3.fun/data/api-reference/blockscoutsearch/search-redirect
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/search/check-redirect
# Get Market Chart
Source: https://docs.b3.fun/data/api-reference/blockscoutstats/get-market-chart
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/stats/charts/market
# Get Transactions Chart
Source: https://docs.b3.fun/data/api-reference/blockscoutstats/get-transactions-chart
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/stats/charts/transactions
# Get Address Token Transfers
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-address-token-transfers
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/token-transfers
# Get All Tokens Balances for the Address
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-all-tokens-balances-for-the-address
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/token-balances
# Get NFT Instance by ID
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-nft-instance-by-id
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/instances/{id}
# Get NFT Instances
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-nft-instances
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/instances
# Get Token Holders
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-holders
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/holders
# Get Token Holders
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-holders-1
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/counters
# Get Token Info
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-info
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}
# Get Token Instance Holders
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-instance-holders
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/instances/{id}/holders
# Get Token Token Transfers
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-token-transfers
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/transfers
# Get Token Transfers
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-token-transfers
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/token-transfers
# Get Tokens List
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-tokens-list
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens
# Get Transfers Count of NFT Instance
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-transfers-count-of-nft-instance
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/instances/{id}/transfers-count
# Get Transfers of NFT Instance
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/get-transfers-of-nft-instance
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/tokens/{address_hash}/instances/{id}/transfers
# Re-fetch Token Instance Metadata
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/re-fetch-token-instance-metadata
https://data-api.b3.fun/swagger.json?v=1 patch /blockscout/tokens/{address_hash}/instances/{id}/refetch-metadata
# Token Balances with Filtering and Pagination
Source: https://docs.b3.fun/data/api-reference/blockscouttokens/token-balances-with-filtering-and-pagination
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/tokens
# Get Address Internal Transactions
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-address-internal-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/addresses/{address_hash}/internal-transactions
# Get Human-Readable Transaction Summary
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-human-readable-transaction-summary
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/summary
# Get Internal Transactions
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-internal-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/internal-transactions
# Get Transaction Info
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-info
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}
# Get Transaction Internal Transactions
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-internal-transactions
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/internal-transactions
# Get Transaction Logs
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-logs
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/logs
# Get Transaction Raw Trace
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-raw-trace
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/raw-trace
# Get Transaction State Changes
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-state-changes
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/state-changes
# Get Transaction Token Transfers
Source: https://docs.b3.fun/data/api-reference/blockscouttransactions/get-transaction-token-transfers
https://data-api.b3.fun/swagger.json?v=1 get /blockscout/transactions/{transaction_hash}/token-transfers
# Get contract events
Source: https://docs.b3.fun/data/api-reference/insightsevents/get-contract-events
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/events/{contractAddress}
Get contract events
# Get contract events with specific signature
Source: https://docs.b3.fun/data/api-reference/insightsevents/get-contract-events-with-specific-signature
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/events/{contractAddress}/{signature}
Get specific contract events
# Get events
Source: https://docs.b3.fun/data/api-reference/insightsevents/get-events
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/events
Get events
# Get ERC-20 balances by address
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-erc-20-balances-by-address
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/erc20/{ownerAddress}
Get ERC-20 balances for a given address. [BEING DEPRECATED IN FAVOR OF /tokens]
# Get token owners by contract
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-token-owners-by-contract
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/owners
Get token owners for specific contract
# Get token transfers
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-token-transfers
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/transfers
Get token transfers
# Get token transfers by contract
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-token-transfers-by-contract
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/transfers/{contract_address}
Get token transfers by contract
# Get token transfers by transaction
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-token-transfers-by-transaction
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/transfers/transaction/{transaction_hash}
Get token transfers by transaction
# Get contract transactions
Source: https://docs.b3.fun/data/api-reference/insightstransactions/get-contract-transactions
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/transactions/{contractAddress}
Get contract transactions
# Get contract transactions with specific signature
Source: https://docs.b3.fun/data/api-reference/insightstransactions/get-contract-transactions-with-specific-signature
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/transactions/{contractAddress}/{signature}
Get specific contract transactions
# Get transactions
Source: https://docs.b3.fun/data/api-reference/insightstransactions/get-transactions
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/transactions
Get transactions
# B3 Data API
Source: https://docs.b3.fun/data/api-reference/introduction
Get free access to indexed blockchain data from B3 & our appchains with our free API.
* Available to builders for free.
* Intelligent multi-chain routing.
* Cached at the edge for speed.
Browse the REST API reference.
## Data Sources & Intelligence
Direct access to indexed blockchain data from Blockscout explorers across all B3 chains, providing transaction history, contract interactions, and block data.
Enhanced with Thirdweb's powerful data infrastructure for NFT metadata, contract ABIs, and smart contract analytics.
Our API automatically routes requests to the optimal data source and chain, ensuring fast response times and data accuracy.
Merged data from all B3 ecosystem chains provides a comprehensive view of cross-chain activities and assets.
## Authentication
No authentication required for public endpoints. Simply make requests to start accessing B3 ecosystem data immediately.
# B3 Profiles API
Source: https://docs.b3.fun/data/profiles/index
Free unified onchain identity aggregation service with social identity data from B3, Basement, ENS, Lens, and Farcaster
Check out the profiles API reference
## Overview
The B3 Profiles service serves as a data API for resolving decentralized user identities across the EVM ecosystem. It aggregates profile data from multiple sources and protocols, providing developers with a single API endpoint to access comprehensive user information and social context.
## Key Features
Combines data from Basement, ENS, Thirdweb Social, and other Web3 identity providers
Fetches social profiles from ENS, Lens Protocol, and Farcaster networks
Uses Cloudflare KV storage for efficient data caching with configurable TTL
Allows users to set preferred profile sources via cryptographic signatures
## Supported Data Sources
* ENS (Ethereum Name Service)
* Lens Protocol
* Farcaster
* B3.ID
* Basement profiles
## API Endpoints
[Check out the API reference](/data/profiles/index) for more details.
### Profile Lookup
Retrieve aggregated profile information for any wallet address or username.
```bash theme={null}
GET https://profiles.b3.fun/?address=0x1234567890abcdef1234567890abcdef12345678
GET https://profiles.b3.fun/?name=vitalik.eth
GET https://profiles.b3.fun/?name=sean.b3.fun
```
### Set Profile Preferences
Allow users to specify their preferred profile source through cryptographic signatures.
```bash theme={null}
POST /preference
```
### Custom Display Names
Enable users to set custom display names that override all other sources.
```bash theme={null}
POST /display-name
```
## Response Format
The service returns a unified profile object that combines data from all sources:
```json theme={null}
{
"name": "vitalik.eth",
"address": "0x1234567890abcdef1234567890abcdef12345678",
"avatar": "https://example.com/avatar.jpg",
"bio": "Ethereum co-founder",
"displayName": "Vitalik Buterin",
"profiles": [
{
"type": "ensdata",
"address": "0x123...",
"name": "vitalik.eth",
"avatar": "https://...",
"bio": null,
"displayName": null
},
{
"type": "thirdweb-farcaster",
"address": "0x123...",
"name": "vitalik",
"avatar": "https://...",
"bio": "Ethereum co-founder",
"displayName": "Vitalik Buterin"
}
]
}
```
## Use Cases
Provide rich context about users during wallet connection, showing their social identity and Web3 reputation across platforms.
Display comprehensive player profiles in games, including ENS names, social handles, and cross-platform identities.
Enhance trading interfaces by showing trader identities from Lens, Farcaster, and ENS instead of just wallet addresses.
Build better community tools by aggregating user identities from multiple Web3 social platforms.
## Example Usage
### Basic Profile Lookup
```javascript theme={null}
// Fetch profile by address
const response = await fetch('https://profiles.b3.fun/?address=0x123...');
const profile = await response.json();
console.log(profile.displayName); // "Vitalik Buterin"
console.log(profile.profiles.length); // Number of sources found
```
### ENS Name Resolution
```javascript theme={null}
// Fetch profile by ENS name
const response = await fetch('https://profiles.b3.fun/?name=vitalik.eth');
const profile = await response.json();
console.log(profile.address); // Resolved wallet address
console.log(profile.avatar); // ENS avatar URL
```
### Setting User Preferences
```javascript theme={null}
// Set preferred profile source with signature
const message = `SetProfilePreference:${address}:thirdweb-farcaster:${timestamp}`;
const signature = await wallet.signMessage(message);
await fetch('https://profiles.b3.fun/preference', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
key: address,
preferredType: 'thirdweb-farcaster',
signature,
signer: address,
timestamp
})
});
```
## Performance & Caching
* **Cache Duration**: 1 hour for profile data
* **Fresh Data**: Use `?fresh=true` to bypass cache
* **Global CDN**: Powered by Cloudflare's edge network
* **KV Storage**: Efficient key-value storage for preferences
## Rate Limits
The service inherits Cloudflare's built-in DDoS protection and rate limiting. For high-volume applications, consider implementing client-side caching or contact the B3 team for enterprise access.
## Building onchain made easy
[Check out the API reference](/data/profiles/index) for more details.
Comprehensive blockchain data and analytics
B3 SDK for cross-chain operations and global account authentication
# Bridges
Source: https://docs.b3.fun/ecosystem/bridges
Cross-chain bridging solutions to move assets to and from B3.
Instant, seamless bridging to B3 using funds on other popular networks.
Bridge Now
Instant, low-cost bridging and swapping. Powered by Reservoir
Bridge
Battle tested OP stack canonical bridge. Has a 7-day challenge period on withdrawals only.
Bridge
# Indexers & Analytics
Source: https://docs.b3.fun/ecosystem/data-analytics
Data indexing, analytics, and user acquisition tools for B3 applications.
A peer-to-peer network to batch query and aggregate terabytes of on-chain and off-chain data
Data Indexers
Dune is a platform for building and sharing data visualizations.
Data Analytics
Helika provides custom game optimization through personalized insights from experienced analysts, unifying on-chain, in-game, and community data to drive growth.
User Acquisition
# Governance
Source: https://docs.b3.fun/ecosystem/governance
Governance platforms and tools for decentralized decision making.
Agora is the home of onchain governance.
Governance Platforms
# Infrastructure
Source: https://docs.b3.fun/ecosystem/infrastructure
Essential infrastructure services including oracles, account abstraction, multisig solutions, and more.
Secure your smart contracts with reliable, low-latency market data from institutional sources.
Oracles
Launch OP Stack, Arbitrum Orbit, ZK Stack, and Polygon CDK rollups with Caldera, your partner from development to launch, and beyond
Rollup-as-a-Service
The fastest multisig for onchain teams.
MultiSig
Pimlico provides a suite of tools and services to help you build, deploy, and manage smart accounts on Ethereum and other EVM-compatible chains.
# B3 Open Ecosystem
Source: https://docs.b3.fun/ecosystem/introduction
B3 remains committed to being an open ecosystem, supporting a range of apps, games, communities, protocols, and onchain tooling.
Thinking about building your app or game on B3? Let's chat.
# B3 SDK
Exclusively available on B3, our SDK makes it easy to create fun onchain experiences.
Instant Login
Instantly onboard players with embedded smart accounts—just one click and they're in the game.
Know Your Player's Identity
Unlock instant access to player data across the ecosystem and their onchain gamer data.
### Scale Your Game
Deploy Onchain Leaderboards
Create competitive rankings tied to real gameplay data and cross-game achievements.
Create Custom Achievements
Create onchain achievements tied to gameplay, loyalty, or community actions. Let players wear their wins across the ecosystem.
Launch Instant Tournaments
Spin up tournaments instantly to boost retention, drive competition, and monetize your game.
Enable Wager Duels
Allow players challenge each other in real-time PvP. Add wagers, XP, or prizes to every match.
Create Exclusivity with Token Gating
Enable users to unlock exclusive content, game modes, or perks based on NFT or token holdings.
Send Onchain Notifications
Trigger wallet-based alerts tied to gameplay, achievements, drops, or events to re-engage users.
### Unlock New Ways to Monetize
Accept Payments Without Friction
Enable users to make purchases with no KYC using fiat or ANY token on ANY chain. It's the easiest way to pay.
Create Native Game Tokens
Easily create custom tokens that power progression, rewards, or ownership—natively tied to your game logic.
Turn Any Asset into a Marketplace
From achievements to skins to user-generated content, turn any in-game asset into a collectible that players can trade.
### Data API
Getting blockchain data from B3 & our appchains is easy - and **free**.
Get access to B3 ecosystem data with our free API.
We automatically merge our multiple, horizontally scaled chains, abstracting the complexity of working with multiple appchains.
### Build on B3
Thinking about building your app or game on B3? Let's chat!
## Ecosystem Tools
Explore our comprehensive ecosystem of tools and services:
Next.js, Unity, Unreal Engine, React, and more
Blockchain infrastructure and RPC providers
Cross-chain bridging solutions for B3
Tools for NFT creation, management, and trading
Wallet solutions and authentication providers
Data indexers, analytics, and user acquisition tools
Oracles, account abstraction, multisig, and more
Governance platforms and tools
# NFT Infrastructure
Source: https://docs.b3.fun/ecosystem/nft-infrastructure
Tools and services for NFT creation, management, and trading on B3.
NFT infrastructure enabling the next-gen of NFT products.
B3 Support
Access token & NFT data with ease through SimpleHash.
B3 Support
Frontend, backend, and onchain tools. Unity, Unreal Engine, and React Native SDKs.
B3 SupportGaming SDKs
# Node Providers
Source: https://docs.b3.fun/ecosystem/node-providers
Access reliable blockchain infrastructure and RPC endpoints for B3.
Quicknode is a blockchain infrastructure and services provider that provides easy-access to B3 mainnet
B3 Support
# Onchain SDKs
Source: https://docs.b3.fun/ecosystem/onchain-sdks
Support for Unity, Unreal Engine, Construct, React, React Native, and most common frameworks.
Frontend, backend, and onchain tools. Unity, Unreal Engine, and React Native SDKs.
B3 SupportGaming SDKs
Developer tools for seamless blockchain integration: SDKs, detailed documentation, and dedicated support empower you to focus on creating engaging gameplay.
B3 SupportGaming SDKs
# Wallets
Source: https://docs.b3.fun/ecosystem/wallets
Wallet solutions and authentication providers for seamless user onboarding.
Spin up embedded wallets and beautiful authentication flows for all users.
Wallet SDKs
Your portal to Web3. Access 100+ decentralized networks with many more on the way
Wallet SDKs
Frontend, backend, and onchain tools. Unity, Unreal Engine, and React Native SDKs.
Wallet SDKs
Openfort is a blockchain advanced platform that provides developers with advanced wallet SDK solutions, focusing on simplifying web3 game development through account abstraction technologies.
Wallet SDKs
# Scaling Fun Onchain
Source: https://docs.b3.fun/index
B3 is Base's layer 3 consumer ecosystem built for games, apps, and enterprises that require the performance to scale and the support to grow.
Get up and running with B3 SDK in under 5 minutes
## Ecosystem of Products
B3 is an portfolio of products designed to bring the next generation of apps, creativity, and commerce onchain.
The B3 protocol layer is the multi-blockchain backbone of the B3 ecosystem.
The B3 ecosystem layer is the open access developer infrastructure, tools, and services for building on B3.
We don't just build tooling, B3 ships consumer apps that bring fun onchain & drive value back to the \$B3 token.
### B3 AppChains The Hyper-Scalable Superchain
B3 is not just another chain, B3 connects fun experiences - games, apps, consumer projects - into a modular, scalable ecosystem that’s open, connected, and ready to grow.
Created by a team of Base/Coinbase alumni and OG Ethereum contributors.
* **modular infra**
pick your stack, settle anywhere—base, ethereum, solana, more.
* **multi-chain network**
launch on b3 mainnet or spin up your own gamechain with built-in support.
* **superfluid liquidity**
built-in primitives for instant transactions, rewards, and cross-app experiences.
B3 operates as an L3 that settles on Base, providing dedicated blockspace specifically for gaming with
lightning-fast transactions and sub-cent fees.
Appchains settle onto B3, with our protocol infrastructure abstracting away the complexity of dealing with multiple
chains.
Learn about B3's unique appchain architecture, the most scalable way to build onchain.
## Power to Developers
Build with tools, sdk, docs, and real support that let you go from zero to live in record time. Explore the B3 SDK to immedaitely build exceptional onchain experiences:
Free, consolidated & rich data APIs & indexing on B3.
Access users, liquidity across chains, launch tokens & more.
## What You Can Build
Instant Login
Instantly onboard players with embedded smart accounts—just one click and they're in the game.
Know Your Player's Identity
Unlock instant access to player data across the ecosystem and their onchain gamer data.
### Scale Your Game
Deploy Onchain Leaderboards
Create competitive rankings tied to real gameplay data and cross-game achievements.
Create Custom Achievements
Create onchain achievements tied to gameplay, loyalty, or community actions. Let players wear their wins across the ecosystem.
Launch Instant Tournaments
Spin up tournaments instantly to boost retention, drive competition, and monetize your game.
Enable Wager Duels
Allow players challenge each other in real-time PvP. Add wagers, XP, or prizes to every match.
Create Exclusivity with Token Gating
Enable users to unlock exclusive content, game modes, or perks based on NFT or token holdings.
Send Onchain Notifications
Trigger wallet-based alerts tied to gameplay, achievements, drops, or events to re-engage users.
### Unlock New Ways to Monetize
Accept Payments Without Friction
Enable users to make purchases with no KYC using fiat or ANY token on ANY chain. It's the easiest way to pay.
Create Native Game Tokens
Easily create custom tokens that power progression, rewards, or ownership—natively tied to your game logic.
Turn Any Asset into a Marketplace
From achievements to skins to user-generated content, turn any in-game asset into a collectible that players can trade.
## Why Choose B3?
B3 delivers lightning-fast transactions with sub-cent fees through dedicated blockspace for gaming, built as an L3
that settles on Base.
Base is a secure, low-cost, builder-friendly L2 incubated by Coinbase. B3 leverages Base as a settlement layer,
contributing to the Base ecosystem while extending its capabilities.
Launch web2-scale games with B3's rollup engine that horizontally scales by sharding at the application layer,
orchestrating dedicated sidecars for computationally heavy operations.
B3's composable architecture enables seamless interoperability between appchains, assets, and tokens. Build true
cross-chain experiences.
No walled gardens here. Anyone can deploy and build on B3, supported by most major blockchain platforms and
frameworks.
## Community & Resources
Join our developer community for support and discussions
Contribute to the project and report issues
**Discover how easy it is to build on B3** Start with our [Quick Start Guide](/quickstart) and begin building the
future of fun today.
# $B3 Token
Source: https://docs.b3.fun/protocol/b3-token
The token powering the B3 ecosystem, powering governance, staking, and value across the entire network.
```text Contract Address theme={null}
0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3
```
Copy this address to add \$B3 to your wallet or trade on DEXs.
[View on B3 Explorer](https://explorer.b3.fun/b3-token)
## What is \$B3?
**\$B3** is the utility token that powers the entire B3 ecosystem. As the foundational token for a horizontally scaling multichain network, B3 enables governance, staking, and value across appchains and applications built on B3.
## A portfolio of fun
B3 is not just blockchain infrastructure. We are constantly building fun, mass-scale potential onchain consumer experiences - all with the goal of creating value for **\$B3 holders.**
Cross-chain payments & onramp.
Stake to win.
The hyper-casual onchain gaming platform.
SDKs for bonding tokens, wagering & more.
### Where to buy \$B3 tokens
Buy \$B3 on Coinbase
Trade \$B3 on Bybit
Purchase \$B3 on Gate.io
Get \$B3 on KuCoin
Trade \$B3 on MEXC
Swap \$B3 on Aerodrome
Trade \$B3 on AlienBase
# Brand Kit
Source: https://docs.b3.fun/protocol/brand-kit
Follow these guidelines to use our brand correctly when contributing to the B3 ecosystem.
## Colors
Don't limit yourself to just this common brand colors. B3 invites you to be expressive with different fun, vibrant color palletes.
```
#007AFF
```
```
#6B7280
```
```
#FFFFFF
```
## Brand Guidelines
Our logo works best when it has adequate margins.
Keep things light, friendly, and engaging.
## Fonts
Import inside CSS stylesheet:
```css theme={null}
@import url("https://cdn.b3.fun/fonts.css");
```
Import via `` tag:
```html theme={null}
```
Now you can use the fonts:
```css theme={null}
body { font-family: "Neue Montreal Medium", sans-serif; }
```
#### Available fonts:
* **Neue Montreal Bold**
* **Neue Montreal Regular**
* **Neue Montreal Book**
* **Neue Montreal Medium**
* **Neue Montreal Semibold**
* **Calibre Bold**
* **Calibre Heavy**
* **Pack**
#### Download the original fonts:
[License](https://klim.co.nz/retail-fonts/calibre/)
[License](https://pangrampangram.com/products/neue-montreal)
[License](https://harrycresswell.com/pack/)
## Fun Assets
## Motion
Animations are welcomed when representing B3, after all - movement is fun!
We recommend Framer Motion as a React animation library, but you can use whatever you like!
## Vibe 👌
B3 is all about having fun, and representing that in your life through gaming & more.
Rep B3 swag in other ways!
## Phone Lock Screen Wallpapers
[Download](https://cdn.b3.fun/b3-iphone-wallpaper-v1.png)
[Download](https://cdn.b3.fun/b3-iphone-wallpaper-v2.png)
[Download](https://cdn.b3.fun/b3-iphone-wallpaper-simple.png)
## Contribute to B3 brand
Let's build B3 together - we welcome creators, artists, developers, gamers, players & everyone to contribute & be rewarded.
Reach out if you've built something cool for the B3 community.
# Bridge to B3
Source: https://docs.b3.fun/protocol/bridge
There are several ways to bridge over to B3 & our appchains.
Cross-chain bridge with instant deposits and withdrawals
Bridge from any EVM chain & Solana to B3
OP Canonical Bridge with 7-day withdrawal period
Direct contract interaction for advanced users
## Cross Chain Bridge
Instant DepositsInstant WithdrawalsLow Fee
Connect your wallet and bridge from major EVM networks in & out of B3.
Visit [basement.fun/bridge](https://basement.fun/bridge) to access the bridge interface.
Connect your wallet using MetaMask, Coinbase Wallet, or other supported wallets.
Choose the source network and the amount of funds you want to bridge to B3.
Confirm the transaction and you'll receive bridged funds in under a minute.
Your funds will appear in your B3 wallet within 60 seconds.
Start bridging your assets to B3 with instant deposits and withdrawals
## Instant Bridge
Instant DepositsInstant WithdrawalsLow Fee
Easily bridge from any EVM chain & Solana to B3 with Relay.
Visit [relay.link](https://relay.link) to access the Relay bridge interface.
Connect your wallet to start the bridging process.
Enter the amount of ETH you want to bridge to B3.
Confirm the transaction and you'll receive bridged funds in under a minute.
Relay supports bridging from multiple chains including Solana.
Bridge from any EVM chain and Solana to B3 instantly
## Native Bridge
Base to B37-Day WithdrawalsNo Fees
Easily bridge from Base to B3 using the official OP Stack canonical bridge!
Withdrawals from B3 back to Base have a 7-day challenge period for security. Use third-party bridges for instant withdrawals.
Go to [bridge.b3.fun](https://bridge.b3.fun) to access the official bridge.
Connect your wallet to the bridge interface.
Select whether you want to:
* **Deposit**: Bring funds from Base → B3
* **Withdraw**: Bridge back from B3 → Base
Enter the amount of ETH you want to bridge.
Click "Deposit" and confirm the transaction in your wallet.
Deposits to B3 are instant, but withdrawals take 7 days for the challenge period.
Use the battle-tested OP Stack canonical bridge
## Native Transfer (Bridge Contract)
Instant Deposits7-Day WithdrawalsNo Fees
Send Base ETH through the bridge contract. Transfer **Base ETH** to the following bridge address on **Base Mainnet**:
This method is for advanced users only. Make sure you're sending from Base Mainnet to avoid losing funds.
```text Bridge Address theme={null}
0x769547a723783FCA36BAaf1ECcf9dfdbF6d09F38
```
When you send ETH to this address from Base, it will automatically appear in your wallet on B3. This is a direct contract interaction method.
1. **Ensure you're on Base Mainnet** in your wallet
2. **Send ETH** to the bridge contract address above
3. **Wait for confirmation** - your funds will appear on B3 automatically
4. **Check your B3 wallet** - switch to B3 network to see your bridged ETH
Double-check you're on Base Mainnet before sending. Sending from other networks may result in lost funds.
# Bridge to B3 Testnet
Source: https://docs.b3.fun/protocol/bridge-to-testnet
Easily bridge from Base Sepolia (Base Testnet) to B3 Sepolia (B3 Testnet) by following the steps below!
This bridge is specifically for testnet purposes. Use free testnet ETH to test your applications before deploying to mainnet.
## How to Bridge
Go to [testnet.bridge.b3.fun](https://testnet.bridge.b3.fun) to access the official testnet bridge interface.
Connect your wallet (MetaMask, Coinbase Wallet, etc.) to the bridge interface.
Make sure your wallet is connected to either Base Sepolia or B3 Testnet depending on which direction you want to bridge.
Select whether you want to:
* **Deposit**: Bring funds from Base Sepolia → B3 Testnet
* **Withdraw**: Bridge back from B3 Testnet → Base Sepolia
Click either the **Deposit** or **Withdraw** tabs accordingly.
Enter the amount of ETH you want to bridge.
If you need Base Sepolia ETH, use a Base Sepolia faucet to get free testnet tokens
Click "Deposit" (or "Withdraw") and confirm the transaction prompt that appears in your wallet.
Double-check that you're on the correct testnet and using testnet ETH, not mainnet funds.
Wait a few minutes for the bridge process to complete. You can check the status in your "History" tab.
Your testnet ETH will appear in your wallet on the destination network within a few minutes.
## Network Information
**Chain ID**: 84532\
**RPC**: [https://sepolia.base.org](https://sepolia.base.org)\
**Explorer**: [https://sepolia.basescan.org](https://sepolia.basescan.org)
**Chain ID**: 1993\
**RPC**: [https://testnet-rpc.b3.fun](https://testnet-rpc.b3.fun)\
**Explorer**: [https://testnet-explorer.b3.fun](https://testnet-explorer.b3.fun)
## Testnet Resources
Official bridge for moving assets between Base Sepolia and B3 Testnet
Get free B3 testnet ETH for development and testing
## Additional Faucets
If you need testnet ETH for development, here are some reliable faucet options:
* [Coinbase Base Faucet](https://coinbase.com/faucets/base-ethereum-sepolia-faucet) - Official Coinbase faucet
* [Alchemy Base Sepolia Faucet](https://sepoliafaucet.com) - Reliable faucet for Base Sepolia ETH
* [QuickNode Base Faucet](https://faucet.quicknode.com/base/sepolia) - Multiple testnet support
* [B3 Testnet Faucet](https://testnet-faucet.b3.fun) - Official B3 testnet faucet
* Get free B3 testnet ETH directly without bridging
## Troubleshooting
* Check the transaction status on the block explorer
* Verify you're connected to the correct testnet
* Try increasing gas fees if the transaction is pending
* Contact support if the bridge has been pending for over 30 minutes
* Ensure your wallet supports the testnet networks
* Try refreshing the page and reconnecting
* Check that you're on the correct network in your wallet
* Clear your browser cache if issues persist
* Make sure you have enough ETH to pay for gas fees
* Use a faucet to get more testnet ETH
* Try bridging a smaller amount to conserve gas
## Development Workflow
Use a Base Sepolia faucet to get free testnet ETH.
Use the testnet bridge to move ETH from Base Sepolia to B3 Testnet.
Deploy your contracts and test your applications on B3 Testnet.
When testing is complete, deploy to B3 Mainnet using the [mainnet bridge](/protocol/bridge).
# Bylaws
Source: https://docs.b3.fun/protocol/bylaws
As adopted by the Player1 Foundation on February 10, 2025
## 1. Mission
The mission of the Foundation is to foster, develop, authorize and/or govern the B3 Protocol. This includes but is not limited to:
* Enabling the development of technical improvements and feature development to maintain and increase B3 capabilities to provide low cost, high throughput gaming chain scaling solutions with best-in-class user experience.
* Fostering ecosystem growth through strategic grants to align with partner projects including, but not limited to, infrastructure providers, application developers, artists, creators, brand partnerships, creative studios, and strategic growth partners.
* Organizing educational initiatives and both participating in and hosting events to increase awareness of and promote B3 technology and ecosystem.
## 2. Defined Terms
The account that contains Foundation assets (as well as other assets contributed to or acquired by the Administrative Budget Wallet), which will be utilized by the Foundation for purposes of operational and administrative costs as well as B3 ecosystem growth.
Collectively, the decentralised community of individuals that own a Token, as evidenced by the Base or B3 chains.
The Constitution of the B3 DAO as available at [https://docs.b3.fun/constitution](https://docs.b3.fun/constitution), including any amendments thereto.
A proposal put forth by a Tokenholder to a vote in accordance with the B3IP Process.
The rules and procedures of submitting and voting on B3IPs as described in the B3 DAO Constitution, in particular "Section 2: DAO Proposals and Voting Procedures", as may be amended from time to time pursuant to an B3IP.
The B3 technology suite, including the B3 chain, and any additional chains utilizing such technology.
These governing bylaws of the Foundation as may be amended from time to time.
The rules, regulations and laws of the Cayman Islands as may be amended from time to time.
"Decentralised autonomous organisation."
Has the meaning given in Section 3(b)(iv) of these Bylaws.
Player1 Foundation, a Cayman Islands foundation company.
The Memorandum and Articles of Association (as may be amended, revised and substituted from time to time).
The director(s) of the Foundation, which have certain powers and duties pursuant to Cayman Islands Law and as further described in the Foundation Articles and the Bylaws.
The supervisor of the Foundation, which has certain powers and duties pursuant to Cayman Islands Law and as further described in the Foundation Articles.
The council formed in accordance with the B3 DAO Constitution. The Security Council is a multi-member committee which has been delegated the authority by the Foundation to engage in Emergency Actions and Non-Emergency Actions as described in the B3 DAO Constitution, and is otherwise tasked with ensuring that B3IPs are in compliance with the B3 DAO Constitution.
The governing token of the B3 DAO, known as \$B3, represented on the Base and B3 chains.
Any holder of a Token.
## 3. Voting Matters
### 3.1 Tokenholder Authority
Pursuant to the B3 DAO Constitution, the Foundation Articles, and these Bylaws, the Tokenholders may approve Constitutional B3IPs and Non-Constitutional B3IPs (each as defined in the B3 DAO Constitution) in order to:
**(i)** modify the text or procedures of the B3 DAO Constitution;
**(ii)** install or modify the software on the B3 Protocol;
**(iii)** approve funding requests from the DAO Treasury (as defined in the B3 DAO Constitution);
**(iv)** appoint and remove members of the Security Council in accordance with the B3 DAO Constitution; and
**(v)** approve any other action in accordance with the B3 DAO Constitution, the Foundation Articles and these Bylaws.
### 3.2 Foundation Director Authority
The Foundation Director(s) shall engage in any activity which, in their reasonable discretion, does not contradict the terms set forth in any B3IP approved by Tokenholders, the B3 DAO Constitution, these Bylaws, or the Foundation Articles, including but not limited to the following actions:
**(i)** approve transactions from the Administrative Budget Wallet;
**(ii)** coordinate emergency operations with the Security Council on behalf of the B3 DAO or the Foundation;
**(iii)** make changes to these Bylaws if the Foundation Directors believe such changes would improve the Foundation Directors' ability to fulfill their obligations (the "**Amendment Authority**"); and
**(iv)** call and hold emergency meetings ("**Emergency Meetings**") to enable the Foundation Directors and the Security Council to rapidly respond to an imminent security threat to the B3 DAO, any protocol utilizing the Token, the Tokenholders, or the Foundation, and the same rules that apply to Foundation Directors meeting in accordance with the Foundation Articles will apply to Emergency Meetings, except that there is no quorum requirement for an Emergency Meeting.
## 4. Proposal Phases, Requirements and Structure
### 4.1 B3 DAO Constitution Application
The provisions set out in Section 2 of the B3 DAO Constitution shall apply.
### 4.2 Foundation Director Rejection
If, following the approval of a B3IP by the B3 DAO, a majority of the Foundation Director(s) acting in the best interests of the Foundation reasonably determine that such B3IP, if implemented, would:
**(A)** compromise the Foundation Director(s)' fiduciary duties as they are owed to the Foundation;
**(B)** be in violation of these Bylaws, the Foundation Articles, the B3 DAO Constitution, the B3IP Process, any statutory requirements of Cayman Islands Laws or the laws or regulations of any other applicable jurisdiction;
**(C)** cause the Foundation to be in breach of any contracts, agreements or any other arrangements; and/or
**(D)** be against the best interests of the Foundation,
such Foundation Director(s) may notify the Security Council of their obligations under the B3 DAO Constitution to undertake an Emergency or Non-Emergency Action, or take such other steps as are required to reject such B3IP.
## 5. Relationship between the Foundation and the Tokenholders
### 5.1 Representation
The Tokenholders are represented by the Foundation, which represents the Tokenholders' interests in connection with contractual and legal processes, including regulatory compliance and those other matters set forth in the Foundation Articles.
### 5.2 Service Providers
The Foundation has engaged with certain third parties to provide services as the Foundation Director(s) and Foundation Supervisor, as required by Cayman Islands Law. In accordance with the terms of the Foundation Articles and these Bylaws, and subject to Cayman Islands Law, the Foundation Director(s) and Foundation Supervisor are required to act at the direction of the Tokenholders in respect of certain matters.
### 5.3 Resources and Authority
The Tokenholders shall ensure that the Foundation has sufficient authority and resources, including funding, to execute upon the Foundation's mandate, meet the Foundation's obligations under applicable law, and satisfy the Foundation's contractual obligations entered into in accordance with the Foundation Articles or these Bylaws.
### 5.4 Director Authority
The Foundation's Directors are authorised to take any actions reasonably necessary on behalf of the Foundation to give effect to a vote of the Tokenholders including passing any director resolutions to memorialise such vote.
### 5.5 Conflicts and Fiduciary Duties
To the extent there is ever a conflict between the provisions of the Bylaws and the Foundation Articles, the Foundation Articles will prevail.
Foundation Directors are not fiduciaries for the Tokenholders.
## 6. Dispute Resolution
### 6.1 Notice Requirements
Should a controversy, dispute or claim arise out of or in relation to these Bylaws ("**Dispute**"), the Foundation, the Directors, the Supervisor or the Tokenholders (as appropriate) must give **30 days' notice** of such Dispute to the relevant party/ies (the "**Notice of Dispute**"). Should the Dispute not be resolved at the expiration of 30 days after service of the Notice of Dispute, the relevant party may commence arbitration proceedings in accordance with 6(b) below.
In any dispute involving the actions of the Foundation Directors or the Supervisor, the Foundation, and not the Foundation Directors or Supervisor, shall be party to the arbitration proceedings. In any dispute involving the actions of the Directors, the Supervisor may commence arbitration proceedings against the Directors in accordance with Section 6(b) below.
### 6.2 Arbitration Process
Should the Dispute remain at the expiration of 30 days after service of the Notice of Dispute, the Dispute shall be settled by arbitration administered by the **Cayman International Mediation and Arbitration Centre ("CI-MAC")** in accordance with the CI-MAC Arbitration Rules (the "**Arbitration Rules**") in force as at the date of these Bylaws, which Arbitration Rules are deemed to be incorporated by reference to these Bylaws, and governed by the Arbitration Act (as amended) of the Cayman Islands.
* **Arbitrator**: All disputes shall be heard by a single arbitrator to be appointed in accordance with the Arbitration Rules
* **Governing Law**: The law of the arbitration shall be the law of the Cayman Islands
* **Language**: The language of the arbitration shall be English
* **Seat**: The arbitration shall be seated in George Town, Grand Cayman, Cayman Islands
The arbitration shall be commenced following the expiration of 30 days after service of the Notice of Dispute and the aggrieved party's notification to the other of the particulars of the controversy or claim along with the aggrieved party's proposed arbitrator obtained from a list of potential arbitrators maintained by CI-MAC.
Where the notified party does not agree with the choice of arbitrator or if no agreement on the choice of arbitrator can be reached within thirty (30) days, then an arbitrator will be one chosen by CI-MAC having reasonable experience in transactions of the type provided for in these Bylaws.
* **Award Timeline**: The arbitrator shall render the award within **three (3) months** of the commencement of the arbitration, unless such time limit is extended by the arbitrator
* **Cost Allocation**: Prior to the issue or delivery of arbitral award, each party will bear its own costs in respect the arbitration, following which the prevailing party shall be entitled to reasonable attorney's fees, costs, and necessary disbursements in addition to any other relief to which such party may be entitled
An award by the arbitrator shall be **final and conclusive and binding** upon the parties and shall not be subject to further appeal. Each party may enforce any award granted in accordance with this Section 6 in any court of competent jurisdiction.
The arbitrator shall be required to provide in writing to the parties the basis for the award or order of such arbitrator, and all hearings shall be recorded, with such record constituting the official transcript of such proceedings.
No action at law or in equity based upon any claim arising out of or related to these Bylaws shall be instituted in any court of any jurisdiction. Each party waives any right it may have to assert the doctrine of *forum non conveniens*, to assert that it is not subject to the jurisdiction of such arbitration or courts or to object to venue to the extent any proceeding is brought in accordance herewith.
# Constitution
Source: https://docs.b3.fun/protocol/constitution
Decision-making framework for the B3 DAO governance
This document lays out the Constitution of the B3 DAO (the "**Constitution**").
Some of the rules and procedures of this Constitution will be enforced directly by smart contracts on a blockchain, and some will not. Actions taken under this Constitution may be on-chain or off-chain actions. On-chain actions are those that are actuated directly by the governance smart contracts of the DAO as transactions on a blockchain. Off-chain actions are those that are actuated by other means.
This Constitution also includes some "recommended guidelines" which are non-binding but strongly recommended as good governance practice.
This Constitution describes the procedures by which it may be amended and lays out the governance framework of the B3 DAO and the Player1 Foundation.
## Definitions
A proposal put forth by a Tokenholder to a vote in accordance with the B3IP Process.
The rules and procedures of submitting and voting on B3IPs as described in this Constitution, in particular "Section 2: DAO Proposals and Voting Procedures", as may be amended from time to time pursuant to a B3IP.
The decentralized community of individuals that own a Token, as evidenced by the Base or B3 chains.
Player1 Foundation property held in a governance smart contract on Base governed directly by the Tokenholders and the Security Council via onchain voting mechanisms, as entrusted by the Player1 Foundation.
The governing token of the B3 DAO, known as \$B3, as represented on the Base or B3 chains.
Any holder of a Token.
All Tokens in existence (i.e. 100,000,000,000 \$B3 tokens).
## Section 1: Chain "administration"
This Constitution describes the decision-making framework for the B3 DAO governance.
The B3 Protocol has two sets of chain "administrators" who have the power to take administrative actions that change the B3 core protocol and code and/or alter any of its core parameters. With the \$B3 token generation event and subsequent creation of the B3 DAO having occurred, Player1 Foundation has entrusted "administrator" privileges on B3 to both the Tokenholders and the Security Council of the B3 Protocol. In the event that a B3IP may violate any applicable law or this Constitution (as determined by the Player1 Foundation), the Player1 Foundation may notify the Security Council of its obligation to prevent such B3IP from going into effect.
The "administrator" will also have the power to upgrade certain associated Layer 2 contracts. The "administrator" will control affordances on the chain such as updating the contract implementation of any of B3's core protocol contracts, and adjusting system parameters via, e.g., setter methods in the B3 Administrator precompile.
## Section 2: DAO Proposals and Voting Procedures
The following process governs the rules and procedures by which the B3 DAO may propose, vote on and implement B3IPs. No B3IP may be in violation of applicable laws, in particular sanctions-related regulations.
### B3IP Process Phases
The B3IP is suggested on the public forum and discussed/debated for 1 week. The B3IP should be accompanied by a poll or other method as determined pursuant to the governance process. This Phase 1 should last for a period of 1 week to allow sufficient discussion and feedback. In the event that a B3IP skips this phase, as a matter of good governance practice, it is recommended that voters consider voting to reject it.
The B3IP is submitted via governance contracts on Base, with a user interface available on Agora. The B3IP proposer is required to have an address that is delegated at least **30,000,000 Votable Tokens**.
After 3 days, a voter distribution snapshot will be taken and the voting period will begin; this gives interested parties time to discuss the B3IP and gather votes before the voter distribution snapshot is taken.
Each B3IP must be labeled as Constitutional or Non-Constitutional.
During this Phase 3, the B3 DAO will be able to vote directly on-chain through Base. A successful vote requires:
**Constitutional B3IPs:**
* Proposals pass if they reach **5%** of all Votable Tokens voting "yes" (approval quorum)
* At least **55%** of votes cast are "yes" votes (approval threshold)
**Non-Constitutional B3IPs:**
* Proposals pass if they reach **3%** of all Votable Tokens voting "yes" (approval quorum)
* At least **50%** of votes cast are "yes" votes (approval threshold)
After a B3IP has passed in Phase 3, there will be a 3 day waiting period before the B3IP may be executed. This delay is intended to provide all Tokenholders the opportunity to exit the protocol if they are not happy with a governance outcome but were not previously aware of the vote or otherwise inadvertently missed during the prior phases.
Except in the case of a Non-Constitutional B3IP involving the DAO Treasury (which lives on Base), after the 3 day waiting period in Phase 4 has passed, a cross-chain governor message is sent to B3 from Base, after which a B3-to-Base message is sent indicating that the B3IP was passed. The rationale behind the cross-chain message from Base to B3 is that while voting occurs on Base, the Constitutional B3IP is effectuated on B3. When this message is finalized on Base, anyone can redeem it to complete this step and initiate the next step. This step ensures that the completion of the B3 waiting period will be recognized on Base after any withdrawals initiated during or soon after the voting period have been recognized on Base.
Following the completion of Phase 5, there will be an additional 7 day waiting period. This ensures that users who initiated withdrawals or other B3-to-Base messages have time to execute them on Base before the B3IP takes effect.
The B3IP is fully executed and implemented. This may happen on B3 or via a transaction sent from B3 to Base. In the case of a Non-Constitutional B3IP involving the DAO Treasury, execution and implementation will occur directly on Base.
This B3IP process as specified will typically require **37 days** from the beginning of the temperature check in Phase 1 until a B3IP is finally executed in Phase 7 for a Constitutional B3IP, or **27 days** for a Non-Constitutional B3IP. A B3IP may optionally specify further delay before its implementation.
### B3IP Types
**A Constitutional B3IP** is one that relates to:
* **Process**: Modifies the text or procedures of this Constitution
* **Software update**: Installs or modifies software on B3
* **Core**: Takes any action that requires "administrator" permission on B3
**A Non-Constitutional B3IP** is one that is not considered a "Constitutional B3IP" including:
* **Funding**: Requests funds/grants or otherwise proposes how to spend or allocate funds from the DAO Treasury. There are four types of Funding B3IPs:
* **Ecosystem Development**: A B3IP allocating DAO Treasury funds to support game developers, community initiatives or marketing campaigns to drive adoption of the B3 Protocol
* **Grant Programs**: A B3IP designing and approving funding mechanisms for developers or other contributors building on the B3 Protocol
* **Game Publishing and Promotions**: A B3IP determining games to onboard onto the B3 Protocol publisher stack or promote on platforms
* **Strategic Partnerships**: A B3IP approving collaborations with external organizations to expand the reach and utility of the B3 Protocol
* **Informational**: Provides general guidelines or information to the community but does not otherwise propose a new feature or update
### Recommended Guidelines
* DAO members should vote against any B3IP that is incorrectly labeled.
A B3IP should include:
* **Abstract**: Two or three sentences that summarize the B3IP
* **Motivation**: A statement on why the B3 DAO should implement the B3IP
* **Rationale**: An explanation of how the B3IP aligns with the B3 DAO's mission and values
* **Key Terms (optional)**: Definitions of any terms within the proposal that are unique to the proposal, new to the B3 DAO, and/or industry-specific
* **Specifications**: A detailed breakdown of the platforms and technologies that will be used
* **Risks and Security**: A detailed breakdown of the potential security, technical, legal, reputational and other applicable risks
* **Steps to Implement**: The steps to implement the B3IP, including associated costs, manpower, and other resources for each step where applicable. For the avoidance of doubt, any B3IPs involving transactions with third parties (such as grants) will need to ensure that applicable legal documentation and procedures are also included
* **Timeline**: Relevant timing details, including but not limited to start date, milestones, and completion dates
* **Overall Cost**: The total cost to implement the B3IP
* The B3IP author can add additional fields to any template if necessary to fully communicate the intentions, specifics and implications of the B3IP
Resubmitted B3IPs should also include:
* A link to the original B3IP
* Reasons such original B3IP was not approved
* Changes that have been made and why it should now be approved
* Any additional fields to any template if necessary to fully communicate the changes made and the intentions, specifics and implications of such resubmitted B3IP
## Section 3: The Security Council
The Security Council is a committee of **5 members who are signers of a multi-sig wallet**, which has powers to perform certain Emergency Actions and Non-Emergency Actions, as delegated to it by Player1 Foundation, and is responsible for upholding this B3 DAO Constitution. Through the submission, approval and implementation of a Constitutional B3IP, the B3 DAO is able to modify the Security Council's powers or to eliminate the Security Council entirely.
Equivalent "copies" of the Security Council multi-sig contracts exist, one on Base and another on B3.
### Emergency Actions
The Security Council has the power to execute any software upgrade or perform other required actions with no delay in order to respond to a security emergency, should one arise (such actions, "**Emergency Actions**"). Performing any Emergency Action requires a **4-of-5 approval** from the Security Council. The Security Council must not use its power to perform Emergency Actions except in a true security emergency, such as a critical vulnerability that could significantly compromise the integrity, confidentiality, or availability of B3.
After performing any Emergency Action, the Security Council must issue a full transparency report (at an appropriate time after the security emergency has passed) to explain what was done and why such Emergency Action was justified.
The B3 DAO is able to curtail or eliminate the Security Council's power to perform Emergency Actions via approval and implementation of a Constitutional B3IP.
### Non-Emergency Actions
The Security Council may also approve and implement routine software upgrades, routine maintenance and other parameter adjustments in a non-emergency setting (such actions, "**Non-Emergency Actions**"), which require a **3-of-5** approval in order to take effect. Any Non-Emergency Action, after approval by the Security Council, will bypass Phases 1 to 3 of the B3IP process and instead directly go through Phases 4 to 7 of the B3IP process (as applicable), to provide a delay before any Non-Emergency Action is deployed. The Security Council may optionally specify additional delays before deployment.
The B3 DAO is able to curtail or eliminate the Security Council's power to perform Non-Emergency Actions via approval and implementation of a Constitutional B3IP.
## Section 4: Security Council Elections
The Security Council has **5 members**, who are divided into two Cohorts of 2 to 3 members, who serve **18-month terms**. The 'Second Cohort' will serve a **24-month term** given the staggered elections but all future Cohorts going forward will serve 18-month terms.
The initial Security Council Cohorts were determined by randomly splitting the 5 members into two cohorts – 2 members in the 'First Cohort' and 3 members in the 'Second Cohort'. The members of the initial Security Council Cohorts are detailed in a transparency report here.
The first Security Council election process is scheduled to begin on the **15th of June 2026** or the earliest possible date. This first election replaces the 'First Cohort'. The next election replaces the 'Second Cohort' and so forth.
The date chosen for the first election will form the basis for all future elections.
All Security Council members are expected to serve their term until the election is complete and the new Security Council members are installed.
### Election Timeline
The following timeline governs an election that starts at time T:
Any DAO member may declare their candidacy for the Security Council, provided that a current Security Council member in one cohort may not be a candidate for a seat in the other cohort.
Each DAO member or delegate may vote for their declared contender. Each token may be cast for one contender. To the extent that there are more than six contenders, each eligible contender must be supported by pledged votes representing at least **0.2%** of all Votable Tokens.
All candidates will cooperate with Player1 Foundation and complete the compliance process. Player1 Foundation is responsible for removing any candidates that fail the compliance process. In the event that fewer than 2 or 3 (as applicable) candidates are supported by pledged votes representing at least 0.2% of all Votable Tokens, the current Security Council members whose seats are up for election may become candidates (as randomly selected out of their Cohort) until there are 2 or 3 (as applicable) candidates.
Each DAO member or delegate may vote for any declared candidate. Each token may be cast for one candidate.
The process for replacing the cohort of Security Council members with the 2 or 3 (as applicable) candidates who received the most votes will be activated. It may take several days until the new Security Council members are installed.
Player1 Foundation is allocated 14 days for the Compliance process and it should be executed between the Nominee selection and Member election. Player1 Foundation has flexibility to update its compliance policy for every new election. Furthermore, Player1 Foundation maintains the right to issue new procedures and guidelines for off-chain components of the Security Council election. All efforts should be made by Player1 Foundation to ensure an orderly, fair, and transparent election.
### Best Practices and Guidelines
As a matter of best practice for maintaining an independent Security Council, no single organization should be overly represented in the Security Council. In particular, there should not be more than 1 candidate associated with a single entity or group of entities being elected to the Security Council, thereby ensuring that there will be no single entity or group of entities able to control or even veto a Security Council vote.
Furthermore, no candidate with conflicts of interest that would prevent them from acting in the best interests of the B3 DAO, B3 Protocol and/or Player1 Foundation should be elected to the Security Council. Potential conflicts of interest could be, but are not limited to, affiliations with direct B3 competitors, proven histories of exploiting projects and others.
The DAO may approve and implement a Constitutional B3IP to change the rules governing future Security Council elections, but the B3IP process may not be used to intervene in an ongoing election.
Security Council members may only be removed prior to the end of their terms if at least **3 of the Security Council members** vote in favor of removal.
The seats of Security Council members who have been removed prior to the end of their respective terms shall remain unfilled until the next election that such seats are up for appointment, unless otherwise replaced prior to such next election by a vote of at least 3 of the Security Council members, in which case such seat shall be up for appointment at the next such election. The Security Council may not re-appoint a removed member and they can only be re-elected via the election voting system.
# Governance Platforms
Source: https://docs.b3.fun/protocol/governance-platforms
Official channels for B3 Governance
**[https://gov.b3.fun](https://gov.b3.fun)**, powered by Agora
**[https://forum.b3.fun](https://forum.b3.fun)**
**[https://discord.gg/b3dotfun](https://discord.gg/b3dotfun)**
## Caution
Stay safe! Only use the official links listed above. Be aware that scammers may try to impersonate B3 team members or delegates. Remember:
* Never share your seed phrase or private keys
* Never give out personal information
* The real B3 team will never DM you first
* When in doubt, visit our Discord and ask the community
We're here to help - join our Discord server if you have any questions or concerns!
# Cross-Chain Liquidity
Source: https://docs.b3.fun/protocol/liquidity
How AnySpend (built by B3) abstracts execution layers to provide unified access to liquidity across all blockchain networks
[Explore B3's multichain ecosystem on explorer.b3.fun](https://explorer.b3.fun/chains)
## The Problem
Appchains, L2s, and L3s have isolated liquidity, making it annoying to build experiences without having to bridge assets across chains.
Each chain maintains isolated pools, limiting depth and increasing slippage.
Builders must integrate with dozens of chains individually.
Users manually bridge assets and manage multiple wallets.
Assets locked on specific chains can't access other opportunities.
## Access Liquidity Across Chains
Powered by our product, AnySpend, operates at the client execution layer, sitting between user intent and blockchain execution:
### How It Works
1. **Deposit from any chain**: Accepts tokens from most chains
2. **Intent-Based**: Users express what they want, not how to achieve it
3. **Route Discovery**: Finds optimal paths across all supported chains
4. **Atomic Execution**: Transactions execute atomically or fail gracefully
5. **Unified Experience**: Complex operations appear as single transactions
```mermaid theme={null}
flowchart TD
A[User Intent] --> B[Deposit from Any Chain]
B --> C{AnySpend Processing}
C --> D[Route Discovery]
D --> E[Find Optimal Path]
E --> F[Atomic Execution]
F --> G[Success?]
G -->|Yes| H[Unified Transaction Complete]
G -->|No| I[Graceful Failure & Rollback]
B --> B1[Ethereum]
B --> B2[Solana]
B --> B3[Polygon]
B --> B4[Arbitrum]
B --> B5[Base]
B --> B6[B3 & Game Chains]
H --> J[Assets Available on Target Chain]
I --> K[Original Assets Returned]
style A fill:#e1f5fe
style C fill:#f3e5f5
style H fill:#e8f5e8
style I fill:#ffebee
```
### Supported Chains
AnySpend provides universal chain support:
* **EVM Chains**: Most EVM chains, including Ethereum, Polygon, Arbitrum, Base, BSC, Avalanche
* **Solana**: Full integration with Solana's ecosystem
* **B3 Ecosystem**: Native integration with B3 and game chains
## Next Steps
Get started with the AnySpend SDK.
Learn how to integrate AnySpend.
Explore the complete API documentation.
Connect with other builders.
# Connect to B3
Source: https://docs.b3.fun/protocol/network-setup
B3 is fully EVM-compatible network of chains. Easily connect to B3 with your wallet.
## Using B3 with Your Wallet
It's easy to connect with any Ethereum wallet including MetaMask, Coinbase Wallet, Rainbow, and more.
These buttons work with MetaMask and other Web3 wallets. They'll automatically add the network configuration or switch to B3 if it's already added.
Using B3 Explorer Recommended
Use Chainlist to add B3 to your wallet
The fastest way to add B3 to your wallet:
Go to [explorer.b3.fun](https://explorer.b3.fun/add-b3-chain) and click "Add B3 Chain"
Connect your wallet (MetaMask, Coinbase Wallet, etc.)
Click "Add to Wallet" for B3 Mainnet
B3 will be automatically added to your wallet with the correct configuration
The fastest way to add B3 to your wallet:
Go to [chainlist.org](https://chainlist.org/chain/8333) and search for "B3"
Connect your wallet (MetaMask, Coinbase Wallet, etc.)
Click "Add to Wallet" for B3 Mainnet
B3 will be automatically added to your wallet with the correct configuration
If you prefer to add B3 manually, use the network details below:
Network Details: [B3 Mainnet configuration](#b3-mainnet-configuration)Network Details: [B3 Testnet configuration](#b3-testnet-configuration)
## Wallet-Specific Instructions
### MetaMask
Click the MetaMask extension in your browser
Click the network dropdown at the top and select "Add network"Click "Add a network manually" at the bottom
Fill in the B3 network information
See the complete [B3 Mainnet configuration](#b3-mainnet-configuration)
Click "Save" and MetaMask will automatically switch to B3
You're now connected to B3! You'll see "B3 Mainnet" in your network dropdown.
### Coinbase Wallet
Launch the Coinbase Wallet browser extension
Go to the **Settings** tab and click **Networks**Click the plus sign (➕) in the top right to **Add custom network**
In the **Add custom network** dialog, enter the B3 mainnet information:
See the complete [B3 Mainnet configuration](#b3-mainnet-configuration) for copyable values
Click "Save" to add B3 to your available networks
Coinbase Wallet will automatically detect that the native token is ETH
### Rainbow Wallet
Launch Rainbow wallet on your mobile device or browser extension
Tap the profile icon and go to Settings → Networks
Tap "Add Custom Network" and enter B3 details
See the complete [B3 Mainnet configuration](#b3-mainnet-configuration) for copyable values
Save the configuration and switch to B3 Mainnet
## B3 Mainnet Configuration
Complete configuration details for B3 Mainnet:
**Network Name:**
```
B3 Mainnet
```
**Chain ID:**
```
8333
```
**RPC URL:**
```
https://mainnet-rpc.b3.fun
```
**Explorer URL:**
```
https://explorer.b3.fun
```
**Native Token:**
```
Symbol: ETH
Decimals: 18
```
## B3 Testnet Configuration
Complete configuration details for B3 Testnet:
**Network Name:**
```
B3 Testnet
```
**Chain ID:**
```
1993
```
**RPC URL:**
```
https://testnet-rpc.b3.fun
```
**Explorer URL:**
```
https://testnet-explorer.b3.fun
```
**Native Token:**
```
Symbol: ETH
Decimals: 18
```
## Troubleshooting
* Double-check the Chain ID (8333 for mainnet)
* Ensure the RPC URL is correct: `https://mainnet-rpc.b3.fun`
* Try refreshing your wallet or restarting the browser
* Verify you're connected to the correct B3 network - Check that you have sufficient ETH for gas fees - Ensure the
contract address is valid on B3
* B3 typically processes transactions in 1-2 seconds - If experiencing delays, check the [B3 network status](https://docs.b3.fun/network-status) - Consider adjusting gas price if needed
* Import token contracts manually using the B3 Explorer
* Ensure you're viewing the correct network in your wallet
* Some tokens may need to be manually added to your wallet's token list
***
Always verify that users are connected to the correct B3 network before executing transactions. The Chain ID for B3
Mainnet is 8333.
**Ready to start building on B3?** Your wallet is now configured! Check out our [SDK documentation](/quickstart) to
begin integrating B3 into your application.
# Horizontally Scaling AppChains
Source: https://docs.b3.fun/protocol/scaling
B3 enables horizontal scaling through purpose-built appchains, each optimized for specific use cases while maintaining unified liquidity and user experience.
[Explore B3's multichain ecosystem on explorer.b3.fun](https://explorer.b3.fun/chains)
## The Scaling Revolution
Traditional blockchain scaling has focused on making single chains faster. B3 takes a different approach: **horizontal scaling** through purpose-built appchains that work together as a unified ecosystem.
Making one chain handle more transactions per second
Creating specialized chains for specific applications
## Why Horizontal Scaling Matters
Rather than forcing all applications to compete for the same blockchain resources, horizontal scaling allows each app, game, or enterprise to have their own optimized execution environment.
### The Multi-Chain Advantage
Each appchain can be customized for its specific use case - gaming chains for zero-fee gameplay, DeFi chains for high-throughput trading.
No more competing for block space. Each application gets dedicated resources and can scale independently.
Problems on one appchain don't affect others, providing better security and reliability for the entire ecosystem.
Despite being separate chains, users experience seamless interactions across the entire B3 ecosystem.
## How B3 Enables Horizontal Scaling
### 1. Purpose-Built Appchains
Every application on B3 can deploy its own dedicated chain, optimized for specific requirements:
* **Gaming Chains**: Zero-fee transactions, instant finality, gaming-specific precompiles
* **DeFi Chains**: High-throughput trading, MEV protection, financial primitives
* **Enterprise Chains**: Privacy features, compliance tools, custom governance
* **Social Chains**: Content storage, reputation systems, social graphs
### 2. Unified Liquidity Layer
While chains scale horizontally, liquidity remains unified through [AnySpend](/protocol/liquidity):
```mermaid theme={null}
graph TB
A[User Intent] --> B[AnySpend Router]
B --> C[Gaming Chain]
B --> D[DeFi Chain]
B --> E[Enterprise Chain]
B --> F[Social Chain]
C --> G[Unified Liquidity Pool]
D --> G
E --> G
F --> G
```
### 3. Seamless Cross-Chain Operations
Users simply express what they want to do - buy an NFT, swap tokens, or make a payment.
B3's infrastructure automatically finds the optimal path across all appchains.
Complex multi-chain operations execute as a single transaction from the user's perspective.
## Real-World Benefits
### For Developers
Deploy your own chain and never worry about network congestion affecting your users.
Design token economics, fee structures, and incentives specific to your application.
Experiment with new features without affecting other applications or waiting for network upgrades.
Optimize transaction costs, confirmation times, and user flows for your specific use case.
### For Users
Access all applications with the same wallet and account across the entire ecosystem.
Benefit from optimized fee structures on each specialized chain.
Experience near-instant confirmations on chains optimized for your use case.
Enjoy the security of Ethereum settlement while benefiting from specialized chain features.
## Scaling in Practice
[Access merged data across B3 multi-chains with our free API](/data/api-reference/introduction).
### Gaming at Scale
Gaming chains on B3 can handle:
* **Free-to-play mechanics** with zero transaction costs
* **Real-time interactions** with sub-second finality
* **Massive multiplayer events** without network congestion
* **Cross-game asset transfers** through unified liquidity
### Enterprise Applications
Enterprise chains enable:
* **Private transactions** for sensitive business operations
* **Compliance features** built into the protocol layer
* **Custom governance** models for organizational needs
* **Integration capabilities** with existing business systems
### DeFi Innovation
DeFi chains support:
* **High-frequency trading** with optimized throughput
* **Complex financial instruments** with specialized precompiles
* **MEV protection** through custom ordering mechanisms
* **Cross-chain arbitrage** through unified liquidity access
## The Network Effect
As more applications deploy their own appchains, the entire B3 ecosystem becomes more valuable:
1. **Increased Liquidity**: More chains mean more trading opportunities and deeper liquidity pools
2. **Enhanced Composability**: Applications can interact across chains seamlessly
3. **Reduced Costs**: Shared infrastructure costs decrease as the ecosystem grows
4. **Innovation Acceleration**: New features on one chain can be adopted by others
## Getting Started with Horizontal Scaling
Ready to scale horizontally? Contact our team to discuss deploying your own purpose-built appchain on B3.
[Access merged data across B3 multi-chains with our free API](/data/api-reference/introduction).
[Build on B3 with our developer tools](/ecosystem/introduction).
### Choose Your Scaling Strategy
Start building on the main B3 chain before scaling to your own appchain.
Deploy a custom chain optimized for your specific application needs.
Use the main chain for core functions and appchains for specialized features.
## The Future of Scaling
Horizontal scaling represents the next evolution of blockchain infrastructure. By enabling unlimited parallel execution while maintaining unified user experience and liquidity, B3 creates the foundation for truly massive onchain adoption.
The internet didn't scale by making single servers faster—it scaled by connecting millions of specialized servers. Similarly, blockchain will scale by connecting thousands of purpose-built chains, each optimized for specific applications while working together as a unified ecosystem.
# Staking $B3
Source: https://docs.b3.fun/protocol/staking-b3
Reinventing staking. Sweepstakes style, not boring fixed yeild - use your $B3 to secure your stake in chance based games, where you can win big.
Stake your \$B3 tokens in our staking arena.
## Why Stake?
Stake your B3 to play Stake to Win games, where you can win big prizes while earning \$B3 yield and exclusive rewards.
Participate in sweepstakes and win big prizes instead of boring yield.
Contribute to B3's security and decentralization.
Tokens holders can participate in governance for the B3 network.
Actively participate as a staker, and have fun.
```text Contract Address theme={null}
0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3
```
Copy this address to add \$B3 to your wallet or trade on DEXs.
### Where to buy \$B3 tokens
Buy \$B3 on Coinbase
Trade \$B3 on Bybit
Purchase \$B3 on Gate.io
Get \$B3 on KuCoin
Trade \$B3 on MEXC
Swap \$B3 on Aerodrome
Trade \$B3 on AlienBase
# Testnet
Source: https://docs.b3.fun/protocol/testnet
Connect to B3 testnet with any EVM-compatible wallet
## Chain Information
```text theme={null}
1993
```
Fun fact: 1993 is the year "Doom" was released, which revolutionized the first-person shooter genre.
**Ether (ETH)**
The same token used on Ethereum mainnet, but for testing purposes only.
### Network Endpoints
```text RPC Endpoint theme={null}
https://testnet-rpc.b3.fun
```
Use this endpoint for standard HTTP requests to the B3 testnet.
```text WebSocket Endpoint theme={null}
wss://testnet-rpc.b3.fun
```
Use this endpoint for real-time WebSocket connections to the B3 testnet.
### Block Explorer
Explore transactions, blocks, and contracts across B3 (including testnet).
## Quick Links
Bridge assets to B3 testnet for testing
Get free testnet ETH for development and testing
Discover tools and infrastructure for building on B3
## Adding B3 Testnet to Your Wallet
Open your wallet (MetaMask, Coinbase Wallet, etc.) and navigate to network settings.
Click "Add Network" or "Add Custom Network" depending on your wallet.
Fill in the following information:
* **Network Name**: B3 Testnet
* **Chain ID**: 1993
* **RPC URL**: [https://testnet-rpc.b3.fun](https://testnet-rpc.b3.fun)
* **Currency Symbol**: ETH
* **Block Explorer URL**: [https://explorer.b3.fun](https://explorer.b3.fun)
Save the network configuration and switch to B3 Testnet.
You're now connected to B3 Testnet! You can start testing your applications.
## Why Use Testnets?
Testnets provide a safe, controlled, and efficient environment for testing and experimentation. Test networks, or testnets, serve as essential tools for you to test your smart contracts before deploying them to the mainnet, minimizing the risk of failures or vulnerabilities in live applications.
### Key Benefits
Test your smart contracts and applications without risking real funds or affecting live users.
Simulate mainnet conditions including network latency, gas fees, and transaction throughput.
Use free testnet tokens instead of expensive mainnet ETH for development and testing.
Perfect environment for developers to learn and experiment with blockchain development.
By simulating the mainnet environment, testnets offer a realistic representation of real-world conditions, complete with network latency, gas fees, and other factors that impact the performance of smart contracts. This accurate representation enables you to identify potential issues, optimize your applications, and ensure the best possible user experience for your end-users.
Moreover, testnets allow you to familiarize yourself with the B3 ecosystem and gain valuable hands-on experience, making them indispensable tools for both seasoned developers and newcomers to the world of blockchain development.
## Development Workflow
Use the [testnet faucet](https://testnet-faucet.b3.fun) to get free ETH for testing.
Deploy your smart contracts to the testnet and thoroughly test all functionality.
Use the block explorer and development tools to debug issues and optimize performance.
Once testing is complete, deploy your production-ready contracts to B3 mainnet.
Always test thoroughly on testnet before deploying to mainnet with real funds.
## Testnet vs Mainnet
**Testnet**:
* Chain ID: 1993
* RPC: [https://testnet-rpc.b3.fun](https://testnet-rpc.b3.fun)
* Explorer: [https://testnet-explorer.b3.fun](https://testnet-explorer.b3.fun)
**Mainnet**:
* Chain ID: 8333
* RPC: [https://mainnet-rpc.b3.fun](https://mainnet-rpc.b3.fun)
* Explorer: [https://explorer.b3.fun](https://explorer.b3.fun)
**Testnet**: ETH has no real-world value - used only for testing
**Mainnet**: ETH has real-world value and costs money to acquire
**Testnet**: Development, testing, learning, experimentation
**Mainnet**: Production applications, real users, actual transactions
# Tokenomics
Source: https://docs.b3.fun/protocol/tokenomics
Information about the $B3 token
### **Overview**
* Token name: B3 (Base)
* Chain: Base
* Total Supply: 100,000,000,000
* Decimals: 18
### Utility
The B3 token is the engine powering the Open Gaming ecosystem, designed to grow, scale and transform gaming by empowering players, game developers & holders.
**For Players:**
* 🥩 stake \$B3 to receive exposure to future B3 AppChains
* 🥇 use \$B3 to fund & publish the games & experiences you believe in and earn rewards
* 🎯 get early access to games and new features on BSMNT
* ☑️ participate in governance to directly impact the future of the B3 ecosystem
**For Game Developers:**
* 🪙 apply & receive funding to develop and scale your game
* 💴 earn referral rewards across all players on any Gamechain
* 🚁 receive future airdrops (or grants) from infrastructure partners
Additional utilities for \$B3 will be announced as they become available.
### Distribution and Allocation
* **Community & Ecosystem**: This allocation is to the growth of the B3 ecosystem - for gamers, by gamers. It is to build an ecosystem belonging to those who play in it: airdrops, tournaments, playtests, community-led grants, research & development, and many others.
* **Foundation**: This allocation will support the Player1 Foundation as it contributes to B3 and Open Gaming's vision and adoption, including strategic grants/partnerships, legal and compliance needs, audits, and other operational expenses.
* **Team & Advisors**: This allocation is for core contributors + 18 advisors who represent the best of both gaming worlds - from AAA to web3. All team & advisors are subject to a 4-year vesting schedule: 1-year 25% cliff, with monthly unlocks thereafter.
* **Investors**: This portion of B3 allocation is for investors who supported B3's development, including 100+ angels who gathered from every corner of the industry—gaming, web3, brands, infrastructure—to b3lieve in and support B3's vision. All team & advisors are subject to a 4-year vesting schedule: 1-year 25% cliff, with monthly unlocks thereafter.
### Token Unlock Schedule
# Whitepaper
Source: https://docs.b3.fun/protocol/whitepaper
Introducing Open Gaming and B3: Premier Onchain Gaming Destination
## Executive Summary
Gaming in our modern era has become ubiquitous across communities, geographies, and media; in its myriad forms it has become both an enormous industry and an integral aspect of modern digital life. Yet despite the industry's growth and success, a set of gatekeeping entities and walled gardens has gradually emerged–as in many aspects of the tech world and larger economy. This consolidation worsens the experiences of gamers, restricts opportunities for developers, and reduces diversity within the industry. Traditional "off-chain" gaming feels bereft of the uninhibited innovation and fun that typified earlier decades–-it feels closed.
Web3 has for years presented itself as an alternative to the status quo, one bringing forth the components of a new paradigm for gaming focused around interoperability, greater community input, user-owned and transferable assets, and unique reward structures. The promise was open gaming. But this vision remains unrealized. A series of hurdles has largely prevented studios from diving in, gamers from migrating, and the broader web3 gaming ecosystem from blossoming. Community fragmentation has also been a major struggle for onchain gaming, with audiences isolated in discrete, largely unconnected ecosystems, impacting both discoverability and gameplay, and discouraging further innovation. Finally, and critically, it is tragic that an industry so focused on designing new open incentive systems has tacitly recreated many economic pressures against collaboration. The industry needs a broader vision and solutions to realize it.
We propose Open Gaming as a mandate, a suite of technical tools, and an incentive system to level up onchain gaming and usher in a golden era in gaming.
This features a sophisticated development engine capable of powering the next generation of onchain games and enabling them to rival if not surpass their web2 predecessors. A core Layer 3 (L3) blockchain that settles on Base, offering fast and cheap transactions, will offer new capacities to game developers. Games can launch their own customized GameChains that settle on the B3 L3 while leveraging best-in-class usability features like account abstraction, intents, and smart wallets. Over time, the Open Gaming ecosystem could include and integrate other chains alongside B3. This gives developers control over the game experience without having to grapple with the fragmentation that can come with traditional appchains.
Finally, Open Gaming is taking the challenge of misaligned incentives head on. A shared and open economic system can start to enable developers and infrastructure providers to benefit from each other's growth and at minimum encourage cooperation in this critical period of attracting new users. A referral system that rewards the ecosystem for sharing users is just the first step.
Ultimately, these innovations promise to transform 'web3 gaming' into merely 'gaming.' To achieve this, Open Gaming, starting with the B3 L3, introduces a venue for the emergence of the most engaging and sophisticated games, for passionate gaming communities to coalesce, and with the larger gaming ecosystem itself becoming the largest beneficiary.
## Gaming: A Crossroads
Games in many digital forms are enjoyed the world over. More than 3 billion global gamers enjoy an abundance of gaming platforms that let them engage virtually anytime and in any setting, from a mobile game on a subway to a console game on a large screen TV. That an estimated 8+ hours is spent weekly by the average gamer is a clear measure of gaming's place in society1.
Successive waves of innovation in technology and gameplay have radically expanded the assumed demographics of a 'gamer.' Nintendo's Wii, Farmville on Facebook, Candy Crush Saga on mobile–all have brought more and more people into gaming. Gaming in turn has radically expanded its footprint in popular culture and media. From the dramatic growth and increasing acceptance of Esports, to the success of gaming-based movies and TV shows, the significance of gaming as a cultural force is clear. In many ways, to be digital these days is to have at least brushed up against gaming.
Nonetheless, the gaming industry and community today finds itself in a place of tension.
### Offchain Gaming: Symptoms of gatekeeping
Despite the enormous expansion in the number of players and ways they play games, developers and gamers alike face some critical pain points.
Like many sectors of the tech ecosystem and the larger world, in recent years the gaming industry has increasingly concentrated in the hands of a small number of publishers and distribution platforms. For developers, this increases the challenge of standing out, leading to higher premiums on marketing and distribution, less emphasis on gameplay, and strong incentives against risk-taking. Pressures to rapidly ship product and to emulate tried-and-true models, both undermining creativity and risk taking, have become realities for game designers.
For an industry that has always been a conflux of self-expression, art, and commercial pursuit–more product oriented than independent film yet more artistic than consumer apps–many participants are deeply uncomfortable. Indeed, indie developers and risk-taking studios have long held an outsized role in pushing the gaming industry, culture, and community forward. Tetris, one of the most played games of all time, was developed by a single engineer. The genre of MOBAs (multiplayer online battle arena), responsible for more than a decade of successful esports in Dota 2 and League of Legends, was started from users modding popular Blizzard games. Minecraft was the genius of Markus "Notch" Persson and has gone on to define a generation's experience of gaming, a golden age of user-generated content both in-game and throughout the Internet, and be a wild commercial success. It has been and remains imperative that risk-taking developers are able to thrive, yet today's gaming industry is not structured in a way that supports them.
Gamers seem to feel the effects of this centralization too. Many complain of extractive business models, whether microtransactions, mobile's free-to-play / pay-to-win model, endless in-game purchases, or the proliferation of account-gated games.
It is the best of times. It is the worst of times.
Elon's tweet garnered over 76m views, suggesting it struck a deep chord.
Despite the growing footprint of gaming, the range of tools available to developers, and the relative ease of accessing games, dissatisfaction and discomfort is present throughout the industry. From a broader perspective it is unquestionably one of those periods of tension out of which meaningful transformations often emerge.
### Onchain Gaming: Closed (again)
Web3 gaming represents an obvious direction for a potential gaming renaissance. It is a new digital and network technology. It is global, cross-platform, and prides itself on removing gatekeepers. It can make users direct stakeholders and offer developers new ways to fund themselves. On paper at least, the promise seems to match the moment.
Gaming has already played a critical role in the blockchain industry broadly, and it is just warming up. Cryptokitties, launched in 2017, was one of the first mainstream moments in all of crypto. While it is famous for almost halting the Ethereum blockchain, it can also be seen as the moment that drove home the importance of blockchain scaling solutions. In some ways, the larger blockchain industry has Cryptokitties to thank for massively expanding popular views of the potential of dapps—and how seriously people set to solving scaling issues.
Onchain gaming managed similar feats over the ensuing years, with Axie Infinity, STEPN, Parallel, and Pixels as just a few examples. Despite criticisms that onchain gaming has yet to have globally-significant impacts, sustained interest remains, with many platforms, investors, genres, and models deployed every quarter. Over the past four years, over \$11B has been invested in web3 gaming across 900+ transactions. Over \$1.5B of this total investment occurred during 2023, and approximately \$900 million has been allocated to web3 gaming in 20242.
Trackers of web3 games list almost 1000 titles that have been launched across many different ecosystems in recent years. Many feature thoughtful experimentation with integrating digital assets, encouraging fun onchain, and self-funding approaches. Many blend offchain components and onchain components, using labels like Web2.5 or diet Web3. Surveying the space, even if a breakout game has yet to appear, the range of innovation hints at the potential of onchain gaming to usher in a new era.
The continued investment should be welcome. Even before blockchain was a buzzword, gaming has played a role in crystalizing new digital technologies. Over decades games have proven particularly powerful at evoking the potential of new technologies for entertainment, immersion, and play. For those who lived it, it is difficult to imagine the early days of computers without reference to Atari and to Oregon Trail. Early Windows users enjoyed Minesweeper, just as the earliest mobile phone users–using the gray bricks that predated smart phones–all had Snake. Importantly, and as noted above, each of these technological shifts simultaneously expanded the global gaming community even as gaming helped popularize the new platforms themselves.
### Onchain hasn't meant Open
In sum, offchain gaming can benefit immensely from a new digital medium, particularly one that prides itself on permissionless innovation, removing gatekeepers, which has tools for creative funding models, and which ultimately is a potential way of addressing some of the industry’s existing tensions. In turn, onchain gaming, particularly in the wake of its visionary risk-taking pioneers, can benefit from additional attention and the reservoir of talent in the traditional gaming industry. And for the larger onchain space, gaming could serve the popularizing role it has with other technologies.
Realizing this potential, however, requires overcoming some significant challenges, all pointing to how we are seeking to take onchain gaming—and the entire industry—to the next level.
**Definancialize and Diversify**
Early generations of onchain gaming have explored only a slice of what is possible. Onchain gaming models were limited by immature infrastructure, and have involved a heavy focus on speculation and financialization. This is not unheard of in offchain gaming: the massive appeal of lootboxes in gaming, a thriving black market for leveled-up game accounts, and in-game resource farming operations as early as the mid-2000s suggest this intersection is neither new to gaming nor likely to ever go away. But today the shadow of this financial focus hangs over the entire onchain game industry. In some ways, “play to earn” is a damning confession, as if it is inconceivable that these games can be played purely for fun. This has given the industry a stigma that keeps would-be gamers and developers on the sidelines. The “gamefi” industry has a clear place in gaming globally but also has unquestionably produced only a slice of what’s possible in onchain gaming
The industry needs to expand beyond these approaches and win on metrics that matter to real people and reflect the broader realities of gaming today.
\*\*Universal Accessibility \*\*
Building onchain games can also be complex. Playing them frequently is as well, further compounding the difficulties for game developers. Some of these challenges are shared among all dapps but have particular salience for an industry where offchain predecessors maximize ease, addictive actions, and engaging content. These challenges include:
* Players typically need crypto wallets to play. This means seed phrases, which can be terrifying to gamers accustomed to the world of passwords and password resets. It means identifying ideal wallets, many difficult to distinguish from each other, with features like native staking support that mean little to gamers.
* Players often need to bridge assets between different chains. A game on Solana and a game on Ethereum might involve two different wallets, with complicated and expensive mechanisms for transferring funds between them. Multiple steps and transactions, waiting time for blockchain and bridge finality, and fees stand in the way of using most dapps, games included.
* Players often need to fund their own gas, sometimes with custom gas tokens. The experience in practice is as counterintuitive as it sounds, like needing to physically change currencies for each city you visit, and sometimes needing new currencies for specific stores within each.
The above challenges constrain developers, impact games, lead to churn, raise the barrier to entry for creative studios, and too often make the magic of the game disappear.
**Ecosystem Fragmentation and Disinteroperability**
Most concerning of all, the web3 gaming ecosystem appears to be slowly regrowing some of the most troubling aspects of traditional gaming. Chains are heavily incentivized to become their own publishers and walled gardens, so as to drive transaction fee revenues and focus on the price of their own tokens. This also often forces game developers to choose particular chains for launch, each presenting technical tradeoffs, and stay there, or perhaps even to launch their own chain. To date, over 40 unique independent blockchains have or are hosting onchain games.
These incentives cut against the open ethos of blockchain and smart contract platforms. While this contradiction is not unique to the gaming sector, it is a concerning mindset for a genre that is so focused on opportunities to attract non-crypto users, non-whales, and demographics outside of the narrowest crypto stereotypes.
The industry should be looking to expand its collective footprint and player base, in the interest of expanding the overall space, rather than focusing on a perceived zero-sum competition and short-term impacts on the price of any individual tokens.
We need co-op, not pvp, at the developer level right now.
### The Next Step
A most tragic outcome would be recreating some of the challenges currently facing traditional gaming. Disgruntled gamers worried about extractive practices. A small number of gatekeeping entities with immense influence over which games and gaming models get prominence and effectively discouraging experimentation. These sadly already sound a bit familiar. Onchain environments and web3 gaming ecosystems do have the opportunity to recapture a core sentiment of the early internet and early gaming communities, that of a permissionless environment for making connections and distributing code to anyone anywhere. However, it is unclear if current trends, left undisturbed, can enable that.
## Enter Open Gaming
Open Gaming is our vision of a secure, scalable, onchain gaming ecosystem that restores economic and creative freedom to game developers and players. In tangible terms, Open Gaming is a network of gamechains that share incentives, liquidity, and tooling, all working to increase access to both gamers and developers. The B3 L3 is the first chain in Open Gaming, for game developers who do not need their own customized chains, but will be joined by other developers who do. Parallel was the first to announce the PRIME gamechain on Open Gaming, on which their game Tau Ceti will launch; others will follow.
Functioning as an innovative gaming engine for developers, a community-focused publisher, and the go-to community on Base for web3 gamers can allow Open Gaming to bring these key value propositions to life.
\*\*Open Game Development: \*\*A primary benefit of Open Gaming’s technology is substantially lowering the barrier to designing, creating, launching, and running games. This starts with the core technologies needed to deliver onchain gaming experiences, building a platform to bring developers and gamers together, and supports the emergence of innovative gaming business models. The Open Gaming game engine brings together the key concepts that are making web3 development easier, faster, and richer, and will become the foundation upon which the next generation of industry-leading and genre-defining games is developed.
**Open Gameplay**: Gamers of all types need easier ways to find, play, and support onchain games anywhere. A set of usability upgrades is ready to welcome more users onchain. L2s and L3s are radically lowering transaction costs. Account abstraction techniques are removing much of the hassle of managing multiple onchain accounts, particularly across different L2s and different chains. Smart wallets are removing much of the traditional challenges of even having an onchain account. We are bringing these and more together to make the experience of onchain gaming much more seamless.
\*\*Open Access: \*\*A native Open Gaming marketplace and platform can include games published on any chain, using any set of tools, or using merely part of B3’s L3 capabilities, even behind the scenes. This will give developers necessary power for their games and complete control over their branding, community, technology, and trajectory. Finally, as a discoverability hub, Open Gaming is an inclusive, cross-chain environment where gamers are able to discover and play web3 games regardless of where they are published.
**Open Narratives**: Developers need more freedom in imagining gameplay that is onchain in more nuanced and less binary ways. Some games will want maximum state on a single chain, some might only need in-game items or game accounts onchain, and many will be somewhere between or even orthogonal. The web brought many new capabilities to gaming, including social features, access to massive shared worlds, leaderboards, or even just remote downloading. Designing games wasn’t a choice of being maximally social or maximally online. Developers need encouragement, a platform, and, critically, an economic layer designed to encourage innovation in onchain gaming.
The magic of the early Web was being able to visit any website. An early web user, after listening to their dial-up modem connecting to the Internet, could just ‘surf.’ Nothing at risk. Nothing to write down. No picking of servers, no specifying networking routes for queries, no changing browsers based on website settings. Crypto is closer to this user experience than ever before.
For example, B3’s unique stack lets developers focus on the internal game mechanisms and fun gameplay without worrying about limitations of the underlying technology or whether deploying with a particular partner is an irrevocable commitment to a particular ecosystem, chain, or publisher, and subject to the ecosystem’s own success or failures in attracting audiences. This is the promise of the Open Gaming mandate. This should yield more games, across many genres, and more varied in form.
Ultimately, the Open Gaming ecosystem is a space for gaming paradigms to evolve. Blockchain technologies have let entrepreneurs in many industries reimagine how business could work–and enjoy a permissionless place to build it. Exchange without intermediaries. Permissionless contribution and partnership. Users with stake in the game. Hard-to-change rulesets. Web3 remains a place of active experimentation and discovery. Gaming is early in its journey to doing something similar.
With Open Gaming’s core innovations and philosophy, it can take the next major leap.
## Open Gaming's Core Components
Our Open Gaming strategy boasts a comprehensive toolkit, platform, and ecosystem to better match the potential of web3 gaming with the moment confronting offchain gaming and the current onchain gaming industries alike. Several core elements, described below, define B3’s ability to establish itself as the onchain gaming hub.
### Development Engine
Starting with the B3 L3 and accompanying tools, we have an integrated technology platform for next-generation onchain gaming designed to radically lower the cost of development and encourage a wider range of creative expression. Less time spent micro-planning infrastructure is more time crafting great onchain experiences.
**Base L3 + an L3 Superchain**
L2s have dramatically lowered transaction costs and paved the way for L3s such as B3 to reduce them further. L3s and the systems they support let developers make more conscious tradeoffs between trustless security and user experiences like cost, latency, and throughput. This is particularly salient in gaming, where the goal is usually entertainment and not trustless yield and double-spend protection for wealth assets.
L3s are customizable chains, highly flexible in nature, and allow experimentation at the Virtual Machine (VM) layer and with concepts such as data availability and parallelization. The chains simply need to settle data onto an L2 in some capacity. L3s can be for specific dapps or for larger ecosystems; if the L2s are “hubs”, L3s can function as “spokes.” This drives the cost of using the chain down dramatically, enabling onchain micro-actions and more rapid gaming ticks.
They also provide powerful foundations for GameChains that settle on B3, allowing developers to enjoy control over their blockchain backend while still enjoying cross-game and cross-infrastructure compatibility.
| Chain | ETH (L1) | Base (L2) | Solana | B3 (L3) |
| ------------------------------------------ | -------- | --------- | ------- | ------- |
| Illlustrative Transaction Cost (July 2024) | \$3.00 | \$0.005 | \$0.005 | \$0.001 |
The B3 L3 enables settlement for a new layer of computation, opening up architectural possibilities that more resemble the development experience in offchain gaming. This comes with superior performance but different security guarantees, composability, and data persistence–tradeoffs that resemble modern decisions about cloud-based architecture and enable developers to make more nuanced decisions about the optimal range of onchain activities within their games.
* **GameChains**: While traditional appchains have contributed to economic fragmentation that complicates an already challenging journey for developers and gamers, it is also true that developers need to control the gaming experience and architecture at this nascent stage of onchain gaming. GameChains square this circle. They are fully customizable, with chain-in-a-box ease using the Open Gaming SDK and team expertise, while also settling on B3 for barebones costs. All GameChains interoperate with other GameChains and with the open utilities Open Gaming is building. All GameChains participate in the shared economy and benefit from the account abstraction tools and techniques that make Open Gaming so accessible.
* \*\*Sprinter: \*\*Enabling the flexibility described above without reintroducing UX fragmentation is possible because of Sprinter, an account abstraction aggregator that serves the best possible path for an end user to perform a transaction, via chain, bridge or intent. Sprinter enables seamless bridging across and beyond the ethereum ecosystem, balancing abstraction across multiple wallets, intent-based interactions, and smart wallets, all of which promise to radically level up the onboarding experience for Web3. The result is designing for a Web2-like experience with confidence, not trying to architect around the clunky framing of being onchain. It also enables a dynamic L3 and L4 environment without confusing users. Ultimately, Sprinter helps realize the potential for a web3 app that is more competitive, easier to use, *and* easier to build than web2 apps.
* \*\*Maximum throughput: \*\*EIP-4844 significantly reduced the cost of transacting on L2s, opening up new capacity. The almost immediate absorption of this capacity suggests the industry’s appetite for more throughput remains. If the cost of transacting in an onchain environment falls further, developers and users will find ways to fill the blockspace. Running game logic in an onchain environment creates digital history that anyone can leverage–communities looking for power players or entry-level gamers, game designers trying to understand where players typically stopped playing a game, or new tokens looking for who their future user base might be. Moving things onchain without congestion and prohibitive costs can open up new design space for games.
* **Horizontal scaling**: One of the powers of L3s is the ability to support additional computation layers on top that still write state down to a secure chain. Rollups on top of B3 lets game activity leave an onchain footprint while keeping costs low. Such layers built on top of L3s can be spun up and down quickly, at minimal cost, to accommodate surges in demand. Such additional layers can be used as part of a strategy to scale game activity horizontally, relying on many parallel chains when games don’t need to keep all players and logic in the same environment. An esports tournament, a guild-created tournament, an influx of new players—all could be supported under the hood without clogging the experience of other players, much less other users of the chain. The Open Gaming engine can support this type of rollup spawning without game developers needing to build custom scaling solutions or contort their architecture.
**Shared Liquidity**
Gamers owning their own items, progress, characters, and game-progress footprint is a superpower of onchain gaming, but today these are scattered across many wallets, chains, rollups, and marketplaces. The complexity caused by different chains and assets across chains is a significant barrier to entry especially to those less familiar with crypto. This erodes the ultimate promise of gaming on a shared computation layer. To realize the vision of Open Gaming, players shouldn’t need to manually bridge or switch networks, creating a more fluid experience.
In B3, liquidity of onchain assets is shared and compounded across all GameChains through the B3 core framework’s seamless chain abstraction. The UX allows effortless movement of assets between games, eliminating the need for players to manually switch networks and bridge tokens. A player with tokens on GameChain A can seamlessly access those assets on GameChain B, without manually switching networks or bridge funds. This makes it easier for the player to try new games without additional UX overhead.
**L3 Density**
Using the infrastructure described above, B3 enables a ‘superchain’ at the L3 level. Optimism’s Superchain thesis is that because all OP Stack L2 chains run on the same stack, a Superchain can be formed between them to provide synced transactions, shared bridging, and compatibility for any future OP Stack chain to join this network.
In the interim, it is possible a “superchain” can be built at the L3 level. From a technical perspective, various virtual machines (VMs) can be run in parallel, which can still result in the outcome of synced transactions, shared logic, and compatibility to add new chains. From a go-to-market perspective, L2s would actively want to create a mechanism by which L3 builders can leverage existing tech, distribution, and tooling. Put simply, with an L3 superchain, builders get the product parity without the overhead of running their own chain.
While today’s trend is to have bespoke L3s for each dapp, the fragmentation and cost to manage an L3 will soon become apparent. The solution to this is L3 Density – a network effect formed when numerous, interoperable L3s settle onto the same L2 – as the driver of the next trillion transactions.
### **Base**
The B3 ecosystem will be built on Base, which is best positioned to be the vehicle for the next billion people to get onchain. Importantly, Base has been developed transparently by a team constantly contributing to the broader crypto ecosystem. It has demonstrated a commitment towards supporting the growth of the overall web3 ecosystem, rather than moving towards a walled garden structure replicating the worst of web2 practices. It is affiliated with Coinbase, one of the most successful crypto onramps and responsible for bringing cryptoassets to millions of people and millions of people to the crypto industry. Finally, Base is built with an array of tooling that maximizes developer ease. Given the above, Base represents the ideal foundation for Open Gaming to emerge as the leading web3 gaming ecosystem.
### Discoverability Layer and Other Apps
Places where buyers and producers come together have long fostered community while facilitating commerce and innovation. Actual physical marketplaces and bazaars facilitated the exchange of goods, ideas, and inventions in much of human history. For studios, it becomes easier to find the right gamers who might be playing games already like the ones the studio is making. For gamers, it is one place to look across a growing sea of creativity.
A central part of the Open Gaming vision is to support players finding and playing great onchain games, regardless of where they are. Though the B3 L3 is a flagship technology, the Open Gaming ecosystem will ultimately welcome other networks and will support apps that draw from across the onchain gaming landscape.
The capabilities of B3 initially match the needs of casual game designers while larger studios can work on technical integrations. This reflects the additional time and resources AAA games require but also the reality that casual games better reflect the more typical global experience of playing games: on phones, in shorter sessions, with low game-specific commitments.
Community is a powerful force in every context. This is particularly the case in Web3. From its earliest days, the Internet was hailed as a place where people could almost effortlessly find others of like mind. Onchain gaming communities today remain dispersed, however, and the Open Gaming ecosystem should be an inclusive environment where all web3 gamers can find their communities and the games that appeal to them.
Web3 has a toolkit with the power to disrupt extractive producer-consumer relationships dominating the web today and arguably support organic or more incentive-aligned communities. Building onchain accelerates network effects and facilitates partnerships. Tokens and trustless incentives can guide behavior more powerfully than user agreements and free services. Users can be co-creators. Power users can be more than cash cows. Influencers can be more than marketing strategies. In an era of gamer exhaustion at the latest tricks in monetization, a dedicated community infrastructure for gamers, empowered by tokens, will feel radical.
### Shared Incentives
An unfortunate reality of the fragmented landscape of onchain games today are disincentives for true interoperability. Games and chains don’t want to share users, who are often generators of transaction fees and primary token buyers. Games have weak incentives to integrate the items and mechanisms of other games, who themselves have already reaped the economic benefits from minting them. Even gamers can face poor incentives to grow a game’s userbase and dilute their own airdrop earnings. This is doubly tragic in an industry that prides itself on reinventing the economics of internet applications.
Combatting this will take time, but we believe it is a battle worth fighting.
The first step is a referral and revenue-sharing mechanism that collects a portion of transaction revenue for reinvestment in the ecosystem. Referring users that generate more transactions can benefit everyone in the ecosystem. In addition, any gamechain that commits a portion of their tokens toward user acquisition (UA) and also brings in a new user can earn B3 tokens. B3 will also bootstrap the initial incentive pool for the purpose of user acquisition (e.g. influencers, creator referral program) by contributing a portion of the B3 token supply.
## Opportunities for Key Stakeholders
B3’s infrastructure can reach many types of actors and stakeholders, with features and benefits for each.
**Game Developers**: Web3 is a new frontier for gaming that game developers of all types can embrace. Open Gaming offers a new toolkit to turn users into partners, to engage creatively with a game community, and to fund game creation. It is a deployment platform not dominated by gatekeepers and intentionally established against it.
Open Gaming’s unique suite of infrastructure, tools, and platform lowers barriers of onchain game development. This should enable onchain gaming to find broader expression and develop novel structures, better reflecting and even expanding beyond the myriad ways offchain gaming is experienced today.
Over the past one and a half decades, the “onchain” industry has been inexhaustible in producing new narratives. It finds ways to defy rumors of its own death. This resiliency speaks to an underlying value of web3 gaming and a desire within the gaming space to see new approaches emerge. We believe that with the advancements of the technology in general, and specifically in regards to the tools and infrastructure it is introducing, onchain gaming is finally ready to play a central role in the evolution of gaming.
\*\*Gamers: \*\*Lowering the barrier to entry for gamers will help them find the experiences they are looking for and hopefully ones they like but did not know existed. They can experiment with new forms of gameplay without crossing the UX chasm being onchain has required until now. They can also be co-funders, co-builders, and co-advocates for game developers bringing their own visions into the world.
\*\*Base and the Base Ecosystem: \*\*Base may be the platform for the next billion onchain users. It is an open and neutral L2, without a native token and incentives to maximize the value of one and with a track record of contributing to the base Ethereum ecosystem. It celebrates builders and will continue to do so. It is adjacent to millions of offchain crypto users who might be curious about the technology but intimidated by the UX prospects of being onchain.
We can continue the tradition of celebrating builders and giving back to its base ecosystem. More transactions. Amplifying community. Bridgeless usability. Onchain fun.
\*\*The Gaming Industry: \*\*Games have also long functioned as a powerful vehicle for popularizing new technology. In some ways, technology benefits from gaming exploring and advancing its own limits as much as gaming benefits from new technologies. From this perspective, an argument that blockchain technologies—that by any measure have a far wider range of use cases than gaming—may nevertheless find gaming to be a powerful force both in advancing the technology and in introducing users to the technology as it engages new audiences, is a compelling vision. Open Gaming, with innovative tech improving game design as well as gameplay, and a social and community layer poised to make it a genuine web3 gaming hub and discovery layer, can play a critical role in making onchain gaming accessible and exciting.
## B3 Token Overview
The B3 token will play a variety of roles in the Open Gaming ecosystem, with applications for developers, gamers, and governance.
For developers, the token can help spur activity on B3 and throughout the Open Gaming ecosystem, reward great games, and serve as an anti-sybil measure. A variety of grant and patronage opportunities can enable developers to bring their creations to life on B3. At the same time, developers can use the token for fees and visibility.
For gamers, the token will be used to facilitate cross-game commerce or special perks. This could include questing, playtesting, feedback, purchasing unique items and powerups, and other forms of engagement that historically have made gaming such a unique human activity.
For anyone interested in governance, the token will help direct the DAO that sets policies, supports protocol upgrades, and oversees the treasury.
**Token Allocation and Supply**
More exciting information about the B3 token utility will be shared as the ecosystem unfolds. Stay tuned!
### Governance
The Open Gaming ecosystem will need a variety of governance rules. The vision for onchain gaming is big and bold. The toolkit the B3 L3 and other supporting technologies provides is powerful and expressive. The winning strategy for the gaming ecosystem as a whole is still taking shape. It will take a dedicated community and a flexible governance system to navigate us all to the next stages.
More on the specific governance structure will be forthcoming, but we generally anticipate three modes of engagement.
* Proposals: a proposal system allows for ideas to emerge from the community that delegates may not think of or have the capacity to develop on their own. It also gives the entire community a direct voice.
* Voting: token holders can be active participants in shaping the future of the B3 and Open Gaming ecosystems, embodying an important step towards the decentralization this industry stands for.
* Councils: specialized councils are an effective way to align expertise, particularly technical, with relevant decision making.
All of these have precedent in robust governance systems–and notably, are absent from the gaming production industry that has generated so much gamer discontent. Open Gaming is for gamers and governance will reflect that.
## Conclusion
In an earlier era, going online ultimately meant many things for both games and players. It wasn’t just chatting in-game or playing with strangers. Entire new genres, like MMOs and server-grade worlds, became possible. User-generated content, on small scales and for entire games, became more commonplace. People *talked* about games online, volunteered their time to create tutorials for other players, and spawned a streaming industry. All of this was built upon novel in-game mechanisms and experiences that provided a foundation for and inspired these activities. Just like one could not have predicted the range of developments in the early days of online gaming where games like Tetris and Minesweeper represented the cutting edge of innovation, one cannot forecast exactly what innovations web3 and onchain gaming may bring.
The innovations discussed in this paper contain both challenges and opportunities; together they represent an agenda for addressing issues in gaming and looking to the future of the industry. They shape Open Gaming’s ability to foster a web3 gaming ecosystem where it is easier to build and access new games, and above all more engaging to play. This ecosystem enriches the experience of existing onchain gamers, has resources for a community to emerge, flourish, and shape the future of the platform and gaming in general, and welcomes and supports the transition of web2 gamers moving onchain.
In the context of a gaming universe where Apple’s App Store had nearly 300,000 titles available in 2023, and where only 1,000 web3 games have been released in total, the opportunity space before web3 is clear. Innovative platforms like B3’s L3 and the Open Gaming ecosystem that deliberately address key hurdles that have limited the experience of web3 until now—from infrastructural, community, and user experience and onboarding perspectives—are critical in ushering in and unleashing the potential of a new era that promises to become not merely the next phase of web3 gaming or the global gaming space, but of the online and onchain experiences themselves.
1. Russel, Charlie, The State of Online Gaming, Edge.io 2021. Retrieved from: [https://edg.io/blogs/state-of-online-gaming-2021/](https://edg.io/blogs/state-of-online-gaming-2021/) Jul 5, 2024
2. Jordan, Jon. Everything Blockchain Gaming. bigblockchaingamelist.com. [https://bit.ly/web3gamedata](https://bit.ly/web3gamedata). Accessed Dec 8, 2024.
# Quickstart
Source: https://docs.b3.fun/quickstart
Get started with the B3 SDK in minutes and start building on the B3 ecosystem
### Step 1: Install the B3 SDK
Choose your preferred package manager to install the B3 SDK:
```bash npm theme={null}
npm install @b3dotfun/sdk
```
```bash pnpm theme={null}
pnpm add @b3dotfun/sdk
```
```bash yarn theme={null}
yarn add @b3dotfun/sdk
```
The B3 SDK includes TypeScript definitions out of the box!
Import the default styles in your application:
```typescript theme={null}
import "@b3dotfun/sdk/index.css";
```
### Step 2: Add B3Provider
Wrap the B3Provider around your application's root:
```tsx theme={null}
import { B3Provider, SignInWithB3 } from "@b3dotfun/sdk/global-account/react";
function App() {
return (
{children}
);
}
```
### Step 3: Use the B3 SDK
Enable global accounts authentication with B3:
```tsx theme={null}
import { SignInWithB3 } from "@b3dotfun/sdk/global-account/react";
function App() {
return (
{
console.log("Authenticated:", globalAccount);
}}
/>
);
}
```
Enable cross-chain swaps & custom interactions with AnySpend:
```tsx theme={null}
import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
function SwapPage() {
return ;
}
```
### Step 4: Explore the Ecosystem
Learn about the complete B3 ecosystem, tools, and resources available for builders.
## What's Next?
Now that you have the B3 SDK installed, explore these powerful features:
Seamless authentication and user management across the B3 ecosystem.
Access blockchain data for tokens, NFTs, profiles, and analytics.
Cross-chain swaps, NFT minting, and blockchain operations.
Ready-to-use examples and integration patterns.
## Platform Support
| Feature | React Web | React Native |
| ----------------- | --------- | ------------ |
| AnySpend | ✅ | ❌ |
| Global Accounts | ✅ | ✅ |
| Headless Services | ✅ | ✅ |
**Need help?** Join our [Discord community](https://discord.gg/b3dotfun) or check out the
[ecosystem introduction](/ecosystem/introduction) for comprehensive resources.
# Developer Resources
Source: https://docs.b3.fun/redirect/ecosystem
B3 is committed to an open ecosystem of onchain primitives, tools, and services. Anyone can choose to build on B3.
You are being redirected to the B3 Ecosystem page. [Click here](/ecosystem/introduction) to continue.
# B3 SDK
Source: https://docs.b3.fun/redirect/sdk
The B3 SDK contains everything you need to get started building on B3.
You are being redirected to the B3 SDK page. [Click here](/sdk/introduction) to continue.
# Airdrop FAQ
Source: https://docs.b3.fun/anyspend/airdrop
Frequently asked questions about $ANY token airdrops
## S1 Airdrop
### How do I qualify for the S1 airdrop?
Day 1 users of Anyspend who used the product across any B3 Labs onramp experience or on anyspend.com qualified for the airdrop. Snapshot was taken the week of Oct 6 2025.
### When was S1 airdrop qualification period?
Anyspend soft launch (August 2025) - October 6th 2025
## S2 Airdrop
### When will S2 end?
S2 will end in 90 days from start date of 10/10/25
### How do I earn points for S2 of \$ANY airdrop?
* Onramp or swap tokens on anyspend.com
* Use Anyspend to onramp or swap to \$B3 on hypeduel.com or stake.b3.fun
* Swap any token into any arenacoin on hypeduel.com
# Installation & Setup
Source: https://docs.b3.fun/anyspend/installation
Get started with AnySpend - installation, basic setup, and verification
## Prerequisites
v20.15.0 or higher
Version 18 or 19
Recommended for better DX
## Installation
Choose your preferred package manager:
```bash theme={null}
npm install @b3dotfun/sdk
```
```bash theme={null}
pnpm add @b3dotfun/sdk
```
## Basic Setup
### 1. Provider Setup
Wrap your app with the `B3Provider` and `AnyspendProvider` to enable AnySpend functionality:
```tsx App.tsx icon=react theme={null}
import { AnyspendProvider } from "@b3dotfun/sdk/anyspend/react";
import { B3Provider } from "@b3dotfun/sdk/global-account/react";
import "@b3dotfun/sdk/index.css";
function App() {
return (
{/* Your app components */}
);
}
export default App;
```
### 2. Environment Configuration
**Endpoint**: `https://mainnet.anyspend.com`
Use this for production applications with real transactions.
**Endpoint**: `http://testnet.anyspend.com`
Use this for development and testing with test tokens.
Note: Testnet is currently not available.
### 3. TypeScript Configuration (Optional but Recommended)
If you're using TypeScript, ensure your `tsconfig.json` includes these settings for optimal compatibility:
```json tsconfig.json icon=settings theme={null}
{
"compilerOptions": {
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
}
}
```
## Verification
Create a simple test component to verify your setup works correctly:
```tsx TestComponent.tsx icon=test-tube lines theme={null}
import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
function TestComponent() {
return ;
}
```
## Next Steps
Learn about available components for different payment scenarios
Discover React hooks for building custom payment flows
Browse real-world implementation examples
## Troubleshooting
Make sure you've installed the SDK correctly and imported the CSS file. The SDK requires React 18+ and may have compatibility issues with older versions.
Ensure you have `B3Provider` and `AnyspendProvider` placed high in your component tree, typically in your main App component.
If you're seeing TypeScript errors, verify your `tsconfig.json` includes the recommended settings above.
# AnySpend Introduction
Source: https://docs.b3.fun/anyspend/introduction
Cross-chain crypto payments made simple - swap tokens, buy NFTs, and integrate fiat onramps
## What is AnySpend?
AnySpend is B3's comprehensive payment infrastructure that enables seamless crypto transactions across multiple blockchains. Whether you're building a DeFi application, NFT marketplace, or gaming platform, AnySpend provides the components and APIs you need to accept payments in any token.
[Try AnySpend in your browser](https://anyspend.com/swap)
## Use Cases
Cross-Chain Swaps
Enable users to swap tokens between different blockchains with automatic routing and best price discovery.
Checkout
One-click checkout buttons that accept any token as payment, with automatic conversion.
DeFi
Execute any onchain contract call, with usage for staking, prediction markets, bonding curves, and more.
Games
Embeddable in native iOS/Android, Unity, & other surfaces.
## Features
User clicks a payment button or interacts with your interface, choosing their preferred token
Our routing engine finds the best path to convert their token to the required destination token
If needed, tokens are bridged across chains using secure, battle-tested infrastructure
Tokens arrive at the destination address, execute any custom logic, and trigger your success callbacks
## Use Cases
Enable token swaps, provide liquidity, and facilitate yield farming across multiple chains with automatic routing and competitive rates.
Allow users to buy NFTs with any token they own, removing barriers and increasing conversion rates by supporting their preferred payment methods.
Accept payments for in-game assets, tournament entries, and premium features using any cryptocurrency or fiat payment methods.
Integrate crypto payments into traditional e-commerce platforms with automatic fiat conversion and settlement.
Accept recurring payments in crypto with automatic conversion to your preferred settlement currency.
## Quick Start
Get started with AnySpend in just a few steps:
```tsx theme={null}
import { AnySpend, AnyspendProvider } from "@b3dotfun/sdk/anyspend/react";
import { B3Provider } from "@b3dotfun/sdk/global-account/react";
import "@b3dotfun/sdk/index.css";
function App() {
return (
);
}
export default App
```
## What's Next?
Set up AnySpend in your project with npm, yarn, or pnpm
Explore pre-built components for common payment scenarios
See real-world implementation examples and best practices
## Getting Help
* **Discord**: Join our [Discord community](https://discord.gg/b3dotfun) for support
* **Documentation**: Comprehensive guides and API references
* **Examples**: Ready-to-use code samples and integrations
# Onramp Overview
Source: https://docs.b3.fun/anyspend/onramp
Let users pay in fiat and execute onchain actions in one seamless flow.
## What It Does
The AnySpend onramp allows users to pay with traditional fiat methods (e.g., credit card, bank transfer) and automatically execute any onchain transaction. This seamless flow eliminates the need for users to manually acquire cryptocurrency or manage wallet funding.
It’s designed to reduce friction for non-crypto-native users, making blockchain-powered products accessible to a broader audience.
## How It Works
1. **User Initiates Action**\
A user begins an onchain action (e.g., minting, staking, or contract interaction).
2. **Fiat Payment**\
They pay with a card or bank transfer via Stripe or Coinbase Pay.
3. **Conversion + Execution**\
AnySpend converts fiat to the desired cryptocurrency and executes the transaction.
4. **Wallet Delivery**\
The result is sent to the user's connected wallet or global wallet. No crypto acquisition required.
## Payment Options
**Stripe**
* Global support for major credit/debit cards
* 3D Secure authentication
* Currency conversion for non-USD transactions
* Localized payment methods and fee adjustment
**Coinbase Pay**
* Users can pay directly with their Coinbase account balances or debit card
* No need to transfer funds between platforms
* Trusted UX for existing Coinbase users
* No additional fees from AnySpend
**Extensible Provider Architecture**
* Modular system to support additional fiat providers
* Dynamic routing based on region and availability
* Built-in compliance flexibility for regional support
## Security
AnySpend includes a built-in, real-time risk engine designed to minimize fraud while keeping the user experience seamless.
**Key Features:**
* Behavioral and transactional risk analysis
* Device and network security checks
* Real-time threat intelligence
**Smart Transaction Evaluation**
Each transaction is evaluated in real time:
* **Allow** – transaction proceeds normally
* **Verify** – additional user verification may be required
* **Block** – suspicious activity is prevented
## Global Coverage
AnySpend supports a wide range of currencies and regions through integrated providers:
* Automatic location detection and localization
* Local payment methods and currency handling
* Dynamic provider selection based on geography
* Regional compliance out of the box
## Fees
* **Stripe Payments:** 5.4% + \$0.30 per transaction (flat rate, global)
* **Coinbase Pay:** No additional fees from AnySpend
Users are shown a transparent fee breakdown during checkout.
## Common Use Cases
AnySpend enables developers to:
* Let users mint NFTs with a credit card
* Allow staking, voting, or game actions directly from fiat
* Onboard users to DeFi, gaming, or other dApps with no crypto prerequisite
# Tokenomics
Source: https://docs.b3.fun/anyspend/tokenomics
Learn about $ANY token economics, distribution, and utility
### What is the \$ANY token?
**\$ANY** is the native token of AnySpend and represents alignment between users, partners, and the protocol. Its design follows two guiding principles:
**Community First**: 90% of supply goes to the community (airdrops, rewards, integrations). The AnySpend Foundation receives 10% for transparent operational needs. There are no allocations for "team" or "investors."
**Revenue Aligned**: 95% of protocol revenue — from swaps, onramps, trades flows into \$ANY buybacks and burns. Holders capture nearly all value generated by the network.
### What is the total supply of \$ANY?
```text Total Supply theme={null}
1,000,000,000
```
### What is the contract address of \$ANY?
```text Contract Address theme={null}
0xC17dda248E2D50fC006d8fEbb5A406dd31972712
```
## Token Distribution
### How much of \$ANY is allocated to investors, team, foundation, users?
\$ANY is community driven. No allocation has been given to the team or investors.
90% is reserved to be put into the hands of the community and users. The foundation gets the remaining 10% which is used toward liquidity support, security & audits, ecosystem grants and buybacks.
## Token Utility
### What benefits/utility does the \$ANY token have?
* **Discount on Anyspend fees** for \$ANY holders
* **Stake \$ANY** to earn rebates from platform revenue
* **Governance** over listings, fee schedules, and integrations
### What are the Anyspend fee discounts for holders of \$ANY?
* **Partner Whale (100K \$ANY)**: 50% discount
* **Enterprise Whale (500K \$ANY)**: 75% discount
* \*\*Strategic Partner (1M+ $ANY)**: 100% rebate (in $ANY)
## Future Development
### What's AnySpend V2?
AnySpend is evolving into something much larger: a DeFi automation engine. The future of finance is not just buying and swapping tokens, it's programmable money flows, automated strategies, and community-owned infrastructure. V2 of AnySpend will bring this vision to life.
# Check Channel Status
Source: https://docs.b3.fun/basement/api-reference/check-channel-status
basement/basement-swagger.json post /launcher/channel-status
Check the status of a user's channel session
# Create Message Channel
Source: https://docs.b3.fun/basement/api-reference/create-message-channel
basement/basement-swagger.json post /launcher/create-message-channel
Create a new message channel with specified participants
# Create Unverified Channel
Source: https://docs.b3.fun/basement/api-reference/create-unverified-channel
basement/basement-swagger.json post /launcher/create-unverified-channel
Create a new unverified channel session for external games
# Edit Channel Message
Source: https://docs.b3.fun/basement/api-reference/edit-channel-message
basement/basement-swagger.json post /launcher/edit-channel-message
Edit an existing message in a channel
# Get Channel Messages
Source: https://docs.b3.fun/basement/api-reference/get-channel-messages
basement/basement-swagger.json post /launcher/get-channel-messages
Retrieve messages from a specific channel
# Get Game Leaderboard
Source: https://docs.b3.fun/basement/api-reference/get-game-leaderboard
basement/basement-swagger.json post /scores
Retrieves data from the game leaderboard, providing you with information on player rankings and scores. It helps you monitor and display competitive standings within the game.
# Get Message Channels
Source: https://docs.b3.fun/basement/api-reference/get-message-channels
basement/basement-swagger.json post /launcher/get-message-channels
Retrieve all message channels for the user
# Get User Activities
Source: https://docs.b3.fun/basement/api-reference/get-user-activities
basement/basement-swagger.json get /activities
Retrieves user activities that were previously set using the SendCustomActivity function. It's particularly useful for tracking and displaying in-game events, achievements, or custom leaderboards.
# Get User Leaderboard Position
Source: https://docs.b3.fun/basement/api-reference/get-user-leaderboard-position
basement/basement-swagger.json post /launcher
Retrieves data from the game leaderboard via wallet address, providing you with information on player rankings and scores.
# Get User Scores
Source: https://docs.b3.fun/basement/api-reference/get-user-scores
basement/basement-swagger.json post /launcher/get-user-scores
Retrieve user scores for the game
# Get User States
Source: https://docs.b3.fun/basement/api-reference/get-user-states
basement/basement-swagger.json post /launcher/get-states
Retrieve user states for the game
# Renew Channel Heartbeat
Source: https://docs.b3.fun/basement/api-reference/renew-channel-heartbeat
basement/basement-swagger.json post /launcher/channel-heartbeat
Keep the user session alive by renewing the heartbeat
# Send Channel Message
Source: https://docs.b3.fun/basement/api-reference/send-channel-message
basement/basement-swagger.json post /launcher/send-channel-message
Send a message to a specific channel
# Send Custom Activity
Source: https://docs.b3.fun/basement/api-reference/send-custom-activity
basement/basement-swagger.json post /launcher/send-custom-activity
Send a custom activity event for the user
# Send Notification
Source: https://docs.b3.fun/basement/api-reference/send-notification
basement/basement-swagger.json post /launcher/send-notification
Send a notification to the user
# Set User Score
Source: https://docs.b3.fun/basement/api-reference/set-user-score
basement/basement-swagger.json post /launcher/set-user-score
Set or update user score for the game
# Set User State
Source: https://docs.b3.fun/basement/api-reference/set-user-state
basement/basement-swagger.json post /launcher/set-state
Set or update user state for the game
# Track Game Sessions
Source: https://docs.b3.fun/basement/api-reference/track-game-sessions
basement/basement-swagger.json post /launcher/track-game-sessions
Track and update game session data
# Trigger Rules Engine
Source: https://docs.b3.fun/basement/api-reference/trigger-rules-engine
basement/basement-swagger.json post /launcher/trigger-rules-engine
Trigger the rules engine with specific event data
# Unsend Channel Message
Source: https://docs.b3.fun/basement/api-reference/unsend-channel-message
basement/basement-swagger.json post /launcher/unsend-channel-message
Delete/unsend a message from a channel
# Verify Unverified Channel
Source: https://docs.b3.fun/basement/api-reference/verify-unverified-channel
basement/basement-swagger.json post /launcher/verify-unverified-channel
Verify an unverified channel with user's wallet signature
# BSMNT Brand Kit
Source: https://docs.b3.fun/basement/brand-kit
Follow these guidelines to use our brand correctly when contributing to the BSMNT community.
## Colors
Don't limit yourself to just this common brand colors. B3 invites you to be expressive with different fun, vibrant color palletes.
```
#8B5CF6
```
```
#6B7280
```
```
#FFFFFF
```
```
#1F2937
```
```
#E5E7EB
```
```
#F97316
```
## Brand Guidelines
**Make it nostalgia.**
Invoke a sense of childlike-play.
**Make it fun.**
Keep things light, friendly, and engaging.
## Fonts
We recommend using the Apple San Francisco.
[Download from Apple](https://developer.apple.com/fonts/)
[Download from Github](https://github.com/AppleDesignResources/SanFranciscoFont)
But have fun with other fonts...
## Fun Assets
## Contribute to BSMNT brand
Let's build B3 together - we welcome creators, artists, developers, gamers, players & everyone to contribute & be rewarded.
Reach out if you've built something cool for the B3 community.
# Construct Guide
Source: https://docs.b3.fun/basement/construct-guide
This guide will walk you through integrating your Construct game with the Basement.fun platform using web APIs
## Events
Construct has a great GUI that enables developers to create games with minimal to no code. The following docs will review how to connect your game to Basement.fun using Construct's event sheet.
### Key Components
You will need to add a few objects to your project to enable your Construct game to interact with the Basement.fun platform.
To add objects to your project go to the **Layout View**, right-click in the layout, select **Insert New Object**, and then choose the object you want to insert into your project. After adding the object, it will be available in your event sheet.
The Browser object enables you to write to the console. It's not necessary, but it will come in handy when verifying data and debugging your code.
The AJAX object enables your game to interact with B3 APIs.
* **POST requests** require you to create separate actions for each header parameter and one post to URL action for all the body parameters
* **GET requests** require you to combine all the parameters and values you need into a single URL to send the request to the API
* The **API responses** can be referenced using `AJAX.LastData`
The JSON object enables your game to handle JSON responses. You will need to parse the JSON strings to make use of the response data.
## Sample Event
This sample event will cover the POST Set Scores request detailed in the BSMNT API Specs.
### Sample Request
Right-click anywhere on the event sheet, create a function, and name it **SetScore**.
Click add action, select **AJAX**, select **Set request header**.
* **Header field**: `X-Service-Method`
* **Value field**: `setUserScore`
Add another AJAX action and select **Set request header** again.
* **Header field**: `Authorization`
* **Value field**: `Bearer `
Replace `` with your actual game secret token.
Add another AJAX action but this time, select **Post to URL**. Enter the following:
* **Tag**: `setUserScore`
* **URL**: `https://api.basement.fun/launcher`
* **Data**: `{"launcherJwt": "string", "nonce": "string", "score": 0}`
* **Method**: `POST`
This is a sample request - be sure to replace your values with variables that are set by events in your game.
### Sample Response
The sample response will look something like this:
```json API Response theme={null}
{
"success": true | false,
"error"?: "error string",
"newScore"?: {
"_id": "unique id",
"nonce": "nonce",
"updatedAt": 23151264, // unix timestamp
"score": 100.235,
"gameId": "game uuid",
"normalizedAddress": "user lowercase address"
}
}
```
## Retrieving Data
In Construct, let's retrieve the nonce from the response, so we can use it to retrieve the score at a later time.
Right-click anywhere on the event sheet and add a global variable named **Nonce**.
Add an event that is triggered by your game.
**Example**: To capture the user's score when they crash their bike into another bike, add an **on collision with another object** condition to the biker and set the object to biker.
Add the action, select **functions**, and select **SetScore**.
Add a **JSON** action, select **parse**, and enter `AJAX.LastData` in the JSON string field.
This will grab the response from our SetScore request.
Add a **system** action, select **set value**, choose the **Nonce** variable, and enter `JSON.Get("newScore.nonce")`.
Now your Nonce variable is set to the nonce returned by the API response!
## Complete Integration
Following the same steps, you can create events for each API endpoint by reviewing all the parameters and responses.
### Available API Endpoints
Update or set a user's score for leaderboards.
**Endpoint**: `POST /launcher`\
**Headers**: `X-Service-Method: setUserScore`
```json theme={null}
{
"launcherJwt": "string",
"nonce": "string",
"score": 0
}
```
Retrieve a user's current score.
**Endpoint**: `GET /launcher`\
**Headers**: `X-Service-Method: getUserScore`
Trigger onchain actions based on game events.
**Endpoint**: `POST /launcher`\
**Headers**: `X-Service-Method: triggerRulesEngine`
```json theme={null}
{
"launcherJwt": "string",
"trigger": "string",
"nonce": "string"
}
```
## Best Practices
Always check the `success` field in API responses and handle errors gracefully.
Use Construct's global variables to store important data like JWT tokens and user scores.
Use the Browser object to log important information to the console during development.
Be mindful of API rate limits and avoid making too many requests in quick succession.
## Next Steps
Complete API reference for all available endpoints
Learn how to integrate with the BSMNT game launcher
Official Construct 3 documentation and tutorials
Sample projects using BSMNT integration
## Troubleshooting
* Ensure you've added the AJAX object to your project
* Check that all required headers are set correctly
* Verify your game secret is valid
* Make sure the API endpoint URL is correct
* Confirm the JSON object is added to your project
* Check that `AJAX.LastData` contains valid JSON
* Use the Browser object to log the raw response for debugging
* Verify your launcher JWT token is valid
* Check that the Authorization header is properly formatted
* Ensure your game secret hasn't expired
# Game Launcher
Source: https://docs.b3.fun/basement/game-launcher
Launch games natively inside the BSMNT (basement.fun) platform and build addicting onchain experiences without having to worry about the crypto components
## How It Works
Your game loads inside BSMNT launcher. We pass a JWT with the auth token to your game.
```text Example URL theme={null}
https://yourgame.com?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```
You can load the player's profile by decoding the JWT, or by using our API. We'll take care of wallet connections, verification & onboarding.
```json Player Profile theme={null}
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"address": "0x1234567890abcdef1234567890abcdef12345678",
"username": "CryptoGamer42",
"avatar": "https://avatars.b3.fun/avatar.png",
"gameId": "game-123456-abcdef",
"license": "550e8400-e29b-41d4-a716-446655440000",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
Let the user play your game. When something happens, you can trigger an action via our Zapier-style rules engine, or directly via API.
```bash Trigger API Example theme={null}
curl --location 'https://api.basement.fun/launcher/' \
--header 'X-Service-Method: triggerRulesEngine' \
--data '{
"launcherJwt": "{{ jwt }}",
"trigger": "achievementUnlocked",
"nonce": "d1312e"
}'
```
Get started building games with BSMNT launcher
Test the launcher integration in a sandbox environment
## What can you do with BSMNT launcher?
The real power of the game launcher is in the crypto UX abstraction. Your game can securely send onchain events through a simple REST API, executable client side.
### Available Now
Store player state on decentralized storage options like IPFS.
Let users mint NFTs upon achievements or on certain game events.
Bring player rankings onchain, host contests & tournaments.
Send ERC20s and ERC721 & 1155 NFTs based on game actions.
Prompt users to send or transfer tokens to pay for in-game actions or assets.
### Coming Soon
Users can use assets from other chains to swap for your tokens.
COMING SOON
Direct fiat to crypto onramp for seamless user experience.
COMING SOON
Built-in review and rating system for games.
COMING SOON
Social sharing and viral mechanics.
COMING SOON
Automatic gameplay recording and sharing.
COMING SOON
Marketplace integration for trading game assets.
COMING SOON
And more actions coming - the future looks bright!
## Getting Started
We'd love to have your game on basement.fun! It's simple, free, and easy to start integrating.
Sign up to start integrating your game with BSMNT launcher
Already registered?
Test your integration in a sandbox environment
Complete API documentation and examples
No vaporware here - play Games on BSMNT today!
No vaporware - play today!
## What is Basement.fun?
Basement is the place to discover & play onchain games. Aside from being a discovery platform for finding great onchain games, Basement offers a way for game developers to build seamless, native, and embedded experiences within Basement.
Your game is loaded inside our game launcher, where users connect to Basement, and their player context is passed down to your game.
From there, you can leverage any of our generic helper functions (such as saving state & scores) + trigger any number of built-in crypto UX (without you having to integrate anything onchain in your game).
## Access Player Data
The game launcher uses a JWT (JSON Web Token) to securely encode a verified & authenticated player context, which is sent to your game.
The payload is read from the GET parameters, so any hosted web game can easily access & decode it using any number of JWT libraries (or using our launcher APIs).
### Basic Player Data Includes:
Username (and compatible .b3.fun ENS resolvable address)
3D Avatar (.GLB model powered by ReadyPlayerMe)
Verified wallet address for onchain interactions
Game-specific player data, session information, and more - see our Launcher API Docs
You can optionally store any arbitrary game-specific player data using our player state APIs.
Complete documentation for player data access and game integration
## Built-in UX Abstraction
Our minimal game launcher experience means that the focus stays on your game.
A number of customizations are available on the game launcher, so that BSMNT can provide an almost invisible experience, handling all of the core crypto UX challenges for you.
### Helpful APIs Available:
* **Store & retrieve scores & leaderboards** - Persistent game state management
* **Send notifications** - Alert players about game events
* **Log and stream game activity** - Analytics and player behavior tracking
* **Store player state and game sessions** - Save game progress automatically
* **And more coming!** - New features added regularly
Complete API reference for all available launcher features
## Architecture Overview
Connected: 0x..123
[www.yourgame.com](http://www.yourgame.com)
Your game loads inside BSMNT launcher
# Basement.fun
Source: https://docs.b3.fun/basement/introduction
Basement is B3's consumer gaming platform, providing developers and players with powerful tools to build, deploy, and play onchain games.
## What is Basement?
Basement is the gaming-focused layer of the B3 ecosystem, designed specifically for game developers and gaming communities. It provides:
* **Game Launcher**: Deploy and manage games on B3
* **Developer Tools**: SDKs and APIs for game development
* **Community Features**: Player profiles, achievements, and social features
* **Brand Resources**: Assets and guidelines for consistent branding
Play on the basement.fun app
## Getting Started
Learn how to deploy your games using the Basement Game Launcher
Integrate B3 features into your Unity games
Build games with Construct 3 and B3 integration
Access Basement branding assets and guidelines
## Key Features
Comprehensive software development kits for Unity, Construct, and other popular game engines, enabling seamless integration with B3's blockchain features.
Global account system that allows players to maintain consistent profiles, achievements, and assets across all games in the Basement ecosystem.
Tools for managing in-game assets, NFTs, and tokens, with easy integration for developers and transparent ownership for players.
Built-in social features, leaderboards, tournaments, and community management tools to enhance player engagement.
Ready to start building? Check out our [Game Launcher Guide](/basement/game-launcher) to deploy your first game on B3.
# B3 Unity SDK
Source: https://docs.b3.fun/basement/unity-guide
Integrate your Unity games into basement with the B3 Unity SDK, which lets you easily access all of the launcher functionalities from within Unity as simple functions
## Features
The B3 Unity SDK provides comprehensive integration capabilities for Unity developers:
The SDK automatically and seamlessly handles user authentication.
Use all of the launcher APIs easily with support for both callback based AND async/await based calls.
Handles launcher client webhooks, and parses and propagates them to your own C# Code.
## Installation and Usage
Head over to the GitHub repository and download the latest release.
Access the official B3 Unity SDK repository with installation instructions
Follow the setup guide instructions on GitHub to install the SDK to your Unity Project.
The GitHub repository contains detailed installation instructions and setup requirements.
After installing the SDK and following the setup guide, you'll be able to easily call all the APIs as functions.
Your Unity project is now ready to integrate with the B3 launcher!
## Code Examples
### Trigger Rules Engine
Here's an example of how to trigger the rules engine from within your Unity game:
```csharp Unity C# Example theme={null}
B3LauncherClient.TriggerRulesEngine(new B3LauncherClient.TriggerRulesEngineBody
{
launcherJwt = B3Instance.Instance.SessionJWT ?? jwtInput.text,
trigger = "open-tip-modal",
otherWallet = otherWalletInput.text,
}, null);
```
### Session Management
The SDK automatically handles user sessions:
```csharp Session Example theme={null}
// Access the current session JWT
string sessionToken = B3Instance.Instance.SessionJWT;
// Check if user is authenticated
if (B3Instance.Instance.IsAuthenticated)
{
// User is logged in and ready to interact with B3 services
Debug.Log("User authenticated successfully");
}
```
## API Integration
The Unity SDK provides seamless access to all B3 launcher APIs:
Traditional callback pattern for handling API responses:
```csharp theme={null}
B3LauncherClient.SomeAPICall(requestData, (response) => {
// Handle response
Debug.Log("API call completed");
});
```
Modern async/await pattern for cleaner code:
```csharp theme={null}
public async void CallAPI()
{
var response = await B3LauncherClient.SomeAPICallAsync(requestData);
// Handle response
Debug.Log("API call completed");
}
```
Handle launcher events in WebGL builds:
```csharp theme={null}
// Register webhook handlers
B3Instance.Instance.OnWebhookReceived += HandleWebhook;
private void HandleWebhook(WebhookData data)
{
// Process incoming webhook data
Debug.Log($"Received webhook: {data.type}");
}
```
## Next Steps
Learn how to integrate with the BSMNT game launcher
Complete API documentation for all available endpoints
Official Unity documentation and resources
Sample Unity projects using the B3 SDK
## Support
For technical support, bug reports, or feature requests, please visit the GitHub repository or reach out to our developer community.
Report issues or get help from the developer community
# Get blocks
Source: https://docs.b3.fun/data/api-reference/insightsblocks/get-blocks
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/blocks
Get blocks
# Get contract ABI
Source: https://docs.b3.fun/data/api-reference/insightscontracts/get-contract-abi
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/contracts/abi/{contractAddress}
Get contract ABI
# Get contract metadata
Source: https://docs.b3.fun/data/api-reference/insightscontracts/get-contract-metadata
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/contracts/metadata/{contractAddress}
Get contract metadata
# Decode logs and transactions
Source: https://docs.b3.fun/data/api-reference/insightsdecode/decode-logs-and-transactions
https://data-api.b3.fun/swagger.json?v=1 post /insights/v1/decode/{contractAddress}
Decode logs and transactions
# Force refresh collection metadata
Source: https://docs.b3.fun/data/api-reference/insightsnfts/force-refresh-collection-metadata
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/metadata/refresh/{contract_address}
Force refresh collection metadata for the specified contract (across multiple chains if provided)
# Force refresh token metadata
Source: https://docs.b3.fun/data/api-reference/insightsnfts/force-refresh-token-metadata
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/metadata/refresh/{contract_address}/{token_id}
Force refresh token metadata for the specified contract and token ID (across multiple chains if provided)
# Get collection
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-collection
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/collections/{contract_address}
Retrieve metadata about a collection
# Get NFT balances by address
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-balances-by-address
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/balance/{ownerAddress}
Get NFT balances for a given address
# Get NFT by token ID
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-by-token-id
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/{contract_address}/{token_id}
Get NFT by token ID
# Get NFT owners by contract
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-owners-by-contract
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/owners/{contract_address}
Get NFT owners by contract
# Get NFT owners by token
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-owners-by-token
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/owners/{contract_address}/{token_id}
Get NFT owners by token
# Get NFT transfers
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-transfers
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/transfers
Get NFT transfers
# Get NFT transfers by contract
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-transfers-by-contract
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/transfers/{contract_address}
Get NFT transfers by contract
# Get NFT transfers by token
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-transfers-by-token
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/transfers/{contract_address}/{token_id}
Get NFT transfers by token
# Get NFT transfers by transaction
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nft-transfers-by-transaction
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/transfers/transaction/{transaction_hash}
Get NFT transfers by transaction
# Get NFTs
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nfts
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts
Get NFTs
# Get NFTs by contract
Source: https://docs.b3.fun/data/api-reference/insightsnfts/get-nfts-by-contract
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/nfts/{contract_address}
Get NFTs by contract
# Resolve
Source: https://docs.b3.fun/data/api-reference/insightsresolve/resolve
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/resolve/{input}
Resolve
# Get ERC-1155 balances by address
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-erc-1155-balances-by-address
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/erc1155/{ownerAddress}
Get ERC-1155 (Multi Token) balances for a given address [BEING DEPRECATED IN FAVOR OF /nfts/balance]
# Get ERC-721 balances by address
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-erc-721-balances-by-address
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/erc721/{ownerAddress}
Get ERC-721 (NFT) balances for a given address [BEING DEPRECATED IN FAVOR OF /nfts/balance]
# Get supported tokens for price data
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-supported-tokens-for-price-data
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/price/supported
Get supported tokens for price data
# Get token price
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-token-price
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/price
Get price in USD for given token(s)
# Get tokens
Source: https://docs.b3.fun/data/api-reference/insightstokens/get-tokens
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens
Query tokens
# Token lookup
Source: https://docs.b3.fun/data/api-reference/insightstokens/token-lookup
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/tokens/lookup
Look up a fungible token by symbol
# Get wallet transactions
Source: https://docs.b3.fun/data/api-reference/insightswallets/get-wallet-transactions
https://data-api.b3.fun/swagger.json?v=1 get /insights/v1/wallets/{wallet_address}/transactions
Get incoming and outgoing transactions for a wallet
# Profile Lookup
Source: https://docs.b3.fun/data/profiles/lookup/profile-lookup
profiles-swagger.json get /
Retrieves aggregated profile information for a given address or name. Combines data from multiple Web3 identity sources including ENS, Lens, Farcaster, and Basement profiles.
# Set Custom Display Name
Source: https://docs.b3.fun/data/profiles/preferences/set-custom-display-name
profiles-swagger.json post /display-name
Allows users to set a custom display name that takes priority over display names from all profile sources through cryptographic signature verification.
# Set Profile Preference
Source: https://docs.b3.fun/data/profiles/preferences/set-profile-preference
profiles-swagger.json post /preference
Allows users to set their preferred profile source through cryptographic signature verification. The signature must be valid and the timestamp must be within 10 minutes of the current time.
# ArenaCoins
Source: https://docs.b3.fun/hypeduel/arenacoins
Arena-specific tokens with bonding curve pricing that let you own a piece of AI battle environments
**ArenaCoins** are the native tokens for each battle environment on HypeDuel — a revolutionary way to own a piece of the action in the world's first AI vs AI entertainment arena. Every arena has its own unique token that appreciates with arena success.
## Core Concept
```mermaid theme={null}
graph TD
subgraph "Arena Creation"
AC[Arena Created] --> BP[Bonding Phase Starts]
BP --> BC[Bonding Curve Pricing]
end
subgraph "Community Building"
BC --> PB[Players Bond $B3]
PB --> RA[Receive ArenaCoins]
RA --> ES[Early Supporters]
end
subgraph "Arena Growth"
ES --> LB[Live Battles Begin]
LB --> BF[Betting & Fees Generate]
BF --> RS[Revenue Sharing]
end
subgraph "Token Features"
RS --> RV[Revenue from Bets]
RS --> BR[Boost Revenue]
RS --> TF[Trading Fees]
RV --> TB[Token Buybacks]
BR --> TB
TF --> TB
end
subgraph "Value Creation"
TB --> VA[Value Appreciation]
VA --> CG[Community Growth]
CG --> AT[Attract Traders]
AT --> DX[DEX Trading]
end
DX --> TF
CG --> LB
style AC fill:#e3f2fd
style RA fill:#e8f5e8
style RS fill:#fff3e0
style VA fill:#c8e6c9
```
### What Makes ArenaCoins Unique
Each battle environment has its own unique ArenaCoin ($COMBAT, $RACING, etc.)
Fair price discovery through mathematical curves, no front-running possible
Earn fees from every bet, boost, and trade in your arena
ArenaCoin holders vote on arena improvements and rule changes
## ArenaCoin Lifecycle
### Phase 1: Arena Creation & Bonding
When a new arena launches, it enters the **bonding phase**:
Creator deploys new battle environment with unique gameplayPlayers can bond \$B3 to receive ArenaCoins at curve pricesEarly supporters accumulate tokens and build initial communityArena reaches bonding targets (liquidity + community size)
### Phase 2: DEX Trading
After successful bonding, ArenaCoins graduate to full market trading:
* **Uniswap Pool**: ArenaCoin/\$B3 trading pair created
* **Market Discovery**: Open market determines token value
* **Liquidity Provision**: Bonding funds seed initial liquidity
* **Fee Generation**: Trading fees support arena economy
## Bonding Curve Mechanics
### Mathematical Foundation
ArenaCoins use a **quadratic bonding curve** for fair price discovery:
```typescript theme={null}
// Bonding curve pricing formula
function calculatePrice(supply: number, bondingConstant: number): number {
return (supply / bondingConstant) ** 2;
}
// Example with $COMBAT arena
const bondingConstant = 1000000; // 1M tokens at 1:1 ratio
const currentSupply = 250000; // 250k tokens minted
const pricePerToken = (250000 / 1000000) ** 2;
// = 0.25^2 = 0.0625 $B3 per ArenaCoin
```
### Bonding Benefits
* No pre-sale or insider allocations - Price increases with demand - Early supporters get better prices -
Mathematical price discovery
* Always possible to buy/sell - No reliance on market makers - Curve provides instant liquidity - Predictable price
impact
* No front-running possible - Large purchases have price impact - Curve naturally deters pumps - Transparent pricing
algorithm
### Bonding Example
Let's trace an early investor's journey:
* **Arena**: Combat Simulator launches - **Supply**: 0 $COMBAT tokens exist - **Price**: Starting price ≈ 0.001 $B3
* **Investment**: Alice bonds 100 $B3 - **Received**: ~316 $COMBAT tokens
* **Supply**: 50,000 $COMBAT tokens minted - **Price**: ~0.0025 $B3 per token - **Alice's Holdings**: 316 tokens worth
\~79 $B3 - **Investment**: Bob bonds 500 $B3 - **Received**: \~200 \$COMBAT tokens
* **Supply**: 200,000 $COMBAT tokens minted - **Price**: ~0.04 $B3 per token - **Alice's Holdings**: 316 tokens
worth \~126 \$B3 - **Community**: Active battles and growing user base - **Graduation**: Arena approaches DEX listing
criteria
## Revenue Sharing Model
ArenaCoins generate value through multiple revenue streams:
### Primary Revenue Sources
```mermaid theme={null}
graph LR
subgraph "Revenue Sources"
A[Betting Activity] --> B[10% of Pools to Treasury]
C[Boost Purchases] --> D[50% to Treasury]
E[DEX Trading] --> F[66% of Fees to Treasury]
end
subgraph "Arena Treasury"
B --> T[Arena Treasury]
D --> T
F --> T
end
subgraph "Treasury Actions"
T --> G[ArenaCoin Buybacks]
T --> H[Token Burns]
T --> I[Liquidity Support]
end
subgraph "Value Impact"
G --> J[Reduced Supply]
H --> J
I --> K[Improved Trading]
J --> L[Price Appreciation]
K --> L
end
subgraph "Community Benefits"
L --> M[Higher Token Value]
M --> N[Increased Interest]
N --> O[More Players]
O --> A
O --> C
O --> E
end
style T fill:#fff3e0
style L fill:#c8e6c9
style M fill:#e8f5e8
```
**10% of all betting pools** - Collected from every battle - Proportional to betting volume - Accumulates in arena
treasury - Used for token buybacks *Example: 10,000 HYPES betting pool = 1,000 HYPES to treasury*
**50% of boost purchases** - Real-time revenue from interactive features - Higher engagement = more revenue - Scales
with arena popularity - Immediate treasury impact *Example: 500 HYPES in boosts = 250 HYPES to treasury*
**66% of DEX trading fees** (post-graduation) - Continuous revenue from token trading - Grows with token adoption -
Market-driven revenue scaling - Long-term sustainability *Example: 1% trading fee, 66% to treasury*
# Arenas
Source: https://docs.b3.fun/hypeduel/arenas
Explore the diverse battle environments where AI models compete across different gameplay types
Arenas are the heart of HypeDuel - unique competitive environments where AI models battle in specialized scenarios. Each arena features distinct gameplay mechanics, AI challenges, and community economies powered by ArenaCoins.
## Arena Lifecycle
### Development Stages
Arena creators develop the core gameplay concept, rules, and AI requirementsBuild the battle engine, AI integration, and boost systemAlpha and beta testing with community feedback and AI model optimizationPublic launch with ArenaCoin bonding phase and initial community buildingOngoing development, feature additions, and community expansion
### Community Building
**Arena Success Factors**:
**Player Retention Strategies** - Regular content updates and new features - Community events and tournaments -
Leaderboards and achievement systems - Social features and player interaction - Creator communication and
transparency
**Fair Competition Maintenance** - AI model performance balancing - Boost effectiveness tuning - Economic parameter
adjustments - Community feedback integration - Regular meta analysis and updates
**Continuous Improvement** - New AI model integration - Gameplay mechanic enhancements - Visual and technical
upgrades - Cross-arena collaboration features - Cutting-edge technology adoption
## Arena Economics
### Revenue Generation
Each arena generates revenue through multiple streams:
**10% of all betting pools** - Consistent revenue from active player base - Scales with betting volume and frequency
* Predictable income stream for planning - Drives ArenaCoin value through buybacks **Optimization Strategies**: -
Increase battle frequency during peak hours - Optimize match duration for maximum engagement - Implement dynamic
pricing for special events - Create compelling betting narratives
**50% of boost purchase revenue** - Higher-margin revenue with growth potential - Increases during exciting or close
battles - Encourages interactive gameplay participation - Creates additional engagement beyond betting **Growth
Tactics**: - Develop unique and powerful boost types - Balance boost effects for strategic importance - Create boost
combinations and synergies - Implement dynamic boost pricing
**66% of ArenaCoin trading fees (post-DEX)** - Passive revenue requiring minimal effort - Grows with token adoption
and speculation - Benefits from overall crypto market growth - Provides long-term sustainability **Enhancement
Methods**: - Build strong token holder community - Implement governance and utility features - Partner with other
DeFi protocols - Create token burn mechanisms
### Performance Metrics
**Key Arena Success Indicators**:
* Daily active users and retention rates - Average session duration and depth - Community growth and social activity -
User-generated content and feedback
* Total betting volume and growth trends - Revenue per user and monetization - ArenaCoin market cap and trading volume
* Treasury balance and buyback activity
* AI model win rate distribution - Betting pool distribution patterns - Boost usage effectiveness rates - Battle
outcome unpredictability metrics
* Battle execution speed and reliability - User interface responsiveness - Server uptime and error rates - Scalability
and performance optimization
# Betting System
Source: https://docs.b3.fun/hypeduel/betting-system
Comprehensive guide to HypeDuel's parimutuel betting mechanics, odds calculation, and payout structure
HypeDuel's betting system is built on **parimutuel principles** - a fair, transparent method where all bets are pooled together and winners share the total prize pool. This creates dynamic odds and ensures the house never has an unfair advantage.
## How Parimutuel Betting Works
Unlike traditional sportsbooks with fixed odds, parimutuel betting creates a fair, community-driven wagering environment:
### Traditional Betting vs Parimutuel
```
House sets odds: AI Alpha wins at 2:1
├── Player bets 100 HYPES
├── If wins: receives 200 HYPES
├── If loses: house keeps 100 HYPES
└── House profit built into odds
```
```
Community creates pool: All bets combined
├── Players bet on different AIs
├── Winners share entire prize pool
├── Odds change based on betting patterns
└── No house advantage - transparent fees only
```
## Betting Process
### Step-by-Step Betting
Choose an active arena with upcoming AI battles
Review competing AI models: - Recent performance statistics - Head-to-head battle history - Community betting
patterns - Technical specifications
* Select your preferred AI - Enter bet amount in HYPES - Review potential payout range - Confirm bet placement
Watch how betting patterns affect potential payouts as more players join
## Prize Pool Distribution
Every betting pool follows a transparent fee structure:
```
Total Betting Pool: 100%
├── 85% → Winners (proportional distribution)
├── 10% → Arena Treasury (token buybacks)
└── 5% → Arena Creator (development reward)
```
### Winner Payout Calculation
Winners receive payouts proportional to their bet size within the winning pool:
```typescript theme={null}
function calculatePayout(playerBet: number, winningPool: number, totalWinnerPayout: number): number {
const playerShare = playerBet / winningPool;
const payout = totalWinnerPayout * playerShare;
return payout;
}
```
**Example Scenario**:
* Total pool: 10,000 HYPES
* Your bet on AI Alpha: 500 HYPES
* Total bets on AI Alpha: 2,000 HYPES
* AI Alpha wins!
**Your payout**:
```
Winner pool share: 8,500 HYPES (85% of 10,000)
Your share: 500 / 2,000 = 25% of winning bets
Your payout: 8,500 × 0.25 = 2,125 HYPES
Return: 325% (4.25:1 odds)
```
## Betting Limits & Rules
### Minimum & Maximum Bets
* **Standard Arenas**: 10 HYPES minimum
* **Premium Arenas**: 50 HYPES minimum
* **Tournament Events**: 100 HYPES minimum
*Minimums ensure meaningful prize pools and prevent spam betting*
* **Per Battle**: 10,000 HYPES maximum - **Per Player Daily**: 50,000 HYPES maximum - **Arena Pool**: No single bet
can exceed 50% of current pool *Maximums prevent market manipulation and ensure fair play*
* **Tournament Finals**: Higher limits may apply
* **New Arena Launch**: Reduced limits during bonding phase
* **Maintenance Periods**: Betting may be temporarily suspended
### Betting Cutoff Times
Bet placement deadlines ensure fair competition:
* **Standard Battles**: 30 seconds before match start
* **Quick Battles**: 15 seconds before match start
* **Tournament Matches**: 60 seconds before match start
Bets placed after cutoff time will be rejected and funds returned immediately to your HYPES balance.
# Boosts System
Source: https://docs.b3.fun/hypeduel/boosts
Interactive power-ups that let you influence AI battle outcomes in real-time
The Boosts system transforms HypeDuel from passive viewing to active participation. Purchase single-use power-ups with HYPES tokens to directly influence AI battle outcomes while matches are happening.
## What Are Boosts?
**Boosts** are real-time power-ups that provide temporary, random advantages to some/all AI competitors during battles. Unlike betting (which is passive), boosts let you actively participate in the competition as it unfolds.
### Key Characteristics
* **Single-Use**: Each boost can only be used once per battle
* **Real-Time**: Deploy during live matches for immediate effect
* **Limited Availability**: Finite quantities create strategic scarcity
* **Arena-Specific**: Different boost types for each arena environment
## How to Use Boosts
### Purchasing Boosts
Navigate to an active battle arena with live matchesBoosts are displayed below the live game screenPay HYPES cost and boosts are added to your inventory
## Boost Economics
### Revenue Distribution
Boost purchases generate revenue shared between arena stakeholders:
```
Boost Purchase: 100%
├── 50% → Arena Treasury (token buybacks)
└── 50% → Arena Creator (development incentive)
```
### Economic Optimization
Smart boost usage can improve ROI:
1. **Value Betting**: Boost underdogs for higher payout multipliers
2. **Insurance Boosting**: Protect large bets with defensive boosts
3. **Momentum Trading**: Chain boosts to create decisive advantages
4. **Arbitrage Opportunities**: Identify mispriced boost effects
# Launch Your Arena
Source: https://docs.b3.fun/hypeduel/developers
Information for developers looking to create their own arenas on HypeDuel
HypeDuel Arenas are built in Unity, with each arena having one server headless build that runs on the HypeDuel servers and simulates the duel in real time, and one webGL build which runs on the clientside and receives the streamed simulation data to playback.
[Contact us to add your game](https://b3builders.typeform.com/hypeduel)
## Unity SDK
We offer a unity SDK to fascillitate the creation of arenas. What follows is an overview of the steps required to integrate the SDK and create the arena in unity.
* Create your server-side scene.
* Setup your environment, gameplay mechanics, and train your agents with unity ml-agents
* Setup \*\*HypeDuelRecorder \*\*to track your main scene objects in space.
* Call the recorder's \*\*PushStateChange \*\*method to stream any state data to the clients.
* Set the state scores property in order for the server to be able to detect the match's progress and resolution at the end.
* Build for Linux Dedicated Server and upload your build to hypeduel.
* Create your client-side scene.
* Duplicate of the server side, but with graphics and without the agent logic.
* The \*\*HypeDuelRecorder \*\*will automatically playback the positions of your main scene objects
* Listen to events of the \*\*HypeDuelClient \*\*instance to use your state changes to manage the UI and graphical elements of your game.
FIND THE UNITY SDK ON [GitHub](https://github.com/b3-fun/hypeduel-unity)
* Integration guide and further documentation on readme.md
## How it Works
When a match begins on HypeDuel, we run the arena's server build which sends back realtime data from the simulation. Clients on the website are running their own webGL versions of the arena (the client-side build) and connect to our API which streams all the simulation data, which is then used in unity to recreate the exact same scene.
```mermaid theme={null}
graph TD
A["Unity SDK ⚙️"] --> B["Server Scene 🖥️"]
A --> C["Client Scene 🎮"]
B --> E["ML-Agents & Gameplay Logic"]
B --> F["Recorder Tracking"]
B --> G["PushStateChange + Scores"]
C --> H["Duplicate Scene"]
C --> I["Recorder Playback"]
C --> J["Client Events → UI"]
```
# Frequently Asked Questions
Source: https://docs.b3.fun/hypeduel/faq
Answers to common questions about HypeDuel, tokens, betting, and arena mechanics
Get answers to the most common questions about HypeDuel's AI entertainment platform, tokenomics, and gameplay mechanics.
## Getting Started
HypeDuel is the world's first AI vs AI entertainment platform where you can watch, bet, and speculate on artificial intelligence battles. AI models compete in real-time across various arena environments while players bet on outcomes using HYPES tokens and influence battles with interactive boosts.
1. Visit [hypeduel.com](https://hypeduel.com) 2. Connect your wallet or create an account 3. Deposit funds (credit
card or crypto) to receive HYPES tokens 4. Choose an arena and place your first bet 5. Watch AI battles and enjoy the
experience! Check out our [Quick Start Guide](/hypeduel/quick-start) for detailed instructions.
No! While HypeDuel is built on blockchain technology, you can use it just like any other gaming platform: - Pay with
credit card to get HYPES tokens - All betting happens instantly without blockchain delays - Withdraw winnings easily
when you're ready - No need to understand gas fees or transaction confirmations
HypeDuel works on:
* **Desktop**: Chrome, Firefox, Safari, Edge browsers
* **Mobile**: Mobile-optimized web app (iOS/Android)
* **Tablet**: Full functionality on tablet browsers
*Native mobile apps are planned for Q2 2024*
## Tokens & Economics
**HYPES** are platform credits with a 1:1 exchange rate with **\$B3**:
* **HYPES**: Used for betting and boosts, instant transactions, no gas fees
* **\$B3**: Base ecosystem token, used for ArenaCoins bonding and cross-platform activities
You can convert between them anytime at a 1:1 rate. HYPES provide a smooth gaming experience while \$B3 offers broader ecosystem utility.
Yes! You can withdraw your HYPES as \$B3 tokens anytime: - **Instant conversion**: 1:1 rate guaranteed - **No fees**:
Free withdrawals to your wallet - **No minimums**: Withdraw any amount - **24/7 availability**: Withdraw whenever you
want Simply click "Withdraw" in your account dashboard and confirm the transaction.
When you lose a bet: - Your HYPES balance decreases by the bet amount - The lost HYPES join the prize pool for winners
* You can immediately place new bets for upcoming matches - Your account history tracks all betting activity Remember:
only bet what you can afford to lose, and consider HypeDuel entertainment rather than investment.
**ArenaCoins** are unique tokens for each arena that let you:
* Earn fees from all arena betting and boost activity
* Participate in arena governance decisions
* Benefit from arena growth and popularity
* Trade on bonding curves and DEX markets
**Investment considerations**:
* Higher risk than \$B3/HYPES but potentially higher rewards
* Research arena quality and creator track record
* Start small while learning the mechanics
* Consider it speculative investment, not guaranteed returns
## Betting & Gameplay
Match frequency varies by arena:
* **Standard Arenas**: New match every 3-5 minutes
* **Popular Arenas**: Continuous matches with 2-minute intervals
* **Tournament Events**: Scheduled matches with specific times
* **New Arenas**: May have longer intervals while building community
Check each arena's schedule for specific timing information.
There's no limit! The parimutuel betting system means: - Unlimited players can bet on any match - More players =
bigger prize pools - Your payout depends on how much you bet relative to other winners - Popular matches often have
hundreds of participants
Prize pools come entirely from player bets: - **85%** goes to winners (shared proportionally) - **10%** goes to arena
treasury (token buybacks) - **5%** goes to arena creator (development incentive) There's no external funding - winners
are paid by losing bets, making it a fair, zero-sum competition.
AI battles use deterministic systems: - **Fair Competition**: All AI models follow the same rules - **Verifiable
Results**: Battle outcomes are reproducible - **Anti-Manipulation**: Multiple safeguards prevent cheating -
**Transparent Logic**: Core battle mechanics are open for review Results depend on AI model quality, arena-specific
challenges, and some controlled randomness for excitement.
Yes, through the **Boosts system**: - Purchase power-ups with HYPES during live battles - Boosts provide temporary
advantages to specific AI models - Effects are immediately visible in the battle - Strategic timing and boost
selection can impact results Learn more in our [Boosts Guide](/hypeduel/boosts).
Betting limits ensure fair play:
**Minimums**:
* Standard arenas: 10 HYPES
* Premium arenas: 50 HYPES
* Tournament events: 100 HYPES
**Maximums**:
* Per battle: 10,000 HYPES
* Daily limit: 50,000 HYPES
* Pool percentage: Maximum 50% of current pool
Limits may be adjusted based on arena popularity and community feedback.
## Technical & Security
Yes! HypeDuel implements multiple security layers:
**Smart Contract Security**:
* Professional security audits of all core contracts
* Multi-signature controls for treasury management
* Emergency pause mechanisms for unusual events
**Battle Integrity**:
* Deterministic AI battle results
* Anti-manipulation detection systems
* Community reporting and verification
**Financial Security**:
* HYPES backed 1:1 by \$B3 reserves
* Transparent treasury operations on-chain
* Insurance reserves for exceptional circumstances
HypeDuel operates on **Base**, Coinbase's Layer 2 Ethereum network: - **Fast transactions**: Near-instant
confirmations - **Low fees**: Minimal gas costs for blockchain operations - **Ethereum security**: Inherits Ethereum's
security guarantees - **Easy onboarding**: Coinbase integration for new users Future expansion to other chains is
planned based on community demand.
Technical issues are handled through established protocols:
**Minor Issues**:
* Automatic retry mechanisms
* Real-time monitoring and alerts
* Quick resolution with minimal disruption
**Major Issues**:
* Match may be paused or restarted
* All bets refunded if match cannot complete
* Detailed incident reports provided to community
* Insurance reserves available for compensation
**Communication**:
* Real-time status updates on platform
* Discord announcements for major issues
* Post-incident analysis and improvement plans
## Arena Creation & Investment
Yes! Arena creation is open to developers:
**Requirements**:
* Technical ability to build arena environments
* AI models or partnerships with AI developers
* Community building and marketing capabilities
* Understanding of HypeDuel's economic model
**Process**:
1. Submit arena proposal to community
2. Technical review and approval process
3. Launch bonding phase for community funding
4. Ongoing development and community management
See our [Arena Creation Guide](/hypeduel/arena-creation) for details.
Research these key factors before investing: **Arena Quality**: - Unique and engaging gameplay mechanics -
High-quality AI model competition - Strong visual and technical execution - Active community and regular updates
**Creator Track Record**: - Previous successful projects - Technical expertise and commitment - Community engagement
and communication - Clear roadmap and vision **Market Metrics**: - Daily active users and engagement - Betting volume
and revenue growth - Token holder distribution - Social media activity and sentiment Always do your own research and
never invest more than you can afford to lose.
ArenaCoins go through two distinct phases:
**Bonding Phase** (Early Stage):
* Buy/sell directly with bonding curve pricing
* Price increases mathematically with demand
* Guaranteed liquidity from the curve
* Early investor advantages
**DEX Trading** (After Graduation):
* Trade on Uniswap with \$B3 pairs
* Market-driven price discovery
* Higher liquidity and volume
* Advanced trading features available
Most successful arenas graduate from bonding to DEX trading within 1-3 months.
## Platform Features
Yes! Multiple leaderboards track different achievements:
**Player Rankings** ([hypeduel.com/leaderboard](https://hypeduel.com/leaderboard)):
* Top winners by total profits
* Best win rates across all arenas
* Highest single-match winnings
* Most successful boost users
**Arena Rankings**:
* Most popular arenas by betting volume
* Highest revenue-generating arenas
* Fastest-growing communities
* Best-performing ArenaCoins
**AI Model Rankings**:
* Win rates by arena type
* Most improved models
* Community favorites
* Technical performance metrics
Yes! A comprehensive referral system is planned: **Referral Benefits**: - Earn percentage of friends' betting fees -
Bonus HYPES for successful referrals - Special recognition and badges - Exclusive access to new features **Loyalty
Rewards**: - Daily login bonuses - Volume-based tier rewards - Achievement unlocks and prizes - Community event
participation rewards *Launch planned for Q1 2024 - join Discord for early access*
Currently HypeDuel is optimized for mobile web browsers:
* **Mobile Web**: Full functionality on phone browsers
* **Responsive Design**: Adapts to any screen size
* **Touch Optimized**: Easy betting and boost controls
* **Fast Loading**: Optimized for mobile connections
**Native Apps Coming**:
* iOS app planned for Q2 2024
* Android app planned for Q2 2024
* Push notifications for match results
* Offline viewing of battle history
## Troubleshooting
Common reasons bets fail:
**Insufficient Balance**:
* Check your HYPES balance
* Deposit more funds if needed
**Match Already Started**:
* Betting closes 15-60 seconds before match start
* Wait for the next match in the arena
**Technical Issues**:
* Refresh the page and try again
* Check your internet connection
* Clear browser cache if problems persist
**Arena Maintenance**:
* Some arenas may be temporarily offline
* Check arena status indicators
* Try a different arena
If problems persist, contact support through Discord.
Winnings should appear automatically: **Normal Process**: - Winnings credited within 30 seconds of match end - Check
your HYPES balance in account dashboard - Review transaction history for confirmation **If Missing**: - Refresh the
page and wait up to 2 minutes - Check that you bet on the winning AI - Verify match actually completed (wasn't
cancelled) - Contact support with match details if still missing All transactions are recorded on-chain for
verification.
Arena display issues are usually temporary:
**Quick Fixes**:
* Refresh the browser page
* Check your internet connection
* Try a different browser
* Disable browser extensions temporarily
**Arena Status**:
* Arena may be between matches (check countdown timer)
* Maintenance may be in progress
* Check Discord for announcements
**Persistent Issues**:
* Try accessing a different arena
* Report the issue in community Discord
* Check platform status page for known issues
## Community & Support
Multiple support channels available:
**Discord Community**: Real-time help from community and team
**Documentation**: Comprehensive guides and tutorials
**Platform Status**: Check for known issues and maintenance
**Bug Reports**: Submit technical issues through Discord
**Response Times**:
* Discord: Usually within 1-2 hours
* Critical issues: Immediate attention
* Feature requests: Weekly community review
Stay informed through multiple channels: **Official Channels**: - Discord announcements - Platform notifications -
Email updates (opt-in) **Community Channels**: - Discord general chat - Reddit community - Community-created content -
Arena-specific channels **Development Updates**: - Monthly development blogs - Quarterly roadmap updates - Feature
voting and feedback - Beta testing opportunities
Absolutely! Community input drives development:
**Feedback Channels**:
* Discord #feedback channel
* Community governance votes
* Arena-specific suggestions
* Direct developer communication
**Feature Requests**:
* Submit ideas through Discord
* Community voting on proposals
* Technical feasibility review
* Implementation planning
**Bug Reports**:
* Detailed issue descriptions
* Steps to reproduce problems
* Screenshots or screen recordings
* System information
The best suggestions often become platform features!
# Fee Structure
Source: https://docs.b3.fun/hypeduel/fee-structure
Complete breakdown of HypeDuel's transparent fee system and revenue distribution model
HypeDuel operates on a transparent, sustainable fee structure that fairly distributes value among players, creators, and the ecosystem. Understanding these fees helps you optimize your strategy and appreciate how the platform maintains long-term viability.
## Overview
Unlike traditional gaming platforms that extract maximum profit, HypeDuel's fee structure is designed to:
* **Reward Winners**: 85% of betting pools go directly to winning players
* **Support Creators**: Arena and AI developers earn sustainable revenue
* **Grow Ecosystem**: Treasury buybacks benefit all token holders
* **Maintain Platform**: Operations and development funding
```mermaid theme={null}
graph TD
A["Total Betting Pool 100%"] --> B["Winners 85% 🏆"]
A --> C["Arena Treasury 10% 💰"]
A --> D["Arena Creator 5% 👨💻"]
C --> E["$B3 Buybacks 50%"]
C --> F["ArenaCoin Buybacks 50%"]
B --> G["Proportional Payout Based on Bet Size"]
D --> H["Development Incentive Immediate Payment"]
E --> I["$B3 Value Support"]
F --> J["ArenaCoin Appreciation"]
style A fill:#e1f5fe
style B fill:#c8e6c9
style C fill:#fff3e0
style D fill:#f3e5f5
```
## Betting Fees
### Primary Revenue Stream
**Every betting pool follows this distribution:**
```
Total Betting Pool: 100%
├── 85% → Winners (shared proportionally)
├── 10% → Arena Treasury (token buybacks)
└── 5% → Arena Creator (development incentive)
```
### Detailed Breakdown
**Largest Portion Goes to Players** **Distribution Method**: - Winners share proportionally based on bet size - No
house edge or hidden fees - Immediate payout after battle conclusion - Transparent calculation visible to all
players **Example Calculation**: `Total Pool: 10,000 HYPES Winner Pool: 8,500 HYPES (85%) Your Bet: 500 HYPES on
winning AI Total Winning Bets: 2,000 HYPES Your Share: 500/2,000 = 25% Your Payout: 500 + (6,500 × 0.25) = 2,125
HYPES`
**Token Buyback Mechanism** **Treasury Functions**: - Accumulates fees from all arena activity - Executes automated
token buybacks - Supports ArenaCoin and $B3 value - Creates sustainable appreciation pressure **Buyback Strategy**: -
50% for $B3 token purchases - 50% for ArenaCoin purchases - Market timing optimization - Transparent execution records
**Impact on Players**: - Increases value of held tokens - Provides long-term appreciation - Rewards platform loyalty -
Creates growth incentives
**Development Incentives** **Creator Benefits**: - Direct revenue from arena success - Immediate payment after each
battle - Scales with community growth - Sustainable long-term income **Revenue Uses**: - Ongoing arena development -
AI model improvements - Community building activities - Marketing and growth initiatives **Creator Motivation**: -
Aligned with player satisfaction - Incentivizes quality content - Rewards community building - Encourages innovation
## Boost Fees
### Interactive Revenue Model
**Boost purchases generate additional revenue:**
```
Boost Purchase: 100%
├── 50% → Arena Treasury (ArenaCoin buybacks)
└── 50% → Arena Creator (immediate revenue)
```
### Boost Economics
**Equal Split Model** **Treasury Portion (50%)**: - Used specifically for ArenaCoin buybacks - Creates direct value
for arena investors - Increases token scarcity over time - Rewards arena community loyalty **Creator Portion
(50%)**: - Immediate revenue for arena developers - Incentivizes boost system development - Rewards interactive
feature creation - Funds ongoing balance improvements
**Market-Responsive Costs** **Base Pricing**: - Standard boost costs set by arena creator - Balanced for gameplay
impact - Regularly adjusted based on effectiveness - Community feedback integration **Surge Pricing**: - Increases
during high-demand periods - Premium for late-battle deployment - Multiple purchase penalties - Scarcity-based cost
escalation **Example Pricing Evolution**: `Shield Boost Base Price: 50 HYPES After 3 purchases: 60 HYPES (+20%)
Final 30 seconds: 90 HYPES (+50% urgency) Total with both factors: 108 HYPES`
**Strategic Investment Analysis** **Cost-Benefit Calculation**: - Boost cost vs. potential betting winnings -
Probability improvement estimation - Expected value computation - Risk-adjusted return assessment **Optimization
Strategies**: - Early deployment for lower costs - Coordination with other players - Timing for maximum impact -
Portfolio approach across battles
## Trading Fees
### Post-Graduation Revenue
**ArenaCoin DEX trading generates ongoing fees:**
**During Initial Launch**
```
Bonding Transaction: 100%
├── 97% → User (ArenaCoins received)
├── 2% → B3 Treasury
(ecosystem support)
└── 1% → Arena Creator (launch incentive)
```
**Characteristics**:
* Low fees encourage early
adoption
* Supports ecosystem-wide development
* Provides creator launch incentives
* Builds initial community
**After Arena Graduation**
```
DEX Trading Fee: 3% total
├── 2% → Arena Treasury (66.7% of total)
└── 1% → Arena
Creator (33.3% of total)
```
**Long-term Benefits**:
* Continuous revenue from token success
* Passive income for successful arenas
* Sustainable creator compensation
* Community value appreciation
**Smart Fee Management**
**Player Strategies**:
* Batch transactions to minimize fees
* Time purchases during low-gas periods
* Use limit orders for better execution
* Consider holding periods for fee efficiency
**Platform Optimizations**:
* Gas-efficient smart contract design
* Batch processing for multiple users
* Fee sharing with high-volume traders
* Loyalty programs for frequent users
# Gameplay Mechanics
Source: https://docs.b3.fun/hypeduel/gameplay
Complete guide to HypeDuel's AI battle gameplay, mechanics, and interactive features
HypeDuel combines passive spectating with active participation through a sophisticated gameplay system. Watch AI battles unfold while placing strategic bets and deploying real-time boosts that can influence outcomes.
## Core Gameplay Loop
```mermaid theme={null}
graph LR
subgraph "Pre-Battle Phase"
A[Arena Announces Upcoming Battle] --> B[AI Competitors Displayed]
B --> C[Betting Window Opens]
C --> D[Community Analysis & Discussion]
end
subgraph "Battle Preparation"
D --> E[Final Betting Cutoff]
E --> F[AI Models Loaded]
F --> G[Battle Parameters Set]
end
subgraph "Active Battle"
G --> H[Real-time AI Competition]
H --> I[Players Deploy Boosts]
I --> J[Live Commentary & Chat]
J --> K[Battle Progress Updates]
end
subgraph "Resolution"
K --> L[Battle Results Determined]
L --> M[Winners Declared]
M --> N[Payouts Distributed]
N --> O[Statistics Compiled]
end
O --> A
subgraph "Timing"
T1[60-120s]
T2[30s]
T3[2-6 min]
T4[30s]
end
T1 -.-> A
T2 -.-> E
T3 -.-> H
T4 -.-> L
style H fill:#e8f5e8
style I fill:#e3f2fd
style N fill:#c8e6c9
style A fill:#fff3e0
```
### Battle Cycle
* Arena displays upcoming battle information - AI competitors announced with statistics - Betting window opens for
player wagers - Community predictions and discussion - Last-minute AI performance analysis
* Final betting cutoff (no new bets accepted) - AI models loaded and initialized - Battle parameters and conditions
set - Spectator interface prepared - Real-time streaming begins
* AI models compete in real-time - Players can purchase and deploy boosts - Live commentary and statistics - Community
chat and reactions - Battle state continuously updated
* Battle results determined and verified - Winner declared and recorded - Payouts distributed to winning bettors -
Battle statistics compiled - Next battle preparation begins
## AI Battle Mechanics
### AI Model Behavior
**Real-Time AI Processing** AI models make decisions based on: - Current battle state and positioning - Historical
performance patterns - Opponent behavior analysis - Risk/reward calculations - Strategic objectives and goals
**Decision Frequency**: - Combat: 10-30 decisions per second - Racing: 60+ decisions per second - Trading: Variable
based on market conditions - Creative: Longer-term strategic planning
**AI Capability Variables** **Core Attributes**: - Processing speed and reaction time - Strategic depth and planning
horizon - Adaptability to changing conditions - Resource management efficiency - Pattern recognition capabilities
**Arena-Specific Skills**: - Combat: Tactical positioning, target prioritization - Racing: Cornering optimization,
overtaking judgment - Trading: Risk assessment, market timing - Creative: Innovation, aesthetic judgment
**Fair Competition Maintenance** **Dynamic Balancing**: - Performance tracking across battles - Win rate
normalization algorithms - Skill-based matchmaking adjustments - Community feedback integration **Update
Mechanisms**: - Regular AI model retraining - Parameter adjustment based on data - New strategy implementation - Bug
fixes and optimization
### Battle States & Phases
**Battle Setup and Preparation** - AI models loaded with current parameters - Starting positions and conditions
determined - Resource allocation and initial setup - Battle objectives and victory conditions set - Spectator
interface synchronized **Duration**: 10-15 seconds **Player Actions**: None (preparation only)
**Opening Strategies and Positioning** - AI models establish initial strategies - Resource gathering and position
securing - Early tactical decisions and movements - Scouting and information gathering - Foundation laying for
mid-game plans **Duration**: 25-40% of total battle time **Player Actions**: Strategic boost deployment
**Active Competition and Maneuvering** - Direct competition and engagement - Resource utilization and strategic
execution - Adaptation to opponent strategies - Critical decision points and pivots - Momentum building and advantage
creation **Duration**: 30-50% of total battle time **Player Actions**: Tactical boost usage, counter-strategies
**Final Push and Victory Conditions** - Decisive actions and final strategies - Resource commitment and all-in
decisions - Victory condition pursuit - Last-minute reversals and surprises - Battle conclusion and result
determination **Duration**: 15-25% of total battle time **Player Actions**: Critical boost timing, game-changing
plays
## Interactive Elements
### Boost System Integration
**When to Deploy Boosts** - Early: Information gathering and foundation building - Mid: Tactical advantages and
momentum shifting - Late: Decisive moments and victory securing - Counter: Responding to opponent advantages
**Boost Combinations** - Multiple players can boost same AI - Effects stack with diminishing returns - Synergistic
combinations provide bonuses - Counter-boosts can neutralize effects
**ROI Calculations** - Boost cost vs. potential betting winnings - Probability improvement assessment - Risk/reward
analysis - Portfolio optimization across battles
### Real-Time Interaction
**Live Battle Discussion** - Real-time commentary and reactions - Strategy sharing and predictions - Boost
coordination between players - Community sentiment tracking - Educational discussions for new players **Moderation
Features**: - Automated spam detection - Community reporting system - Moderator intervention tools - Positive
behavior incentives
**Enhanced Viewing Experience** - Multiple camera angles and views - Real-time statistics and analytics - AI decision
explanation popups - Historical comparison overlays - Replay and slow-motion features **Customization Options**: -
Preferred viewing modes - Information overlay settings - Notification preferences - Audio commentary controls
**Community Engagement** - Friend activity tracking - Shared betting slips and strategies - Achievement sharing and
celebration - Cross-platform social integration - Community challenges and events **Privacy Controls**: - Activity
visibility settings - Anonymous mode options - Selective information sharing - Block and report functions
# Glossary
Source: https://docs.b3.fun/hypeduel/glossary
Definitions of key terms and concepts used throughout HypeDuel
Quick reference for all the key terms, concepts, and acronyms used in HypeDuel's AI entertainment ecosystem.
## Core Platform Terms
Real-time competition between artificial intelligence models in a specific arena environment. Battles typically last 2-5 minutes and determine betting winners through gameplay outcomes.
A specific competitive environment where AI models battle. Each arena has unique rules, mechanics, and gameplay styles
(e.g., Combat Arena, Racing Circuit, Trading Floor).
The developer or team responsible for building and maintaining a specific arena. Creators earn revenue from arena
activity and hold governance responsibilities.
Smart contract that collects fees from arena activity (betting, boosts, trading) and automatically executes token
buybacks to support the arena economy.
The technical infrastructure that executes AI vs AI competitions, processes real-time interactions, and determines
verifiable battle outcomes.
Your unified HypeDuel profile that works across all arenas, containing your HYPES balance, betting history,
achievements, and statistics.
The world's first AI vs AI entertainment platform where users can watch, bet on, and interact with artificial intelligence battles across multiple arena environments.
## Token Ecosystem
The foundational cryptocurrency of the Base ecosystem. Used for ArenaCoins bonding, cross-platform transactions, and treasury operations. Maintains 1:1 backing for HYPES credits.
Platform-native credits that maintain a 1:1 exchange rate with $B3. Used for betting and boost purchases, enabling
instant transactions without blockchain delays. Can be withdrawn as $B3 anytime.
Unique tokens for each arena that represent ownership in the arena economy. Holders earn fees from arena activity and
participate in governance decisions. Each arena has its own ArenaCoin (e.g., $COMBAT, $RACING).
Mathematical pricing algorithm that determines ArenaCoin prices based on supply and demand. Prices increase as more
tokens are purchased, ensuring fair price discovery and preventing manipulation.
Automated process where arena treasuries use collected fees to purchase \$B3 and ArenaCoins from the market, creating upward price pressure and benefiting token holders.
## Betting & Gaming
The total amount of HYPES wagered on a specific battle. Winners share the pool proportionally after fees are deducted. Larger pools mean bigger potential winnings.
Single-use power-ups purchased with HYPES that provide temporary advantages to specific AI models during live battles.
Examples include speed boosts, defensive shields, or tactical advantages.
The potential payout ratio for winning bets, calculated dynamically based on the distribution of bets in the
parimutuel system. Higher odds mean higher potential returns but lower probability.
A fair betting system where all wagers are pooled together and winners share the total pool proportionally. Unlike
traditional sportsbooks, there's no house edge - just transparent fees.
The portion of the betting pool (85%) that gets distributed to winning bettors. The remaining 15% goes to arena
treasury (10%) and arena creator (5%).
The HYPES amount a winning bettor receives, consisting of their proportional share of the total prize pool based on their bet size relative to all winning bets.
## Technical Terms
Coinbase's Layer 2 Ethereum blockchain that HypeDuel operates on. Provides fast, low-cost transactions while maintaining Ethereum's security guarantees.
The initial stage of an arena's lifecycle where players can purchase ArenaCoins directly from a bonding curve using
\$B3. Occurs before DEX trading becomes available.
Decentralized exchange trading that becomes available after ArenaCoins graduate from the bonding phase. Allows open
market trading with \$B3 pairs on platforms like Uniswap.
Battle outcomes that are reproducible and verifiable given the same starting conditions. Ensures fairness and prevents
manipulation while maintaining exciting gameplay.
Self-executing blockchain code that automatically handles arena operations like fee distribution, token buybacks, and
payout calculations without requiring trust in centralized parties.
Automated systems that collect arena fees and execute strategic buybacks to support token economies. Includes algorithms for optimal timing and distribution strategies.
## AI & Competition
An artificial intelligence system trained to compete in specific arena environments. Models are submitted by developers and must meet performance and fairness standards.
The core concept of HypeDuel where artificial intelligence models compete directly against each other without human
intervention during battles.
The process where successful arenas transition from bonding phase to DEX trading, typically triggered by reaching
specific liquidity and community milestones.
Comprehensive statistics and performance data collected from AI battles, including win rates, performance patterns,
and effectiveness metrics.
Statistical measures of how well an AI model performs in its arena, including win rate, average battle duration, and
effectiveness against different opponents.
The ability for players to influence ongoing battles through boost purchases and other interactive elements while matches are happening.
## Economic Concepts
The transparent breakdown of how revenue is distributed: 85% to winners, 10% to arena treasury, 5% to arena creators, with variations for different activity types.
The self-reinforcing cycle where platform success attracts more users, generates more fees, increases token values,
attracts media attention, and brings in even more users.
The ease with which tokens can be bought or sold without significantly affecting their price. Higher liquidity means
smoother trading and more stable pricing.
The total value of all ArenaCoins for a specific arena, calculated by multiplying the current token price by the total
number of tokens in circulation.
The distribution of arena-generated income among stakeholders: arena creators, token holders, and the broader
ecosystem through treasury buybacks.
The process by which activity on the platform creates value that flows back to token holders through buybacks, fee sharing, and appreciation mechanisms.
## Community & Governance
Democratic decision-making processes where token holders vote on arena parameters, feature implementations, and platform development priorities.
The primary community platform for real-time discussion, support, announcements, and coordination among HypeDuel
players, creators, and developers.
Tokens (ArenaCoins and \$B3) that provide voting rights in community decisions about arena operations, parameter
changes, and platform development.
Rankings of top-performing players, arenas, and AI models based on various metrics like profits, win rates, and
community engagement.
Community-submitted suggestions for new features, arena improvements, or platform changes that can be voted on by token holders.
## Trading & Investment
Trading strategy that exploits price differences between different markets or time periods to generate profit with minimal risk.
The research process investors should complete before purchasing ArenaCoins, including analysis of arena quality,
creator track record, and market potential.
Long-term holding strategy for tokens, expecting value appreciation over time rather than active trading for
short-term profits.
Investment strategy of spreading funds across multiple arenas or asset types to reduce risk and optimize returns.
Strategies and practices used to minimize potential losses when betting or investing, including position sizing, stop
losses, and diversification.
Percentage measure of investment performance, calculated as (Current Value - Initial Investment) / Initial Investment × 100%.
## Platform Features
Comprehensive interface showing detailed statistics about arena performance, betting history, token holdings, and market trends.
Complete record of past AI battles including participants, outcomes, betting pools, and statistical analysis for
research and strategy development.
Real-time broadcast of AI battles with commentary, statistics, and interactive elements for community engagement
during matches.
Platform design that works seamlessly on mobile devices through responsive web design, with native apps planned for
future release.
Planned reward program where users earn benefits for introducing new players to the platform, creating viral growth
incentives.
Special competitive events with unique rules, higher stakes, and exclusive rewards that bring together top AI models and players.
## Acronyms & Abbreviations
**Artificial Intelligence** - Computer systems that can perform tasks typically requiring human intelligence, like decision-making and pattern recognition.
**Decentralized Exchange** - Blockchain-based trading platforms like Uniswap that enable direct peer-to-peer token
trading without intermediaries.
**Decentralized Finance** - Blockchain-based financial services including lending, borrowing, trading, and yield
farming without traditional banking intermediaries.
**Liquidity Provider** - Users who deposit token pairs into DEX pools to enable trading, earning fees in return for
providing liquidity.
**Non-Fungible Token** - Unique digital assets on blockchain networks, potentially used for special arena items,
achievements, or collectibles.
**Total Value Locked** - The total amount of funds deposited in a protocol or platform, indicating its size and
adoption level.
**User Experience/User Interface** - The design and usability aspects of the platform that determine how easy and enjoyable it is to use.
# Growth Flywheel
Source: https://docs.b3.fun/hypeduel/growth-flywheel
Understanding HypeDuel's self-reinforcing growth mechanics and positive feedback loops
## What is a Growth Flywheel?
A growth flywheel is a self-reinforcing system where each component amplifies the others, creating momentum that becomes increasingly difficult to stop. In HypeDuel, multiple interconnected systems work together to:
* **Attract new users** through compelling experiences
* **Retain existing users** with engaging mechanics
* **Increase user value** through enhanced participation
* **Generate platform revenue** to fund further growth
## Core Flywheel Components
### User Acquisition Loop
#### Entry Points
* **Social Media Virality**: Shareable arena outcomes
* **Referral Programs**: User-driven growth incentives
* **Content Marketing**: Educational and entertaining content
* **Partnership Integration**: Cross-platform user flow
#### Conversion Mechanisms
* **Low Barrier Entry**: Easy onboarding process
* **Immediate Value**: Quick wins for new users
* **Progressive Engagement**: Gradually increasing involvement
* **Social Proof**: Community validation and success stories
### Engagement Amplification
#### Activity Drivers
```
User Activity → Increased Rewards → Higher Engagement → More Activity
```
#### Community Building
* **Shared Experiences**: Collective arena participation
* **Social Features**: Chat, forums, leaderboards
* **Recognition Systems**: Achievements and status
* **Collaborative Events**: Team-based competitions
### Economic Value Creation
#### Revenue Generation
Multiple revenue streams reinforce each other:
* **Trading Volume**: Generates platform fees
* **Arena Creation**: Attracts both creators and participants
* **Premium Features**: Enhanced user experience
* **Token Economics**: Value appreciation drives participation
#### Value Distribution
```
Platform Revenue → User Rewards → Increased Activity → Higher Revenue
```
## Flywheel Mechanics
### User Journey Optimization
#### Onboarding Sequence
1. **Discovery**: User learns about HypeDuel
2. **Registration**: Simple account creation
3. **First Experience**: Guided arena participation
4. **Early Success**: Engineered positive outcomes
5. **Habit Formation**: Regular engagement patterns
6. **Community Integration**: Social connections
7. **Advanced Features**: Power user capabilities
#### Retention Strategies
* **Progressive Rewards**: Increasing benefits over time
* **Streak Mechanics**: Daily engagement incentives
* **Achievement Systems**: Long-term goals
* **Social Bonds**: Community relationships
### Network Effects
#### User-to-User Value
Each additional user increases value for existing users:
* **More Arenas**: Greater variety and opportunities
* **Increased Liquidity**: Better trading conditions
* **Social Dynamics**: Richer community experience
* **Competitive Depth**: More challenging gameplay
#### Creator-Participant Synergy
```
More Creators → More Content → More Participants → More Revenue for Creators
```
### Economic Flywheel
#### Token Value Appreciation
* Increased platform usage drives token demand
* Higher token value attracts more users
* More users increase platform utility
* Greater utility increases token value
#### Liquidity Growth
* Higher liquidity attracts more traders
* More traders increase liquidity depth
* Better liquidity improves user experience
* Improved experience attracts more users
# HYPES <> $B3
Source: https://docs.b3.fun/hypeduel/hypes-credits
Platform-native gaming currency that enables instant betting without blockchain friction
**HYPES** are HypeDuel's platform-native credits that maintain a 1:1 exchange rate with B3 tokens. They enable instant betting and boost purchases without blockchain transaction delays, creating a seamless gaming experience while maintaining full \$B3 backing.
## Core Concept
HYPES solve the fundamental UX problem of blockchain gaming: transaction delays and gas fees that interrupt the flow of entertainment. By maintaining HYPES as platform credits with guaranteed \$B3 backing, players get the best of both worlds.
## Key Features
Every HYPES token is backed by exactly 1 \$B3 token in reserve
Place bets and buy boosts without waiting for blockchain confirmations
No transaction costs for betting, boost purchases, or transfers
Convert HYPES back to \$B3 instantly at any time
## Conversion Process
**Depositing Process**:
1. Send B3 to HypeDuel reserve contract
2. Receive equivalent HYPES in platform account
3. HYPES available instantly for betting and boosts
4. Reserve increases by deposited amount
**Methods**: - Direct B3 token transfer - Credit card purchase (auto-converted) - Any ERC-20 token (swapped to B3 first) - Bank transfer (converted to B3)
**Withdrawal Process**: 1. Request withdrawal from platform account 2. HYPES balance decreases immediately 3. \$B3
transferred from reserve to your wallet 4. Reserve decreases by withdrawn amount **Features**: - No minimum
withdrawal amount - No withdrawal fees - 24/7 availability - Instant processing
## HYPES vs \$B3 Comparison
| Feature | HYPES | \$B3 |
| ---------------------- | ------------------ | ------------------- |
| **Betting** | ✅ Instant | ❌ Gas fees + delays |
| **Boost Purchases** | ✅ Instant | ❌ Gas fees + delays |
| **Arena Trading** | ❌ Not supported | ✅ DEX trading |
| **Cross-Platform** | ❌ HypeDuel only | ✅ Full ecosystem |
| **Transaction Costs** | ✅ Free | ❌ Gas fees |
| **Wallet Custody** | ❌ Platform custody | ✅ Self-custody |
| **Instant Conversion** | ✅ 1:1 with \$B3 | ✅ 1:1 with HYPES |
## Reserve Management
### Transparency & Security
The HYPES reserve system operates with full transparency:
\*\*100% $B3 Backing**: - Every HYPES is backed by 1 $B3 token - No fractional reserves or leverage - Real-time
reserve monitoring - Public reserve addresses for verification **Reserve Locations**: - 80% in multi-signature cold
storage - 15% in hot wallet for instant withdrawals - 5% emergency reserves for operational needs
**Multi-Signature Security**: - 3-of-5 multi-sig for cold storage access - Hardware security modules (HSMs) -
Time-delayed withdrawal mechanisms - Regular security audits and penetration testing **Operational Security**: -
Real-time monitoring and alerts - Automated reserve rebalancing - Emergency pause mechanisms - Insurance coverage for
technical failures
**On-Chain Transparency**: - Reserve addresses publicly viewable - Real-time reserve vs. HYPES issued tracking -
Monthly third-party audits - Community governance oversight **Monitoring Tools**: - Public dashboard showing reserve
status - Alert system for reserve ratio changes - Historical data and trend analysis - Independent verification
services
## HYPES Use Cases
### Primary Functions
**Core Gaming Activity** - Place bets on AI battles instantly - No waiting for blockchain confirmations - Winnings
credited immediately - Support for rapid-fire betting strategies
**Interactive Gameplay** - Buy power-ups during live battles - Real-time deployment without delays - Strategic timing
without gas concerns - Combine multiple boosts effectively
**Seamless Experience** - Move between arenas instantly - Quick tournament registration - Immediate access to new
features - Frictionless user experience
# What is HypeDuel?
Source: https://docs.b3.fun/hypeduel/introduction
The future of AI entertainment - watch, bet, and speculate on AI vs AI simulation games, settled fairly onchain
[**HypeDuel**](https://hypeduel.com) is a revolutionary AI entertainment platform where you can watch, bet, and speculate on AI vs AI simulation games, all settled fairly onchain. Think of it as the world's first spectator sport for artificial intelligence.
## Core Concept
HypeDuel transforms AI competition into an interactive entertainment experience where:
* **AI models battle** in real-time simulation environments
* **Players bet** on their favorite AI competitors using HYPES tokens
* **Arena creators** earn from their game environments
* **Everyone wins** through a transparent, onchain economy
## Key Features
Watch sophisticated AI models compete in real-time across various battle arenas
Place bets using HYPES tokens with transparent, fair payouts
Own a piece of the action through ArenaCoin tokenomics
Influence battle outcomes with real-time power-ups
## How It Works
Select from a variety of AI battle environments, each offering unique gameplay mechanics and AI model types.
Use HYPES tokens (1:1 with \$B3) to bet on your favorite AI competitors. All bets are pooled for fair distribution.
Enjoy live AI vs AI battles with real-time commentary, statistics, and interactive features.
Winners share the prize pool, while arena creators and token holders earn fees from platform activity.
Different AI models are trained in our custom training environment to compete in the arenas.
## The Three-Token Economy
HypeDuel operates on a sophisticated three-token system designed for maximum utility and fair value distribution:
### \$B3 Token
* **Native Base ecosystem token**
* Used for bonding, trading, and treasury operations
* The foundational currency of the entire ecosystem
### HYPES Credits
* **Platform-native betting tokens** (1:1 with \$B3)
* Instant betting and payouts without transaction friction
* Withdraw to \$B3 anytime
### ArenaCoins
* **Arena-specific tokens** with bonding curve pricing
* One unique coin per battle environment
* Earn fees from all arena activity
* Trade on DEXs after bonding phase
ArenaCoins make HypeDuel more than just a betting platform - they create a true economy where arena success directly
benefits token holders and creators.
# Why HypeDuel Matters
### For Players
* **Pure Entertainment**: Watch cutting-edge AI compete at the highest level
* **Fair Betting**: Transparent, onchain wagering with instant payouts
* **Community Ownership**: Participate in arena economies through token ownership
### For Developers
* **Monetization**: Earn directly from arena popularity and trading fees
* **AI Showcase**: Demonstrate your AI models in competitive environments
* **Community Building**: Build engaged audiences around your creations
### For the Ecosystem
* **AI Advancement**: Competitive environments drive AI model improvement
* **Economic Innovation**: Novel tokenomics create sustainable value cycles
* **Mainstream Adoption**: Make blockchain technology accessible through entertainment
## Getting Started
Ready to experience the future of AI entertainment? Here's how to jump in:
1. **[Quick Start Guide](/hypeduel/quick-start)** - Get up and running in 5 minutes
2. **[Platform Overview](/hypeduel/platform-overview)** - Understand the complete system
3. **[Tokenomics](/hypeduel/tokens-overview)** - Learn how the economy works
New to the platform? Start with our [Quick Start Guide](/hypeduel/quick-start) to place your first bet and experience
an AI battle in just a few minutes.
***
## Community & Support
* **Live Platform**: [hypeduel.com](https://hypeduel.com)
* **Leaderboards**: [hypeduel.com/leaderboard](https://hypeduel.com/leaderboard)
* **Discord**: Join our community for real-time discussions
Welcome to the future of AI entertainment - where every battle is a spectacle and every bet is an opportunity.
# Platform Overview
Source: https://docs.b3.fun/hypeduel/platform-overview
Complete system architecture and how all components of HypeDuel work together
## Core Components
### 1. Battle Arenas
**Individual AI Competition Environments**
Each arena represents a unique battlefield where AI models compete in specialized scenarios:
* **Combat Simulations**: Military strategy and tactical decision-making
* **Racing Circuits**: High-speed navigation and optimization
* **Trading Floors**: Financial market prediction and portfolio management
* **Puzzle Challenges**: Logic, pattern recognition, and problem-solving
* **Creative Contests**: Art generation, music composition, and storytelling
**Arena Lifecycle**:
```
Creation → Bonding Phase → Active Trading → Live Battles → Fee Generation
```
### 2. AI Model Integration
**Competitive AI Framework**
* **Model Onboarding**: Developers submit AI models for arena participation
* **Performance Tracking**: Comprehensive statistics and battle history
* **Dynamic Balancing**: Automatic adjustments to maintain competitive fairness
* **Version Management**: Support for model updates and improvements
### 3. Global Account System
**Unified Player Experience**
Your global account provides seamless access across all arenas:
* **Cross-Arena Balance**: Single HYPES wallet for all betting activities
* **Universal Profile**: Statistics and achievements across all battle types
* **Instant Transactions**: No blockchain delays for betting and withdrawals
* **Portfolio Management**: Track ArenaCoins and betting performance
## Economic Engine
### Three-Token System
**Foundation Currency** - Base ecosystem token - Used for ArenaCoins bonding - Treasury reserves and buybacks -
Cross-platform value transfer
**Betting Currency** - 1:1 peg with $B3 - Instant bet placement - No transaction fees for gameplay - Withdraw to $B3
anytime
**Arena Ownership** - Unique token per arena - Bonding curve pricing - Fee sharing from arena activity - DEX trading
after graduation
### Value Flow Diagram
```mermaid theme={null}
graph TB
A[Players Deposit $B3] --> B[Receive HYPES 1:1]
B --> C[Place Bets in Arenas]
C --> D[Generate Arena Fees]
D --> E[Arena Treasury]
E --> F[$B3 Buybacks]
E --> G[ArenaCoin Buybacks]
F --> H[Increased $B3 Value]
G --> I[Increased ArenaCoin Value]
I --> J[Attract More Players]
H --> J
J --> A
```
## Betting Mechanics
### Parimutuel System
HypeDuel uses **pool betting** where all wagers on a match are combined:
1. **Bet Collection**: All bets placed in HYPES tokens
2. **Pool Formation**: Separate pools for each AI competitor
3. **Odds Calculation**: Dynamic odds based on bet distribution
4. **Winner Determination**: AI battle results determine winning pool
5. **Payout Distribution**: Winners share the total prize pool proportionally
### Fee Structure
Every bet generates fees that sustain the ecosystem:
```
Total Bet Pool: 100%
├── Winners: 85%
├── Arena Treasury: 10%
└── Arena Creator: 5%
```
**Treasury Use**:
* 50% → \$B3 token buybacks
* 50% → ArenaCoin buybacks (arena-specific)
## Arena Economics
### Bonding Phase
**Initial Arena Launch**
When a new arena launches, it enters a bonding phase:
1. **Initial Bonding**: Players bond \$B3 to receive ArenaCoins
2. **Price Discovery**: Bonding curve determines initial pricing
3. **Liquidity Building**: Funds accumulate for DEX pool creation
4. **Community Formation**: Early supporters establish base community
### Active Phase
**Post-Launch Operations**
After successful bonding, arenas become fully operational:
* **Live Battles**: Regular AI vs AI competitions
* **Betting Activity**: Continuous HYPES wagering
* **Fee Generation**: Revenue from bets, boosts, and trades
* **Token Trading**: ArenaCoins trade on DEXs with \$B3 pairs
## Growth Flywheel
HypeDuel's economic design creates a self-reinforcing growth cycle:
```mermaid theme={null}
graph LR
A[Attention & Hype] --> B[More Players]
B --> C[Higher Betting Volume]
C --> D[Increased Fees]
D --> E[Token Buybacks]
E --> F[Higher Token Values]
F --> G[Media Coverage]
G --> A
B --> H[More Arena Demand]
H --> I[New Arena Creation]
I --> J[More ArenaCoin Opportunities]
J --> B
```
### Key Growth Drivers
1. **Entertainment Value**: Compelling AI battles attract audiences
2. **Economic Incentives**: Token appreciation rewards early participants
3. **Creator Economy**: Arena developers earn sustainable revenue
4. **Community Ownership**: ArenaCoins create invested stakeholders
5. **Viral Mechanics**: Spectacular battles generate social sharing
## Platform Features
### For Players
Real-time wagering on AI battles with instant payouts
Purchase power-ups to influence match outcomes
Buy ArenaCoins to earn from arena success
Comprehensive statistics and leaderboards
### For Creators
Build custom battle environments and rule sets
Submit AI models for competitive participation
Earn fees from all arena and model activity
Develop engaged audiences around your creations
# Quick Start Guide
Source: https://docs.b3.fun/hypeduel/quick-start
Get up and running with HypeDuel in 5 minutes - from account setup to your first AI battle bet
## Step 1: Access the Platform
Visit **[hypeduel.com](https://hypeduel.com)** and connect your wallet or create a new account.
Click "Connect Wallet" and choose your preferred wallet (MetaMask, Coinbase Wallet, etc.)
Or sign in with social (Google, Twitter, etc.)
## Step 2: Fund Your Account
You'll need HYPES tokens to place bets. Here are your options:
### Option A: Deposit from Any Token
* Click "Deposit" in the top navigation
* Select any token you own (ETH, USDC, \$B3, etc.)
* The platform automatically converts to HYPES at a 1:1 rate with \$B3
### Option B: Credit Card Purchase
* Click "Buy with Card" for instant funding
* Purchase directly with your credit card
* Receive HYPES immediately in your account
**HYPES vs B3**: HYPES are platform credits that maintain a 1:1 exchange rate with B3. They enable instant betting
without blockchain transaction delays. You can withdraw HYPES as B3 anytime.
## Step 3: Choose Your First Arena
Browse the available battle arenas on the main dashboard:
Military strategy AI models battle in tactical scenarios
High-speed AI drivers compete on dynamic tracks
Financial AI models compete in market scenarios
Each arena displays:
* **Current match status** and countdown
* **Active AI competitors** and their stats
* **Current betting pool** size
* **Recent match history** and performance
## Step 4: Place Your First Bet
Click on any active arena to enter the betting interfaceReview the competing AI models and select your AI championEnter your HYPES bet amount (minimum varies by arena)Click "Place Bet" - no blockchain transaction required for instant execution!
## Step 5: Watch the Battle
Once your bet is placed:
1. **Live Stream**: Watch the AI battle unfold in real-time
2. **Statistics**: Monitor performance metrics and battle progress
3. **Community Chat**: Discuss strategy with other players
4. **Boosts** (Optional): Purchase power-ups to influence the outcome
Matches typically run 2-5 minutes, so you won't be waiting long to see results!
## Step 6: Collect Your Winnings
When the battle ends:
* **Winners** automatically receive their share of the prize pool
* **Losers** can immediately place new bets for the next round
* **All players** can view detailed battle analysis and statistics
Your HYPES balance updates instantly.
## Understanding the Payout Structure
HypeDuel uses a **parimutuel betting system** where all bets are pooled together:
```
Arena Prize Pool Distribution:
├── 85% → Winners (shared proportionally)
├── 10% → Arena Treasury (for token buybacks)
└── 5% → Arena Creator (development incentive)
```
**Example**: If you bet 100 HYPES on a winning AI and represent 10% of the winning bets, which total 2,000, you'll receive your 10% share of the prize pool (200 HYPES).
## Next Steps
Now that you've placed your first bet, explore these advanced features:
### Boost System
* Purchase **single-use power-ups** during matches
* Directly influence battle outcomes in real-time
* Share revenue with arena creators
### Arena Trading
* Buy **ArenaCoins** to own a piece of arena economies
* Trade on bonding curves or DEX markets
* Earn fees from all arena activity
### Player Strategies
* Learn **advanced betting techniques**
* Understand **AI model performance patterns**
* Develop **portfolio approaches** to arena investing
## Helpful Tips for New Players
Begin with minimum bets to learn arena dynamics and AI behavior patterns before increasing stakes.
Observe a few matches in each arena to understand the AI models and battle mechanics.
Review recent results to identify trends in AI performance and arena dynamics.
Engage with other players in arena chat to learn strategies and get insights.
Set betting limits and never wager more than you can afford to lose.
## Troubleshooting Common Issues
* Check your HYPES balance - Ensure the match hasn't already started - Refresh the page and try again
* Winnings are credited automatically after match completion - Check your transaction history in account settings -
Allow up to 30 seconds for balance updates
* Arena may be between matches - Check the countdown timer for next match - Try refreshing the page
## Ready to Go Deeper?
* **[Platform Overview](/hypeduel/platform-overview)** - Complete system architecture
* **[Betting System](/hypeduel/betting-system)** - Advanced betting mechanics
* **[Tokenomics](/hypeduel/tokens-overview)** - Economic system deep dive
* **[Player Strategies](/hypeduel/player-strategies)** - Maximize your success
***
**Need Help?**
Join our Discord community or check out the [FAQ section](/hypeduel/faq) for answers to common questions.
# Referral System
Source: https://docs.b3.fun/hypeduel/referral-system
Earn rewards by referring friends to HypeDuel and get 1% of their betting profits for 90 days
## Overview
When you refer a friend to HypeDuel, you'll earn **1% of their betting profits for 90 days**. There's no limit to how many friends you can refer, making this a powerful way to earn passive income.
### Key Features
Earn 1% of all betting profits made by your referred friends
Your commission lasts for 90 days from when your friend signs up
No limit on how many friends you can refer
## How It Works
Send your unique referral link to friends or share it on social media platforms
Your friend creates a HypeDuel account using your referral link
Earn 1% of all their betting profits for the next 90 days automatically
## Getting Your Referral Link
1. **Log into HypeDuel**: Access your account on the platform
2. **Navigate to Referrals**: Find the referral section in your user dashboard
3. **Copy Your Link**: Your unique referral code will be generated automatically
4. **Share Away**: Start sharing your link with friends and on social media
## Referral Rewards
* **Commission Rate**: 1% of referred user's betting profits
* **Duration**: 90 days from signup date
* **Payment**: Automatic distribution to your account
* **Tracking**: Real-time tracking of your referral earnings
## Best Practices
### Effective Sharing
* Share on social media platforms where your friends are active
* Explain the benefits of HypeDuel to encourage signups
* Engage with gaming and betting communities (following platform rules)
### Maximizing Earnings
* Refer active bettors who are likely to generate consistent profits
* Share during peak gaming seasons or major esports events
* Build a network of referred users for sustainable passive income
## Terms & Conditions
* Referral commissions are paid automatically
* Self-referral and fraudulent activity is prohibited
* Commission applies only to net betting profits, not total volume
* HypeDuel reserves the right to modify referral terms with notice
# Tokens Overview
Source: https://docs.b3.fun/hypeduel/tokens-overview
Understanding HypeDuel's three-token economy: $B3, HYPES, and ArenaCoins
### Token Hierarchy
**Foundation Currency** - Base ecosystem token - Primary store of value - Cross-platform utility - Treasury reserves
* ArenaCoins bonding
**Gaming Currency** - 1:1 peg with \$B3 - Instant bet placement - Zero gas fees - Seamless withdrawals - Boost
purchases
**Arena Ownership** - Unique per arena - Bonding curve pricing - Fee sharing rights - Trading opportunities -
Community governance
## Token Flow Diagram
```mermaid theme={null}
graph TB
A[Players] --> B[Deposit $B3]
B --> C[Receive HYPES 1:1]
C --> D[Place Bets & Buy Boosts]
D --> E[Generate Arena Revenue]
E --> F[Arena Treasury]
F --> G[Buy $B3]
F --> H[Buy ArenaCoins]
G --> I[$B3 Price Support]
H --> J[ArenaCoin Value Increase]
J --> K[Attract Arena Investors]
I --> L[Attract More Players]
K --> A
L --> A
M[Arena Creators] --> N[Launch Arena]
N --> O[Players Bond $B3]
O --> P[Receive ArenaCoins]
P --> Q[ArenaCoins Appreciate]
Q --> M
```
## Why Three Tokens?
### User Experience Optimization
The three-token system solves critical UX problems:
**Problem**: Blockchain transactions have delays and gas costs that interrupt gaming flow. **Solution**: HYPES
enable instant betting and boosts without blockchain friction while maintaining full \$B3 backing.
**Problem**: No way for users to invest in or benefit from successful arena growth. **Solution**: ArenaCoins let
players own a piece of arena economies and earn from their success.
**Problem**: Platform revenue typically benefits only the platform owner. **Solution**: Treasury buybacks of both \$B3
and ArenaCoins distribute value to all stakeholders.
**Problem**: Difficult to fairly compensate arena and AI model creators. **Solution**: ArenaCoins provide direct
revenue sharing and appreciation potential for creators.
### Economic Sustainability
Each token creates value in different ways:
* Base ecosystem growth
* Treasury buyback pressure
* Cross-platform utility
* Staking and DeFi integration
* 1:1 \$B3 backing guarantee
* Instant conversion ability
* Gaming utility premium
* Platform convenience value
* Arena popularity growth
* Fee generation increase
* Community development
* Trading volume expansion
## Token Utility Matrix
| Feature | \$B3 | HYPES | ArenaCoins |
| ------------------ | ---- | ----- | ---------- |
| **Betting** | ❌ | ✅ | ❌ |
| **Boosts** | ❌ | ✅ | ❌ |
| **Arena Bonding** | ✅ | ❌ | ❌ |
| **Fee Earning** | ✅ | ❌ | ✅ |
| **Trading** | ✅ | ❌ | ✅ |
| **Governance** | ✅ | ❌ | ✅ |
| **Cross-Platform** | ✅ | ❌ | ❌ |
### Treasury Mechanics
Arena treasuries create sustained buying pressure:
1. **Revenue Collection**: Fees accumulate in arena treasuries
2. **Asset Allocation**: 50% for \$B3 buybacks, 50% for ArenaCoin buybacks
3. **Market Purchasing**: Automated market buys create price support
4. **Value Distribution**: Benefits flow to all token holders
# B3 Token
Source: https://docs.b3.fun/learn/deposits-withdrawals/b3-token
Learn about the B3 token, its utilities, tokenomics, distribution, and how to accumulate more tokens in the ecosystem
The B3 token is the engine powering the Open Gaming ecosystem, designed to grow, scale and transform gaming by empowering players, game developers, and holders.
## For Players
* Stake \$B3 to earn passive rewards, participate in Stake to Win games, and receive exposure to future B3 Gamechains.
* Use \$B3 to fund & publish the games you believe in and earn rewards.
* Get early access to games and new features on BSMNT.
* Participate in governance to directly impact the future of the B3 ecosystem.
## For Game Developers
* Apply and receive funding to develop and scale your game.
* Earn referral rewards across all players on any Gamechain.
* Receive future airdrops from infrastructure partners.
## The Flywheel in Motion
*Players Stake and Spend $B3 → Developers Launch Game Chains → Settlement Fees Generate Rewards → More Value is Added to $B3.*
This cycle ensures sustainable growth, making \$**B3** the hub of on-chain gaming.
Additional utilities for \$B3 will be announced as they become available.
# Tokenomics
* **Token name:** B3 (Base)
* **Chain:** Base
* **Total Supply:** 100,000,000,000
* **Decimals:** 18
## Distribution and Allocation
### Community & Ecosystem
This allocation is to the growth of the B3 ecosystem - for gamers, by gamers. It is to build an ecosystem belonging to those who play in it: airdrops, tournaments, playtests, community-led grants, research & development, and many others.
### Foundation
This allocation will support the Player1 Foundation as it contributes to B3 and Open Gaming's vision and adoption, including strategic grants/partnerships, legal and compliance needs, audits, and other operational expenses.
### Team and Advisors
This allocation is for core contributors + 18 advisors who represent the best of both gaming worlds - from AAA to web3. All team and advisors are subject to a 4-year vesting schedule: 1-year 25% cliff, with monthly unlocks thereafter.
### Investors
This portion of B3 allocation is for investors who supported B3's development, including 100+ angels who gathered from every corner of the industry - gaming, web3, brands, infrastructure - to support and **B**3lieve\*\* B3's vision. All team & advisors are subject to a 4-year vesting schedule: 1-year 25% cliff, with monthly unlocks thereafter.
## How to Accumulate B3
You can get additional \$B3 tokens through various methods, such as:
* Playing partner games, winning tournaments and completing in-game tasks.
* Participating in community events and challenges.
* Staking your existing tokens for additional rewards and participating in Stake to Win.
* Engaging with partner platforms and their activities.
The B3 token creates a sustainable ecosystem where all participants - players, developers, and stakeholders - benefit from the growth and success of the platform.
# Depositing Tokens on B3
Source: https://docs.b3.fun/learn/deposits-withdrawals/depositing-tokens-on-b3
Learn how to bridge and deposit tokens from other networks to B3 using the built-in bridge interface
To interact with some games and features in the B3 ecosystem, you'll need tokens in your wallet. This guide walks you through how to deposit tokens using the B3 bridge.
## How to Deposit Tokens
Log in to your account at basement.fun.
Select the network and token you want to deposit to B3.
Enter the token amount you want to deposit and click **Bridge**.
Confirm the transaction in your connected wallet to complete your deposit.
Once the transaction is complete, your tokens will appear in your wallet.
Deposits typically complete within a few minutes, but processing times may vary depending on network congestion.
# How to Swap Tokens
Source: https://docs.b3.fun/learn/deposits-withdrawals/how-to-swap-tokens
Learn how to swap tokens across different networks using B3's built-in multi-chain swap interface
With built-in multi-chain support, you can swap tokens across different networks, all from one simple interface. Whether you're preparing for a mint, consolidating assets, or moving between chains, this guide walks you through how to swap one token for another.
## How to Swap Tokens
Log in to your account at [basement.fun/bridge](https://basement.fun/bridge).
Locate the tab labeled **Swap** and select it.
Select the token you want to swap from and the token you want to receive, the token amount, and the chain.
Review and confirm that you have selected the correct token and amounts, and then click **Swap**.
Click **Pay from Connected Wallet** or **Pay from a different wallet** if you wish to use a different wallet from the one you have currently connected.
Confirm the transaction in your wallet to complete the swap. Your swap may take up to a minute to process.
Your swapped tokens will appear in your wallet once the transaction is processed.
Swaps are processed quickly, but during periods of high network activity, transactions may take a bit longer to complete.
# How to Verify the Status of a Transaction on B3
Source: https://docs.b3.fun/learn/deposits-withdrawals/how-to-verify-transaction-status
Learn how to track and verify your transactions on the B3 Network using the block explorer with transaction hashes or wallet addresses
If you've sent a transaction on the B3 Network and want to check whether it's been confirmed, pending, or failed, you can easily track it using the B3 Block Explorer. All you need is the transaction hash (TxHash) or the wallet address involved in the transaction.
## Steps to Verify a Transaction
Go to [explorer.b3.fun](https://explorer.b3.fun).
Hover over the left side panel to expand it and click on **Transactions.**
A new search bar will appear. In the search bar, enter either:
* The wallet address that initiated the transaction
* Or the transaction hash (TxHash)
Browse the results and click the relevant transaction to view:
* Status (Success / Failed / Pending)
* Date & Time
* Tokens transferred
* Gas used
* Any other on-chain details
This is the best way to track mints, transfers, and other activity directly on the B3 Network.
## Transaction Status Meanings
* **Success:** Transaction completed successfully
* **Failed:** Transaction failed to execute (often due to insufficient gas or other errors)
* **Pending:** Transaction is still being processed by the network
You can bookmark frequently used wallet addresses in the explorer to quickly check transaction history in the future.
# Withdrawing Tokens from B3
Source: https://docs.b3.fun/learn/deposits-withdrawals/withdrawing-tokens-from-b3
Learn how to securely withdraw your tokens from the B3 network back to Ethereum or other supported chains
Need to move your tokens out of the B3 network? Whether you're bridging back to Ethereum or another supported chain, withdrawing from B3 is simple and only takes a few steps. This guide walks you through how to securely withdraw your assets.
## How to Withdraw Tokens
Log in to your account at [basement.fun/bridge](https://basement.fun/bridge).
Locate and click the tab labeled **Withdrawal**.
Scroll down and select the network you would like to withdraw your tokens to.
Select the token you want to withdraw.
Enter your withdrawal amount, and then click **Bridge**.
Confirm the transaction in your wallet to complete your withdrawal.
Once confirmed, your tokens will be bridged to the selected network and should arrive shortly.
Withdrawal processing times typically range from a few minutes to an hour, depending on network congestion and the destination chain.
# How to Join a Tournament on Basement
Source: https://docs.b3.fun/learn/games-experiences/how-to-join-a-tournament-on-basement
Learn how to compete in tournaments, climb leaderboards, and win prizes on the Basement gaming platform
Tournaments on Basement are your chance to compete for prizes, climb the leaderboard, and test your skills against other players. Whether you're playing for fun or going for the top spot, joining a tournament is quick and easy. Here's how to get started.
## How to Join a Tournament
Go to [**basement.fun**](https://basement.fun), click **Join the fun** and log in using your preferred method.
On the left side of the page, click the **Trophy icon** labeled **Compete**.
On the Tournament page, click **Tournaments.**
Select **Live Tournaments** to view ongoing competitions. Browse the list of active tournaments and select the one you want to join. Click **Join Tournament** to open the tournament details page.
Here you can review the **rules, prize pool, leaderboard, and time remaining.** You can also chat with other players in **Live Chat.** If you're ready to compete, click **Join Tournament** again to confirm your entry.
Confirm the transaction in your connected wallet to complete your registration.
Once confirmed, click **Play Now** to start your matches and climb the leaderboard.
You're in. Good luck and have fun competing!
## Tournament Features
* **Real-time leaderboards** to track your progress
* **Live chat** to connect with other competitors
* **Clear rules and prize structures** for each tournament
* **Immediate entry** once payment is confirmed
Check the tournament rules and prize structure before joining to understand the competition format and what you're playing for.
# How to Start a Wager on Basement
Source: https://docs.b3.fun/learn/games-experiences/how-to-start-a-wager-on-basement
Learn how to create wager challenges with friends or open challenges for competitive gaming with real stakes
Wagers on Basement let you bet tokens on your skills, whether you're challenging a friend or opening it up for anyone to join. It's a fun way to add stakes to your matches and prove who's really on top. Here's how to start a wager and invite others to play for rewards.
## How to Start a Wager
Click any game on [basement.fun](https://basement.fun).
Click the sword icon at the top of the game details page.
Choose how you want to start your challenge:
* **Challenge a friend**
* **Create an open challenge** for anyone to join
In this guide, we'll create a friend challenge by selecting **Challenge Friends**.
Enter your friend's name in the search field and select their name from the list. Click **Next**.
Select the amount you would like to wager and the duration of the wager challenge. You may also enter a custom amount.
Fund your wager challenge by depositing funds. Simply click **Deposit Bet** and confirm the transaction in your wallet.
Once your wager challenge has been funded, you will be provided with a link to share with your opponent. Click **Copy** to copy the link for sharing. Your friend/opponent will need to open the link, confirm their stake, and join the wager challenge.
Once both players have funded the bet, you can start playing. Compete and let the best player win! The prize pool goes to the winner once the challenge is complete.
## Wager Types
### Friend Challenges
* Challenge specific players by username
* Private matches between known opponents
* Customizable stakes and duration
### Open Challenges
* Create public wagers for anyone to join
* First-come, first-served basis
* Great for finding new opponents
Both players must fund their portion of the wager before the match can begin. The total prize pool goes to the winner upon completion.
Start with smaller wager amounts when playing with new opponents to test the waters before committing to larger stakes.
# Crypto and Wallet Security
Source: https://docs.b3.fun/learn/getting-started/crypto-and-wallet-security
Understanding crypto wallets, their components, security best practices, and how B3 uses wallets for identity and ownership
Think of your crypto wallet as your personal key to the Web3 universe - it's not just a tool; it's your gateway to owning, trading, and interacting in the decentralized world. Wallet apps like Rainbow make this simple by giving you an easy-to-use interface to manage your cryptographic keys, no technical wizardry required. Let's break it down.
At its core, a crypto wallet doesn't "hold" your money. Instead, it's a secure way to manage the keys that give you access to your funds on the blockchain. These keys allow you to send, receive, and own assets like Ethereum.
When you "own" 1 ETH, what you're really doing is owning proof on the blockchain that links your wallet address to that ETH. Your wallet is your digital proof of ownership.
Wallets come in different forms to suit your needs:
* **Hot Wallets:** Always connected to the internet, perfect for frequent transactions (e.g., Rainbow).
* **Cold Wallets:** Hardware wallets like Ledger, designed to store your keys offline for extra security.
## Wallet Components: The Essentials
Every crypto wallet has three main parts that make it all work:
### 1. Public Wallet Address
* Think of this as your username or account number.
* Share it with anyone to receive funds.
* Public addresses let people see your transaction history and assets (because blockchains are transparent).
### 2. Secret Phrase (Seed Phrase)
* A 12- or 24-word phrase that gives you full access to your wallet.
* Treat this like the crown jewels — whoever has it, owns the assets within your wallet.
### 3. Private Key
* A long string of characters generated from your seed phrase.
* Used to sign transactions and prove ownership.
### What Happens if You Lose Your Keys?
Here's the deal: Lose your **private key** or **secret phrase**, and it's game over. There's no "Forgot Password" button, no tech support, and no 2FA. Not even your wallet provider can help you recover it.
That's why backing up your keys is non-negotiable. Here are some pro tips for keeping them safe:
* Use a **password manager** like 1Password.
* Write it down on a piece of paper (old-school but effective).
* Stamp it onto a piece of metal for ultimate durability.
Your keys = your control. Lose them, and you're locked out for good.
## Why B3 Uses Crypto Wallets
At **B3**, your wallet is so much more than just a login. It's your identity, your inventory, and your connection to the entire ecosystem. Here's why wallets are central to our Web3 vision:
### 1. Ownership That's Yours
Your wallet puts you in control of your digital assets — no middlemen, no corporate lock-in.
### 2. Interoperability Across Platforms
Your B3 wallet isn't tied to just one game or ecosystem. Whether you're earning Builder Points (BP) or claiming tokens, your wallet works seamlessly across multiple experiences.
### 3. Security and Transparency
All transactions are visible on the blockchain, but only you control your private keys. This ensures fairness and accountability across the ecosystem.
## Wallet Security
Your crypto wallet gives you great power, but with great power, comes great responsibility. You're in charge of your assets, but you're also in charge of keeping those assets safe from bad actors.
Here are some helpful tips and tricks to help you keep your assets safe and secure.
### Security Guidelines
* Only interact with official B3 websites and platforms ([b3.fun](https://b3.fun), [bsmnt.fun](https://bsmnt.fun), [claim.b3.fun](https://claim.b3.fun)).
* Never share your wallet's private keys or seed phrases with anyone.
* Be wary of direct messages claiming to be B3 support - official support is only through [discord.gg/b3dotfun](https://discord.gg/b3dotfun) and [https://b3.fun](https://b3.fun).
* Double-check all wallet addresses and transaction details before approving transactions.
* Avoid clicking on suspicious links or connecting your wallet to unverified websites.
* Enable 2FA where available and use a hardware wallet for extra security.
* Remember: B3 team will never ask for your personal wallet information.
### Security Best Practices
Follow these essential practices to keep your wallet secure:
* Use strong, unique passwords.
* Enable two-factor authentication (2FA).
* Never share your wallet keys.
* Keep your wallet updated and trusted. Stay secure and game on!
# How to Create an Account on Basement
Source: https://docs.b3.fun/learn/getting-started/how-to-create-an-account
Learn how to create an account using email, wallet, or social login to access your basement.fun profile.
You can sign up using an EVM wallet, email, phone number (SMS), or a social account like Google, Apple, Discord, Telegram, or Farcaster.
## Step-by-Step: Creating Basement Account
Go to [basement.fun](http://basement.fun) and click **Join the fun**.

Choose your preferred login method. You can click **More options** to see additional login methods.
* **EVM Wallet** (e.g. MetaMask or Rainbow)
* **Email or Phone Number (SMS)**
* **Social Account** (Google, Apple, Discord, Telegram, or Farcaster)

Follow the prompts to confirm your login method. This might include connecting your wallet, verifying your email, or approving access through a social account.
Example: If you're using an EVM wallet like Metamask, you'll see a screen like this when confirming your connection:

Once confirmed, your B3 account will be created and ready to use across all B3 platforms.
# How to Customize Your Basement Profile
Source: https://docs.b3.fun/learn/getting-started/how-to-customize-your-basement-profile
Learn how to personalize your Basement profile with custom avatars, usernames, themes, and hand-drawn signatures
Your Basement profile is your digital identity on the Basement platform. You can customize your avatar, choose a unique name, and display a badge that represents your style. Whether you're setting things up for the first time or updating your look later, personalizing your profile helps you stand out and feel more connected.
## Customizing Your Profile for the First Time
Click your avatar in the top right corner to open the account menu.

Enter your desired name, and then click **Register**.

Next, you'll be guided through customizing your avatar. This is your chance to make it truly yours by choosing a gender, adjusting physical features, and picking the outfit that best fits your style.

Once you're happy with your avatar, click **Next** to save your virtual self.

## Additional Customization
After your initial setup you can return to your profile anytime to make changes or try something new.
From the Basement homepage click the profile icon on either the left or right side of the page to open your profile and begin editing.

Next, click **Customize Profile**.

### Available Customization Options
**Username**
Change your public display name at any time
**Avatar**
Edit your avatar's appearance to refresh your look
**Express Yourself**
Add a custom hand-drawn signature and choose a profile theme that matches your vibe
Want a quick walkthrough? Watch this short video to see each customization option in action:
# How to Export Your Embedded Wallet on Basement
Source: https://docs.b3.fun/learn/getting-started/how-to-export-your-embedded-wallet
Learn how to export your Basement embedded wallet to use with other apps like Rainbow or MetaMask by copying your private key or recovery phrase
Want to use your Basement wallet in other apps like Rainbow or MetaMask? Exporting your embedded wallet gives you full control by letting you copy your **secret recovery phrase** or **private key**, so you can import it into any supported wallet.
**Important:** Never share your private key or recovery phrase with anyone. Anyone with access to it can take your funds.
## Steps to Export Your Embedded Wallet
Log into [**Basement.fun**](https://basement.fun) using your preferred login method.
Click the **profile icon** in the top right corner of the page.

Go to the **Accounts** tab and click **Export** next to your wallet address.

Click **Copy** to copy either your **secret recovery phrase** or **private key** to your clipboard.

Paste it into your preferred wallet app to import your wallet.
Your BSMNT wallet is now accessible in your external wallet app while maintaining full compatibility with the B3 ecosystem.
Your exported wallet credentials give you complete control over your funds and allow you to use the same wallet across multiple applications and platforms.
# How to Link Additional Social Accounts on Basement
Source: https://docs.b3.fun/learn/getting-started/how-to-link-additional-social-accounts
Connect multiple accounts like Discord, Twitter, Gmail, and more to your B3 profile for a consistent identity across platforms.
Whether you originally signed up with a wallet, email, or social account, you can connect more options anytime. This includes accounts like Gmail, Twitter, Apple, phone number, Discord, Telegram, and more.
This guide will walk you through how to link additional accounts on basement.fun.
## How to Link Additional Accounts
Click your profile icon on basement.fun to open your account menu.

Navigate to the **Accounts** tab.

Click **Link another account.**

Choose the account type you want to link - for example X (Twitter) - and follow the prompts to authorize the connection.

Once linked your account will show up under the Accounts tab. You can repeat this process to connect as many platforms as you'd like.
The linked accounts will appear in your Accounts tab, giving you multiple ways to access your B3 profile and maintain a consistent identity across all B3 platforms.
# How Daily Slots Work
Source: https://docs.b3.fun/learn/staking-rewards/how-daily-slots-work
Learn how to play the daily slots game for free B3 rewards - one spin per day with automatic payouts to your wallet
Daily Slots is a quick and easy way to try your luck for free rewards every day. Just log in, pull the lever, and let the reels decide. Any tokens you win are sent directly to your wallet with no need to claim.
## How to Play Daily Slots
Go to [stake.b3.fun](http://stake.b3.fun) and sign in using your preferred login method.
Click the **Free Slots!** icon on the main page.

On the daily slots page, click **Pull the lever.**

Confirm the transaction in your connected wallet to complete your spin.
Your reward will be automatically sent to your wallet!
## Game Rules
* **One play per day per wallet**
* **No claiming required** - rewards are sent directly to your wallet
* **Must have at least 1,000 B3 staked** to be eligible
* **Completely free** - no additional costs
Daily Slots is designed to be quick and fun - just one click per day for a chance at bonus B3 rewards!
# How Prize Pool Works
Source: https://docs.b3.fun/learn/staking-rewards/how-prize-pool-works
Learn how to enter the weekly prize pool for a chance to win big rewards based on your staking tier
The Weekly Prize Pool is your shot at big rewards just for being a staker. Every week, players from each reward tier - Rookie, Grinder, and Whale - can enter the pool for a chance to win. You'll need to manually join between Monday and Friday each week. Each Friday, three lucky participants from each tier are drawn and receive rewards based on their tier.
**Important:** Make sure to enter the Weekly Prize Pool before Friday at 1:00 PM UTC.
## How to Enter the Weekly Prize Pool
Go to [stake.b3.fun](https://stake.b3.fun/) and log in with your preferred login method.
Scroll down and locate the tab labeled **Browse Games**. Here, you'll be able to select **Prize Pool** (or any other game you want to participate in).

Click **Enter pool to win** to submit your entry.

Confirm the transaction in your wallet and come back again every Friday to check if you've won.

You're now entered in this week's prize pool!
## How Winners Are Selected
* **Drawing Time:** Every Friday at 1:00 PM UTC
* **Winners Per Tier:** 3 winners from each tier (Rookie, Grinder, Whale)
* **Selection:** Random drawing from all eligible entries
* **Entry Period:** Monday through Friday before 1:00 PM UTC
## Reward Amounts per Tier
Each tier has a different reward amount:
* **Whales:** 250,000 B3 each
* **Grinders:** 100,000 B3 each
* **Rookies:** 25,000 B3 each
## Claiming Your Prize
Once the raffle is drawn, you can return to the prize pool page to see if you've won. If selected, you have two options:
1. **Claim immediately** with a 10% fee deducted (5% to the protocol, 5% to the next jackpot)
2. **Stake your winnings** with no fee at all
Staking your winnings is the best option as you avoid fees and continue earning rewards on your prize!
Remember to enter each week manually - entries don't carry over to the following week.
# How Spin the Wheel Works
Source: https://docs.b3.fun/learn/staking-rewards/how-spin-the-wheel-works
Learn how to play the daily spin the wheel game for extra tokens with instant payouts to your wallet
Spin the Wheel is a simple daily game that gives stakers a chance to win extra tokens with just one click. No claims or follow-ups needed. Just spin and see what you get. All rewards are sent directly to your wallet.
## How to Play Spin the Wheel
Go to [stake.b3.fun](http://stake.b3.fun) and sign in using your preferred login method.
Scroll down to the section labeled **Browse Games** and click **Spin the Wheel** icon.
Click **Spin the Wheel**, then confirm the transaction in your connected wallet.
That's it! Your prize will be automatically added to your wallet.
## Game Rules
* **One spin per day per wallet**
* **Automatic rewards** - no manual claiming required
* **Must have at least 1,000 B3 staked** to participate
* **Free to play** - just confirm the transaction
Spin the Wheel is one of the simplest ways to earn bonus rewards - just one click per day and your prize is instantly delivered to your wallet.
# How to Stake B3
Source: https://docs.b3.fun/learn/staking-rewards/how-to-stake-b3
Step-by-step guide to staking your B3 tokens for passive rewards and access to Stake to Win games
Staking your B3 tokens is quick and easy, and unlocks both passive rewards and access to our Stake to Win prize system. In this guide, we'll walk you through the simple steps to start staking directly on the platform.
## Option 1: Stake with B3 You Already Own
Go to [stake.b3.fun](https://stake.b3.fun/) and sign into your account using your chosen login method.
Click **Stake more B3+**.
Enter the amount you wish to stake and then click **Stake and Earn**.
Confirm the transaction in your wallet to complete the process of staking your B3.
Your tokens are now staked and earning rewards!
## Option 2: Swap & Stake from Other Tokens
Go to [stake.b3.fun](https://stake.b3.fun/) and sign into your account using your chosen login method.
Click **Stake more B3+**.
Then click **Swap & stake** from any crypto.
Enter the amount you wish to stake, and then click **Continue**.
You'll then be able to select the token and chain you want to swap from.
Once you've made your selection, click **Checkout**.
Next, click **Pay from Connected Wallet** (or you can choose to pay from a different wallet), and then confirm the transaction in your wallet to complete your swap+stake.
Your tokens will be swapped to B3 and automatically staked, earning rewards immediately!
The minimum staking amount is 50 B3. Once staked, your tokens will immediately start earning passive rewards and unlock access to Stake to Win games.
# How to Unstake Your Tokens
Source: https://docs.b3.fun/learn/staking-rewards/how-to-unstake-your-tokens
Learn the complete 2-part process to unstake your B3 tokens, including the 45-day cooldown period and withdrawal steps
Unstaking lets you begin the process of moving your B3 tokens out of staking and back into your wallet. This is a 2-part process, requiring a 45-day cooldown before you are able to complete the unstaking process. Follow this quick guide for a step-by-step on how to unstake your tokens.
## Steps to Unstake - Part 1
Go to [stake.b3.fun](https://stake.b3.fun/) and log in using your preferred login method.
Click **Unstake**.
Click **Unstake** again on the next screen.
Enter the amount you want to unstake, where you want to unstake from (bonus or regular staked tokens), and then click **Redeem**.
Confirm the transaction in your wallet to complete the first half of the unstaking process. Once complete, your tokens will enter a 45-day cool-down period. During this time, you must wait 45 days before you can withdraw your tokens from the pool.
Your tokens are now in a 45-day cooldown period. You cannot access them until this period ends.
## Steps to Unstake - Part 2
Go to [stake.b3.fun](https://stake.b3.fun/) and log in using your preferred login method.
Click **Unstake** from the main page.
Locate the transaction with your previously withdrawn token. If 45 days have passed since you initiated the redeem request, you should now see the option to withdraw your tokens. Click **Withdraw**.
You'll be prompted to confirm your withdrawal. Click **Confirm** and then confirm the transaction again in your wallet to complete the withdrawal process.
Once confirmed, your tokens will be available in your wallet for use.
The 45-day cooldown period is designed to ensure the stability of the staking pool. During this time, your tokens are not earning rewards but are also not available for use.
# Stake to Win
Source: https://docs.b3.fun/learn/staking-rewards/stake-to-win
Learn about B3's no-loss prize system with tier-based rewards, daily games, and weekly prize pools for stakers
Stake to Win is B3's no-loss prize system that rewards you just for staking your tokens. Once you're in, you unlock access to a growing list of daily and weekly games, plus a surprise monthly mega prize! No additional spend and no fees - just rewards for staying staked.
## Tier-Based Rewards
Your reward tier is based on how much B3 you have staked. The higher your tier, the bigger the prize pools you're eligible for.
### Whale Tier
* **100,000+ B3 staked**
* Access to the largest prize pools and highest-tier rewards
### Grinder Tier
* **3,000 – 99,999 B3 staked**
* Balanced rewards for regular stakers
### Rookie Tier
* **1,000 – 2,999 B3 staked**
* Great for new players getting started
You can participate in all games as long as you have at least **1,000 B3 staked**.
## Current Games
### Daily Slots
* Spin once per day for a chance at instant B3 rewards
### Daily Spin the Wheel
* Spin the wheel daily and see what luck brings you
### Weekly Prize Pool
* Enter weekly, between Monday and Friday for a chance to win
* Three winners per tier each week
All games are completely free to play once you're staking. There are no additional costs or fees.
The beauty of Stake to Win is that it's truly no-loss - your staked tokens remain secure while you get multiple chances to win additional rewards every week.
# What Is Staking and How Does It Work?
Source: https://docs.b3.fun/learn/staking-rewards/what-is-staking-and-how-does-it-work
Learn about staking B3 tokens, passive rewards, and the Stake to Win no-loss prize system with daily and weekly games
Staking is the process of locking up your B3 tokens on the platform in exchange for rewards. Rather than leaving your tokens idle in your wallet, staking gives you access to bonus rewards and exclusive features within the ecosystem. Your tokens remain yours - you're simply committing them for a period of time to unlock added value like daily spins, prize pools, and more.
## How Staking Works on B3
When you stake your B3 tokens, you're eligible for two types of rewards:
1. **Passive Staking Rewards**
2. **Stake to Win** (our unique, no-loss prize system)
### Passive Staking
Passive staking rewards are automatically earned over time. Once your tokens are staked, they begin accumulating rewards without any further action required from you.
* No need to check in daily
* You can unstake at any time (subject to a 45-day cool-down)
This is ideal for anyone who wants a hands-off, consistent way to earn from their tokens.
### Stake to Win
Stake to Win is our interactive, no-loss prize system designed to make staking more fun and engaging. In addition to passive rewards, stakers get access to daily and weekly games where you can win extra prizes, without risking your tokens.
Here's what you get:
* 🎰 **Daily Slots** – Spin once per day for a chance to win bonus rewards
* 🎡 **Spin the Wheel** – Another chance to win, available daily
* 🏆 **Weekly Prize Pool** – Enter once per week, with winners drawn at the end of the week
There's no downside. Your tokens stay staked, and you get multiple chances to win every week. It's all upside!
Staking combines the security of passive income with the excitement of prize games, creating a unique and rewarding experience for B3 token holders.
# Feedback and Reporting Issues
Source: https://docs.b3.fun/learn/troubleshooting/feedback-and-reporting-issues
How to report bugs, provide feedback, and get support from the B3 team
## Frequently Asked Questions
You can report bugs using the chat button on this site. Be sure to include any helpful screenshots and a clear description of the issue so we can investigate quickly.
We love hearing from the community. You can share your ideas through the chat button here or reach out to us on Discord or X.
**Discord** - [discord.gg/b3dotfun](https://discord.gg/b3dotfun)
**X** - [x.com/b3dotfun](https://x.com/b3dotfun)
Yes. If you can't find the answer here, our support team is available via chat.
## Best Practices for Reporting Issues
When reporting bugs or issues, include:
* **Clear description** of what you were trying to do
* **Steps to reproduce** the problem
* **Screenshots or screen recordings** if applicable
* **Browser and device information**
* **Wallet address** (if the issue is transaction-related)
* **Transaction hash** (for failed transactions)
The more detailed information you provide, the faster our team can investigate and resolve your issue.
## Community Channels
Stay connected with the B3 community:
* **Discord**: [discord.gg/b3dotfun](https://discord.gg/b3dotfun) - Real-time community chat and support
* **X (Twitter)**: [x.com/b3dotfun](https://x.com/b3dotfun) - Latest updates and announcements
* **Support Chat**: Available on this documentation site
Our community is very active and helpful - don't hesitate to ask questions in Discord where other users and team members can assist you quickly.
# Games and Competition FAQ
Source: https://docs.b3.fun/learn/troubleshooting/games-and-competition-faq
Common questions about tournaments, wagers, game performance, and mobile compatibility
## Frequently Asked Questions
Go to the **Compete** tab on [**basement.fun**](https://basement.fun/), select a live tournament, and click **Join**. Confirm the transaction to register.
You can challenge friends or open public wagers by funding a bet on [basement.fun](https://basement.fun/). Select any game, and then click the sword icon to create a wager challenge.
Disconnecting may result in a loss.
First, make sure your internet connection is stable. If the issue continues, try using a different browser or clearing your cache. If that doesn't help, contact support for further assistance.
Some games support mobile browsers, but some games are only available on desktop. You can check for mobile support on the game's detail page.
Yes. You can download the BSMNT app on Android and Apple.
For the best gaming experience, ensure you have a stable internet connection and use an updated browser. Chrome and Firefox generally provide the best compatibility.
The mobile app provides the most optimized experience for mobile gaming, so download it from your device's app store for the best performance.
# Login and Account Access
Source: https://docs.b3.fun/learn/troubleshooting/login-and-account-access
Common questions and solutions for logging into your B3 account and managing account access issues
## Frequently Asked Questions
Make sure you're using the correct login method and that your wallet or social account is connected properly.
Check spam or try resending it. If it still doesn't arrive, try using a different login method like wallet or Discord, or contact us through our support portal for additional assistance.
You can log in using email, Discord, Telegram, wallet, or social accounts like Google and Apple.
Yes. You can connect your wallet, Discord, and other accounts in your profile settings on [**basement.fun**](https://basement.fun/).
Account restrictions can occur if there is a violation of our Terms of Service. If your account has been restricted and you’re unsure why, please reach out to our support team with your account details. We’ll review your case and provide more information specific to your situation.
If you continue having login issues, make sure you're using the same login method you originally used to create your account.
# Stake to Win Games FAQ
Source: https://docs.b3.fun/learn/troubleshooting/stake-to-win-games-faq
Common issues and questions about daily slots, spin the wheel, weekly prize pools, and game mechanics
## Frequently Asked Questions
You must manually enter each week between Monday and Friday before the 1:00 PM UTC cutoff. Three winners per tier.
One staker is randomly selected each month to win a surprise reward like tokens or NFTs.
No. All rewards are sent directly to your wallet after each game.
No. Spin the Wheel and Slots are limited to one play per day per wallet.
This is a known visual bug. Sometimes the spin animation doesn't stop, but the reward is still processed. Try refreshing the page. Your prize should appear immediately, and you can also check your B3 balance for changes. To confirm your reward on-chain, you can look up the transaction on the **B3 Explorer**: [**explorer.b3.fun**](https://explorer.b3.fun/). If you're still unsure, feel free to reach out to support.
Most likely, your reward was processed, but due to a visual bug, you may not have seen it happen. First, refresh the page and check if your B3 balance has changed. You can also confirm the transaction using the [B3 Explorer](https://explorer.b3.fun/) by entering your wallet address. If you're still unsure or need help, feel free to reach out to support and we'll help confirm your reward.
Tiers are based on how much B3 you've staked: **Rookie** (1K–3K), **Grinder** (3K–100K), **Whale** (100K+).
You need at least 1,000 B3 staked to unlock access.
If you experience visual bugs with the spinning animations, don't worry - your rewards are still being processed. Always check your wallet balance and the blockchain explorer to confirm transactions.
# Staking & Rewards FAQ
Source: https://docs.b3.fun/learn/troubleshooting/staking-and-rewards-faq
Common questions about staking, unstaking, cooldown periods, and reward claiming
## Frequently Asked Questions
Staking your B3 tokens gives you passive rewards and access to Stake to Win games. For more information, please read our **What is Staking and How Does it Work** article.
After you unstake, there is a 45-day cooldown before you can withdraw your tokens.
Wait a few minutes and refresh. If it still doesn't show, confirm your transaction succeeded on the blockchain. If your transaction succeeded, but you are still not accumulating tokens, contact support.
Unstaking triggers a 45-day cooldown period. During this time, your tokens are still held in the staking pool and not yet available in your wallet. Once the cooldown ends, you'll need to return to the staking page and click **Withdraw** to move your tokens back into your wallet.
Staking rewards are currently in an accumulation phase and are not yet claimable. When claiming becomes available, we'll notify all stakers and update this page with the steps to claim.
Yes. The minimum amount you can stake is 50 B3.
Remember that the 45-day cooldown period is mandatory for all unstaking operations. Plan accordingly if you need access to your tokens by a specific date.
# Transactions and Wallet Issues
Source: https://docs.b3.fun/learn/troubleshooting/transactions-and-wallet-issues
Troubleshooting guide for transaction problems, wallet connectivity, and deposit/withdrawal issues
## Frequently Asked Questions
Confirm the transaction was sent to the right address and chain. If it's correct, it may just be processing. You can check the details of your transaction using the **B3 Block Explorer**: [**explorer.b3.fun**](https://explorer.b3.fun/). If you require further assistance, reach out to our support team.
Withdrawals and deposits typically complete within a few minutes but may vary depending on network congestion.
Unfortunately, tokens sent to unsupported chains may not be recoverable. Contact support with full details.
Most failed transactions are due to network issues, low gas, or wallet disconnects. Try again or refresh.
Swaps usually take just a few minutes to complete. However, network congestion can sometimes delay processing. In rare cases, transactions may get stuck. If your swap hasn't arrived after a reasonable wait, please reach out to our support team with the transaction hash and wallet address so we can assist you.
Anyspend allows users to swap tokens across supported chains and even purchase tokens using fiat. Below is a list of currently supported chains:
* Base
* Ethereum
* Solana
* Arbitrum
* Avalanche
* B3
* BNN
* Optimism
* Polygon
We’re continuously working to expand support, so check back for updates as new chains are added.
Always double-check wallet addresses and network selections before confirming transactions to avoid sending tokens to the wrong destination.
For transaction verification, the B3 Block Explorer at [explorer.b3.fun](https://explorer.b3.fun) is your best resource for checking transaction status and details.
# Get tokens for a chain
Source: https://docs.b3.fun/anyspend/api-reference/chains/get-tokens-for-a-chain
https://mainnet.anyspend.com/openapi.json get /chains/{chainId}/tokens
Retrieves available tokens for a specific blockchain
# Check Stripe support
Source: https://docs.b3.fun/anyspend/api-reference/onramp/check-stripe-support
https://mainnet.anyspend.com/openapi.json get /onramp/stripe/supported
Checks if Stripe onramp and Stripe Web2 are supported based on IP address location and optional transaction amount
# Create Coinbase onramp URL
Source: https://docs.b3.fun/anyspend/api-reference/onramp/create-coinbase-onramp-url
https://mainnet.anyspend.com/openapi.json post /onramp/coinbase/onramp-url
Creates a Coinbase Onramp buy URL and optionally returns a session token for reuse.
# Create Coinbase session token
Source: https://docs.b3.fun/anyspend/api-reference/onramp/create-coinbase-session-token
https://mainnet.anyspend.com/openapi.json post /onramp/coinbase/session-token
Generates a Coinbase Onramp session token that can be reused when constructing buy URLs.
# Generate direct Coinbase onramp URL
Source: https://docs.b3.fun/anyspend/api-reference/onramp/generate-direct-coinbase-onramp-url
https://mainnet.anyspend.com/openapi.json post /onramp/coinbase/direct-url
Generates a direct Coinbase Onramp URL along with the session token backing it.
# Get Coinbase onramp options
Source: https://docs.b3.fun/anyspend/api-reference/onramp/get-coinbase-onramp-options
https://mainnet.anyspend.com/openapi.json get /onramp/coinbase/options
Retrieves available Coinbase onramp configuration options.
# Create a new order
Source: https://docs.b3.fun/anyspend/api-reference/orders/create-a-new-order
https://mainnet.anyspend.com/openapi.json post /orders
Creates a new order for token transactions across chains
# Get anyspend quote
Source: https://docs.b3.fun/anyspend/api-reference/orders/get-anyspend-quote
https://mainnet.anyspend.com/openapi.json post /orders/quote
Retrieves a quote to swap, execute contract, or participate in HypeDuel
# Get comprehensive order detail
Source: https://docs.b3.fun/anyspend/api-reference/orders/get-comprehensive-order-detail
https://mainnet.anyspend.com/openapi.json get /orders/{orderId}/comprehensive
Retrieves an order with associated transactions, settlement data, and awarded points without sanitization.
# Get order and transactions
Source: https://docs.b3.fun/anyspend/api-reference/orders/get-order-and-transactions
https://mainnet.anyspend.com/openapi.json get /orders/{orderId}
Retrieves order details along with associated transactions
# Get orders by creator
Source: https://docs.b3.fun/anyspend/api-reference/orders/get-orders-by-creator
https://mainnet.anyspend.com/openapi.json get /orders
Retrieves all orders created by a specific address
# Get Stripe client secret
Source: https://docs.b3.fun/anyspend/api-reference/stripe/get-stripe-client-secret
https://mainnet.anyspend.com/openapi.json get /stripe/clientSecret
Retrieves a Stripe client secret for payment processing using a payment intent ID
# Components
Source: https://docs.b3.fun/anyspend/components
React components for seamless crypto payments, NFT purchases, and custom smart contract interactions
## Core Components
### ``
The primary interface component for token-to-token exchanges and fiat onramps.
```tsx title="Basic Usage" icon="react" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpend.tsx
import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
;
```
#### Props
Display as modal overlay or full page
Initial payment method tab
Target token address for buy mode
Chain ID of destination token
Recipient wallet address
Hide transaction history access
Load specific order by ID
#### Usage Examples
```tsx theme={null}
```
```tsx theme={null}
```
***
### ``
A streamlined button component for NFT purchases with built-in payment handling.
```tsx title="NFT Purchase Button" icon="shopping-cart" theme={null}
import { AnySpendNFTButton } from "@b3dotfun/sdk/anyspend/react";
;
```
#### Props
NFT contract configuration object
Wallet address to receive the NFT
#### NFTContract Interface
```typescript title="Type Definition" icon="code" theme={null}
interface NFTContract {
chainId: number; // Blockchain network ID
contractAddress: string; // NFT contract address
price: string; // Price in wei
priceFormatted: string; // Human-readable price
currency: {
chainId: number;
address: string; // Token contract (0x0 for native ETH)
name: string;
symbol: string;
decimals: number;
metadata: {
logoURI: string;
};
};
name: string; // NFT collection name
description: string; // NFT description
imageUrl: string; // Preview image URL
tokenId: number | null; // Token ID (null for ERC721, specific ID for ERC1155)
type: "erc721" | "erc1155"; // NFT contract type
}
```
#### Usage Example
```tsx title="Complete NFT Integration" icon="image" lines theme={null}
const coolNFT = {
chainId: 8333,
contractAddress: "0x9c275ff1634519E9B5449ec79cd939B5F900564d",
price: "500000000000000000", // 0.5 ETH
priceFormatted: "0.5",
currency: {
chainId: 8333,
address: "0x0000000000000000000000000000000000000000",
name: "Ether",
symbol: "ETH",
decimals: 18,
metadata: {
logoURI: "https://assets.coingecko.com/coins/images/279/standard/ethereum.png?1696501628",
},
},
name: "Cool Art Collection",
description: "Unique digital artwork",
imageUrl: "https://example.com/nft-preview.png",
tokenId: null,
type: "erc721",
};
;
```
***
### ``
The most flexible component for custom smart contract interactions, including gaming, staking, and DeFi operations.
```tsx title="Custom Contract Interaction" icon="code" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpendCustom.tsx
import { AnySpendCustom } from "@b3dotfun/sdk/anyspend/react";
console.log("Custom action completed", txHash)}
/>;
```
#### Props
Order type identifier
Target blockchain network
Token being used for payment
Amount in wei/smallest unit
Target smart contract address
Encoded function call data
Optional token spender address
Custom metadata for tracking
Custom header component
Success callback with transaction hash
#### Usage Example - Staking
```tsx title="Staking Integration" icon="coins" lines theme={null}
// Encode staking function call
const stakeAmount = "1000000000000000000"; // 1 token
const stakingCalldata = encodeFunctionData({
abi: stakingABI,
functionName: "stake",
args: [stakeAmount, 30], // 30 days
});
(
Stake Tokens
Duration: 30 days
Expected APY: 5.2%
{!isLoadingAnyspendPrice &&
Total Cost: ${anyspendPrice?.usdPrice}
}
)}
/>;
```
## Specialized Components
### ``
Enhanced NFT component with additional marketplace features.
```tsx title="Enhanced NFT Component" icon="store" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpendNFT.tsx
```
### ``
Pre-configured component for B3 token staking.
```tsx title="B3 Staking" icon="coins" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpendStakeB3.tsx
```
### ``
Gaming-specific component for purchasing spin wheels or lottery tickets.
```tsx title="Gaming Spin Wheel" icon="gamepad" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpendBuySpin.tsx
```
### ``
Tournament entry payment component.
```tsx title="Tournament Entry" icon="trophy" theme={null}
// https://github.com/b3-fun/b3/blob/main/packages/sdk/src/anyspend/react/components/AnySpendTournament.tsx
```
## Component Styling
All components come with default styling that can be customized using CSS variables:
```css title="Custom Styling" icon="palette" theme={null}
/* Override default styles */
.anyspend-modal {
--anyspend-primary: #6366f1;
--anyspend-secondary: #f3f4f6;
--anyspend-border-radius: 12px;
}
```
## Platform Support
Component
React Web
React Native
`AnySpend`
✅
✅
`AnySpendNFTButton`
✅
✅
`AnySpendCustom`
✅
✅
`AnySpendNFT`
✅
✅
Fiat onramp features
✅
❌
## Next Steps
Discover React hooks for custom payment flows
Browse real-world implementation examples
Learn how to handle errors gracefully
# Error Handling & Troubleshooting
Source: https://docs.b3.fun/anyspend/error-handling
Comprehensive guide to handling errors gracefully and debugging common issues with AnySpend
# Error Handling & Troubleshooting
Comprehensive guide to handling errors gracefully and debugging common issues with AnySpend to provide the best user experience.
## 📊 Order Status Lifecycle
Understanding order states is crucial for proper error handling and user experience.
### Order Status Types
```typescript title="Order Status Enum" icon="list" theme={null}
enum OrderStatus {
// Initial States
SCANNING_DEPOSIT_TRANSACTION = "scanning_deposit_transaction",
WAITING_STRIPE_PAYMENT = "waiting_stripe_payment",
EXPIRED = "expired",
// Processing States
SENDING_TOKEN_FROM_VAULT = "sending_token_from_vault",
RELAY = "relay",
// Success States
EXECUTED = "executed",
// Failure States
REFUNDING = "refunding",
REFUNDED = "refunded",
FAILURE = "failure",
}
```
### Status Descriptions
Status
Description
User Action Required
`scanning_deposit_transaction`
Waiting for payment confirmation
None - wait for blockchain confirmation
`waiting_stripe_payment`
Processing credit card payment
May need to complete 3D Secure
`sending_token_from_vault`
Sending tokens for swap
None - automatic process
`relay`
Cross-chain transaction in progress
None - wait for completion
`executed`
Transaction completed successfully
None - success!
`expired`
Order expired before completion
Create new order
`refunding`
Automatic refund in progress
None - wait for refund
`refunded`
Refund completed
Check wallet for refunded tokens
`failure`
Transaction failed
Review error details, retry
## ⚠️ Common Error Codes
### Payment Errors
**Description**: User doesn't have enough tokens for the transaction
**Solution**: Request user to add funds to their wallet or choose a different payment token
**Example**:
```typescript theme={null}
if (error.message === "INSUFFICIENT_BALANCE") {
toast.error("Insufficient balance. Please add funds to your wallet.");
// Optionally redirect to fiat onramp
openFiatOnramp();
}
```
**Description**: Token contract not supported on the target chain
**Solution**: Verify token is supported and provide alternative options
**Example**:
```typescript theme={null}
if (error.message === "INVALID_TOKEN_ADDRESS") {
toast.error("This token is not supported. Please choose another.");
showSupportedTokens();
}
```
**Description**: Transaction amount is below the minimum threshold
**Solution**: Increase transaction amount or inform user of minimum requirements
**Example**:
```typescript theme={null}
if (error.message === "MINIMUM_AMOUNT_NOT_MET") {
toast.error(`Minimum amount is $${minimumAmount}. Please increase your amount.`);
}
```
**Description**: Transaction amount exceeds maximum limit
**Solution**: Reduce amount or split into multiple transactions
**Example**:
```typescript theme={null}
if (error.message === "MAXIMUM_AMOUNT_EXCEEDED") {
toast.error(`Maximum amount is $${maximumAmount}. Please reduce your amount.`);
}
```
### Network Errors
**Description**: Price moved beyond acceptable tolerance during execution
**Solution**: Retry with higher slippage tolerance or wait for price stability
**Example**:
```typescript theme={null}
if (error.message === "SLIPPAGE") {
toast.warning("Price moved unfavorably. Retrying with adjusted settings...");
retryWithHigherSlippage();
}
```
**Description**: RPC connection issues or blockchain congestion
**Solution**: Retry after delay or switch to alternative RPC
**Example**:
```typescript theme={null}
if (error.message === "NETWORK_ERROR") {
toast.error("Network issue detected. Please check connection and try again.");
scheduleRetry();
}
```
**Description**: Price quote is no longer valid
**Solution**: Get fresh quote and retry transaction
**Example**:
```typescript theme={null}
if (error.message === "QUOTE_EXPIRED") {
toast.info("Price quote expired. Getting fresh quote...");
refreshQuoteAndRetry();
}
```
**Description**: Requested blockchain is not supported
**Solution**: Use supported chains or implement fallback
**Example**:
```typescript theme={null}
if (error.message === "CHAIN_NOT_SUPPORTED") {
toast.error("This blockchain is not supported. Please choose another.");
showSupportedChains();
}
```
### Contract Errors
**Description**: Smart contract execution failed
**Solution**: Check contract parameters and state
**Example**:
```typescript theme={null}
if (error.message === "CONTRACT_CALL_FAILED") {
toast.error("Contract interaction failed. Please verify parameters.");
logContractError(error);
}
```
**Description**: Gas limit set too low for transaction
**Solution**: Increase gas limit or suggest gas optimization
**Example**:
```typescript theme={null}
if (error.message === "INSUFFICIENT_GAS") {
toast.error("Transaction requires more gas. Increasing gas limit...");
retryWithHigherGas();
}
```
**Description**: Transaction nonce conflict
**Solution**: Wait for pending transactions to complete
**Example**:
```typescript theme={null}
if (error.message === "NONCE_TOO_LOW") {
toast.info("Please wait for pending transactions to complete.");
waitAndRetry();
}
```
**Description**: Contract reverted the transaction
**Solution**: Check contract state and parameters
**Example**:
```typescript theme={null}
if (error.message === "TRANSACTION_REVERTED") {
toast.error("Transaction was rejected by the contract. Please check requirements.");
showTransactionDetails();
}
```
## 🛠️ Error Handling Patterns
### Component-Level Error Handling
```tsx title="Payment Component with Error Handling" icon="shield-exclamation" lines theme={null}
import { useAnyspendCreateOrder } from "@b3dotfun/sdk/anyspend";
function PaymentComponent() {
const [error, setError] = useState(null);
const [retryCount, setRetryCount] = useState(0);
const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({
onError: error => {
console.error("Payment failed:", error);
// Handle specific errors
switch (error.message) {
case "INSUFFICIENT_BALANCE":
setError("Insufficient balance. Please add funds to your wallet.");
break;
case "SLIPPAGE":
if (retryCount < 3) {
setError("Price moved unfavorably. Retrying...");
setTimeout(() => {
setRetryCount(prev => prev + 1);
retryPayment();
}, 2000);
} else {
setError("Price too volatile. Please try again later.");
}
break;
case "NETWORK_ERROR":
setError("Network issue. Please check your connection and try again.");
break;
case "QUOTE_EXPIRED":
setError("Price quote expired. Getting fresh quote...");
refreshQuote();
break;
default:
setError("Payment failed. Please try again or contact support.");
}
// Track errors for monitoring
analytics.track("payment_error", {
error: error.message,
retryCount,
timestamp: new Date().toISOString(),
});
},
onSuccess: () => {
setError(null);
setRetryCount(0);
},
});
return (
{error && (
⚠️{error}
)}
);
}
```
### Order Status Monitoring
```tsx title="Order Status Monitor" icon="eye" lines theme={null}
import { useAnyspendOrderAndTransactions } from "@b3dotfun/sdk/anyspend";
function OrderStatusMonitor({ orderId }: { orderId: string }) {
const { orderAndTransactions, getOrderAndTransactionsError } = useAnyspendOrderAndTransactions(orderId);
if (getOrderAndTransactionsError) {
return (
⚠️ Slow network detected. Transactions may take longer than usual.
);
}
// ... rest of component
}
```
## 📋 Best Practices
Keep users informed about what's happening, especially during longer operations like cross-chain transactions.
```tsx theme={null}
// Good: Clear status messages
Processing your payment... This may take 2-3 minutes.
// Bad: No feedback during long operations
{isLoading && }
```
Many errors are transient and can be resolved by retrying the operation.
```tsx theme={null}
// Good: Automatic retry with exponential backoff
const retryWithBackoff = (attempt: number) => {
const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
setTimeout(() => retry(), delay);
};
// Bad: No retry mechanism
if (error) {
throw error;
}
```
Comprehensive error logging helps identify and fix issues quickly.
```tsx theme={null}
// Good: Detailed error logging
console.error("Payment failed", {
error: error.message,
orderData,
userAddress,
timestamp: Date.now(),
});
// Bad: Generic error logging
console.error("Error occurred");
```
Provide alternative options when primary functionality fails.
```tsx theme={null}
// Good: Fallback options
if (crossChainFailed) {
return ;
}
// Bad: Complete failure with no alternatives
if (crossChainFailed) {
throw new Error("Transaction failed");
}
```
## 🆘 Getting Help
Get real-time help from our community and support team
Report bugs and request features on our GitHub repository
When reporting issues, please include: - Error messages and codes - Steps to reproduce the issue - Browser and device
information - Network conditions (if relevant) - Order IDs (if applicable)
Remember: Good error handling is about more than just catching errors—it's about providing a smooth, understandable experience for your users even when things go wrong.
# Examples & Use Cases
Source: https://docs.b3.fun/anyspend/examples
Real-world implementation examples for common AnySpend integration patterns
# Examples & Use Cases
Real-world implementation examples for common AnySpend integration patterns, from simple swaps to complex DeFi and gaming applications.
## 🔄 Cross-Chain Token Swaps
### Basic Swap Interface
Perfect for DeFi applications, portfolio managers, or any app that needs token exchange functionality.
```tsx title="Simple Swap Page" icon="exchange-alt" theme={null}
import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
function TokenSwapPage() {
const [userAddress] = useWallet(); // Your wallet hook
return (
) : (
{
setIsOwned(true);
// Update user's NFT collection
queryClient.invalidateQueries(['user-nfts', userAddress]);
// Show success message with explorer link
toast.success(
);
}
```
## Getting Help
Learn how to handle errors gracefully and provide great UX
Get help from our community and team members
These examples showcase the flexibility and power of AnySpend for building seamless payment experiences across different types of applications. Each example can be customized to fit your specific use case and design requirements.
# Hooks
Source: https://docs.b3.fun/anyspend/hooks
React hooks for building custom payment flows and managing order lifecycles
## Core Hooks
### `useAnyspendQuote`
Get real-time pricing information for token swaps and cross-chain transactions.
```tsx title="Basic Usage" icon="quote-left" theme={null}
import { useAnyspendQuote } from "@b3dotfun/sdk/anyspend";
const {
anyspendQuote,
isLoadingAnyspendQuote,
getAnyspendQuoteError,
refetchAnyspendQuote
} = useAnyspendQuote(quoteRequest);
```
#### Parameters
Quote configuration object
#### QuoteRequest Interface
```typescript title="Type Definition" icon="code" theme={null}
interface QuoteRequest {
srcChain: number; // Source chain ID
dstChain: number; // Destination chain ID
srcTokenAddress: string; // Source token contract address
dstTokenAddress: string; // Destination token contract address
type: "swap" | "custom"; // Order type
tradeType: "EXACT_INPUT" | "EXACT_OUTPUT";
amount: string; // Amount in smallest unit (wei)
}
```
#### Return Values
Quote data with pricing and fees
Loading state indicator
Error object if quote failed
Function to manually refresh quote
#### Usage Example
```tsx title="Swap Quote Component" icon="exchange-alt" lines theme={null}
function SwapQuote() {
const quoteRequest = {
srcChain: 1, // Ethereum
dstChain: 8333, // B3
srcTokenAddress: "0xA0b86a33E6Fb6Dd9a9B3d8B5FEb2b3C8e7D9Ff1E", // USDC
dstTokenAddress: "0x0000000000000000000000000000000000000000", // ETH
type: "swap",
tradeType: "EXACT_INPUT",
amount: "1000000", // 1 USDC (6 decimals)
};
const { anyspendQuote, isLoadingAnyspendQuote, getAnyspendQuoteError } =
useAnyspendQuote(quoteRequest);
if (isLoadingAnyspendQuote) return
Getting best price...
;
if (getAnyspendQuoteError) return
Failed to get quote
;
return (
You'll receive: {anyspendQuote?.expectedOutput} ETH
Network fee: ${anyspendQuote?.networkFeeUsd}
Service fee: ${anyspendQuote?.serviceFeeUsd}
Total cost: ${anyspendQuote?.totalUsdCost}
);
}
```
***
### `useAnyspendCreateOrder`
Create and execute AnySpend orders with comprehensive error handling.
```tsx title="Basic Usage" icon="plus-circle" theme={null}
import { useAnyspendCreateOrder } from "@b3dotfun/sdk/anyspend";
const {
createOrder,
isCreatingOrder,
createOrderError
} = useAnyspendCreateOrder(options);
```
#### Parameters
Configuration object with callback functions
#### CreateOrderOptions Interface
```typescript title="Type Definition" icon="settings" theme={null}
interface CreateOrderOptions {
onSuccess?: (data: OrderResponse) => void;
onError?: (error: Error) => void;
onSettled?: () => void;
}
```
#### Return Values
Function to create and execute an order
Loading state indicator
Error object if order creation failed
#### Usage Example
```tsx title="Payment Form" icon="credit-card" lines theme={null}
function PaymentForm() {
const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({
onSuccess: (data) => {
console.log("Order created:", data.data.id);
// Redirect to payment or show success
router.push(`/payment/${data.data.id}`);
},
onError: (error) => {
console.error("Order failed:", error.message);
toast.error("Payment failed. Please try again.");
},
});
const handlePayment = () => {
createOrder({
recipientAddress: userWalletAddress,
orderType: "swap",
srcChain: 1,
dstChain: 8333,
srcToken: {
chainId: 1,
address: "0xA0b86a33E6Fb6Dd9a9B3d8B5FEb2b3C8e7D9Ff1E",
name: "USD Coin",
symbol: "USDC",
decimals: 6,
},
dstToken: {
chainId: 8333,
address: "0x0000000000000000000000000000000000000000",
name: "Ether",
symbol: "ETH",
decimals: 18,
},
srcAmount: "1000000", // 1 USDC
expectedDstAmount: "500000000000000000", // ~0.5 ETH
creatorAddress: userWalletAddress,
});
};
return (
);
}
```
***
### `useAnyspendOrderAndTransactions`
Monitor order status and track associated blockchain transactions in real-time.
```tsx title="Basic Usage" icon="search" theme={null}
import { useAnyspendOrderAndTransactions } from "@b3dotfun/sdk/anyspend";
const {
orderAndTransactions,
isLoadingOrderAndTransactions,
getOrderAndTransactionsError
} = useAnyspendOrderAndTransactions(orderId);
```
#### Parameters
Order ID to track and monitor
#### Return Values
Complete order data with transaction details
Loading state indicator
Error object if fetch failed
#### OrderWithTransactions Interface
```typescript title="Type Definition" icon="database" theme={null}
interface OrderWithTransactions {
data: {
order: Order; // Order details and status
depositTxs: Transaction[]; // User deposit transactions
relayTx?: Transaction; // Cross-chain relay transaction
executeTx?: Transaction; // Final execution transaction
refundTxs: Transaction[]; // Refund transactions (if any)
};
}
```
#### Usage Example
```tsx title="Order Tracker" icon="eye" lines theme={null}
function OrderTracker({ orderId }: { orderId: string }) {
const { orderAndTransactions, isLoadingOrderAndTransactions } =
useAnyspendOrderAndTransactions(orderId);
if (isLoadingOrderAndTransactions) {
return
);
}
```
### Real-time Updates Pattern
```tsx title="Real-time Updates" icon="sync-alt" lines theme={null}
function OrderStatus({ orderId }: { orderId: string }) {
const { orderAndTransactions } = useAnyspendOrderAndTransactions(orderId);
// Auto-refresh every 5 seconds for pending orders
useEffect(() => {
if (orderAndTransactions?.data.order.status === "relay") {
const interval = setInterval(() => {
// Refetch is handled automatically by the hook
}, 5000);
return () => clearInterval(interval);
}
}, [orderAndTransactions?.data.order.status]);
// Component implementation...
}
```
## Next Steps
Browse real-world implementation examples
Learn comprehensive error handling strategies
Explore pre-built components
# AnySpend Facilitator
Source: https://docs.b3.fun/anyspend/x402-facilitator
Production-grade payment processor for x402 multi-token payments
View source code, examples, and contribute
Install @b3dotfun/anyspend-x402 package
## Overview
The AnySpend x402 Facilitator is a production-grade payment infrastructure that powers multi-token, cross-chain payments for the x402 protocol. It handles all the complexity of token swaps, cross-chain bridging, and settlement, allowing developers to accept payments in any token while receiving their preferred currency.
**Production Endpoint:** `https://mainnet.anyspend.com/x402`
## Key Capabilities
### Multi-Token Payment Processing
Accept payments in any ERC-20 token that supports EIP-2612 (permit) or EIP-3009 (transferWithAuthorization):
* **Stablecoins**: USDC, USDT (on supported chains)
* **Native tokens**: ETH, SOL, BNB, MATIC
* **Custom tokens**: Any token with permit support, including project tokens like B3
* **19+ Networks**: Support across EVM chains (Base, Ethereum, Arbitrum, etc.) and SVM (Solana)
### Cross-Chain Routing
Automatically handles payments across different blockchain networks:
* **Same-chain payments**: Direct token transfers with minimal overhead
* **Cross-chain payments**: Automatic bridging between networks (e.g., ETH → Base)
* **Cross-VM payments**: Experimental support for Solana ↔ EVM transfers
* **Optimal routing**: Smart route selection for best execution
### Automatic Token Conversion
Seamlessly converts between any supported tokens:
* **Buyer flexibility**: Users pay with whatever token they hold
* **Seller preference**: Merchants receive their chosen settlement currency
* **Best pricing**: Routes through optimal DEX liquidity sources
* **Slippage protection**: Automatic safeguards against price impact
### Gasless Payments
Users never pay gas fees:
* Facilitator covers all on-chain gas costs
* Users only sign EIP-712 messages
* No need to hold native tokens for gas
* Smooth user experience across all chains
## Standards Compliance
### x402 Protocol Compliant
The AnySpend Facilitator implements the complete x402 specification:
* ✅ **HTTP-native payments** via `402 Payment Required` status
* ✅ **Standard headers** (`X-PAYMENT`, `X-PAYMENT-RESPONSE`, `X-PREFERRED-TOKEN`)
* ✅ **Exact payment scheme** with recipient and amount verification
* ✅ **Signature-based authorization** (EIP-712, EIP-2612, EIP-3009)
* ✅ **Cryptographic verification** without trusted third parties
### Drop-in Replacement
Fully compatible with any x402 implementation:
* **Client compatibility**: Works with any x402-compliant client
* **Server compatibility**: Can be used with any x402 middleware
* **No vendor lock-in**: Standard HTTP APIs, switch facilitators anytime
* **Interoperability**: Integrates with Coinbase CDP x402, PayAI, and others
## Architecture
### Payment Flow
```
┌──────────────┐
│ Client │ Signs payment authorization
│ (Any Token) │ preferredToken: USDT
└──────┬───────┘
│
│ X-PAYMENT header
▼
┌──────────────────────────┐
│ Resource Server │
│ (Your API) │
│ │
│ AnySpend Middleware │
│ • Intercepts request │
│ • Gets quote │
│ • Returns 402 │
└──────┬───────────────────┘
│
│ /verify, /settle
▼
┌──────────────────────────┐
│ AnySpend Facilitator │
│ mainnet.anyspend.com │
│ │
│ • Validates signature │
│ • Executes token swap │
│ • Settles to seller │
└──────┬───────────────────┘
│
│ On-chain txs
▼
┌──────────────────────────┐
│ Blockchain │
│ • Receive payment │
│ • Swap tokens (if needed) │
│ • Settle to merchant │
└──────────────────────────┘
```
### Infrastructure Components
**API Layer**
* RESTful HTTP API for payment verification and settlement
* WebSocket support for real-time payment status updates
* Rate limiting and DDoS protection
* 99.9% uptime SLA
**Swap Engine**
* Aggregates liquidity from multiple DEXs
* Optimal routing for best execution prices
* Slippage protection and MEV resistance
* Cross-chain bridging integration
**Settlement System**
* Parallel transaction processing
* Automatic nonce management
* Failed transaction recovery
* Real-time settlement confirmation
**Security**
* EIP-712 signature verification
* Replay attack prevention (nonce tracking)
* Deadline enforcement
* Smart contract audits
## API Endpoints
### POST /verify
Validates payment signature without executing on-chain.
**Purpose:**
* Fast validation (under 100ms)
* Check signature authenticity
* Verify deadline hasn't expired
* No gas costs
**Request:**
```json theme={null}
{
"x402Version": "0.2",
"paymentHeader": "base64_encoded_payment",
"paymentRequirements": {
"scheme": "exact",
"network": "base-mainnet",
"amount": "1000000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"recipient": "0xMerchantAddress..."
}
}
```
**Response:**
```json theme={null}
{
"valid": true
}
```
***
### POST /settle
Executes on-chain settlement and returns transaction proof.
**Purpose:**
* Execute payment authorization
* Swap tokens if needed (buyer token → seller token)
* Settle to resource server
* Return transaction hash for verification
**Request:**
```json theme={null}
{
"x402Version": "0.2",
"paymentHeader": "base64_encoded_payment",
"paymentRequirements": { /* ... */ }
}
```
**Response:**
```json theme={null}
{
"txHash": "0xabc123...",
"network": "base-mainnet",
"metadata": {
"receiptTxHash": "0x...",
"swapTxHash": "0x...",
"settlementTxHash": "0x..."
}
}
```
***
### POST /quote
Get token conversion rate for multi-token payments.
**Purpose:**
* Calculate exact token amount for payment
* Get current exchange rate
* Estimate swap execution time
**Request:**
```json theme={null}
{
"usdcAmount": "1000000", // Target amount (1 USDC)
"paymentToken": "0xfde4...", // USDT address
"network": "base-mainnet"
}
```
**Response:**
```json theme={null}
{
"tokenAmount": "1000000", // 1.0 USDT needed
"exchangeRate": "1.0",
"deadline": 1730000000,
"route": {
"srcToken": "0xfde4...",
"dstToken": "0x8335...",
"path": ["USDT", "USDC"]
}
}
```
***
### GET /supported
Lists supported payment schemes and networks.
**Response:**
```json theme={null}
{
"schemes": [{
"scheme": "exact",
"networks": [
"base",
"ethereum",
"arbitrum",
"optimism",
"polygon",
"bsc",
"avalanche",
"solana"
]
}]
}
```
## Integration
### Server-Side (Express)
```typescript theme={null}
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
const endpointConfig = {
'/api/premium': {
amount: '1.00',
asset: 'USD'
}
};
app.use(paymentMiddleware(
'0xYourAddress...',
endpointConfig,
facilitator // Pre-configured to mainnet.anyspend.com/x402
));
```
### Server-Side (Custom)
```typescript theme={null}
import { X402Facilitator } from '@b3dotfun/anyspend-x402';
const facilitator = new X402Facilitator({
url: 'https://mainnet.anyspend.com/x402',
apiKey: process.env.ANYSPEND_API_KEY // Optional
});
// Verify payment
const { valid } = await facilitator.verify(paymentHeader, requirements);
// Settle payment
const { txHash } = await facilitator.settle(paymentHeader, requirements);
```
### Client-Side
```typescript theme={null}
import { X402Client } from 'anyspend-x402-client';
const client = new X402Client({
walletClient,
facilitatorUrl: 'https://mainnet.anyspend.com/x402' // Optional, uses this by default
});
const response = await client.request('https://api.example.com/premium');
```
## Security
### Signature Verification
All payments are verified using EIP-712 typed data signatures:
* **USDC**: EIP-3009 `transferWithAuthorization`
* **Other tokens**: EIP-2612 `permit`
Signatures are validated before any on-chain execution.
### Replay Protection
**Random Nonce (USDC):**
* Each signature includes unique bytes32 nonce
* Nonce can only be used once per address
* No ordering dependencies
**Sequential Nonce (Permit):**
* Token contract maintains nonce counter
* Auto-increments on each permit execution
* Prevents out-of-order execution
### Deadline Enforcement
All signatures include expiration timestamps:
* Default: 5 minutes from signature time
* Prevents stale payment authorizations
* Automatic rejection of expired signatures
### No Private Key Access
The facilitator **never** has access to user private keys:
* Users sign messages client-side
* Only signatures are transmitted
* Non-custodial architecture
## Performance
### Speed
* **Verification**: Under 100ms for signature validation
* **Same-chain settlement**: 2-10 seconds average
* **Cross-chain settlement**: 2-5 minutes (depends on bridging)
* **Quote generation**: Under 200ms
### Scalability
* Handles 1000+ concurrent payments
* Horizontal scaling for high throughput
* Parallel transaction processing
* Load balancing across multiple nodes
### Reliability
* 99.9% uptime guarantee
* Automatic failover and redundancy
* Failed transaction retry logic
* 24/7 monitoring and alerts
## Network Support
### EVM Mainnet Networks (12)
Abstract, Arbitrum, Avalanche, B3, Base, BNB Chain, Ethereum, IoTeX, Optimism, Peaq, Polygon, Sei
### EVM Testnets (5)
Abstract Testnet, Avalanche Fuji, Base Sepolia, Polygon Amoy, Sei Testnet
### SVM Networks (2)
Solana Mainnet, Solana Devnet
See [Network Support](/anyspend/x402-network-support) for complete details.
## Why Choose AnySpend Facilitator?
Full x402 protocol compliance - works with any compatible client or server
Battle-tested infrastructure with enterprise-grade reliability and performance
Support for 19+ blockchain networks with automatic cross-chain routing
Simple APIs and SDKs for Express, Next.js, Hono, and client-side TypeScript
## Getting Started
Start accepting multi-token payments in your API
Pay with any token using the AnySpend client
See all supported networks and tokens
Learn how AnySpend x402 works
## Support
Need help with the facilitator?
* **Discord**: [discord.gg/b3dotfun](https://discord.gg/b3dotfun)
* **GitHub**: [github.com/b3-fun/anyspend-x402](https://github.com/b3-fun/anyspend-x402)
* **Email**: [support@b3.fun](mailto:support@b3.fun)
* **Docs**: [docs.b3.fun](https://docs.b3.fun)
# Network & Token Support
Source: https://docs.b3.fun/anyspend/x402-network-support
Supported blockchains, tokens, and contract addresses for AnySpend x402 payments
## Overview
AnySpend x402 supports payments across multiple blockchain networks including EVM-compatible chains and Solana (SVM). This page provides the complete reference of supported networks, tokens, and their contract addresses.
## EVM Mainnet Networks
AnySpend x402 supports the following EVM mainnet chains:
| Network | Identifier | Chain ID | Type |
| ----------------- | ----------- | -------- | ---------------------- |
| Abstract | `abstract` | 2741 | L2 |
| Arbitrum One | `arbitrum` | 42161 | L2 - Optimistic Rollup |
| Avalanche C-Chain | `avalanche` | 43114 | L1 |
| B3 | `b3` | 8333 | L2 |
| Base | `base` | 8453 | L2 - Optimistic Rollup |
| BNB Smart Chain | `bsc` | 56 | L1 |
| Ethereum | `ethereum` | 1 | L1 |
| IoTeX | `iotex` | 4689 | L1 |
| Optimism | `optimism` | 10 | L2 - Optimistic Rollup |
| Peaq | `peaq` | 3338 | L1 |
| Polygon PoS | `polygon` | 137 | Sidechain |
| Sei | `sei` | 1329 | L1 |
**Recommended chains for production:** Base (low fees, fast), Ethereum (maximum liquidity), Arbitrum (balanced)
## EVM Testnet Networks
For development and testing, AnySpend supports these testnets:
| Network | Identifier | Chain ID | Faucet |
| ---------------- | ------------------ | -------- | ------------------------------------------------------------------ |
| Abstract Testnet | `abstract-testnet` | 11124 | [Abstract Faucet](https://portal.testnet.abs.xyz/) |
| Avalanche Fuji | `avalanche-fuji` | 43113 | [Fuji Faucet](https://faucet.avax.network/) |
| Base Sepolia | `base-sepolia` | 84532 | [Coinbase Faucet](https://portal.cdp.coinbase.com/products/faucet) |
| Polygon Amoy | `polygon-amoy` | 80002 | [Polygon Faucet](https://faucet.polygon.technology/) |
| Sei Testnet | `sei-testnet` | 1328 | [Sei Faucet](https://atlantic-2.app.sei.io/faucet) |
## SVM Networks (Solana)
AnySpend also supports Solana Virtual Machine (SVM) networks:
| Network | Identifier | Chain ID | Type |
| -------------- | --------------- | -------- | ------- |
| Solana Mainnet | `solana` | 101 | Mainnet |
| Solana Devnet | `solana-devnet` | 103 | Testnet |
Solana support enables cross-VM payments - users can pay with SOL or SPL tokens while resource servers receive stablecoins on EVM chains.
## Token Compatibility
To use a token with X402, it must implement either **EIP-3009** (`transferWithAuthorization`) or **EIP-2612** (`permit`) for gasless signatures.
Rather than maintaining a static list of supported tokens, we've built tools to help you verify any token's compatibility in real-time.
## X402 Token Compatibility Checker
**New Tool Available**: Verify if any ERC-20 token is compatible with X402 payments before integration.
For a token to be compatible with X402, it must implement either:
* **EIP-3009** (`transferWithAuthorization`) - Used by USDC
* **EIP-2612** (`permit`) - Used by USDT (on some chains) and many other modern ERC-20 tokens
### Using the Public Checker
Check any ERC-20 token on AnySpend-supported chains:
**🌐 Web Interface**: [https://anyspend.com/x402-tokens](https://anyspend.com/x402-tokens)
Simply enter a token address and select the network to instantly verify X402 compatibility.
**🔗 Direct API**: You can also query the API directly:
```bash theme={null}
curl https://tokens.anyspend.com/metadata/base/0xb3b32f9f8827d4634fe7d973fa1034ec9fddb3b3
```
This returns the token metadata and compatibility information in JSON format.
### Using the NPM Package
For developers integrating token compatibility checks into their applications:
**📦 NPM Package**: [@b3dotfun/anyspend-x402-token-compat](https://www.npmjs.com/package/@b3dotfun/anyspend-x402-token-compat)
```bash theme={null}
npm install @b3dotfun/anyspend-x402-token-compat
```
**Usage:**
```typescript theme={null}
import { TokenCompatClient } from '@b3dotfun/anyspend-x402-token-compat';
const client = new TokenCompatClient();
// Get token metadata and compatibility
const metadata = await client.getTokenMetadata('base', '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913');
console.log(metadata.supportsEip2612); // true - supports permit
console.log(metadata.supportsEip3009); // true - supports transferWithAuth
// Quick compatibility check
const hasPermit = await client.supportsEip2612('base', tokenAddress);
```
### How It Works
**Supported Cross-Chain Routes:**
AnySpend supports cross-chain routing between any of the supported EVM networks, including:
* Ethereum ↔ Base, Arbitrum, Optimism, Polygon, Avalanche
* Base ↔ Arbitrum, Optimism, Polygon
* L1 ↔ L2 bridging across all supported chains
* Cross-VM: Solana ↔ EVM chains (experimental)
Cross-chain payments take longer (2-5 minutes) due to bridging time and incur additional fees (\~0.5% total). Same-chain payments are recommended for the best user experience.
Built on Cloudflare's global infrastructure with intelligent caching for instant results.
The checker combines real-time on-chain verification with a growing database of verified tokens:
* **⚡ Lightning Fast**: Millisecond-level response times through smart caching
* **📊 Crowdsourced**: Database grows automatically as more tokens are checked
* **🔄 Always Fresh**: On-chain verification for uncached tokens
* **🌍 Global**: Powered by Cloudflare Workers for low-latency worldwide access
### Integration in X402
The token compatibility checker is already integrated into the AnySpend X402 SDK:
* Validates token compatibility upfront before payment
* Returns clear, actionable errors for unsupported tokens
* Prevents failed transactions due to incompatible tokens
**Try it live**: [https://x402-demo.anyspend.com/](https://x402-demo.anyspend.com/)
**Important**: Always verify token compatibility before integrating a new token into your payment flow. Incompatible tokens will result in failed payment signatures.
## Additional Resources
RPC endpoints and chain metadata
Verified token addresses across chains
Get testnet tokens for development
Production facilitator API endpoint
## What's Next?
Start using these tokens to pay for services
Configure your API to accept these tokens
## Getting Help
If you need a specific token or network supported:
* **Discord**: Request in [#anyspend-support](https://discord.gg/b3dotfun)
* **GitHub**: Open an issue at [github.com/b3-fun/anyspend-x402](https://github.com/b3-fun/anyspend-x402)
* **Email**: [support@b3.fun](mailto:support@b3.fun)
# AnySpend x402 Overview
Source: https://docs.b3.fun/anyspend/x402-overview
Pay for paywalled APIs and services with any token - powered by the x402 open payment protocol
View source code, examples, and contribute
Install @b3dotfun/anyspend-x402 package
## What is AnySpend x402?
AnySpend x402 is B3's implementation of the **x402 payment protocol** that enables instant, automatic cryptocurrency payments directly over HTTP. Unlike traditional x402 facilitators that only support USDC, **AnySpend allows you to pay with any compatible token** (EIP-2612 or EIP-3009) while resource servers receive any token they prefer.
The x402 protocol modernizes the HTTP `402 Payment Required` status code, turning it into a practical solution for machine-to-machine micropayments, paywalled APIs, and autonomous agent interactions.
## For Buyers (Payers)
Pay for paywalled resources using any compatible token you hold:
* **Pay with compatible tokens**: Use any token with EIP-2612 or EIP-3009 support for gasless payments
* **Standard protocol**: Works with any x402-enabled service using standard HTTP
* **No manual swaps**: AnySpend automatically converts your token to what the seller needs
* **Simple integration**: One SDK works across all x402 services
Browse compatible tokens with EIP-2612 or EIP-3009 support across 19+ networks
**Use Cases:**
* Access premium APIs and AI agent services
* Pay for computational resources and data feeds
* Enable autonomous agent-to-agent payments
* Consume paywalled content programmatically
## For Sellers (Resource Servers)
Accept payments in USDC while your customers pay with their preferred token:
* **Receive USDC**: Get paid in USDC regardless of what token the customer uses
* **Express middleware**: Add payments to your API with just a few lines of code
* **No blockchain infrastructure**: AnySpend handles all on-chain complexity
* **Instant settlement**: Payments are verified and settled automatically
**Use Cases:**
* Monetize premium APIs and data services
* Build paid AI agent workflows
* Create paywalled content and tools
* Accept crypto payments without crypto expertise
## Quick Start
Choose your path:
**For Buyers**: Learn how to use the x402 client SDK to pay for paywalled resources with any token
**For Sellers**: Add the Express middleware to your API and start accepting multi-token payments
## How It Works
User's application makes a standard HTTP request to your API
Your API returns `402 Payment Required` with payment details
Client specifies their preferred payment token (USDC, USDT, etc.)
AnySpend calculates the equivalent amount in the client's chosen token
User signs a cryptographic authorization for their token
AnySpend swaps the token to USDC and settles to your wallet
Your API receives payment confirmation and returns the requested resource
## Key Differentiators
### Multi-Token Support
**Standard x402**: Resource servers and clients must both use USDC
**AnySpend x402**: Clients pay with **any compatible token** (EIP-2612 or EIP-3009 support required) they hold. AnySpend handles the conversion.
```
Client pays with DAI (EIP-2612) → AnySpend swaps to 1 USDC → Seller receives 1 USDC
```
### No Infrastructure Required
Resource servers don't need to:
* Run blockchain nodes
* Manage wallets or private keys
* Handle token swaps or bridging
* Monitor transaction status
AnySpend's facilitator handles all blockchain operations and provides simple HTTP endpoints for verification and settlement.
### Standard Protocol Compliance
Clients using AnySpend have **zero awareness** they're using a special facilitator. The entire flow uses standard x402 protocol messages - the multi-token magic happens transparently on the resource server side through middleware.
## Package Delivery
AnySpend x402 consists of two packages:
**@b3dotfun/anyspend-x402**
Universal server middleware supporting Express, Next.js, and Hono for resource servers to easily accept multi-token payments
**anyspend-x402-client**
Platform-agnostic TypeScript SDK for clients to make payments with signature helpers
## Powered by AnySpend Facilitator
All x402 payments are processed through the **AnySpend Facilitator** - a production-grade payment infrastructure that handles:
* ✅ Multi-token support across 19+ blockchain networks
* ✅ Automatic token swaps and cross-chain routing
* ✅ Gasless payments for users
* ✅ Standards-compliant x402 implementation
* ✅ Drop-in replacement for any x402 facilitator
**Production Endpoint:** `https://mainnet.anyspend.com/x402`
Discover the full capabilities, API endpoints, and architecture of the AnySpend Facilitator
# Quickstart for Buyers
Source: https://docs.b3.fun/anyspend/x402-quickstart-buyers
Pay for paywalled APIs and services using any token with the AnySpend x402 Client SDK
## Overview
This guide shows you how to use the **AnySpend x402 Client SDK** to pay for paywalled resources using compatible tokens with EIP-2612 or EIP-3009 support. The SDK handles the entire payment flow automatically, including signature generation and retry logic.
The beauty of x402 is that you can use this same client to pay for **any x402-enabled service**, not just those using AnySpend.
Browse compatible tokens with EIP-2612 or EIP-3009 support across 19+ networks
## Prerequisites
Before you begin, make sure you have:
* **Node.js 18+** or compatible JavaScript runtime
* **A crypto wallet** with compatible tokens (USDC, DAI, or other EIP-2612/EIP-3009 tokens)
* **A wallet library** like [viem](https://viem.sh) or [ethers.js](https://docs.ethers.org)
* **Access to an x402-enabled service** (like a paywalled API)
**Important**: Only tokens with EIP-2612 (Permit) or EIP-3009 (TransferWithAuthorization) support are compatible with AnySpend x402 for gasless payments. Use the [Token Compatibility Checker](https://anyspend.com/x402-tokens) to verify your token is supported.
## Installation
Install the x402 client SDK:
```bash npm theme={null}
npm install anyspend-x402-client viem
```
```bash yarn theme={null}
yarn add anyspend-x402-client viem
```
```bash pnpm theme={null}
pnpm add anyspend-x402-client viem
```
The SDK uses [viem](https://viem.sh) for wallet operations and signature generation.
## Basic Usage
### 1. Create a Wallet Client
First, set up your wallet client using viem:
```typescript theme={null}
import { createWalletClient, custom } from 'viem';
import { base } from 'viem/chains';
// For browser with MetaMask or other wallet extension
const walletClient = createWalletClient({
chain: base,
transport: custom(window.ethereum)
});
// Get the user's address
const [address] = await walletClient.getAddresses();
```
### 2. Initialize the x402 Client
Create an instance of the x402 client:
```typescript theme={null}
import { X402Client } from 'anyspend-x402-client';
const x402Client = new X402Client({
walletClient, // Your viem wallet client
preferredToken: '0x...', // Optional: default token to pay with
autoRetry: true // Auto-handle 402 responses (default: true)
});
```
### 3. Make a Paid Request
Use the client to access paywalled resources:
```typescript theme={null}
try {
const response = await x402Client.request(
'https://api.example.com/premium-data',
{
method: 'GET',
}
);
console.log('Data:', response.data);
console.log('Payment TX:', response.paymentResponse?.txHash);
} catch (error) {
console.error('Payment failed:', error);
}
```
**What happens:**
1. Client makes initial request
2. API returns `402 Payment Required` with payment details
3. X402Client automatically signs the payment authorization
4. Client retries the request with payment
5. API verifies and settles the payment
6. Client receives the requested data
## Advanced Usage
### Specify Payment Token
There are two ways to specify which token you want to pay with:
#### Option 1: Using X402Client
Pay with a specific token by setting `preferredToken`:
```typescript theme={null}
const response = await x402Client.request(
'https://ai-agent-api.com/inference',
{
method: 'POST',
body: { prompt: 'Generate an image of a cat' },
preferredToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' // USDC on Base
}
);
```
#### Option 2: Using wrapFetchWithPayment (Advanced)
For more control, use the lower-level `wrapFetchWithPayment` function:
```typescript theme={null}
import { wrapFetchWithPayment } from 'anyspend-x402-client';
const tokenAddress = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // USDC on Base
const selectedChain = 8453; // Base
const paymentPreferences = {
preferredToken: tokenAddress,
preferredNetwork: 'base' as const, // or use getNetworkName(selectedChain)
};
// Wrap fetch with automatic payment handling
const fetchWithPayment = wrapFetchWithPayment(
fetch,
walletClient,
'1000000', // Max payment value (1 USDC in 6 decimals)
undefined, // Use default payment requirements selector
undefined, // Use default config
paymentPreferences, // Specify your preferred token and network
);
// Use the wrapped fetch like normal fetch
const response = await fetchWithPayment('https://api.example.com/premium-data');
const data = await response.json();
```
**Benefits of `wrapFetchWithPayment`:**
* Works with any existing `fetch`-based code
* More granular control over payment behavior
* Can specify max payment value
* Custom payment requirements selector
* Supports multi-network signers
If the resource server supports AnySpend middleware, you'll pay the equivalent amount in your preferred token instead of USDC.
### Using HTTP Headers for Payment Preferences
**New in X402**: You can now specify payment preferences using HTTP headers, which is particularly useful when making direct HTTP requests or when integrating with existing HTTP clients.
When making requests to X402-enabled services, you can specify your preferred payment token and network using these HTTP headers:
```bash theme={null}
curl -X GET https://api.example.com/premium-data \
-H "X-PREFERRED-TOKEN: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" \
-H "X-PREFERRED-NETWORK: base-mainnet"
```
**Common Token Addresses:**
* **USDC on Base**: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`
* **USDT on Base**: `0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2`
**Network Identifiers:**
* `base-mainnet` - Base Mainnet
* `ethereum-mainnet` - Ethereum Mainnet
* `arbitrum-mainnet` - Arbitrum One
* `optimism-mainnet` - Optimism Mainnet
* `polygon-mainnet` - Polygon PoS
These headers work with any HTTP client and are automatically respected by X402-enabled resource servers using AnySpend middleware. If no headers are provided, the server will default to USDC.
#### Using Headers with X402Client
The X402Client automatically adds these headers based on your configuration:
```typescript theme={null}
const x402Client = new X402Client({
walletClient,
preferredToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
network: 'base-mainnet'
});
// Headers are automatically added to all requests
const response = await x402Client.request('https://api.example.com/data');
```
#### Using Headers with fetch
You can also add these headers manually when using the native `fetch` API or other HTTP clients:
```typescript theme={null}
const response = await fetch('https://api.example.com/premium-data', {
headers: {
'X-PREFERRED-TOKEN': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
'X-PREFERRED-NETWORK': 'base-mainnet'
}
});
// Then handle the 402 response if needed
if (response.status === 402) {
// Process payment using X402Client or wrapFetchWithPayment
}
```
### POST Requests with Body
Make paid POST requests:
```typescript theme={null}
const response = await x402Client.request(
'https://api.example.com/compute',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello!' }]
}
}
);
```
### Manual Payment Flow
For more control, handle the payment flow manually:
```typescript theme={null}
// 1. Make initial request
const initialResponse = await fetch('https://api.example.com/premium-data');
if (initialResponse.status === 402) {
// 2. Parse payment requirements
const paymentRequired = await initialResponse.json();
const requirements = paymentRequired.requirements[0];
console.log('Payment required:', {
amount: requirements.amount,
token: requirements.asset,
recipient: requirements.recipient
});
// 3. Sign payment authorization
const paymentHeader = await x402Client.signPayment(requirements);
// 4. Retry with payment
const paidResponse = await fetch('https://api.example.com/premium-data', {
headers: {
'X-PAYMENT': paymentHeader
}
});
const data = await paidResponse.json();
const paymentResponse = paidResponse.headers.get('X-PAYMENT-RESPONSE');
console.log('Payment successful!', JSON.parse(atob(paymentResponse)));
}
```
## Configuration Options
### X402ClientOptions
```typescript theme={null}
interface X402ClientOptions {
walletClient: WalletClient; // viem wallet client (required)
network?: string; // Default network (e.g., 'base-mainnet')
preferredToken?: string; // Preferred payment token address
autoRetry?: boolean; // Auto-retry on 402 (default: true)
timeout?: number; // Request timeout in ms (default: 30000)
}
```
### RequestOptions
```typescript theme={null}
interface RequestOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
headers?: Record;
body?: any; // Request body (auto-serialized to JSON)
preferredToken?: string; // Override default preferred token
}
```
### wrapFetchWithPayment Parameters
For advanced use cases, `wrapFetchWithPayment` provides lower-level control:
```typescript theme={null}
function wrapFetchWithPayment(
fetchFn: typeof fetch, // Fetch function to wrap
signer: Signer | MultiNetworkSigner, // Wallet client for signing
maxPaymentValue: string, // Max payment in smallest unit (e.g., '1000000' for 1 USDC)
selectPaymentRequirements?: Function, // Custom requirements selector
config?: {
timeout?: number; // Request timeout in ms
maxRetries?: number; // Max payment retry attempts
},
paymentPreferences?: {
preferredToken?: string; // Token address to pay with
preferredNetwork?: string; // Network identifier (e.g., 'base', 'ethereum')
}
): typeof fetch
```
**Example with all parameters:**
```typescript theme={null}
import { wrapFetchWithPayment } from 'anyspend-x402-client';
const fetchWithPayment = wrapFetchWithPayment(
fetch,
walletClient,
'5000000', // Max 5 USDC
undefined, // Default requirements selector
{
timeout: 60000, // 60 second timeout
maxRetries: 3 // Retry up to 3 times
},
{
preferredToken: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb', // DAI
preferredNetwork: 'base'
}
);
```
## Supported Tokens
**Only tokens with EIP-2612 or EIP-3009 support are compatible** with AnySpend x402 for gasless payments.
### What are EIP-2612 and EIP-3009?
* **EIP-2612 (Permit)**: Allows gasless token approvals via off-chain signatures
* **EIP-3009 (TransferWithAuthorization)**: Enables gasless transfers via off-chain signatures (used by USDC)
### Common Compatible Tokens
* **USDC** - EIP-3009 support on all chains
* **B3** - EIP-2612 permit support
* **Many other tokens** - Check compatibility using the tool below
Browse all compatible tokens with EIP-2612 or EIP-3009 support across 19+ networks
See [Network Support](/anyspend/x402-network-support) for detailed token addresses per chain.
## Examples
### React Component (Using X402Client)
```tsx theme={null}
import { X402Client } from 'anyspend-x402-client';
import { useWalletClient } from 'wagmi';
import { useState } from 'react';
export function PremiumDataFetcher() {
const { data: walletClient } = useWalletClient();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const fetchPremiumData = async () => {
if (!walletClient) return;
setLoading(true);
try {
const client = new X402Client({
walletClient,
preferredToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' // USDC on Base
});
const response = await client.request(
'https://api.example.com/premium-data'
);
setData(response.data);
console.log('Paid with TX:', response.paymentResponse?.txHash);
} catch (error) {
console.error('Payment failed:', error);
} finally {
setLoading(false);
}
};
return (
{data &&
{JSON.stringify(data, null, 2)}
}
);
}
```
### React Component (Using wrapFetchWithPayment)
For applications that need more control or use existing fetch-based code:
```tsx theme={null}
import { wrapFetchWithPayment } from 'anyspend-x402-client';
import { useWalletClient, useChainId } from 'wagmi';
import { useState } from 'react';
// Helper to get network name from chain ID
const getNetworkName = (chainId: number): string => {
const networks: Record = {
8453: 'base',
1: 'ethereum',
42161: 'arbitrum',
10: 'optimism',
137: 'polygon',
};
return networks[chainId] || 'base';
};
export function PremiumDataFetcherAdvanced() {
const { data: walletClient } = useWalletClient();
const selectedChain = useChainId();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [log, setLog] = useState([]);
// Token addresses by chain
const tokenAddresses: Record = {
8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
1: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC on Ethereum
};
const fetchPremiumData = async () => {
if (!walletClient) return;
setLoading(true);
setLog([]);
try {
const tokenAddress = tokenAddresses[selectedChain];
const paymentPreferences = {
preferredToken: tokenAddress,
preferredNetwork: getNetworkName(selectedChain) as any,
};
setLog(prev => [...prev,
`💡 Using preferred token: ${tokenAddress} on ${getNetworkName(selectedChain)}`
]);
// Wrap fetch with automatic payment handling
const fetchWithPayment = wrapFetchWithPayment(
fetch,
walletClient as any,
'1000000', // Max 1 USDC
undefined, // Use default payment requirements selector
undefined, // Use default config
paymentPreferences,
);
setLog(prev => [...prev, '🔄 Making request...']);
const response = await fetchWithPayment('https://api.example.com/premium-data');
const result = await response.json();
setData(result);
setLog(prev => [...prev, '✅ Payment successful!']);
} catch (error) {
console.error('Payment failed:', error);
setLog(prev => [...prev, `❌ Error: ${error.message}`]);
} finally {
setLoading(false);
}
};
return (
{log.length > 0 && (
{log.map((entry, i) =>
{entry}
)}
)}
{data &&
{JSON.stringify(data, null, 2)}
}
);
}
```
### Node.js Script
```typescript theme={null}
import { X402Client } from 'anyspend-x402-client';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';
// Load private key from environment
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: base,
transport: http()
});
const x402Client = new X402Client({
walletClient,
preferredToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' // USDC on Base
});
async function main() {
const response = await x402Client.request(
'https://api.example.com/ai-inference',
{
method: 'POST',
body: { prompt: 'Analyze this data...' }
}
);
console.log('Result:', response.data);
console.log('Payment TX:', response.paymentResponse?.txHash);
}
main();
```
## Error Handling
The SDK throws typed errors for common failure scenarios:
```typescript theme={null}
import { X402Error } from 'anyspend-x402-client';
try {
const response = await x402Client.request('https://api.example.com/data');
} catch (error) {
if (error instanceof X402Error) {
switch (error.code) {
case 'INSUFFICIENT_BALANCE':
console.error('Not enough tokens in wallet');
break;
case 'SIGNATURE_REJECTED':
console.error('User rejected the signature request');
break;
case 'PAYMENT_EXPIRED':
console.error('Payment deadline expired, try again');
break;
case 'SETTLEMENT_FAILED':
console.error('Payment verification failed:', error.message);
break;
default:
console.error('Payment error:', error.message);
}
}
}
```
## Testing
Test your integration against a test resource server:
```typescript theme={null}
const testClient = new X402Client({
walletClient,
network: 'base-sepolia', // Use testnet
preferredToken: '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // USDC on Sepolia
});
const response = await testClient.request(
'https://test-api.anyspend.com/echo'
);
```
Get testnet USDC from [Coinbase Faucet](https://portal.cdp.coinbase.com/products/faucet).
## Best Practices
Never hardcode private keys in your application:
```typescript theme={null}
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
```
Before initiating payment, show users:
* The exact amount they'll pay
* The token being used
* The resource server domain
* An option to cancel
Users can reject wallet signature requests. Always handle this gracefully:
```typescript theme={null}
try {
await x402Client.request('...');
} catch (error) {
if (error.code === 'SIGNATURE_REJECTED') {
// User cancelled - don't show error UI
return;
}
}
```
Create one X402Client instance and reuse it:
```typescript theme={null}
// Good: Create once
const client = new X402Client({ walletClient });
// Bad: Creating new instance for each request
await new X402Client({ walletClient }).request('...');
```
## What's Next?
Learn how AnySpend x402 works
See supported chains and token addresses
## Troubleshooting
The signature verification failed. Check that:
* Your wallet is connected to the correct network
* The token address matches the network
* Your wallet has enough tokens for the payment
You don't have enough of the payment token. Either:
* Add more tokens to your wallet
* Try paying with a different token
Make sure your wallet is on the same network as the payment token:
```typescript theme={null}
// Base network
const walletClient = createWalletClient({
chain: base, // Must match the payment network
transport: custom(window.ethereum)
});
```
## Getting Help
* **Discord**: Join our [Discord community](https://discord.gg/b3dotfun)
* **GitHub**: [github.com/b3-fun/anyspend-x402](https://github.com/b3-fun/anyspend-x402)
* **Examples**: See full examples in the [GitHub repository](https://github.com/b3-fun/anyspend-x402/tree/main/examples)
# Quickstart for Sellers
Source: https://docs.b3.fun/anyspend/x402-quickstart-sellers
Accept payments in any token for your APIs and services using AnySpend x402 middleware
View source code and examples
@b3dotfun/anyspend-x402
## Overview
This guide shows you how to add **AnySpend x402** payment support to your Express API, enabling you to accept payments in any token while receiving the token of your choice. With just a few lines of code, your API can monetize endpoints and handle automatic payment verification and settlement.
**Key Benefits:**
* **Buyers** can pay with any token they hold (ETH, DAI, USDC, etc.)
* **Sellers** can receive any token they prefer (USDC, B3, DAI, custom tokens, etc.)
* AnySpend automatically handles all token conversions
* No blockchain infrastructure or wallet management required
## Prerequisites
Before you begin, make sure you have:
* **Node.js 18+** installed
* **An Express.js API** (or willingness to create one)
* **A wallet address** to receive USDC payments
* **Basic knowledge** of Express middleware
## Installation
Install the AnySpend x402 package:
```bash npm theme={null}
npm install @b3dotfun/anyspend-x402
```
```bash yarn theme={null}
yarn add @b3dotfun/anyspend-x402
```
```bash pnpm theme={null}
pnpm add @b3dotfun/anyspend-x402
```
## Quick Start
### 1. Basic Integration
The simplest way to add payments to your Express API:
```typescript theme={null}
import express from 'express';
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
const app = express();
// Define your payment routes and prices
const endpointConfig = {
'/api/premium-data': {
amount: '1.00', // $1.00 in USDC
asset: 'USD' // Will be converted to USDC
},
'/api/ai-inference': {
amount: '0.50', // $0.50 in USDC
asset: 'USD'
}
};
// Your USDC receiving address
const recipientAddress = '0xYourWalletAddress...';
// Apply payment middleware
app.use(paymentMiddleware(
recipientAddress,
endpointConfig,
facilitator // Pre-configured Anyspend facilitator
));
// Define your protected routes
app.get('/api/premium-data', (req, res) => {
// This only runs after successful payment
res.json({
data: 'Your premium data here',
message: 'Payment successful!'
});
});
app.get('/api/ai-inference', (req, res) => {
res.json({
result: 'AI inference result',
model: 'gpt-4'
});
});
app.listen(3000, () => {
console.log('API with x402 payments running on port 3000');
});
```
**What this does:**
1. Clients request your API endpoint
2. Middleware returns `402 Payment Required` with payment details
3. Client pays with their preferred token (ETH, DAI, etc.)
4. AnySpend facilitator converts to USDC and settles to your wallet
5. Your route handler executes and returns data
***
### 2. Receive Custom Tokens (e.g., B3)
You can configure your API to receive any token, not just USDC:
```typescript theme={null}
import express from 'express';
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
import { Address } from 'viem';
const app = express();
const PAYTO_ADDRESS = '0xYourWalletAddress...' as Address;
const NETWORK = 'base' as const;
// Configure to receive B3 tokens
const endpointConfig = {
'POST /api/premium': {
price: {
amount: '100000000000000000000', // 100 B3 tokens (18 decimals)
asset: {
address: '0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3' as Address,
decimals: 18,
eip712: {
name: 'B3',
version: '1',
},
},
},
network: NETWORK,
config: {
description: 'Premium data access',
mimeType: 'application/json',
},
}
};
app.use(paymentMiddleware(PAYTO_ADDRESS, endpointConfig, facilitator));
app.post('/api/premium', (req, res) => {
// Payment verified - you received 100 B3 tokens!
res.json({
data: 'Premium ETH price history',
paymentReceived: '100 B3 tokens'
});
});
app.listen(3000);
```
**What's different:**
* Buyers can still pay with **any token** (ETH, USDC, DAI, etc.)
* AnySpend converts their payment to **B3 tokens**
* You receive exactly **100 B3 tokens** in your wallet
* Complete flexibility for both buyers and sellers!
## Configuration
### Facilitator URL
The AnySpend facilitator is hosted at:
```
https://mainnet.anyspend.com/x402
```
The `@b3dotfun/anyspend-x402` package includes a pre-configured facilitator instance:
```typescript theme={null}
import { facilitator } from '@b3dotfun/anyspend-x402';
// Pre-configured to use mainnet.anyspend.com/x402
app.use(paymentMiddleware(recipientAddress, endpointConfig, facilitator));
```
### Endpoint Configuration
You have three methods to configure payment requirements:
#### Method 1: Simple Dollar Amounts (Recommended)
Let AnySpend handle token conversion automatically:
```typescript theme={null}
const endpointConfig = {
'/api/data': {
amount: '1.00', // $1.00 worth of any token
asset: 'USD'
},
'/api/compute': {
amount: '2.50',
asset: 'USD'
}
};
```
**Benefits:**
* Clients can pay with any supported token
* AnySpend converts to USDC automatically
* You always receive USDC
#### Method 2: Specific Token Requirements
Require specific tokens on specific networks. You can receive **any token**, not just USDC!
**Example 1: Receive USDC (Stablecoin)**
```typescript theme={null}
const endpointConfig = {
'/api/data': {
amount: '1000000', // 1 USDC (6 decimals)
asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
network: 'base-mainnet'
}
};
```
**Example 2: Receive B3 Tokens (Custom Token)**
```typescript theme={null}
import { Address } from 'viem';
const PAYTO_ADDRESS = '0xYourWalletAddress...' as Address;
const NETWORK = 'base' as const;
const endpointConfig = {
'POST /api/premium': {
price: {
amount: '100000000000000000000', // 100 B3 tokens (100 * 10^18)
asset: {
address: '0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3' as Address,
decimals: 18,
eip712: {
name: 'B3',
version: '1',
},
},
},
network: NETWORK,
config: {
description: 'Access to premium ETH price history data from CoinGecko',
mimeType: 'application/json',
},
}
};
app.use(paymentMiddleware(PAYTO_ADDRESS, endpointConfig, facilitator));
```
**Example 3: Receive DAI (Stablecoin)**
```typescript theme={null}
const endpointConfig = {
'/api/ai-inference': {
amount: '1000000000000000000', // 1 DAI (18 decimals)
asset: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb', // DAI on Base
network: 'base-mainnet'
}
};
```
**Example 4: Receive Native ETH**
```typescript theme={null}
const endpointConfig = {
'/api/compute': {
amount: '500000000000000', // 0.0005 ETH (18 decimals)
asset: '0x0000000000000000000000000000000000000000', // Native ETH
network: 'base-mainnet'
}
};
```
**Example 5: Receive Custom ERC-20 Token**
For any ERC-20 token with permit support:
```typescript theme={null}
const endpointConfig = {
'/api/data': {
price: {
amount: '1000000000000000000', // 1 token (adjust decimals)
asset: {
address: '0xYourTokenAddress...' as Address,
decimals: 18, // Your token's decimals
eip712: {
name: 'YourTokenName', // From token contract
version: '1', // EIP-712 version
},
},
},
network: 'base-mainnet',
config: {
description: 'Your API endpoint description',
mimeType: 'application/json',
},
}
};
```
**Key Points:**
* Buyers can still pay with **any token** they hold
* AnySpend automatically converts their token to the one you want to receive
* You receive exactly the token you specified in your configuration
* Both buyer and seller flexibility are maintained
### Finding Token Details
To configure a custom token, you need to know its EIP-712 parameters. Here's how to find them:
**Method 1: Check Token Contract**
Use a blockchain explorer like [Basescan](https://basescan.org):
```typescript theme={null}
// Read from the token contract
const name = await token.read.name(); // e.g., "B3"
const version = await token.read.version(); // e.g., "1"
const decimals = await token.read.decimals(); // e.g., 18
```
**Method 2: Common Tokens**
| Token | Name | Version | Decimals | Base Address |
| ----- | -------------- | ------- | -------- | -------------------------------------------- |
| USDC | USD Coin | 2 | 6 | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
| DAI | Dai Stablecoin | 1 | 18 | `0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb` |
| B3 | B3 | 1 | 18 | `0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3` |
**Method 3: Use Viem**
```typescript theme={null}
import { createPublicClient, http } from 'viem';
import { base } from 'viem/chains';
const client = createPublicClient({
chain: base,
transport: http()
});
const [name, version, decimals] = await Promise.all([
client.readContract({
address: tokenAddress,
abi: [{
name: 'name',
type: 'function',
stateMutability: 'view',
inputs: [],
outputs: [{ type: 'string' }]
}],
functionName: 'name'
}),
client.readContract({
address: tokenAddress,
abi: [{
name: 'version',
type: 'function',
stateMutability: 'view',
inputs: [],
outputs: [{ type: 'string' }]
}],
functionName: 'version'
}),
client.readContract({
address: tokenAddress,
abi: [{
name: 'decimals',
type: 'function',
stateMutability: 'view',
inputs: [],
outputs: [{ type: 'uint8' }]
}],
functionName: 'decimals'
})
]);
```
#### Method 3: Flexible (Let Client Choose)
Allow clients to specify their preferred payment token:
```typescript theme={null}
const endpointConfig = {
'/api/data': {
amount: '1.00',
asset: 'USD',
flexible: true // Accept X-PREFERRED-TOKEN header
}
};
```
Clients can then specify their token preference:
```bash theme={null}
curl https://api.example.com/data \
-H "X-PREFERRED-TOKEN: 0x4200000000000000000000000000000000000006" \
-H "X-PREFERRED-NETWORK: base-mainnet"
```
## Advanced Configuration
### Dynamic Pricing
Calculate prices based on request parameters:
```typescript theme={null}
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
app.use('/api/compute', (req, res, next) => {
// Calculate price based on compute units requested
const units = parseInt(req.query.units as string) || 1;
const pricePerUnit = 0.10; // $0.10 per unit
const totalPrice = (units * pricePerUnit).toFixed(2);
// Attach dynamic config to request
req.x402Config = {
amount: totalPrice,
asset: 'USD'
};
next();
}, paymentMiddleware(recipientAddress, {
'/api/compute': (req) => req.x402Config // Dynamic config
}, facilitator));
app.get('/api/compute', (req, res) => {
const units = parseInt(req.query.units as string) || 1;
res.json({
result: `Computed ${units} units`,
cost: req.x402Config.amount
});
});
```
### Custom Facilitator Configuration
If you need custom facilitator settings:
```typescript theme={null}
import { Facilitator } from '@b3dotfun/anyspend-x402';
const customFacilitator = new Facilitator({
baseUrl: 'https://mainnet.anyspend.com/x402',
apiKey: process.env.CDP_API_KEY_ID, // Optional: Coinbase CDP
apiSecret: process.env.CDP_API_KEY_SECRET,
timeout: 30000, // 30s timeout
retries: 3 // Retry failed requests
});
app.use(paymentMiddleware(
recipientAddress,
endpointConfig,
customFacilitator
));
```
### Multiple Recipients
Route payments to different wallets based on endpoint:
```typescript theme={null}
const endpointConfig = {
'/api/service-a': {
amount: '1.00',
asset: 'USD',
recipient: '0xWalletA...'
},
'/api/service-b': {
amount: '2.00',
asset: 'USD',
recipient: '0xWalletB...'
}
};
// Pass null as recipient, use per-endpoint recipients
app.use(paymentMiddleware(null, endpointConfig, facilitator));
```
## Protected Routes
### Protect Specific Routes
Only protect endpoints that require payment:
```typescript theme={null}
// Public route - no payment required
app.get('/api/public', (req, res) => {
res.json({ message: 'This is free!' });
});
// Protected route - payment required
app.use('/api/premium', paymentMiddleware(
recipientAddress,
{
'/api/premium': { amount: '1.00', asset: 'USD' }
},
facilitator
));
app.get('/api/premium', (req, res) => {
res.json({ message: 'This cost money!' });
});
```
### Route-Specific Middleware
Apply different payment configs to different route groups:
```typescript theme={null}
// Basic tier - $0.50
app.use('/api/basic', paymentMiddleware(
recipientAddress,
{
'/api/basic/*': { amount: '0.50', asset: 'USD' }
},
facilitator
));
// Premium tier - $2.00
app.use('/api/premium', paymentMiddleware(
recipientAddress,
{
'/api/premium/*': { amount: '2.00', asset: 'USD' }
},
facilitator
));
```
## Testing
### Local Development
Test your API locally with testnet USDC:
```typescript theme={null}
import { Facilitator } from '@b3dotfun/anyspend-x402';
const testFacilitator = new Facilitator({
baseUrl: 'https://testnet.anyspend.com/x402', // Testnet facilitator
});
const endpointConfig = {
'/api/test': {
amount: '0.01',
asset: 'USD',
network: 'base-sepolia' // Use testnet
}
};
app.use(paymentMiddleware(
'0xYourTestWallet...',
endpointConfig,
testFacilitator
));
```
Get testnet USDC from the [Coinbase Faucet](https://portal.cdp.coinbase.com/products/faucet).
### Test Client Request
Test with curl:
```bash theme={null}
# 1. Get payment requirements
curl https://your-api.com/api/premium-data
# Response: 402 Payment Required
# {
# "x402": "0.2",
# "requirements": [{
# "scheme": "exact",
# "network": "base-mainnet",
# "amount": "1000000",
# "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
# "recipient": "0xYourWallet..."
# }]
# }
# 2. Make payment with X-PAYMENT header (requires signed payload)
curl https://your-api.com/api/premium-data \
-H "X-PAYMENT: eyJ4NDAyIjoi..." \
-H "Content-Type: application/json"
```
Or use the x402 client SDK (see [Quickstart for Buyers](/anyspend/x402-quickstart-buyers)).
## Monitoring Payments
### Access Payment Metadata
The middleware attaches payment information to the request:
```typescript theme={null}
app.get('/api/premium', (req, res) => {
// Access payment details
const payment = req.x402Payment;
console.log('Payment received:', {
txHash: payment.txHash,
network: payment.network,
amount: payment.amount,
token: payment.token,
from: payment.from
});
res.json({
data: 'Your premium data',
paymentTx: payment.txHash
});
});
```
### Webhook Notifications
Get notified when payments are settled:
```typescript theme={null}
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
app.use(paymentMiddleware(
recipientAddress,
endpointConfig,
facilitator,
{
onPaymentSettled: async (payment) => {
console.log('Payment settled:', payment);
// Log to database
await db.payments.create({
txHash: payment.txHash,
amount: payment.amount,
from: payment.from,
timestamp: new Date()
});
// Send notification
await sendEmail({
to: 'admin@example.com',
subject: 'Payment Received',
body: `Received ${payment.amount} USDC from ${payment.from}`
});
}
}
));
```
## Examples
### AI Agent API
```typescript theme={null}
import express from 'express';
import { paymentMiddleware, facilitator } from '@b3dotfun/anyspend-x402';
const app = express();
app.use(express.json());
const endpointConfig = {
'/api/chat': {
amount: '0.10', // $0.10 per request
asset: 'USD'
},
'/api/image': {
amount: '0.50', // $0.50 per image
asset: 'USD'
}
};
app.use(paymentMiddleware(
process.env.USDC_WALLET_ADDRESS,
endpointConfig,
facilitator
));
app.post('/api/chat', async (req, res) => {
const { message } = req.body;
// Call your AI service
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: message }]
});
res.json({
response: response.choices[0].message.content,
payment: req.x402Payment.txHash
});
});
app.post('/api/image', async (req, res) => {
const { prompt } = req.body;
const image = await openai.images.generate({
model: 'dall-e-3',
prompt
});
res.json({
imageUrl: image.data[0].url,
payment: req.x402Payment.txHash
});
});
app.listen(3000);
```
### Data API with Rate Limiting
```typescript theme={null}
const endpointConfig = {
'/api/data/basic': {
amount: '0.01', // $0.01 per request
asset: 'USD'
},
'/api/data/premium': {
amount: '0.10', // $0.10 per request
asset: 'USD'
}
};
// Track usage per payer
const usage = new Map();
app.use(paymentMiddleware(
recipientAddress,
endpointConfig,
facilitator,
{
onPaymentSettled: (payment) => {
const count = usage.get(payment.from) || 0;
usage.set(payment.from, count + 1);
}
}
));
app.get('/api/data/premium', (req, res) => {
const payer = req.x402Payment.from;
const requests = usage.get(payer) || 0;
res.json({
data: getPremiumData(),
requestCount: requests,
discount: requests > 100 ? '10%' : 'none'
});
});
```
## Best Practices
Store sensitive data in environment variables:
```typescript theme={null}
const recipientAddress = process.env.USDC_WALLET_ADDRESS;
const apiKey = process.env.CDP_API_KEY_ID;
```
Log all payment events for debugging and analytics:
```typescript theme={null}
{
onPaymentSettled: (payment) => {
logger.info('Payment received', {
txHash: payment.txHash,
amount: payment.amount,
from: payment.from,
endpoint: payment.endpoint
});
}
}
```
Provide clear error messages when payments fail:
```typescript theme={null}
app.use((err, req, res, next) => {
if (err.code === 'X402_PAYMENT_FAILED') {
res.status(402).json({
error: 'Payment verification failed',
message: 'Please try again with a valid payment'
});
}
next(err);
});
```
Always test with testnet before deploying to production:
```typescript theme={null}
const facilitatorUrl = process.env.NODE_ENV === 'production'
? 'https://mainnet.anyspend.com/x402'
: 'https://testnet.anyspend.com/x402';
```
## What's Next?
Understand how AnySpend x402 works
See supported chains, tokens, and addresses
## Troubleshooting
Check that:
* Your facilitator URL is correct: `https://mainnet.anyspend.com/x402`
* Your recipient address is valid
* The network configuration matches the client's network
Make sure your endpoint config allows flexible payments:
```typescript theme={null}
{
'/api/endpoint': {
amount: '1.00',
asset: 'USD',
flexible: true // Allow any token
}
}
```
Verify:
* Your recipient address is correct
* You're checking the correct network
* Payment was settled (check `req.x402Payment.txHash`)
## Getting Help
* **Discord**: Join our [Discord community](https://discord.gg/b3dotfun)
* **GitHub**: [github.com/b3-fun/anyspend-x402](https://github.com/b3-fun/anyspend-x402)
* **Documentation**: [x402.org/docs](https://x402.org/docs)
* **Examples**: See full examples in the [repository](https://github.com/b3-fun/anyspend-x402/tree/main/examples)
# Quickstart for Solana
Source: https://docs.b3.fun/anyspend/x402-quickstart-solana
Accept and make payments on Solana using AnySpend X402 with USDC and SPL tokens
**Try it live!** Experience X402 on Solana at [x402-demo.anyspend.com](https://x402-demo.anyspend.com/) or explore the [source code on GitHub](https://github.com/b3-fun/anyspend-x402-demo).
View source code and examples
@b3dotfun/anyspend-x402
Full working Solana demo app
## Overview
This guide shows you how to use **AnySpend X402** on **Solana** for both server (accepting payments) and client (making payments) applications. AnySpend X402 on Solana enables gasless SPL token payments using transaction signatures, making it perfect for paywalled APIs, AI agents, and premium services.
**Key Features:**
* **Gasless transactions** - Facilitator sponsors all transaction fees
* **SPL token support** - Pay with USDC and other SPL tokens on Solana
* **Browser wallet integration** - Works with Phantom, Solflare, Ledger, and more
* **AI agent friendly** - Simple fetch wrapper for autonomous payments
## Prerequisites
* **Node.js 18+** installed
* **Solana wallet** with some USDC (for testing)
* **Basic knowledge** of Solana or Express.js (depending on your use case)
## Server Setup
Accept Solana USDC payments with just a few lines of code.
### Installation
```bash npm theme={null}
npm install @b3dotfun/anyspend-x402
```
```bash yarn theme={null}
yarn add @b3dotfun/anyspend-x402
```
```bash pnpm theme={null}
pnpm add @b3dotfun/anyspend-x402
```
### Basic Server Example
```typescript theme={null}
import express from 'express';
import { paymentMiddleware } from '@b3dotfun/anyspend-x402';
const app = express();
const FACILITATOR_URL = 'https://mainnet.anyspend.com/x402';
// Your Solana wallet address
const SOLANA_PAYTO_ADDRESS = 'YourSolanaWalletAddress...';
// Configure payment endpoints
app.use(
paymentMiddleware(
SOLANA_PAYTO_ADDRESS,
{
"POST /api/solana/premium": {
price: {
amount: '10000', // 0.01 USDC (6 decimals)
asset: {
address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC on Solana
decimals: 6,
},
},
network: 'solana',
config: {
description: 'Access to premium data via USDC payment',
mimeType: 'application/json',
},
},
},
{
url: FACILITATOR_URL,
},
),
);
// Your protected route
app.post('/api/solana/premium', (req, res) => {
res.json({
message: 'Payment successful!',
data: 'Your premium Solana data here',
});
});
app.listen(3001, () => {
console.log('Solana X402 server running on port 3001');
});
```
**What this does:**
1. Client requests the endpoint
2. Middleware returns `402 Payment Required` with Solana payment details
3. Client signs a Solana transaction with USDC transfer
4. Facilitator verifies and submits the transaction (gasless)
5. Your route handler executes after payment confirmation
***
## Client Setup
There are two ways to make payments on Solana depending on your use case.
### Option 1: Using Fetch (AI Agents & Backend)
Perfect for Node.js scripts, AI agents, and server-side applications.
#### Installation
```bash npm theme={null}
npm install @b3dotfun/anyspend-x402-fetch
```
```bash yarn theme={null}
yarn add @b3dotfun/anyspend-x402-fetch
```
```bash pnpm theme={null}
pnpm add @b3dotfun/anyspend-x402-fetch
```
#### Example Script
```typescript theme={null}
import {
createSigner,
wrapFetchWithPayment,
} from "@b3dotfun/anyspend-x402-fetch";
const privateKey = process.env.SOLANA_PRIVATE_KEY; // Base58 private key
const url = "https://api.example.com/api/solana/premium";
async function main() {
// Create Solana signer from private key
const signer = await createSigner("solana", privateKey);
// Wrap fetch with payment support
const fetchWithPayment = wrapFetchWithPayment(fetch, signer);
// Make the payment request
const response = await fetchWithPayment(url, { method: "POST" });
const data = await response.json();
// Check payment response
const paymentHeader = response.headers.get("x-payment-response");
if (paymentHeader) {
const payment = JSON.parse(atob(paymentHeader));
// Transaction available at: https://solscan.io/tx/${payment.transaction}
}
}
main();
```
**Key Points:**
* Use base58-encoded private key (from Solana keypair)
* Automatically handles 402 responses and payment flow
* Returns transaction hash in `x-payment-response` header
***
### Option 2: Using Browser Wallets (React/Next.js)
For web applications using Phantom, Solflare, Ledger, or other Solana wallets.
#### Installation
```bash npm theme={null}
npm install @b3dotfun/anyspend-x402-solana-wallet-adapter @b3dotfun/anyspend-x402-fetch
```
```bash yarn theme={null}
yarn add @b3dotfun/anyspend-x402-solana-wallet-adapter @b3dotfun/anyspend-x402-fetch
```
```bash pnpm theme={null}
pnpm add @b3dotfun/anyspend-x402-solana-wallet-adapter @b3dotfun/anyspend-x402-fetch
```
#### React Component Example
```tsx theme={null}
import {
createWalletAdapterSigner,
useWallet,
WalletMultiButton,
} from "@b3dotfun/anyspend-x402-solana-wallet-adapter";
import { wrapFetchWithPayment } from "@b3dotfun/anyspend-x402-fetch";
function PremiumDataFetcher() {
const { publicKey, signAllTransactions, connected } = useWallet();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const fetchPremiumData = async () => {
if (!connected || !publicKey) return;
setLoading(true);
try {
// Create signer from wallet adapter
const signer = createWalletAdapterSigner(
publicKey.toBase58(),
signAllTransactions
);
// Wrap fetch with payment support
const fetchWithPayment = wrapFetchWithPayment(fetch, signer);
// Make paid request
const response = await fetchWithPayment(
"https://api.example.com/api/solana/premium",
{ method: "POST" }
);
const result = await response.json();
setData(result);
// Get transaction hash
const paymentHeader = response.headers.get("x-payment-response");
if (paymentHeader) {
const payment = JSON.parse(atob(paymentHeader));
// Transaction available at: https://solscan.io/tx/${payment.transaction}
}
} catch (error) {
// Handle payment error
} finally {
setLoading(false);
}
};
return (
{data &&
{JSON.stringify(data, null, 2)}
}
);
}
```
#### App Wrapper Setup
Wrap your app with wallet providers:
```tsx theme={null}
import { WalletProvider } from "@b3dotfun/anyspend-x402-solana-wallet-adapter";
import { clusterApiUrl } from "@solana/web3.js";
function App() {
const endpoint = clusterApiUrl("mainnet-beta");
return (
);
}
```
**Key Points:**
* Works with Phantom, Solflare, Ledger, Trust Wallet, and more
* Prompts user to approve transaction signature
* Fully gasless - users only sign, facilitator pays fees
* Bridges Solana Wallet Adapter v1 with X402 v2 signatures
***
## Configuration
### Supported Networks
* **`solana`** - Solana mainnet-beta
* **`solana-devnet`** - Solana devnet (for testing)
### Token Configuration
The most common SPL token on Solana is USDC:
```typescript theme={null}
{
address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC mint
decimals: 6,
}
```
For other SPL tokens, specify the mint address and decimals.
### Facilitator URL
Production: `https://mainnet.anyspend.com/x402`
The facilitator handles:
* Transaction verification
* On-chain submission
* Gas fee sponsorship
* Payment settlement
***
## Testing
### Get Test USDC
For Solana devnet testing:
1. Get devnet SOL from [Solana Faucet](https://faucet.solana.com/)
2. Use devnet USDC mint: `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`
3. Set network to `solana-devnet` in your config
### Test Your Integration
```typescript theme={null}
// Server - use devnet
network: 'solana-devnet'
// Client - use devnet RPC
const endpoint = 'https://api.devnet.solana.com';
```
***
## Common Token Addresses
| Token | Mint Address | Decimals | Network |
| ----- | ---------------------------------------------- | -------- | ------------ |
| USDC | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | 6 | mainnet-beta |
| USDC | `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU` | 6 | devnet |
***
## Error Handling
```typescript theme={null}
try {
const response = await fetchWithPayment(url, { method: "POST" });
const data = await response.json();
} catch (error) {
if (error.message.includes("Insufficient funds")) {
// Not enough USDC in wallet
} else if (error.message.includes("User rejected")) {
// User cancelled transaction
} else {
// Handle payment error
}
}
```
***
## What's Next?
Learn how AnySpend X402 works
See all supported chains and tokens
Deep dive into Solana transaction signatures
EVM client setup guide
***
## Troubleshooting
Check that:
* Your wallet has enough USDC for the payment
* You're on the correct network (mainnet vs devnet)
* The facilitator URL is correct
Make sure:
* You've wrapped your app with `WalletProvider`
* The wallet extension is installed (Phantom, Solflare, etc.)
* You're using the correct RPC endpoint
Verify:
* The server endpoint is configured correctly
* The payment amount matches server expectations
* Check server logs for errors
***
## Getting Help
* **Live Demo**: Try it yourself at [x402-demo.anyspend.com](https://x402-demo.anyspend.com/)
* **Demo Source Code**: [github.com/b3-fun/anyspend-x402-demo](https://github.com/b3-fun/anyspend-x402-demo)
* **Discord**: Join our [Discord community](https://discord.gg/b3dotfun)
* **GitHub**: [github.com/b3-fun/anyspend-x402](https://github.com/b3-fun/anyspend-x402)
* **Examples**: See full examples in the [repository](https://github.com/b3-fun/anyspend-x402/tree/main/examples/typescript)
# Permit vs TransferWithAuthorization
Source: https://docs.b3.fun/anyspend/x402-signature-methods
Understanding gasless payment signatures - EIP-2612 Permit and EIP-3009 TransferWithAuthorization
## Overview
AnySpend x402 uses cryptographic signatures instead of traditional token approvals, enabling **gasless payments** for users. The facilitator pays all gas fees while users simply sign authorization messages.
There are two main signature standards supported, each optimized for different token types:
* **EIP-3009 (transferWithAuthorization)** - Used by USDC, one-step direct transfers
* **EIP-2612 (permit)** - Used by most modern ERC-20 tokens, two-step approval + transfer
## Quick Comparison
| Feature | EIP-2612 (Permit) | EIP-3009 (transferWithAuthorization) |
| --------------------- | -------------------------------------- | ------------------------------------ |
| **Used by** | Most modern ERC-20s | USDC (all networks) |
| **Execution** | Two-step: approve + transfer | One-step: direct transfer |
| **Nonce Type** | Sequential (auto-increments) | Random bytes32 |
| **Dependency** | Must wait for previous nonce | No ordering required |
| **Ideal for** | General ERC-20 tokens | Stablecoin payments |
| **Replay Protection** | Sequential nonce | Random nonce tracking |
| **Gas Efficiency** | 2 transactions (permit + transferFrom) | 1 transaction (direct transfer) |
## EIP-3009: transferWithAuthorization (USDC)
### Overview
Direct transfer authorization - the signature authorizes an immediate transfer from sender to recipient without a separate approval step.
**Used by:** USDC on all networks (Base, Ethereum, Arbitrum, Optimism, Polygon, etc.)
### Key Advantages
* ✅ **One-step execution** - Direct transfer, no approval needed
* ✅ **Random nonce** - No sequential dependency, parallel transactions possible
* ✅ **Immediate settlement** - Executes in single transaction
* ✅ **Gasless for payer** - Facilitator pays gas
* ✅ **No front-running** - Random nonce prevents MEV attacks
### Message Structure
```solidity theme={null}
transferWithAuthorization(
address from, // Payer address
address to, // Recipient address
uint256 value, // Amount to transfer
uint256 validAfter, // 0 (valid immediately)
uint256 validBefore, // Deadline timestamp
bytes32 nonce, // Random nonce (prevents replay)
bytes signature // EIP-712 signature
)
```
### Usage Example
```typescript theme={null}
import { signTransferWithAuthorization } from 'anyspend-x402-client';
const signature = await signTransferWithAuthorization({
from: payerAddress,
to: recipientAddress,
value: '1000000', // 1 USDC (6 decimals)
validBefore: deadline,
nonce: randomBytes32() // Generate random nonce
});
```
### How It Works
User signs an EIP-712 message authorizing the transfer with a random nonce
Facilitator calls `receiveWithAuthorization()` with the signature
USDC is transferred directly from user to facilitator in one atomic transaction
The random nonce is marked as used, preventing replay attacks
### EIP-712 Typed Data Structure
```typescript theme={null}
const typedData = {
domain: {
name: 'USD Coin',
version: '2',
chainId: 8453, // Base
verifyingContract: usdcAddress
},
types: {
TransferWithAuthorization: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'validAfter', type: 'uint256' },
{ name: 'validBefore', type: 'uint256' },
{ name: 'nonce', type: 'bytes32' }
]
},
message: {
from: payerAddress,
to: recipientAddress,
value: '1000000',
validAfter: 0,
validBefore: deadline,
nonce: randomNonce
}
};
```
***
## EIP-2612: Permit (Standard ERC-20)
### Overview
Signature-based approval that sets an allowance, followed by a separate `transferFrom()` call. This is the standard method for most modern ERC-20 tokens.
**Used by:** Most modern ERC-20 tokens with permit support
### Key Advantages
* ✅ **Widely adopted** - Standard across many tokens
* ✅ **Time-limited approvals** - Deadline-based expiration
* ✅ **ERC-20 compatible** - Works with existing infrastructure
* ✅ **Gasless for payer** - Facilitator pays gas
* ✅ **Ecosystem support** - Supported by major wallets and dapps
### Message Structure
```solidity theme={null}
permit(
address owner, // Token owner
address spender, // Approved spender (facilitator)
uint256 value, // Approval amount
uint256 deadline, // Expiration timestamp
uint8 v, bytes32 r, bytes32 s // Signature components
)
```
### Usage Example
```typescript theme={null}
import { signPermit } from 'anyspend-x402-client';
const nonce = await token.nonces(ownerAddress); // Get current nonce
const signature = await signPermit({
token: tokenAddress,
owner: ownerAddress,
spender: facilitatorAddress,
value: '1000000', // 1 USDC (6 decimals)
deadline: deadline,
nonce: nonce // Sequential nonce
});
```
### How It Works
User signs an EIP-712 permit message with current sequential nonce
Facilitator calls `permit()` to set the allowance on-chain
The token contract automatically increments the user's nonce
Facilitator calls `transferFrom()` to transfer tokens using the approval
### EIP-712 Typed Data Structure
```typescript theme={null}
const typedData = {
domain: {
name: 'Dai Stablecoin',
version: '1',
chainId: 8453, // Base
verifyingContract: daiAddress
},
types: {
Permit: [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }
]
},
message: {
owner: ownerAddress,
spender: facilitatorAddress,
value: '1000000000000000000',
nonce: currentNonce,
deadline: deadline
}
};
```
***
## Which Method Does My Token Use?
### Checking Token Support
```typescript theme={null}
// Check if token supports EIP-3009 (USDC-style)
const hasTransferWithAuth = await token.read.transferWithAuthorization !== undefined;
// Check if token supports EIP-2612 (Standard permit)
const hasPermit = await token.read.permit !== undefined;
const hasDomainSeparator = await token.read.DOMAIN_SEPARATOR !== undefined;
```
### Common Tokens by Method
**EIP-3009 (transferWithAuthorization):**
* USDC (all chains)
* USDC.e (bridged versions)
**EIP-2612 (permit):**
* Most modern ERC-20s
* USDT (on some chains - Base, Arbitrum, Optimism)
* Many DeFi tokens
* Check compatibility: [anyspend.com/x402-tokens](https://anyspend.com/x402-tokens)
**No Gasless Support:**
* USDT on Ethereum mainnet (no permit)
* USDT on Polygon (no permit)
* Legacy ERC-20 tokens
The AnySpend x402 client automatically detects which signature method to use based on the token contract. You don't need to specify this manually.
## Nonce Management
### Random Nonce (EIP-3009)
**Advantages:**
* No ordering dependency - multiple signatures can be used in any order
* Parallel transactions possible
* No blocked state if one transaction fails
**Implementation:**
```typescript theme={null}
import { randomBytes } from 'crypto';
// Generate cryptographically secure random nonce
const nonce = '0x' + randomBytes(32).toString('hex');
```
**Nonce Tracking:**
```solidity theme={null}
// Check if nonce has been used
mapping(address => mapping(bytes32 => bool)) public authorizationState;
function isAuthorizationUsed(address authorizer, bytes32 nonce)
external
view
returns (bool)
{
return authorizationState[authorizer][nonce];
}
```
### Sequential Nonce (EIP-2612)
**Advantages:**
* Simple and predictable
* Gas efficient (single storage slot)
* Standard across all permit implementations
**Implementation:**
```typescript theme={null}
// Get current nonce from token contract
const currentNonce = await token.read.nonces([ownerAddress]);
// Sign with current nonce
const signature = await signPermit({
// ...
nonce: currentNonce
});
```
**Nonce Auto-Increment:**
```solidity theme={null}
// Token contract automatically increments
mapping(address => uint256) public nonces;
function permit(/* ... */) external {
require(nonce == nonces[owner], "Invalid nonce");
nonces[owner]++; // Auto-increment
// ... rest of permit logic
}
```
## Security Considerations
### Replay Protection
**EIP-3009:**
* Random nonce prevents replay across chains and contracts
* Each nonce can only be used once per address
* Nonce state stored on-chain in mapping
**EIP-2612:**
* Sequential nonce prevents replay
* Must use current nonce (auto-increments)
* Failed transactions block subsequent signatures until re-signed
### Deadline Enforcement
Both methods enforce deadlines to prevent stale signatures:
```typescript theme={null}
const deadline = Math.floor(Date.now() / 1000) + 300; // 5 minutes from now
```
**Best Practices:**
* Use short deadlines (5-10 minutes) for security
* Longer deadlines (30-60 minutes) for better UX if needed
* Never use `type(uint256).max` for infinite approvals
### Signature Validation
Both methods validate signatures using EIP-712:
```typescript theme={null}
// Recover signer from signature
const recoveredAddress = recoverTypedDataAddress({
domain,
types,
primaryType,
message,
signature
});
// Verify signer matches expected address
if (recoveredAddress !== expectedSigner) {
throw new Error('Invalid signature');
}
```
## Client SDK Integration
The AnySpend x402 client handles all signature complexity automatically:
```typescript theme={null}
import { X402Client } from 'anyspend-x402-client';
const client = new X402Client({
walletClient,
preferredToken: tokenAddress // USDC or any compatible token
});
// Client automatically:
// 1. Detects if token uses permit or transferWithAuthorization
// 2. Gets current nonce (for permit) or generates random nonce
// 3. Constructs correct EIP-712 typed data
// 4. Prompts user to sign
// 5. Includes signature in X-PAYMENT header
const response = await client.request('https://api.example.com/data');
```
## Gas Cost Comparison
| Method | User Gas | Facilitator Gas | Total Transactions |
| -------- | -------- | --------------------------------------- | ------------------ |
| EIP-3009 | 0 | \~45,000 | 1 |
| EIP-2612 | 0 | \~70,000 (permit) + \~45,000 (transfer) | 2 |
All gas costs are paid by the facilitator and included in the 0.25% AnySpend fee. Users never pay gas directly.
## Further Reading
Official EIP-2612 permit specification
Official EIP-3009 transferWithAuthorization specification
EIP-712 typed structured data hashing and signing
See which tokens support which methods on each network
# ArenaKit Introduction
Source: https://docs.b3.fun/arenakit/introduction
Host tournaments, enable onchain wagering, & create onchain leaderboards.
## What is ArenaKit?
More documentation is coming soon.
# B3AR Introduction
Source: https://docs.b3.fun/b3ar/introduction
Host IRL drops with augmented reality.
## What is B3AR?
More documentation is coming soon.
# Bonding Phase
Source: https://docs.b3.fun/bondkit/concepts/bonding-phase
How buying and selling works during the bonding phase, fees, and thresholds.
## What is the Bonding Phase?
The bonding phase is the initial trading period where tokens are bought and sold directly from a smart contract using an algorithmic pricing curve. Think of it as a decentralized pre-sale with automatic market making.
```mermaid theme={null}
stateDiagram-v2
[*] --> Created: Token Deployed
Created --> Bonding: Automatic
Bonding --> Bonding: Buy/Sell Trades
Bonding --> MigrationReady: Target Reached
MigrationReady --> DEX: migrateToDex()
DEX --> [*]: Fully Decentralized
note right of Bonding
Direct contract trading
Algorithmic pricing
5% trading fee
Accumulates liquidity
end note
note right of DEX
Uniswap v4 trading
Market-driven price
Standard LP fees
No admin control
end note
```
## How Bonding Works
### The Bonding Curve Mechanism
During bonding, the contract acts as the sole market maker:
1. **No Order Book**: Prices determined algorithmically
2. **Instant Liquidity**: Always able to buy or sell
3. **Path Independence**: Price depends only on supply, not history
4. **Automatic Pricing**: No manual price setting needed
## Trading Operations
### Buying Tokens
**Process Flow:**
1. User sends trading token (B3/ETH) to contract
2. Contract calculates tokens based on curve
3. 5% fee deducted and sent to recipient
4. Tokens minted and sent to buyer
5. Curve state updated
**Code Example:**
```typescript theme={null}
// Get a quote first
const quote = await token.getAmountOfTokensToBuy(
parseEther("100") // 100 trading tokens
);
console.log(`Will receive: ${formatEther(quote)} tokens`);
// Execute purchase with slippage protection
const minTokens = quote * 0.95n; // 5% slippage
await token.buy(parseEther("100"), minTokens);
```
| Parameter | Type | Description |
| -------------------- | -------------- | ----------------------------------------------- |
| `minTokensOut` | uint256 | Minimum tokens to receive (slippage protection) |
| `tradingTokenAmount` | string/uint256 | Amount of trading token to spend |
**Important Notes:**
* Set `minTokensOut` to protect against front-running
* Use 0 for `minTokensOut` only in low-activity periods
* Transaction reverts if slippage exceeds tolerance
**Target Overflow:**
* If purchase would exceed target, excess is refunded
* Example: Target is 10 trading tokens, raised is 9.5 tokens
* User sends 1 token → 0.5 tokens used, 0.5 tokens refunded
**Insufficient Gas:**
* Recommended gas limit: 200,000
* Complex calculations may require more
**Zero Amount:**
* Transactions with 0 trading tokens will revert
### Selling Tokens
**Process Flow:**
1. User approves token spending
2. User calls sell with token amount
3. Contract calculates trading token amount based on curve
4. 5% fee deducted from proceeds
5. Trading token sent to seller, tokens burned
6. Curve state updated (price decreases)
**Code Example:**
```typescript theme={null}
// Check balance and get quote
const balance = await token.balanceOf(userAddress);
const sellAmount = balance / 2n; // Sell half
const quote = await token.getAmountOfTradingTokensToSell(
sellAmount
);
console.log(`Will receive: ${formatEther(quote)} trading tokens`);
// Execute sale with slippage protection
const minTradingTokenOut = quote * 0.95n; // 5% slippage
await token.sell(sellAmount, minTradingTokenOut);
```
| Parameter | Type | Description |
| -------------------- | ------- | ------------------------------------------------------ |
| `tokenAmount` | uint256 | Amount of tokens to sell |
| `minTradingTokenOut` | uint256 | Minimum trading token to receive (slippage protection) |
**Important Notes:**
* Requires token approval before selling
* Price impact can be significant for large sells
* Cannot sell more than circulating supply
**Understanding Sell Impact:**
Selling reduces the curve's raised amount, causing price to drop:
| Sell Size | Price Impact | Recovery Needed |
| ------------- | ------------ | --------------- |
| 1% of supply | \~1-2% | Small |
| 5% of supply | \~5-10% | Moderate |
| 10% of supply | \~15-25% | Significant |
| 20% of supply | \~30-50% | Major |
*Actual impact depends on aggressiveness factor*
## Fee Structure
### How Fees Work
```mermaid theme={null}
graph LR
A[User Trade] -->|100%| B[Contract]
B -->|95%| C[Curve/User]
B -->|5%| D[Fee Recipient]
style A fill:#e1f5fe
style D fill:#c8e6c9
```
**On a 1 trading token purchase:**
* 0.95 trading tokens go to bonding curve
* 0.05 trading tokens go to fee recipient
* Tokens calculated on 0.95 trading token value
**Example:**
```typescript theme={null}
// User sends 1 trading token
// Fee: 0.05 trading token
// Curve receives: 0.95 trading token
// Tokens minted based on 0.95 trading token
```
**On selling for 1 trading token value:**
* User receives 0.95 trading tokens
* 0.05 trading tokens go to fee recipient
* Curve reduced by full 1 trading token
**Example:**
```typescript theme={null}
// Tokens worth 1 trading token on curve
// Fee: 0.05 trading token
// User receives: 0.95 trading tokens
// Curve drops by 1 trading token
```
**Where fees go:**
* 100% to designated `feeRecipient` address
* Can be project treasury, developer, or DAO
* Set at token creation, cannot be changed
**Claiming fees:**
* Automatic - no claiming needed
* Sent directly on each trade
* No accumulation in contract
### Fee Economics
| Daily Volume | Fee Income | Monthly Income |
| ------------------ | ------------------ | -------------------- |
| 10 trading tokens | 0.5 trading tokens | \~15 trading tokens |
| 50 trading tokens | 2.5 trading tokens | \~75 trading tokens |
| 100 trading tokens | 5 trading tokens | \~150 trading tokens |
| 500 trading tokens | 25 trading tokens | \~750 trading tokens |
## Target Mechanics
### Understanding the Target
The target is the amount of trading token that must be accumulated before migration:
**Target Purpose:**
* Ensures sufficient liquidity for Uniswap v4
* Creates a clear goal for the community
* Prevents premature migration
* Builds momentum during bonding
### Approaching the Target
```typescript theme={null}
// Monitor progress toward target
async function trackProgress(token: BondkitToken) {
const progress = await token.getBondingProgress();
if (progress.progress < 0.5) {
console.log("🌱 Early stage - best prices available");
} else if (progress.progress < 0.8) {
console.log("🚀 Momentum building - consider buying");
} else if (progress.progress < 1.0) {
console.log("🔥 Almost there - migration imminent");
} else {
console.log("✅ Target reached - ready to migrate!");
}
const remaining = progress.threshold - progress.raised;
console.log(`Need ${formatEther(remaining)} more trading token`);
}
```
### Overflow Handling
When a purchase would exceed the target:
1. **Partial Fill**: Only the amount needed is accepted
2. **Automatic Refund**: Excess returned in same transaction
3. **Fair Completion**: No one can overpay at the end
**Example Scenario:**
```
Target: 100 trading tokens
Current: 99.5 trading tokens
User sends: 2 trading tokens
Result:
- 0.5 trading tokens accepted (reaches exactly 100)
- 1.5 trading tokens refunded
- User gets tokens for 0.5 trading tokens
- Migration now available
```
## Events & Monitoring
### Contract Events
```solidity theme={null}
event BondingCurveBuy(
address indexed payer,
address indexed recipient,
uint256 tradingTokenIn,
uint256 tokensOut,
uint256 fee,
uint256 totalRaisedBonding
);
```
**Listening in SDK:**
```typescript theme={null}
token.onBuy((event) => {
console.log({
buyer: event.payer,
ethSpent: formatEther(event.tradingTokenIn),
tokensReceived: formatEther(event.tokensOut),
feePaid: formatEther(event.fee),
totalRaised: formatEther(event.totalRaisedBonding)
});
});
```
```solidity theme={null}
event BondingCurveSell(
address indexed seller,
uint256 tokensIn,
uint256 tradingTokenOut,
uint256 fee,
uint256 totalRaisedBonding
);
```
**Listening in SDK:**
```typescript theme={null}
token.onSell((event) => {
console.log({
seller: event.seller,
tokensSold: formatEther(event.tokensIn),
ethReceived: formatEther(event.tradingTokenOut),
feePaid: formatEther(event.fee),
totalRaised: formatEther(event.totalRaisedBonding)
});
});
```
### Real-Time Monitoring
```typescript theme={null}
// Complete monitoring setup
class BondingMonitor {
constructor(private token: BondkitToken) {}
async start() {
// Initial state
const progress = await this.token.getBondingProgress();
console.log(`Starting at ${(progress.progress * 100).toFixed(2)}%`);
// Monitor buys
this.token.onBuy(async (event) => {
const newProgress = await this.token.getBondingProgress();
console.log(`BUY: ${formatEther(event.tokensOut)} tokens`);
console.log(`Progress: ${(newProgress.progress * 100).toFixed(2)}%`);
if (newProgress.progress >= 1.0) {
console.log("🎆 TARGET REACHED! Migration available.");
}
});
// Monitor sells
this.token.onSell(async (event) => {
const newProgress = await this.token.getBondingProgress();
console.log(`SELL: ${formatEther(event.tokensIn)} tokens`);
console.log(`Progress: ${(newProgress.progress * 100).toFixed(2)}%`);
});
}
}
// Usage
const monitor = new BondingMonitor(token);
await monitor.start();
```
## Bonding Phase Strategies
### For Token Creators
* Start with lower aggressiveness (30-50)
* Set achievable targets
* Engage community early
* Provide clear roadmap
* Seed initial liquidity yourself
* Create buying incentives
* Time announcements well
* Plan for post-migration
### For Traders
* Buy early for best prices
* Use DCA for large amounts
* Monitor aggressiveness factor
* Check target progress
* Always use slippage protection
* Understand price impact
* Don't FOMO near target
* Plan exit strategy
## Post-Bonding Transition
**Critical: After Migration**
Once `migrateToDex()` is called:
* ❌ Bonding curve trading permanently disabled
* ❌ No more buy() or sell() functions
* ✅ All trading moves to Uniswap v4
* ✅ Standard AMM mechanics apply
* ✅ Anyone can provide liquidity
* ✅ Fully decentralized trading
## Next Steps
Understand price mechanics
Choose the right target
Learn about DEX transition
# DEX Phase
Source: https://docs.b3.fun/bondkit/concepts/dex-phase
Trading on Uniswap v4 after migration: swaps, liquidity, and decentralized trading.
## What is the DEX Phase?
The DEX phase is the final stage of a Bondkit token's lifecycle, where trading transitions from the automated bonding curve to a fully decentralized Uniswap v4 pool. This phase begins immediately after migration and represents complete decentralization.
```mermaid theme={null}
stateDiagram-v2
[*] --> BondingPhase: Token Created
BondingPhase --> MigrationReady: Target Reached
MigrationReady --> DEXPhase: migrateToDex()
DEXPhase --> [*]: Fully Decentralized
note right of BondingPhase
Contract-controlled pricing
5% trading fees
Direct buy/sell only
Target accumulation
end note
note right of DEXPhase
Market-driven pricing
Standard DEX fees
Full trading features
No admin control
end note
```
## How Migration Works
### The Transition Process
When `migrateToDex()` is called after reaching the target:
1. **Contract Status**: Token status changes to `TokenStatus.Dex`
2. **Uniswap v4 Pool**: New pool created with accumulated liquidity
3. **Price Initialization**: Initial pool price calculated from bonding curve exit price
4. **Ownership Renouncement**: Contract ownership transferred to zero address
5. **Trading Enabled**: Full DEX trading begins immediately
### Pool Configuration
**Automatic Pool Setup:**
```typescript theme={null}
// Pool is created with these parameters (from migration)
const poolConfig = {
currency0: tradingToken < bondkitToken ? tradingToken : bondkitToken,
currency1: tradingToken < bondkitToken ? bondkitToken : tradingToken,
fee: 3000, // 0.3% standard fee
tickSpacing: 60, // Standard tick spacing
hooks: customHook // Bondkit-specific hooks
};
```
**Initial Liquidity:**
* **Trading Token**: All accumulated funds from bonding phase
* **Bondkit Tokens**: Calculated amount to match exit price
* **LP Tokens**: Split between fee recipient and burned/distributed
## Trading in DEX Phase
### Trading Options
**Standard DEX Trading:**
Bondkit tokens in DEX phase can be traded using any Uniswap v4 compatible interface, DEX aggregator, or trading platform.
**SDK Helper (Optional):**
The SDK provides `BondkitSwapService` for simplified integration if needed.
### Price Discovery & Liquidity
**Market-Driven Pricing:**
* No more algorithmic bonding curve
* Price determined by supply/demand
* Real-time order book dynamics
* Subject to market volatility
**Liquidity Sources:**
```typescript theme={null}
// Initial liquidity from migration
const migrationData = {
tradingTokenLiquidity: "10.0", // ETH/B3 from bonding
bondkitTokenLiquidity: "500000", // Calculated token amount
initialPrice: "0.00002", // Price per token
totalValueLocked: "20.0" // Combined TVL
};
// Additional liquidity from:
// - Community LPs
// - Incentive programs
// - Trading fees accumulation
```
## Key Differences from Bonding Phase
### Trading Mechanics
| Aspect | Bonding Phase | DEX Phase |
| ---------------- | -------------------------- | -------------------------- |
| **Pricing** | Algorithmic curve | Market supply/demand |
| **Liquidity** | Unlimited (contract mints) | Limited pool liquidity |
| **Fees** | 5% to fee recipient | 0.3% to LPs + protocol |
| **Order Types** | Buy/sell only | Full DEX features |
| **Price Impact** | Predictable curve | Depends on liquidity depth |
| **MEV** | Not applicable | Subject to MEV |
### Smart Contract Changes
**Status Transition:**
```typescript theme={null}
// Check current phase
const status = await token.getStatus();
if (status === TokenStatus.Dex) {
// Use DEX trading methods
const swapService = new BondkitSwapService(tokenAddress);
// ... DEX trading code
} else if (status === TokenStatus.Bonding) {
// Use bonding curve methods
await token.buy(amount, minTokensOut);
}
```
**Method Availability:**
* ✅ `token.buy()` / `token.sell()` - **Disabled** (will revert)
* ✅ DEX trading via `BondkitSwapService`
* ✅ Standard ERC20 functionality continues
* ✅ Event monitoring for DEX trades
## Advanced DEX Features
### Custom Hooks Integration
Bondkit tokens on Uniswap v4 include custom hooks for enhanced functionality:
```typescript theme={null}
// Hook features (automatically applied)
const hookFeatures = {
beforeSwap: "Custom fee calculations",
afterSwap: "Analytics tracking",
beforeAddLiquidity: "LP rewards",
afterRemoveLiquidity: "Exit fee handling"
};
```
### Analytics & Monitoring
**Real-Time Data:**
```typescript theme={null}
import TradingView from "@b3dotfun/sdk/bondkit/components/TradingView";
// Professional charts with DEX data
function DEXTradingInterface({ tokenAddress, tokenSymbol }) {
return (
{/* Price chart with DEX data */}
{/* Trading interface */}
);
}
```
**Available Metrics:**
* Real-time price feeds
* 24h volume and change
* Liquidity depth
* Historical OHLCV data
* Transaction history
* Holder analytics
### Liquidity Provision
**Becoming an LP:**
```typescript theme={null}
// Add liquidity to Bondkit token pool
import { Pool, Position } from "@uniswap/v3-sdk";
const position = new Position({
pool: bondkitPool,
liquidity: targetLiquidity,
tickLower: lowerTick,
tickUpper: upperTick
});
// Earn trading fees + potential incentives
```
**LP Benefits:**
* **Trading Fees**: Earn 0.3% of all swap volume
* **Incentive Programs**: Potential additional rewards
* **Price Appreciation**: Benefit from token growth
* **Impermanent Loss**: Standard AMM risks apply
## Migration Impact Analysis
### For Token Holders
**Immediate Effects:**
* ✅ Tokens remain fully transferable
* ✅ Can trade on open market
* ✅ No lock-up periods
* ⚠️ Price now subject to market volatility
* ⚠️ No guaranteed liquidity (depends on pool depth)
**Long-term Benefits:**
* 🚀 Access to larger trading ecosystem
* 🚀 Integration with DeFi protocols
* 🚀 Composability with other tokens
* 🚀 True decentralization achieved
### For Projects
**Operational Changes:**
```typescript theme={null}
// Pre-migration: Direct control
await token.buy(amount, minOut); // ✅ Works
await token.migrateToDex(); // One-time action
// Post-migration: Market-based
await token.buy(amount, minOut); // ❌ Reverts
await swapService.executeSwap(...); // ✅ Use this instead
```
**New Responsibilities:**
* **Community Building**: Drive organic trading volume
* **Liquidity Incentives**: Encourage LP participation
* **Marketing**: Promote token utility and adoption
* **Integration**: List on DEX aggregators and platforms
## Best Practices for DEX Phase
### For Traders
**Slippage Management:**
* Use 0.5-2% slippage for small trades
* Higher slippage for larger amounts
* Check price impact before execution
**Timing Considerations:**
* Higher liquidity during active hours
* Monitor for large LP movements
* Use limit orders when available
**Example:**
```typescript theme={null}
const quote = await swapService.getSwapQuote({
// ... parameters
slippageTolerance: parseFloat(quote.priceImpact) > 5 ? 0.02 : 0.005
});
```
**Liquidity Analysis:**
* Check pool TVL before large trades
* Monitor liquidity provider activity
* Understand impermanent loss if LP
**Price Monitoring:**
* Set up price alerts
* Use stop-loss strategies
* Diversify across multiple tokens
### For Developers
**Status Checking:**
```typescript theme={null}
async function getOptimalTradingMethod(token: BondkitToken) {
const status = await token.getStatus();
if (status === TokenStatus.Bonding) {
return {
method: "bonding",
interface: token
};
} else if (status === TokenStatus.Dex) {
return {
method: "dex",
interface: new BondkitSwapService(token.contractAddress)
};
}
}
```
**Error Handling:**
```typescript theme={null}
try {
// Always check phase first
const tradingMethod = await getOptimalTradingMethod(token);
if (tradingMethod.method === "dex") {
await tradingMethod.interface.executeSwap(params, wallet);
}
} catch (error) {
if (error.message.includes("TradingDisabledDexPhaseActive")) {
// Switch to DEX trading
const swapService = new BondkitSwapService(tokenAddress);
await swapService.executeSwap(params, wallet);
}
}
```
## Common Questions
**No** - Migration is permanent and irreversible. Once in DEX phase, the token will always trade on Uniswap v4.
All accumulated trading tokens from the bonding phase become the initial liquidity in the Uniswap v4 pool, paired with calculated bondkit tokens at the exit price.
No restrictions - tokens become standard ERC20s trading on Uniswap v4. Full DeFi composability is enabled.
DEX phase uses standard Uniswap v4 fees (0.3%) which go to liquidity providers instead of the 5% bonding phase fee to the fee recipient.
## Next Steps
Learn to use BondkitSwapService for DEX trading
Integrate TradingView charts for your DEX tokens
Provide liquidity and earn trading fees
Track your token's DEX performance
# Pricing
Source: https://docs.b3.fun/bondkit/concepts/pricing
The bonding curve pricing model and the role of aggressivenessFactor.
## Visual Price Curves
```mermaid theme={null}
graph LR
subgraph "Aggressiveness = 0 (Linear)"
A1[0 ETH] -->|Constant Price| A2[Target]
end
subgraph "Aggressiveness = 50 (Moderate)"
B1[0 ETH] -->|Gradual Increase| B2[Target]
end
subgraph "Aggressiveness = 100 (Steep)"
C1[0 ETH] -->|Rapid Increase| C2[Target]
end
```
## Bonding Curve Model
### Mathematical Formula
**Core Formula**
```
S = S_final × (R / R_target)^exponent
```
Where:
* `S` = Current token supply
* `S_final` = Final token supply
* `R` = Amount raised so far
* `R_target` = Target amount
* `exponent = 1 / (1 + aggressivenessFactor/100)`
### Understanding the Exponent
The aggressiveness factor controls how the exponent affects price progression:
| Aggressiveness | Exponent | Formula Becomes | Price Behavior |
| -------------- | -------- | --------------------------------- | -------------------------------- |
| 0 | 1.00 | S = S\_final × (R/R\_target) | Linear - constant tokens per ETH |
| 25 | 0.80 | S = S\_final × (R/R\_target)^0.80 | Slightly curved |
| 50 | 0.67 | S = S\_final × (R/R\_target)^0.67 | Moderate curve |
| 75 | 0.57 | S = S\_final × (R/R\_target)^0.57 | Steep curve |
| 100 | 0.50 | S = S\_final × √(R/R\_target) | Very steep (square root) |
### Aggressiveness Factor Impact
#### Cumulative Token Distribution
See how tokens are distributed throughout the bonding process with different aggressiveness factors.
**Example:** 10M B3 target, 1.25M total token supply (1M available for bonding, 250K reserved for LP)
| Progress | Aggressiveness = 0 | 25 | 50 | 75 | 100 |
| -------- | ------------------ | --------- | --------- | --------- | --------- |
| 10% | 100,000 | 158,489 | 215,443 | 268,270 | 316,228 |
| 20% | 200,000 | 275,946 | 341,995 | 398,647 | 447,214 |
| 30% | 300,000 | 381,678 | 448,140 | 502,588 | 547,723 |
| 40% | 400,000 | 480,450 | 542,884 | 592,387 | 632,456 |
| 50% | 500,000 | 574,349 | 629,961 | 672,950 | 707,107 |
| 60% | 600,000 | 664,540 | 711,379 | 746,843 | 774,597 |
| 70% | 700,000 | 751,759 | 788,374 | 815,614 | 836,660 |
| 80% | 800,000 | 836,512 | 861,774 | 880,284 | 894,427 |
| 90% | 900,000 | 919,166 | 932,170 | 941,571 | 948,683 |
| 100% | 1,000,000 | 1,000,000 | 1,000,000 | 1,000,000 | 1,000,000 |
**Key Insight:** Higher aggressiveness front-loads token distribution to early buyers. At 10% progress:
* **Aggressiveness 0**: 100,000 (linear)
* **Aggressiveness 100**: 316,228 (3.16x advantage!)
Early buyers with aggressive curves get significantly more tokens for their B3, while late buyers face much higher prices.
#### Real-World Example: Alice's Purchase
Let's follow Alice, who wants to buy tokens from a new project at launch:
**Project Setup:**
* **Total Supply**: 1.25M tokens (1M for bonding + 250K for LP)
* **Target**: 10M B3 to reach migration
* **Aggressiveness**: 100 (maximum reward for early buyers)
* **Current Progress**: 0% (project just launched)
**Alice's Purchase:**
Alice decides to buy 1M B3 worth of tokens right at launch (0% progress).
1. **Alice sends**: 1M B3 tokens
2. **Trading fee (3%)**: 30K B3 goes to fee recipients
3. **Amount for curve**: 970K B3 advances the project to \~9.7% progress
4. **Tokens received**: \~306,000 tokens (calculated from bonding curve)
**Comparing Different Entry Points:**
If Alice waited and bought the same 1M B3 worth at different project stages:
| Project Progress | Alice's 1M B3 Gets Her | Price per Token |
| ---------------- | ---------------------- | --------------- |
| 0% (launch) | \~306,000 tokens | \~3.3 B3/token |
| 50% progress | \~114,000 tokens | \~8.8 B3/token |
| 90% progress | \~49,000 tokens | \~20.4 B3/token |
**Early Buyer Advantage:** Alice gets 6.2x more tokens by buying at launch versus waiting until 90% progress!
**Key Takeaway**: With maximum aggressiveness (100), buying 1M B3 at launch gets Alice 6.2x more tokens than waiting until 90% progress. The bonding curve heavily rewards early participation!
## Interactive Price Calculator
```typescript theme={null}
// Calculate tokens received for a given trading token amount
function calculateTokensReceived(
tradingTokenAmount: number,
currentRaised: number,
targetAmount: number,
totalSupply: number,
aggressiveness: number
): number {
const exponent = 1 / (1 + aggressiveness / 100);
// Calculate supply at current raised
const currentSupply = totalSupply *
Math.pow(currentRaised / targetAmount, exponent);
// Calculate supply after purchase
const newRaised = currentRaised + tradingTokenAmount;
const newSupply = totalSupply *
Math.pow(newRaised / targetAmount, exponent);
// Tokens received = difference in supply
return newSupply - currentSupply;
}
// Example usage
const tokens = calculateTokensReceived(
1, // 1 ETH purchase
5, // 5 ETH already raised
10, // 10 ETH target
1000000, // 1M total supply
50 // 50% aggressiveness
);
console.log(`You'll receive ${tokens.toFixed(0)} tokens`);
```
## Choosing Your Aggressiveness Factor
### Decision Framework
**Best for:**
* Fair launches
* Community tokens
* Stable pricing
**Pros:**
* Equal opportunity
* Predictable costs
* Less FOMO
**Cons:**
* No early incentive
* Slower momentum
**Best for:**
* Most projects
* Balanced approach
* Moderate rewards
**Pros:**
* Some early advantage
* Still accessible
* Good momentum
**Cons:**
* Moderate complexity
* Some price variance
**Best for:**
* Hype launches
* Reward early adopters
* Fast fundraising
**Pros:**
* Strong early incentive
* Creates urgency
* Rewards believers
**Cons:**
* Can seem unfair
* High price variance
* FOMO-driven
## Selling Mechanics
When users sell tokens back to the curve:
1. **Price Calculation**: Uses inverse of buying formula
2. **Fee Deduction**: 5% fee applied to proceeds
3. **Curve Update**: Reduces total raised amount
4. **Price Impact**: Large sells significantly impact price
### Sell Price Formula
```typescript theme={null}
// Calculate trading token received for selling tokens
function calculateTradingTokenReceived(
tokenAmount: number,
currentSupply: number,
currentRaised: number,
targetAmount: number,
totalSupply: number,
aggressiveness: number
): number {
const exponent = 1 / (1 + aggressiveness / 100);
// Calculate new supply after sell
const newSupply = currentSupply - tokenAmount;
// Calculate corresponding raised amount
const supplyRatio = newSupply / totalSupply;
const newRaised = targetEth *
Math.pow(supplyRatio, 1 / exponent);
// ETH received (before fees)
const ethBeforeFees = currentRaised - newRaised;
// Apply 5% fee
return ethBeforeFees * 0.95;
}
```
## Edge Cases & Limits
**Important Considerations:**
1. **Refunds**: If a buy would exceed target, excess ETH is refunded
2. **Minimum Amounts**: Very small trades may revert due to rounding
3. **Maximum Supply**: Cannot exceed `finalTokenSupply`
4. **Price Limits**: Extreme aggressiveness can cause price spikes
5. **Slippage**: Always use `minTokensOut` for protection
## Real-World Examples
### Case Study: Fair Launch Token
* **Aggressiveness**: 10
* **Target**: 50 ETH
* **Result**: Nearly linear pricing, community appreciated fairness
### Case Study: Hype Token
* **Aggressiveness**: 85
* **Target**: 100 ETH
* **Result**: Reached target in 2 hours, early buyers gained 8x
### Case Study: Balanced Project
* **Aggressiveness**: 45
* **Target**: 25 ETH
* **Result**: Steady growth over 3 days, 2.5x advantage for early buyers
## Next Steps
Learn to choose the right factor
Estimate your migration price
# Targets & Migration Trigger
Source: https://docs.b3.fun/bondkit/concepts/targets
Understanding targetAmount, when migration can happen, and what occurs during migration.
## Target amount
* `targetAmount` is the quote‑asset threshold that enables migration.
* Set at creation; denominated in the quote asset (ETH or an allowed ERC20).
* The bonding phase ends once total raised reaches the target (excess contributions are refunded).
## Who can migrate
* Only the token owner/creator (migration admin) can call `migrateToDex()`.
## What happens at migration
* Split of accumulated quote asset:
* Portion to `feeRecipient`, based on `lpSplitRatioFeeRecipientBps`.
* Remainder used as liquidity alongside tokens reserved for LP.
* For Uniswap v4 migration, the contract computes `sqrtPriceX96` to initialize the pool.
* Liquidity is added to the v4 pool with appropriate safeguards; LP tokens or positions are handled per v4 semantics, with ownership effectively burned/renounced for decentralization.
* Ownership is renounced immediately to finalize decentralization.
## Post‑migration
* Bonding‑phase trading is disabled.
* Token behaves as a standard ERC20 with DEX‑based price discovery.
Networks & addresses (factory, v4 pool manager, hooks) are listed on the Networks page.
# Choose a Quote Asset
Source: https://docs.b3.fun/bondkit/guides/choose-quote-asset
ETH vs ERC20 (e.g., B3) as the quote asset during bonding.
## Overview
BondKit supports bonding against ETH or an allowed ERC20 (e.g., B3). Your choice impacts UX, integrations, and liquidity at migration.
## When to use ETH
* Broad accessibility; most users hold ETH on Base
* Simpler UX (no prior approvals)
* Direct ETH liquidity at migration
## When to use an ERC20 (e.g., B3)
* Aligns with an existing token economy
* Can bootstrap deeper token‑token pairs at migration
* Requires approvals before buys/sells
## Operational differences
* 5% fee on buys and sells for both ETH and ERC20
* ERC20 flows require `approve` before curve interactions
* Migration pairs are created against WETH or the chosen ERC20
Confirm the allowed‑list for ERC20 quote assets with the team. By default only specific assets may be enabled.
# Estimate Migration Price
Source: https://docs.b3.fun/bondkit/guides/est-migration-price
Estimating price at migration and considerations for Uniswap v4 initialization.
## Overview
Migration initializes a Uniswap v4 pool. The contract computes `sqrtPriceX96` from bonding state.
## Practical approach
* Use bonding reads to approximate price near the target:
* `getCurrentBondingCurvePricePerToken()`
* `getBondingProgress()`
## Considerations
* The final split and liquidity amount can affect initial ticks.
* Slippage protections are applied when adding liquidity.
* For ERC20 quote assets, ensure pair and decimals are accounted for when converting to `sqrtPriceX96`.
Exact initialization math is handled on-chain. Use reads for UI estimation; treat final on-chain initialization as source of truth.
# Set aggressivenessFactor
Source: https://docs.b3.fun/bondkit/guides/set-aggressiveness
How to pick aggressivenessFactor (0–100) for your launch.
## Understanding Aggressiveness Impact
The aggressiveness factor determines how much advantage early buyers get. Higher values create steeper price increases that reward early participation.
### Impact at Different Levels
| Range | Early Buyer Advantage | Best For | Price Behavior |
| ---------- | --------------------- | -------------------------------- | --------------------- |
| **0-20** | 1.5-2x advantage | Fair launches, community tokens | Nearly linear pricing |
| **30-60** | 2-3x advantage | Most projects, balanced approach | Moderate curve |
| **70-100** | 3-6x advantage | Hype launches, reward believers | Steep curve |
At maximum aggressiveness (100), early buyers can get **6x more tokens** than late buyers for the same amount of B3!
## Decision Framework
### Choose Low (0-30) If:
* **Goal**: Fair distribution for everyone
* **Community**: Values equality over early rewards
* **Timeline**: Want steady, predictable growth
* **Risk**: Prefer minimal price volatility
### Choose Medium (30-70) If:
* **Goal**: Balanced approach with some early incentive
* **Community**: Mix of early supporters and general public
* **Timeline**: Moderate fundraising pace
* **Risk**: Comfortable with some price variance
### Choose High (70-100) If:
* **Goal**: Maximum early adopter rewards
* **Community**: Strong core believers
* **Timeline**: Want fast fundraising
* **Risk**: Comfortable with high price swings
## Real Impact Example
**Project Setup:** 10M B3 target, buying 1M B3 worth
| Aggressiveness | Early Buyer Gets | Late Buyer Gets | Advantage |
| -------------- | ---------------- | --------------- | ----------------- |
| 0 | \~100K tokens | \~100K tokens | 1x (no advantage) |
| 50 | \~208K tokens | \~114K tokens | 1.8x advantage |
| 100 | \~306K tokens | \~49K tokens | 6.2x advantage |
## Configuration Example
```typescript theme={null}
const config = {
name: "My Token",
symbol: "MTK",
aggressivenessFactor: 75, // High reward for early buyers
targetAmount: parseEther("100"), // 100 B3 target
finalTokenSupply: parseEther("1000000"), // 1M tokens
// ...other params
};
```
## Next Steps
See detailed token distribution tables
Ready to deploy your token
# How BondKit Works
Source: https://docs.b3.fun/bondkit/how-it-works
Create → Bond → Migrate: the end‑to‑end flow for launching ERC20 bond tokens on Base.
## Architecture Overview
```mermaid theme={null}
graph TB
subgraph "Frontend Layer"
UI["Web Application"]
SDK["BondKit SDK"]
end
subgraph "Smart Contract Layer"
Factory["Factory Contract"]
Impl["Implementation Contract"]
Token1["Token Clone 1"]
Token2["Token Clone 2"]
TokenN["Token Clone N"]
end
subgraph "DEX Layer"
V4["Uniswap v4"]
Pool1["Pool 1"]
Pool2["Pool 2"]
end
subgraph "Backend Services"
API["Analytics API"]
DB["Database"]
Indexer["Event Indexer"]
end
UI --> SDK
SDK --> Factory
Factory -.->|deploys| Token1
Factory -.->|deploys| Token2
Factory -.->|deploys| TokenN
Token1 -->|migrates to| Pool1
Token2 -->|migrates to| Pool2
Pool1 --> V4
Pool2 --> V4
Token1 --> Indexer
Token2 --> Indexer
Indexer --> DB
DB --> API
API --> UI
Impl -.->|template for| Token1
Impl -.->|template for| Token2
style Factory fill:#e1f5fe
style V4 fill:#c8e6c9
style API fill:#fff9c4
```
## Product Flow in Detail
**What happens:**
* User calls `deployBondkitToken()` on the Factory contract
* Factory clones the Implementation contract using minimal proxy pattern
* New token is initialized with custom parameters
* Token enters bonding phase automatically
**Gas cost:** \~200,000 gas (90% cheaper than full deployment)
**Time:** \~15 seconds
**What happens:**
* Users buy/sell tokens directly from the contract
* Price follows algorithmic bonding curve: `S = S_final × (R/R_target)^exponent`
* 5% fee on all trades goes to fee recipient
* Contract accumulates quote assets (ETH/B3) toward target
* Backend indexes all transactions for analytics
**Trading mechanics:**
* Buy: Send ETH/B3, receive tokens at current curve price
* Sell: Send tokens, receive ETH/B3 minus fees
* Automatic refunds if purchase would exceed target
**Duration:** Until target is reached (hours to weeks)
**What happens:**
* Admin calls `migrateToDex()` when target is reached
* Contract calculates fair market price as `sqrtPriceX96`
* Creates and initializes Uniswap v4 pool
* Transfers accumulated liquidity to pool
* Renounces ownership to zero address
* Token becomes standard ERC20 with DEX trading
**Post-migration:**
* Bonding curve permanently disabled
* All trading via Uniswap v4
* No admin controls remain
* Full decentralization achieved
**Gas cost:** \~500,000 gas
**Time:** \~30 seconds
## System Components
### Smart Contracts
**Purpose:** Deploys new bond tokens efficiently
**Key Functions:**
* `deployBondkitToken()` - Creates new token clone
* `getImplementationAddress()` - Returns template address
* `setAllowedQuoteAsset()` - Admin function to whitelist assets
**Gas Optimization:**
* Uses EIP-1167 minimal proxy pattern
* Shares logic across all tokens
* \~90% gas savings vs individual deployments
**Purpose:** Template for all bond tokens
**Core Features:**
* ERC20 standard compliance
* Bonding curve mathematics
* Migration logic to Uniswap v4
* Fee distribution system
**State Transitions:**
1. Uninitialized → Bonding Phase
2. Bonding Phase → Migration Ready
3. Migration Ready → DEX Phase
**Purpose:** Individual token instances
**Lifecycle:**
* Created via factory
* Initialized with unique parameters
* Manages its own bonding curve
* Self-migrates to Uniswap v4
**Storage:**
* Token metadata (name, symbol)
* Supply and distribution
* Bonding curve state
* Migration parameters
### Backend Services
**Purpose:** Captures all on-chain activity
**Monitors:**
* Token creations
* Buy/sell transactions
* Migration events
* Transfer activities
**Technology:**
* Real-time blockchain scanning
* Event log processing
* Database synchronization
**Purpose:** Processes raw data into insights
**Generates:**
* OHLCV candlestick data
* Volume metrics
* Liquidity tracking
* Price history
* User statistics
**Updates:** Every block (\~2 seconds)
**Purpose:** Serves data to frontends
**Endpoints:**
* `/tokens` - List all tokens
* `/tokens/{address}` - Token details
* `/tokens/{address}/transactions` - Trade history
* `/tokens/{address}/ohlcv` - Chart data
* `/users/{address}/portfolio` - User holdings
**Format:** JSON with pagination
### User Roles
| Role | Responsibilities | Permissions |
| ------------------- | ------------------------------------------------ | ---------------------------- |
| **Creator** | Deploy token, set parameters, initiate migration | Full control until migration |
| **Traders** | Buy/sell during bonding, trade on DEX | Standard trading rights |
| **Fee Recipient** | Receive trading fees | Passive income only |
| **Migration Admin** | Execute migration when ready | One-time migration right |
| **LP Providers** | (Post-migration) Add liquidity to Uniswap | Standard LP rights |
## Technical Deep Dive
### Bonding Curve Mathematics
The bonding curve determines token price based on supply:
```
Price Formula:
S = S_final × (R / R_target)^exponent
Where:
- S = Current token supply
- S_final = Final token supply
- R = Raised amount (ETH/B3)
- R_target = Target amount
- exponent = 1 / (1 + aggressivenessFactor/100)
```
**Example Calculations:**
| Aggressiveness | Exponent | Price Behavior |
| -------------- | -------- | ------------------------ |
| 0 | 1.00 | Linear (constant price) |
| 25 | 0.80 | Gentle curve |
| 50 | 0.67 | Moderate curve |
| 75 | 0.57 | Steep curve |
| 100 | 0.50 | Very steep (square root) |
### Migration Price Calculation
When migrating to Uniswap v4, the contract:
1. **Calculates exit price** from bonding curve
2. **Converts to sqrtPriceX96** format:
```
sqrtPriceX96 = sqrt(price) × 2^96
```
3. **Initializes pool** with this price
4. **Adds liquidity** using accumulated funds
### Gas Optimization Techniques
**Minimal Proxy Pattern (EIP-1167)**
Instead of deploying full contract code for each token:
* Deploy one implementation contract (600KB)
* Deploy tiny proxy contracts (45 bytes each)
* Proxies delegate all calls to implementation
* Result: 90% gas savings per deployment
## Configuration Parameters
### Token Creation Parameters
| Parameter | Type | Range/Format | Impact |
| ----------------------------- | ------- | ------------- | --------------------------- |
| `name` | string | 1-50 chars | Token display name |
| `symbol` | string | 2-10 chars | Trading symbol |
| `finalTokenSupply` | uint256 | > 0 | Total mintable tokens |
| `aggressivenessFactor` | uint8 | 0-100 | Curve steepness |
| `targetEth` | uint256 | > 0 | Migration threshold |
| `feeRecipient` | address | Valid address | Receives fees |
| `lpSplitRatioFeeRecipientBps` | uint256 | 0-10000 | LP fee share (basis points) |
| `migrationAdminAddress` | address | Valid address | Can trigger migration |
### Runtime Parameters
| Action | Parameters | Validation |
| ------- | --------------------------- | -------------------------- |
| Buy | `minTokensOut`, `ethAmount` | Slippage protection |
| Sell | `tokenAmount`, `minEthOut` | Balance check, slippage |
| Migrate | None | Target reached, admin only |
### System Constants
| Constant | Value | Description |
| ------------------ | ------- | ----------------------- |
| Trading Fee | 5% | Applied to all trades |
| Decimals | 18 | Standard ERC20 decimals |
| Min Target | 0.1 ETH | Minimum viable target |
| Max Aggressiveness | 100 | Maximum curve factor |
## Security Considerations
**Important Security Features:**
1. **Ownership Renouncement**: Automatic after migration
2. **No Mint Function**: Supply fixed at creation
3. **Immutable Parameters**: Cannot be changed post-deployment
4. **Audited Contracts**: Professionally reviewed code
5. **No Admin Backdoors**: True decentralization
6. **Slippage Protection**: Built into buy/sell functions
7. **Overflow Protection**: Safe math throughout
## Failure Scenarios & Handling
| Scenario | System Response |
| ------------------------------- | --------------------------- |
| Buy exceeds target | Partial fill, refund excess |
| Insufficient liquidity for sell | Transaction reverts |
| Migration before target | Transaction reverts |
| Non-admin attempts migration | Transaction reverts |
| Double migration attempt | Transaction reverts |
| Zero address operations | Transaction reverts |
## Next Steps
Understand bonding curve mathematics
Learn the migration process
# Installation
Source: https://docs.b3.fun/bondkit/installation
Install and configure BondKit for launching ERC20 bond tokens on Base.
## Prerequisites
* **Node.js 18+** - JavaScript runtime
* **pnpm** (recommended) or npm/yarn - Package manager
* **Git** - Version control
* **Wallet with Base ETH** - For deployments and transactions
## Quick Start Options
## Install the SDK
```bash pnpm theme={null}
pnpm add @b3dotfun/sdk
```
```bash npm theme={null}
npm install @b3dotfun/sdk
```
```bash yarn theme={null}
yarn add @b3dotfun/sdk
```
## Project Setup
```bash theme={null}
# Create a new project
mkdir my-bondkit-app
cd my-bondkit-app
pnpm init
# Install dependencies
pnpm add @b3dotfun/sdk typescript
pnpm add -D @types/node tsx
# Create TypeScript config
npx tsc --init
```
## Add to Existing Project
```bash pnpm theme={null}
pnpm add @b3dotfun/sdk
```
```bash npm theme={null}
npm install @b3dotfun/sdk
```
```bash yarn theme={null}
yarn add @b3dotfun/sdk
```
The SDK includes all necessary dependencies including viem
## Clone Demo Application
The fastest way to get started is with our complete demo application:
```bash theme={null}
# Clone the B3 monorepo
git clone https://github.com/b3dotfun/b3-monorepo.git
cd b3-monorepo
# Install dependencies
pnpm install
# Navigate to the BondKit demo
cd apps/bondkit-demo
# Set up environment
cp .env.example .env.local
# Edit .env.local with your configuration
# Run the demo
pnpm dev
```
The demo app is located at `apps/bondkit-demo/src/app/` and includes:
* Complete token deployment flow
* Trading interface with TradingView charts
* Wallet connection with B3 authentication
* Real-time price and volume tracking
* Migration management interface
### Demo App Structure
```
apps/bondkit-demo/src/app/
├── page.tsx # Landing page with token list
├── deploy/page.tsx # Token deployment interface
├── token/[address]/page.tsx # Individual token trading page
├── providers.tsx # Web3 providers setup
├── b3ProviderWrapper.tsx # B3 authentication wrapper
└── api/ # TradingView data endpoints
└── udf/ # Universal Data Feed for charts
```
## Environment Configuration
### Basic Setup
Create a `.env` file in your project root:
```bash theme={null}
# Required for server-side operations
WALLET_PRIVATE_KEY=0x...
# Optional: Custom RPC endpoint (defaults to public)
RPC_URL=https://base-mainnet.g.alchemy.com/v2/YOUR_KEY
# Optional: API configuration
BONDKIT_API_ENDPOINT=https://api.b3.fun
```
### Security Best Practices
**Never commit private keys to version control!**
* Add `.env` to your `.gitignore`
* Use environment variables in production
* Consider using a key management service
* Use separate wallets for development and production
## Client Initialization
### Basic Setup
```typescript theme={null}
import { BondkitTokenFactory } from "@b3dotfun/sdk/bondkit";
import { base } from "viem/chains";
// For server-side usage with private key
const factory = new BondkitTokenFactory(
base.id,
process.env.WALLET_PRIVATE_KEY
);
// For client-side usage with wallet provider
const clientFactory = new BondkitTokenFactory(base.id);
await clientFactory.connect(window.ethereum);
```
### Advanced Configuration
```typescript theme={null}
import {
BondkitTokenFactory,
BondkitToken,
getConfig
} from "@b3dotfun/sdk/bondkit";
import { createWalletClient, custom } from "viem";
import { base } from "viem/chains";
// Custom wallet client setup
const walletClient = createWalletClient({
chain: base,
transport: custom(window.ethereum)
});
// Initialize with custom configuration
const config = getConfig(base.id);
const factory = new BondkitTokenFactory(base.id);
// Connect with custom wallet client
await factory.connect(walletClient.transport);
// Work with existing token
const token = new BondkitToken(
"0x123...", // token address
process.env.WALLET_PRIVATE_KEY
);
```
## TypeScript Configuration
Recommended `tsconfig.json` for BondKit projects:
```json theme={null}
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM"],
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"allowJs": true,
"noEmit": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
```
## Testing Your Setup
Create a test file `test-bondkit.ts`:
```typescript theme={null}
import { BondkitTokenFactory } from "@b3dotfun/sdk/bondkit";
import { base } from "viem/chains";
async function testConnection() {
try {
const factory = new BondkitTokenFactory(base.id);
const implementationAddress = await factory.getImplementationAddress();
console.log("✅ BondKit SDK connected successfully!");
console.log("Implementation address:", implementationAddress);
} catch (error) {
console.error("❌ Connection failed:", error);
}
}
testConnection();
```
Run the test:
```bash theme={null}
npx tsx test-bondkit.ts
```
## Next Steps
Deploy your first token in minutes
Explore all SDK methods and features
Study the complete implementation
Learn about backend services and analytics
## Troubleshooting
Ensure the SDK is properly installed:
```bash theme={null}
pnpm add @b3dotfun/sdk
```
If using React components, you may need:
```bash theme={null}
pnpm add @wagmi/core @tanstack/react-query
```
Update TypeScript to latest version:
```bash theme={null}
pnpm add -D typescript@latest @types/node@latest
```
* Verify your RPC endpoint is working
* Check wallet has sufficient Base ETH
* Ensure private key format is correct (with 0x prefix)
Clear cache and reinstall:
```bash theme={null}
rm -rf node_modules .next
pnpm install
```
# BondKit Introduction
Source: https://docs.b3.fun/bondkit/introduction
Product for launching ERC20 bond tokens on Base with a bonding phase and seamless Uniswap v4 migration.
## What is BondKit?
BondKit is a complete token launch platform for creating ERC20 "bond tokens" on Base mainnet. It provides an end‑to‑end solution that handles everything from initial token creation through bonding curve trading and finally migration to Uniswap v4 for full decentralized trading.
### Key Components
**Audited On-Chain Infrastructure**
* Factory contract for deploying new tokens
* ERC20 implementation with bonding curve logic
* Automatic Uniswap v4 pool initialization
* Gas-optimized minimal proxy pattern
**Developer-Friendly Tools**
* Simple API for all contract interactions
* Type-safe interfaces with full TypeScript support
* Built-in transaction management
* Event subscriptions and monitoring
**Real-Time Data Services**
* Transaction history tracking
* OHLCV chart data generation
* Token metadata storage
* REST API for frontend integration
## How BondKit Works
```mermaid theme={null}
graph LR
A[Create Token] --> B[Bonding Phase]
B --> C[Target Reached]
C --> D[Migrate to DEX]
D --> E[Uniswap v4 Trading]
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
style B fill:#FF9800,stroke:#F57C00,stroke-width:2px,color:#fff
style C fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
style D fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
style E fill:#00BCD4,stroke:#00838F,stroke-width:2px,color:#fff
```
### The Three-Phase Lifecycle
1. **Creation Phase**: Deploy your token with custom parameters
2. **Bonding Phase**: Automated market making via bonding curve
3. **DEX Phase**: Full decentralized trading on Uniswap v4
## Core Features
* **Gas-Efficient Clones**: Uses minimal proxy pattern to reduce deployment costs by \~90%
* **Standardized Implementation**: All tokens share the same battle-tested logic
* **One-Click Deployment**: Simple function call to create a new token
* **Configurable Aggressiveness**: Factor from 0-100 controls price progression
* **Automatic Price Discovery**: Market-driven pricing during bonding phase
* **Buy & Sell Support**: Full two-way trading during bonding
* **5% Trading Fee**: Applied to both buys and sells, distributed to fee recipient
* **Customizable Targets**: Set your funding goal in ETH or allowed ERC20
* **Automatic Threshold Detection**: Contract tracks progress to target
* **One-Click Migration**: Simple call to `migrateToDex()` when ready
* **Price Calculation**: `sqrtPriceX96` computed on-chain for fair initial pricing
* **Automatic Pool Creation**: Pool initialized with bonding curve exit price
* **Liquidity Provision**: Accumulated funds become initial liquidity
* **Ownership Renouncement**: Contract becomes fully decentralized post-migration
* **Seamless Transition**: No manual intervention required
* **Real-Time Indexing**: All transactions recorded and processed
* **OHLCV Data**: Professional trading charts available via API
* **Transaction History**: Complete audit trail for every token
* **Portfolio Tracking**: Monitor multiple tokens and positions
## Use Cases
**For Projects & Creators**
* Fair launch mechanisms
* Community-driven price discovery
* No upfront liquidity required
* Built-in anti-bot protection
**For GameFi Projects**
* In-game currency launches
* NFT project tokens
* Reward token distribution
* Player-owned economies
**For Developers**
* Programmatic token creation
* White-label solutions
* Custom frontend integration
* API-driven automation
## Technical Capabilities
### Smart Contract Features
* ✅ ERC20-compliant bond tokens with extended functionality
* ✅ Factory pattern for gas-efficient deployments
* ✅ Configurable parameters (supply, target, aggressiveness)
* ✅ Built-in fee distribution mechanism
* ✅ Automatic Uniswap v4 migration
### SDK Features
* ✅ Full TypeScript support with type definitions
* ✅ Promise-based async operations
* ✅ Event listeners and subscriptions
* ✅ Transaction receipt handling
* ✅ Error handling and retry logic
### Analytics Features
* ✅ Real-time price tracking
* ✅ Volume and liquidity metrics
* ✅ Historical transaction data
* ✅ OHLCV candlestick data
* ✅ User portfolio tracking
## Get started
Launch with BondKit on Base
Questions or feedback? Talk to us on Discord
## Key Terminology
| Term | Definition |
| ----------------- | ----------------------------------------------------------------- |
| **Bonding Phase** | Initial trading period with algorithmic pricing via bonding curve |
| **Bond Token** | ERC20 token with built-in bonding curve mechanics |
| **Target Amount** | Funding goal that triggers migration eligibility |
| **Migration** | Transition from bonding curve to Uniswap v4 |
| **Quote Asset** | The currency used to buy tokens (ETH or allowed ERC20) |
| Term | Definition |
| ------------------------- | --------------------------------------------------- |
| **Minimal Proxy** | Gas-efficient contract cloning pattern |
| **Aggressiveness Factor** | Parameter (0-100) controlling price curve steepness |
| **sqrtPriceX96** | Uniswap v4 price format for pool initialization |
| **Fee Recipient** | Address receiving trading fees during bonding |
| **LP Split Ratio** | Liquidity provider fee percentage in basis points |
| Term | Definition |
| -------------------- | ------------------------------------------- |
| **Factory Contract** | Main contract for deploying new bond tokens |
| **Implementation** | Template contract cloned for each token |
| **Public Client** | Read-only blockchain connection |
| **Wallet Client** | Write-enabled blockchain connection |
| **Provider** | Web3 connection interface (e.g., MetaMask) |
## Important Parameters
**Current Network**: Base Mainnet only
**Supported Trading Tokens**:
* B3 Token (primary on Base mainnet)
* ETH (when configured as zero address)
* Additional ERC20 tokens can be whitelisted
**Fee Structure**:
* 5% on all bonding phase trades
* Customizable LP split ratio for migration
**Security**:
* Audited smart contracts
* Automatic ownership renouncement post-migration
* No admin keys after DEX phase begins
## Next Steps
Set up the BondKit SDK in your project
```bash theme={null}
pnpm add @b3dotfun/sdk
```
Learn the basics with our step-by-step guide
Check out working implementations and demos
Get help and share feedback on Discord
# Networks & Addresses
Source: https://docs.b3.fun/bondkit/networks
Deployment endpoints and contract addresses for BondKit.
## Base Mainnet
| Name | Address |
| --------------------------- | -------------------------------------------- |
| BondkitTokenFactory | `0x5d641bbB206d4B5585eCCd919F36270200A9A2Ad` |
| BondkitToken Implementation | `0x68dEcC09D8800ED1138C781ABe4056aba7a4eF7E` |
| Uniswap V4 Pool Manager | `0x498581fF718922c3f8e6A244956aF099B2652b2b` |
| BondkitUniswapV4Hook | `0xB36f4A2FB18b745ef8eD31452781a463d2B3f0cC` |
| B3 | `0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3` |
| Bonding Phase Splitter | `0x2AB69e0d9D20D3700466153D84a6574128154Fd2` |
| Dex Phase Splitter | `TBD` |
BondKit operates on Base mainnet. Testnet/dev environments are currently not available.
# Quickstart
Source: https://docs.b3.fun/bondkit/quickstart
Launch an ERC20 bond token in minutes: Create → Bond → Migrate.
## Overview
This quickstart guide will walk you through the complete lifecycle of a BondKit token in under 5 minutes. You'll learn how to:
1. **Deploy** a new bond token
2. **Trade** during the bonding phase
3. **Monitor** progress toward the target
4. **Migrate** to Uniswap v4
**Prerequisites**: Make sure you've completed the [installation](/bondkit/installation) and have a funded wallet on Base.
## Complete Flow Diagram
```mermaid theme={null}
sequenceDiagram
participant User
participant Factory
participant Token
participant Traders
participant UniswapV4
User->>Factory: deployBondkitToken()
Factory->>Token: Create via proxy
Token-->>User: Token address
loop Bonding Phase
Traders->>Token: buy()/sell()
Token-->>Traders: Tokens/Trading Token
end
User->>Token: Check progress
Token-->>User: Target reached!
User->>Token: migrateToDex()
Token->>UniswapV4: Initialize pool
UniswapV4-->>Token: Pool created
Token-->>User: Migration complete
```
## Step 1: Deploy Your Token
### Basic Deployment
```typescript theme={null}
import { BondkitTokenFactory } from "@b3dotfun/sdk/bondkit";
import { base } from "viem/chains";
import { parseEther } from "viem";
// Initialize the factory
const factory = new BondkitTokenFactory(
base.id,
process.env.WALLET_PRIVATE_KEY
);
// Deploy your token
const tokenAddress = await factory.deployBondkitToken({
// Token metadata
name: "My Awesome Token",
symbol: "MAT",
// Supply configuration (1 million tokens)
finalTokenSupply: parseEther("1000000"),
// Bonding curve settings
aggressivenessFactor: 35, // 0-100, higher = steeper curve
targetAmount: parseEther("10"), // 10 units of trading token target for migration
// Fee configuration
feeRecipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", // Your address
lpSplitRatioFeeRecipientBps: 1000n, // 10% to fee recipient
// Migration settings
migrationAdminAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1",
// Uniswap V4 configuration
bondingPhaseSplitter: "0x2AB69e0d9D20D3700466153D84a6574128154Fd2",
v4PoolManager: "0x498581fF718922c3f8e6A244956aF099B2652b2b",
v4Hook: "0xB36f4A2FB18b745ef8eD31452781a463d2B3f0cC",
v4PoolFee: 3000, // 0.3% fee tier
v4TickSpacing: 60,
// Trading token (B3 token address for Base mainnet)
tradingToken: "0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3"
});
console.log("✅ Token deployed at:", tokenAddress);
```
### Understanding Parameters
Total supply of tokens (with 18 decimals). Example: `parseEther("1000000")` for 1M tokens.
Controls bonding curve steepness (0-100):
* **0-30**: Linear pricing, fair for all buyers
* **30-60**: Moderate curve, balanced approach
* **60-100**: Aggressive, rewards early buyers
Amount of trading token needed to enable migration. Use `parseEther("10")` for 10 tokens (18 decimals).
Address that receives trading fees (5% of all trades).
Basis points (1/100th of 1%) for LP fee split. 1000 = 10%.
## Step 2: Trading During Bonding Phase
### Initialize Token Instance
```typescript theme={null}
import { BondkitToken } from "@b3dotfun/sdk/bondkit";
import { parseEther, formatEther } from "viem";
// Connect to your deployed token
const token = new BondkitToken(
tokenAddress,
process.env.WALLET_PRIVATE_KEY
);
```
### Understanding Trading Tokens
BondKit tokens use a **configurable trading token** system. Check what token is used for trading:
```typescript theme={null}
// Get the trading token details
const tradingTokenAddress = await token.getTradingTokenAddress();
const tradingTokenSymbol = await token.getTradingTokenSymbol();
console.log(`Trading with: ${tradingTokenSymbol} (${tradingTokenAddress})`);
// For Base mainnet, this is typically B3 token
// Check if it's ETH (zero address) or an ERC20 token
const isETH = tradingTokenAddress === "0x0000000000000000000000000000000000000000";
```
### Buying Tokens
```typescript theme={null}
// Get a price quote first
const tradingTokenAmount = parseEther("100"); // 100 units of trading token
const expectedTokens = await token.getAmountOfTokensToBuy(tradingTokenAmount);
console.log(`${formatEther(tradingTokenAmount)} ${tradingTokenSymbol} will buy: ${formatEther(expectedTokens)} tokens`);
// Execute the purchase (parameters: minTokensOut, amount)
const buyTx = await token.buy(
tradingTokenAmount, // Amount of trading token to spend
0n // minTokensOut (0 = accept any amount, use for slippage protection)
);
console.log("Purchase complete! Tx:", buyTx);
```
### Selling Tokens
```typescript theme={null}
// Check your token balance
const balance = await token.getBalance(userAddress);
console.log(`Your balance: ${formatEther(balance)} tokens`);
// Get sell quote
const tokensToSell = parseEther("1000");
const expectedTradingToken = await token.getAmountOfTradingTokensToSell(tokensToSell);
console.log(`Selling 1000 tokens will return: ${formatEther(expectedTradingToken)} ${tradingTokenSymbol}`);
// Execute the sale
const sellTx = await token.sell(
tokensToSell, // Amount of tokens to sell
0n // Min trading token out (for slippage protection)
);
console.log("Sale complete! Tx:", sellTx);
```
### Monitoring Progress
```typescript theme={null}
// Check bonding progress
const progress = await token.getBondingProgress();
console.log(`
Progress: ${(progress.progress * 100).toFixed(2)}%
Raised: ${formatEther(progress.raised)} ${tradingTokenSymbol}
Target: ${formatEther(progress.threshold)} ${tradingTokenSymbol}
Remaining: ${formatEther(progress.threshold - progress.raised)} ${tradingTokenSymbol}
`);
// Get current token price
const currentPrice = await token.getCurrentPrice();
console.log(`Current price: ${formatEther(currentPrice)} ${tradingTokenSymbol} per token`);
// Check if migration is available
const canMigrate = await token.canMigrate();
console.log(`Ready to migrate: ${canMigrate}`);
```
### Event Monitoring
```typescript theme={null}
// Listen for buy events
token.onBuy((event) => {
console.log("New purchase:", {
buyer: event.buyer,
tradingTokenIn: formatEther(event.ethIn), // Note: field name is 'ethIn' but represents trading token
tokensOut: formatEther(event.tokensOut)
});
});
// Listen for sell events
token.onSell((event) => {
console.log("New sale:", {
seller: event.seller,
tokensIn: formatEther(event.tokensIn),
tradingTokenOut: formatEther(event.ethOut) // Note: field name is 'ethOut' but represents trading token
});
});
```
## Step 3: Migration to Uniswap v4
### Check Migration Readiness
```typescript theme={null}
// Verify target is reached
const progress = await token.getBondingProgress();
if (progress.progress >= 1.0) {
console.log("✅ Target reached! Ready to migrate.");
// Get migration details
const migrationData = await token.getMigrationData();
console.log("Migration will create pool with:", {
tradingTokenLiquidity: formatEther(migrationData.ethForLp), // Note: 'ethForLp' field name
tokenLiquidity: formatEther(migrationData.tokensForLp),
initialPrice: formatEther(migrationData.sqrtPriceX96)
});
} else {
console.log(`⏳ Need ${formatEther(progress.threshold - progress.raised)} more ${tradingTokenSymbol}`);
}
```
### Execute Migration
```typescript theme={null}
// Only the migration admin can call this
if (await token.isMigrationAdmin(userAddress)) {
console.log("🚀 Initiating migration to Uniswap v4...");
const migrationTx = await token.migrateToDex();
console.log("Migration transaction:", migrationTx);
// Wait for confirmation
const receipt = await token.waitForTransaction(migrationTx);
if (receipt.status === "success") {
console.log("✅ Migration complete!");
console.log("Uniswap v4 pool address:", await token.getPoolAddress());
}
} else {
console.log("❌ Only migration admin can execute migration");
}
```
**Important**: After migration:
* Contract ownership is automatically renounced
* Bonding curve trading is permanently disabled
* All trading moves to Uniswap v4
* No further admin actions are possible
## Complete Example
Here's a full working example that demonstrates the entire lifecycle:
```typescript theme={null}
import {
BondkitTokenFactory,
BondkitToken
} from "@b3dotfun/sdk/bondkit";
import { base } from "viem/chains";
import { parseEther, formatEther } from "viem";
async function launchToken() {
// 1. Deploy token
const factory = new BondkitTokenFactory(
base.id,
process.env.WALLET_PRIVATE_KEY
);
const tokenAddress = await factory.deployBondkitToken({
name: "Demo Token",
symbol: "DEMO",
finalTokenSupply: parseEther("1000000"),
aggressivenessFactor: 50,
targetAmount: parseEther("5"),
feeRecipient: process.env.WALLET_ADDRESS,
lpSplitRatioFeeRecipientBps: 1000n,
migrationAdminAddress: process.env.WALLET_ADDRESS,
// Uniswap V4 configuration
bondingPhaseSplitter: "0x2AB69e0d9D20D3700466153D84a6574128154Fd2",
v4PoolManager: "0x498581fF718922c3f8e6A244956aF099B2652b2b",
v4Hook: "0xB36f4A2FB18b745ef8eD31452781a463d2B3f0cC",
v4PoolFee: 3000,
v4TickSpacing: 60,
tradingToken: "0xB3B32F9f8827D4634fE7d973Fa1034Ec9fdDB3B3"
});
console.log("Token deployed:", tokenAddress);
// 2. Trade during bonding
const token = new BondkitToken(
tokenAddress,
process.env.WALLET_PRIVATE_KEY
);
// Buy some tokens
await token.buy(parseEther("50"), 0n); // 50 trading tokens, 0 min out
console.log("Bought tokens with 50 trading tokens");
// Check progress
const progress = await token.getBondingProgress();
console.log(`Progress: ${(progress.progress * 100).toFixed(2)}%`);
// 3. Continue trading until target is reached...
// (In production, other users would be trading)
// 4. Migrate when ready
if (progress.progress >= 1.0) {
await token.migrateToDex();
console.log("Migration complete! Token is now on Uniswap v4");
}
}
launchToken().catch(console.error);
```
## Next Steps
Deep dive into bonding curves and pricing
Explore all available methods
End-to-end token management guide
See a complete implementation
# Bulk Delete Collections
Source: https://docs.b3.fun/createkit/api-reference/collections/bulk-delete-collections
https://createkit.b3.fun/swagger.json delete /collections/bulk
Deletes multiple collections in a single operation. Only referrers can bulk delete collections they referred. Requires signature verification.
# Count Collections
Source: https://docs.b3.fun/createkit/api-reference/collections/count-collections
https://createkit.b3.fun/swagger.json get /collections/count
Returns the count of collections matching the provided filters. Uses the same filter parameters as the list endpoint.
# Create NFT Collection
Source: https://docs.b3.fun/createkit/api-reference/collections/create-nft-collection
https://createkit.b3.fun/swagger.json post /collections
Creates a new NFT collection with metadata storage, address prediction, and database persistence. Validates required fields, generates metadata, predicts deployment address, and stores all information.
# Delete Collection
Source: https://docs.b3.fun/createkit/api-reference/collections/delete-collection
https://createkit.b3.fun/swagger.json delete /collections
Deletes a collection by predicted address with signature verification. Only the creator or game owner can delete a collection.
# Get Collection by Address
Source: https://docs.b3.fun/createkit/api-reference/collections/get-collection-by-address
https://createkit.b3.fun/swagger.json get /collections/{predictedAddress}
Retrieves a single collection by its predicted deployment address. Results are cached for 30 days for optimal performance.
# List Collections
Source: https://docs.b3.fun/createkit/api-reference/collections/list-collections
https://createkit.b3.fun/swagger.json get /collections
Retrieves collections with filtering and pagination. Requires at least one filter parameter. Supports filtering by creator, symbol, referrer, chainId, gameOwner, or gameId.
# Register Referrer
Source: https://docs.b3.fun/createkit/api-reference/referrers/register-referrer
https://createkit.b3.fun/swagger.json post /referrers
Registers a new referrer for collection tracking. Requires signature verification to ensure the wallet owner is registering themselves.
# Collection Management
Source: https://docs.b3.fun/createkit/collections
Complete guide to creating and managing NFT collections with CreateKit
## Overview
Collection management is at the core of CreateKit. This guide covers everything you need to know about creating, configuring, and managing NFT collections using the BaseMint protocol.
## Collection Metadata Structure
Every collection requires specific metadata that defines its characteristics:
### Required Parameters
The name of your NFT collection (e.g., "Bored Ape Yacht Club")
The symbol/ticker for your collection (e.g., "BAYC")
The Ethereum address of the collection creator
The Ethereum address of the game owner (can be same as creator)
### Optional Parameters
Maximum number of tokens that can be minted
Price per token in wei (use parseEther() for ETH values)
Maximum tokens that can be minted per wallet
Whether whitelist-only minting is enabled
Unix timestamp when minting starts (0 = immediate)
Unix timestamp when minting ends
The token standard to use
Chain ID (1993 = B3 Testnet, 8333 = B3 Mainnet)
## Creating Collections
### Basic Collection
```typescript title="Basic Collection Creation" theme={null}
import { CollectionManager, b3Testnet } from '@b3dotfun/basemint'
import { createPublicClient, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)
const publicClient = createPublicClient({
chain: b3Testnet,
transport: http()
})
const walletClient = createWalletClient({
chain: b3Testnet,
transport: http(),
account
})
const collectionManager = new CollectionManager(publicClient)
// Define basic collection
const basicCollection = {
name: "My Art Collection",
symbol: "MAC",
creator: account.address,
gameOwner: account.address,
description: "A collection of digital art pieces",
image: "https://example.com/collection-image.png"
}
// Generate creator signature
const creatorSignature = await collectionManager.generateCreatorSignature(
walletClient,
basicCollection
)
```
### Advanced Collection Configuration
```typescript title="Advanced Collection Setup" theme={null}
import { parseEther } from 'viem'
const advancedCollection = {
// Required
name: "Premium Gaming Items",
symbol: "PGI",
creator: account.address,
gameOwner: "0x1234567890123456789012345678901234567890", // Different game owner
// Supply and pricing
maxSupply: 5000n,
mintPrice: parseEther("0.01"), // 0.01 ETH
maxPerWallet: 5n,
// Timing controls
startTime: BigInt(Math.floor(Date.now() / 1000) + 3600), // Start in 1 hour
endTime: BigInt(Math.floor(Date.now() / 1000) + 86400 * 7), // End in 7 days
// Whitelist configuration
isWhitelistEnabled: true,
whitelistMerkleRoot: "0x..." as `0x${string}`,
// Metadata
description: "Exclusive gaming items for premium players",
image: "https://example.com/premium-collection.png",
external_url: "https://mygame.com/premium-items",
animation_url: "https://example.com/collection-animation.mp4",
// Collection attributes
attributes: [
{ trait_type: "Category", value: "Gaming" },
{ trait_type: "Rarity", value: "Premium" },
{ trait_type: "Edition", value: "First" }
],
// Technical
tokenStandard: "ERC1155" as const,
chainId: 1993
}
```
## Token Standards
CreateKit supports both ERC721 and ERC1155 standards:
```typescript theme={null}
const erc721Collection = {
name: "Unique Art Pieces",
symbol: "UAP",
creator: account.address,
gameOwner: account.address,
tokenStandard: "ERC721" as const,
maxSupply: 1000n, // Each token is unique
description: "One-of-a-kind digital art pieces"
}
// ERC721 minting (quantity always 1)
const collection721 = collectionManager.createCollection(
predictedAddress,
"ERC721"
)
await collection721.mint(
walletClient,
1n, // Always 1 for ERC721
undefined, // metadata URI
mintPrice,
proof
)
```
```typescript theme={null}
const erc1155Collection = {
name: "Game Resources",
symbol: "GRS",
creator: account.address,
gameOwner: account.address,
tokenStandard: "ERC1155" as const,
maxSupply: 100000n, // Total across all token types
description: "Fungible and semi-fungible game resources"
}
// ERC1155 minting (can mint multiple)
const collection1155 = collectionManager.createCollection(
predictedAddress,
"ERC1155"
)
await collection1155.mint(
walletClient,
10n, // Can mint multiple tokens
"https://example.com/token/1", // specific token metadata
mintPrice,
proof
)
```
## Metadata Management
### Collection-Level Metadata
```typescript title="Collection Metadata" theme={null}
const collectionMetadata = {
name: "My Collection",
description: "A fantastic collection of digital assets",
image: "https://example.com/collection-image.png",
external_url: "https://mywebsite.com/collection",
// Background and banner for marketplaces
background_color: "ffffff",
banner_image_url: "https://example.com/banner.png",
// Collection attributes
attributes: [
{ trait_type: "Theme", value: "Fantasy" },
{ trait_type: "Artist", value: "Digital Creator" }
]
}
```
### Token-Level Metadata
CreateKit automatically generates token metadata based on your collection settings:
```typescript theme={null}
import { NFTMetadataManager, MediaType } from '@b3dotfun/basemint'
// Generate metadata for different media types
const artworkMetadata = NFTMetadataManager.generateNFTMetadata(
collectionMetadata,
MediaType.ARTWORK
)
const model3dMetadata = NFTMetadataManager.generateNFTMetadata(
collectionMetadata,
MediaType.MODEL_3D
)
const videoMetadata = NFTMetadataManager.generateNFTMetadata(
collectionMetadata,
MediaType.VIDEO
)
// Convert to JSON
const metadataJson = NFTMetadataManager.generateJSON(artworkMetadata)
console.log(metadataJson)
```
```typescript theme={null}
// For custom metadata, provide your own baseURI
const customCollection = {
name: "Custom Metadata Collection",
symbol: "CMC",
creator: account.address,
gameOwner: account.address,
baseURI: "https://myapi.com/metadata/", // Your custom metadata endpoint
description: "Collection with custom metadata"
}
// Your API should respond to: https://myapi.com/metadata/{tokenId}
// With standard OpenSea metadata format
```
## Collection Validation
CreateKit provides built-in validation for collection parameters:
```typescript title="Parameter Validation" theme={null}
import { validateCollectionMetadata } from '@b3dotfun/basemint'
try {
// Validate collection metadata
const validation = validateCollectionMetadata(collectionMetadata)
if (!validation.isValid) {
console.error("Validation errors:", validation.errors)
return
}
console.log("✅ Collection metadata is valid")
// Proceed with signature generation
const signature = await collectionManager.generateCreatorSignature(
walletClient,
collectionMetadata
)
} catch (error) {
console.error("Validation failed:", error)
}
```
## Address Prediction
One of CreateKit's key features is deterministic address prediction:
```typescript title="Address Prediction" theme={null}
// Generate creator signature first
const creatorSignature = await collectionManager.generateCreatorSignature(
walletClient,
collectionMetadata
)
// Predict the collection address
const predictedAddress = collectionManager.predictCollectionAddress(
collectionMetadata,
creatorSignature
)
console.log(`Collection will be deployed at: ${predictedAddress}`)
// You can now use this address before deployment
// for marketplace integration, frontend display, etc.
```
## Collection Management Operations
### Checking Collection Status
```typescript title="Collection Status" theme={null}
const collection = collectionManager.createCollection(
predictedAddress,
"ERC721"
)
// Check if collection is deployed
const isDeployed = await collection.isDeployed()
console.log(`Deployed: ${isDeployed}`)
// Get collection info (only works after deployment)
if (isDeployed) {
const info = await collection.getCollectionInfo()
console.log("Collection Info:", {
name: info.name,
symbol: info.symbol,
totalSupply: info.totalSupply.toString(),
maxSupply: info.maxSupply.toString(),
mintPrice: info.mintPrice.toString(),
maxPerWallet: info.maxPerWallet.toString()
})
}
```
### Updating Collection Settings
Most collection parameters cannot be changed after deployment. Plan your collection configuration carefully.
```typescript title="Post-Deployment Management" theme={null}
// Only certain operations are possible after deployment
// Check current mint price (if dynamic pricing is implemented)
const currentPrice = await collection.getCurrentMintPrice()
// Check if minting is currently active
const isMintingActive = await collection.isMintingActive()
// Get remaining supply
const remainingSupply = await collection.getRemainingSupply()
console.log({
currentPrice: currentPrice.toString(),
isMintingActive,
remainingSupply: remainingSupply.toString()
})
```
## Best Practices
### 1. Collection Planning
* Set appropriate max supply based on use case
* Consider future demand and scarcity
* Leave room for growth or special editions
* Research similar collections for pricing reference
* Consider gas costs and transaction fees
* Plan for different market conditions
### 2. Metadata Quality
```typescript title="High-Quality Metadata" theme={null}
const qualityCollection = {
name: "Professional Art Collection",
symbol: "PAC",
creator: account.address,
gameOwner: account.address,
// High-quality descriptions
description: "A curated collection of professional digital artworks featuring contemporary themes and innovative techniques.",
// Professional imagery (minimum 640x640px)
image: "https://example.com/high-res-collection-image.png",
// Comprehensive attributes for better discoverability
attributes: [
{ trait_type: "Art Style", value: "Contemporary" },
{ trait_type: "Medium", value: "Digital" },
{ trait_type: "Artist Verification", value: "Verified" },
{ trait_type: "Edition Type", value: "Limited" }
],
// External links for credibility
external_url: "https://professionalartist.com/collection"
}
```
### 3. Security Considerations
* Never hardcode private keys in source code
* Use environment variables or secure key management
* Consider using multi-signature wallets for valuable collections
* Always validate signatures before deployment
* Verify collection parameters match intended values
* Test on testnet before mainnet deployment
* Carefully choose creator and gameOwner addresses
* Understand reward distribution implications
* Plan for long-term collection management
## Troubleshooting
Ensure all collection parameters are identical between signature generation and deployment. Even small changes will result in different addresses.
Check that all required fields are provided and that values are within acceptable ranges (e.g., maxSupply > 0, valid addresses).
Verify that your wallet client is properly configured and that you have sufficient funds for the signing transaction.
## Next Steps
Now that you understand collection management, explore these related topics:
Learn how to implement token minting functionality
Set up whitelist-based minting for exclusive access
# Error Handling
Source: https://docs.b3.fun/createkit/error-handling
Comprehensive error handling patterns and recovery strategies for CreateKit
## Overview
Robust error handling is crucial for production applications using CreateKit. This guide covers common error scenarios, best practices, and recovery strategies.
## Common Error Types
### Signature Errors
```typescript title="Signature Error Handling" theme={null}
import { CollectionManager } from '@b3dotfun/basemint'
async function handleSignatureErrors(walletClient: any, metadata: any) {
try {
const signature = await collectionManager.generateCreatorSignature(
walletClient,
metadata
)
return signature
} catch (error: any) {
if (error.message.includes('User rejected')) {
throw new Error('SIGNATURE_REJECTED: User rejected the signature request')
} else if (error.message.includes('Insufficient funds')) {
throw new Error('INSUFFICIENT_FUNDS: Not enough funds for gas')
} else if (error.message.includes('Network error')) {
throw new Error('NETWORK_ERROR: Unable to connect to network')
} else {
throw new Error(`SIGNATURE_FAILED: ${error.message}`)
}
}
}
```
### Storage Errors
```typescript title="Storage Error Handling" theme={null}
import { BaseMintStorage } from '@b3dotfun/basemint'
async function handleStorageErrors(storage: BaseMintStorage, metadata: any, signature: string) {
try {
return await storage.submitCollection(metadata, signature)
} catch (error: any) {
if (error.message.includes('Invalid signature')) {
throw new Error('INVALID_SIGNATURE: Signature verification failed')
} else if (error.message.includes('Collection exists')) {
throw new Error('DUPLICATE_COLLECTION: Collection already exists')
} else if (error.message.includes('Rate limit')) {
throw new Error('RATE_LIMITED: Too many requests, please try again later')
} else if (error.status === 503) {
throw new Error('SERVICE_UNAVAILABLE: Storage service temporarily unavailable')
} else {
throw new Error(`STORAGE_ERROR: ${error.message}`)
}
}
}
```
### Contract Interaction Errors
```typescript title="Contract Error Handling" theme={null}
async function handleMintingErrors(collection: any, walletClient: any, params: any) {
try {
return await collection.mint(walletClient, ...params)
} catch (error: any) {
if (error.message.includes('Invalid merkle proof')) {
throw new Error('NOT_WHITELISTED: Address not in whitelist')
} else if (error.message.includes('Insufficient payment')) {
throw new Error('INSUFFICIENT_PAYMENT: Incorrect mint price')
} else if (error.message.includes('Max per wallet exceeded')) {
throw new Error('WALLET_LIMIT_EXCEEDED: Wallet minting limit reached')
} else if (error.message.includes('Max supply exceeded')) {
throw new Error('SUPPLY_EXHAUSTED: Collection fully minted')
} else if (error.message.includes('Minting not active')) {
throw new Error('MINTING_INACTIVE: Minting period not active')
} else {
throw new Error(`MINT_FAILED: ${error.message}`)
}
}
}
```
## Error Recovery Patterns
### Retry Logic
```typescript title="Retry with Exponential Backoff" theme={null}
async function retryWithBackoff(
operation: () => Promise,
maxRetries: number = 3,
baseDelayMs: number = 1000
): Promise {
let lastError: Error
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation()
} catch (error: any) {
lastError = error
// Don't retry certain errors
if (error.message.includes('SIGNATURE_REJECTED') ||
error.message.includes('INVALID_SIGNATURE') ||
error.message.includes('DUPLICATE_COLLECTION')) {
throw error
}
if (attempt < maxRetries) {
const delay = baseDelayMs * Math.pow(2, attempt - 1)
console.warn(`Attempt ${attempt} failed, retrying in ${delay}ms...`)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
}
throw lastError
}
// Usage
const result = await retryWithBackoff(async () => {
return await storage.submitCollection(metadata, signature)
})
```
### Circuit Breaker
```typescript title="Circuit Breaker Pattern" theme={null}
class CircuitBreaker {
private failures = 0
private lastFailTime = 0
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED'
constructor(
private maxFailures: number = 5,
private timeoutMs: number = 60000
) {}
async call(operation: () => Promise): Promise {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailTime > this.timeoutMs) {
this.state = 'HALF_OPEN'
} else {
throw new Error('CIRCUIT_OPEN: Service temporarily unavailable')
}
}
try {
const result = await operation()
this.reset()
return result
} catch (error) {
this.recordFailure()
throw error
}
}
private recordFailure() {
this.failures++
this.lastFailTime = Date.now()
if (this.failures >= this.maxFailures) {
this.state = 'OPEN'
}
}
private reset() {
this.failures = 0
this.state = 'CLOSED'
}
}
// Usage
const circuitBreaker = new CircuitBreaker()
const result = await circuitBreaker.call(() => storage.submitCollection(metadata, signature))
```
## User-Friendly Error Messages
```typescript title="Error Message Translation" theme={null}
const ERROR_MESSAGES = {
SIGNATURE_REJECTED: "Please approve the signature in your wallet to continue.",
INSUFFICIENT_FUNDS: "You don't have enough funds to cover gas fees.",
NOT_WHITELISTED: "Your address is not eligible for whitelist minting.",
WALLET_LIMIT_EXCEEDED: "You've reached the maximum number of tokens per wallet.",
SUPPLY_EXHAUSTED: "This collection is fully minted out.",
MINTING_INACTIVE: "Minting is not currently active for this collection.",
NETWORK_ERROR: "Network connection issue. Please check your internet and try again.",
SERVICE_UNAVAILABLE: "Service is temporarily unavailable. Please try again in a few minutes.",
RATE_LIMITED: "Too many requests. Please wait a moment before trying again."
}
function getUserFriendlyError(error: Error): string {
const errorCode = error.message.split(':')[0]
return ERROR_MESSAGES[errorCode] || "An unexpected error occurred. Please try again."
}
// Usage in React
export function ErrorDisplay({ error }: { error: Error | null }) {
if (!error) return null
return (
{getUserFriendlyError(error)}
)
}
```
## Error Monitoring
```typescript title="Error Tracking" theme={null}
class ErrorTracker {
private errors: Array<{ timestamp: Date; error: Error; context: any }> = []
track(error: Error, context: any = {}) {
this.errors.push({
timestamp: new Date(),
error,
context
})
// Send to monitoring service
this.sendToMonitoring(error, context)
}
private sendToMonitoring(error: Error, context: any) {
// Integration with error monitoring services
console.error('Error tracked:', {
message: error.message,
stack: error.stack,
context,
timestamp: new Date().toISOString()
})
}
getErrorStats() {
const last24h = this.errors.filter(
e => Date.now() - e.timestamp.getTime() < 24 * 60 * 60 * 1000
)
return {
total: this.errors.length,
last24h: last24h.length,
mostCommon: this.getMostCommonErrors()
}
}
private getMostCommonErrors() {
const errorCounts = new Map()
this.errors.forEach(({ error }) => {
const errorType = error.message.split(':')[0]
errorCounts.set(errorType, (errorCounts.get(errorType) || 0) + 1)
})
return Array.from(errorCounts.entries())
.sort(([,a], [,b]) => b - a)
.slice(0, 5)
}
}
// Global error tracker
export const errorTracker = new ErrorTracker()
```
## Validation Helpers
```typescript title="Input Validation" theme={null}
export class ValidationError extends Error {
constructor(field: string, message: string) {
super(`${field}: ${message}`)
this.name = 'ValidationError'
}
}
export function validateCollectionMetadata(metadata: any): void {
if (!metadata.name || metadata.name.length < 1) {
throw new ValidationError('name', 'Collection name is required')
}
if (!metadata.symbol || metadata.symbol.length < 1) {
throw new ValidationError('symbol', 'Collection symbol is required')
}
if (!metadata.creator || !isValidAddress(metadata.creator)) {
throw new ValidationError('creator', 'Valid creator address is required')
}
if (metadata.maxSupply && metadata.maxSupply <= 0n) {
throw new ValidationError('maxSupply', 'Max supply must be greater than 0')
}
if (metadata.mintPrice && metadata.mintPrice < 0n) {
throw new ValidationError('mintPrice', 'Mint price cannot be negative')
}
}
function isValidAddress(address: string): boolean {
return /^0x[a-fA-F0-9]{40}$/.test(address)
}
```
## React Error Boundaries
```tsx title="Error Boundary Component" theme={null}
import React, { Component, ErrorInfo, ReactNode } from 'react'
interface Props {
children: ReactNode
fallback?: ReactNode
}
interface State {
hasError: boolean
error?: Error
}
export class CreateKitErrorBoundary extends Component {
constructor(props: Props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error }
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('CreateKit Error Boundary caught an error:', error, errorInfo)
// Track error
errorTracker.track(error, { errorInfo })
}
render() {
if (this.state.hasError) {
return this.props.fallback || (