@b3dotfun/sdk 0.0.5-alpha.1 → 0.0.5-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@b3dotfun/sdk",
3
- "version": "0.0.5-alpha.1",
3
+ "version": "0.0.5-alpha.3",
4
4
  "source": "src/index.ts",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "react-native": "./dist/cjs/index.native.js",
@@ -0,0 +1,635 @@
1
+ # AnySpend SDK Documentation
2
+
3
+ AnySpend is a powerful cross-chain protocol that enables seamless token swaps, NFT minting, tournament participation, and custom smart contract interactions across multiple blockchain networks. Built for developers who want to provide their users with a frictionless Web3 experience.
4
+
5
+ ## 📦 Overview
6
+
7
+ AnySpend handles the complexity of cross-chain operations, gas management, and payment processing, allowing users to:
8
+
9
+ - **Cross-chain Swaps**: Swap tokens across different blockchain networks
10
+ - **NFT Minting**: Mint NFTs with automatic payment handling
11
+ - **Custom Interactions**: Execute any smart contract operations (tournaments, staking, gaming, etc.)
12
+ - **Fiat Onramp**: Convert fiat currency to crypto using integrated payment providers
13
+ - **Gasless Transactions**: Users don't need to worry about gas fees
14
+
15
+ ### Key Features
16
+
17
+ - **Multi-chain Support**: Works across Ethereum, Base, B3, and other supported networks
18
+ - **Payment Flexibility**: Accept payments in various cryptocurrencies or fiat
19
+ - **Order Management**: Track transaction status in real-time
20
+ - **Error Recovery**: Automatic refund handling for failed transactions
21
+ - **React Integration**: Pre-built components for easy integration
22
+ - **TypeScript Support**: Full type safety and IntelliSense
23
+
24
+ ## 🚀 Getting Started
25
+
26
+ ### Prerequisites
27
+
28
+ - Node.js v20.15.0+
29
+ - React 18/19
30
+
31
+ ### Installation
32
+
33
+ ```bash
34
+ npm install @b3dotfun/sdk
35
+ # or
36
+ pnpm add @b3dotfun/sdk
37
+ ```
38
+
39
+ ### Basic Setup
40
+
41
+ ```tsx
42
+ import { AnySpendProvider } from "@b3dotfun/sdk/anyspend/react";
43
+ import "@b3dotfun/sdk/index.css";
44
+
45
+ function App() {
46
+ return <AnySpendProvider>{/* Your app components */}</AnySpendProvider>;
47
+ }
48
+ ```
49
+
50
+ ### Quick Start Example
51
+
52
+ ```tsx
53
+ import { AnySpendNFTButton } from "@b3dotfun/sdk/anyspend/react";
54
+
55
+ function NFTMinting() {
56
+ const nftContract = {
57
+ chainId: 8333, // B3 network
58
+ contractAddress: "0x9c275ff1634519E9B5449ec79cd939B5F900564d",
59
+ price: "500000000000000000", // 0.5 ETH in wei
60
+ priceFormatted: "0.5",
61
+ currency: {
62
+ chainId: 8333,
63
+ address: "0x0000000000000000000000000000000000000000", // ETH
64
+ name: "Ether",
65
+ symbol: "ETH",
66
+ decimals: 18
67
+ },
68
+ name: "Cool NFT",
69
+ description: "A really cool NFT",
70
+ imageUrl: "https://example.com/nft.png"
71
+ };
72
+
73
+ return (
74
+ <AnySpendNFTButton
75
+ nftContract={nftContract}
76
+ recipientAddress="0x..." // User's wallet address
77
+ onSuccess={txHash => {
78
+ console.log("NFT minted successfully!", txHash);
79
+ }}
80
+ />
81
+ );
82
+ }
83
+ ```
84
+
85
+ ## 📚 API Reference
86
+
87
+ ### Components
88
+
89
+ #### `<AnySpend>`
90
+
91
+ The main swap interface component for token-to-token exchanges.
92
+
93
+ ```tsx
94
+ <AnySpend
95
+ isMainnet={true}
96
+ mode="modal" // or "page"
97
+ defaultActiveTab="crypto" // or "fiat"
98
+ destinationTokenAddress="0x..." // For buy mode
99
+ destinationTokenChainId={8333}
100
+ recipientAddress="0x..."
101
+ hideTransactionHistoryButton={false}
102
+ onSuccess={txHash => console.log("Swap completed", txHash)}
103
+ />
104
+ ```
105
+
106
+ **Props:**
107
+
108
+ - `isMainnet?: boolean` - Whether to use mainnet or testnet (default: `true`)
109
+ - `mode?: "modal" | "page"` - Display mode (default: `"modal"`)
110
+ - `defaultActiveTab?: "crypto" | "fiat"` - Initial payment method (default: `"crypto"`)
111
+ - `destinationTokenAddress?: string` - For buy mode, specify the target token
112
+ - `destinationTokenChainId?: number` - Chain ID of the destination token
113
+ - `recipientAddress?: string` - Where to send the swapped tokens
114
+ - `hideTransactionHistoryButton?: boolean` - Hide the transaction history button
115
+ - `loadOrder?: string` - Load a specific order by ID
116
+ - `onSuccess?: (txHash?: string) => void` - Success callback
117
+
118
+ #### `<AnySpendNFTButton>`
119
+
120
+ A simple button component for NFT minting.
121
+
122
+ ```tsx
123
+ <AnySpendNFTButton
124
+ nftContract={{
125
+ chainId: 8333,
126
+ contractAddress: "0x...",
127
+ price: "1000000000000000000", // 1 ETH in wei
128
+ priceFormatted: "1.0",
129
+ currency: {
130
+ /* token details */
131
+ },
132
+ name: "My NFT",
133
+ description: "NFT description",
134
+ imageUrl: "https://example.com/image.png"
135
+ }}
136
+ recipientAddress="0x..."
137
+ isMainnet={true}
138
+ />
139
+ ```
140
+
141
+ #### `<AnySpendCustom>`
142
+
143
+ For custom smart contract interactions.
144
+
145
+ ```tsx
146
+ <AnySpendCustom
147
+ orderType={OrderType.Custom}
148
+ dstChainId={8333}
149
+ dstToken={
150
+ {
151
+ /* token details */
152
+ }
153
+ }
154
+ dstAmount="1000000000000000000" // Amount in wei
155
+ contractAddress="0x..." // Target contract
156
+ encodedData="0x..." // Encoded function call
157
+ spenderAddress="0x..." // Optional spender
158
+ metadata={
159
+ {
160
+ /* custom metadata */
161
+ }
162
+ }
163
+ header={({ anyspendPrice, isLoadingAnyspendPrice }) => <div>Custom header content</div>}
164
+ onSuccess={txHash => console.log("Custom order completed", txHash)}
165
+ />
166
+ ```
167
+
168
+ > **Note**: For specific use cases like staking, spin wheels, or other gaming mechanics, there are specialized components available (`AnySpendStakeB3`, `AnySpendBuySpin`, etc.). However, `AnySpendCustom` provides the most flexibility for any smart contract interaction.
169
+
170
+ ### Hooks
171
+
172
+ #### `useAnyspendQuote`
173
+
174
+ Get pricing information for a potential order.
175
+
176
+ ```tsx
177
+ import { useAnyspendQuote, OrderType, TradeType } from "@b3dotfun/sdk/anyspend";
178
+
179
+ const { anyspendQuote, isLoadingAnyspendQuote, getAnyspendQuoteError } = useAnyspendQuote(
180
+ true, // isMainnet
181
+ {
182
+ srcChain: 1, // Ethereum
183
+ dstChain: 8333, // B3
184
+ srcTokenAddress: "0x...", // USDC
185
+ dstTokenAddress: "0x...", // Target token
186
+ type: OrderType.Swap,
187
+ tradeType: TradeType.EXACT_INPUT,
188
+ amount: "1000000" // 1 USDC (6 decimals)
189
+ }
190
+ );
191
+ ```
192
+
193
+ #### `useAnyspendCreateOrder`
194
+
195
+ Create a new AnySpend order.
196
+
197
+ ```tsx
198
+ import { useAnyspendCreateOrder, OrderType } from "@b3dotfun/sdk/anyspend";
199
+
200
+ const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({
201
+ onSuccess: data => {
202
+ console.log("Order created:", data.data.id);
203
+ },
204
+ onError: error => {
205
+ console.error("Order creation failed:", error.message);
206
+ }
207
+ });
208
+
209
+ // Create order
210
+ createOrder({
211
+ isMainnet: true,
212
+ recipientAddress: "0x...",
213
+ orderType: OrderType.Swap,
214
+ srcChain: 1,
215
+ dstChain: 8333,
216
+ srcToken: {
217
+ /* source token details */
218
+ },
219
+ dstToken: {
220
+ /* destination token details */
221
+ },
222
+ srcAmount: "1000000",
223
+ expectedDstAmount: "500000000000000000",
224
+ creatorAddress: "0x..."
225
+ });
226
+ ```
227
+
228
+ #### `useAnyspendOrderAndTransactions`
229
+
230
+ Track order status and associated transactions.
231
+
232
+ ```tsx
233
+ import { useAnyspendOrderAndTransactions } from "@b3dotfun/sdk/anyspend";
234
+
235
+ const { orderAndTransactions, getOrderAndTransactionsError } = useAnyspendOrderAndTransactions(
236
+ true, // isMainnet
237
+ "order-id-here"
238
+ );
239
+
240
+ if (orderAndTransactions) {
241
+ const { order, depositTxs, relayTx, executeTx, refundTxs } = orderAndTransactions.data;
242
+ console.log("Order status:", order.status);
243
+ console.log("Deposit transactions:", depositTxs);
244
+ console.log("Execution transaction:", executeTx);
245
+ }
246
+ ```
247
+
248
+ #### `useAnyspendOrderHistory`
249
+
250
+ Get order history for a user.
251
+
252
+ ```tsx
253
+ import { useAnyspendOrderHistory } from "@b3dotfun/sdk/anyspend";
254
+
255
+ const { orderHistory, isLoadingOrderHistory } = useAnyspendOrderHistory(
256
+ true, // isMainnet
257
+ "0x...", // creatorAddress
258
+ 50, // limit
259
+ 0 // offset
260
+ );
261
+ ```
262
+
263
+ ### Service Functions
264
+
265
+ For advanced use cases, you can use the service layer directly:
266
+
267
+ ```tsx
268
+ import { anyspendService } from "@b3dotfun/sdk/anyspend/services";
269
+
270
+ // Get quote
271
+ const quote = await anyspendService.getQuote(true, {
272
+ srcChain: 1,
273
+ dstChain: 8333,
274
+ srcTokenAddress: "0x...",
275
+ dstTokenAddress: "0x...",
276
+ type: "swap",
277
+ tradeType: "exactInput",
278
+ amount: "1000000"
279
+ });
280
+
281
+ // Get token list
282
+ const tokens = await anyspendService.getTokenList(true, 1, "USDC");
283
+
284
+ // Create order
285
+ const order = await anyspendService.createOrder({
286
+ isMainnet: true,
287
+ recipientAddress: "0x...",
288
+ type: "swap",
289
+ srcChain: 1,
290
+ dstChain: 8333,
291
+ srcTokenAddress: "0x...",
292
+ dstTokenAddress: "0x...",
293
+ srcAmount: "1000000",
294
+ payload: {
295
+ /* order payload */
296
+ },
297
+ metadata: {
298
+ /* order metadata */
299
+ }
300
+ });
301
+ ```
302
+
303
+ ## 🔧 Environment Configuration
304
+
305
+ ### Environment Variables
306
+
307
+ ```bash
308
+ # Optional: Custom AnySpend API endpoints
309
+ NEXT_PUBLIC_ANYSPEND_BASE_URL=https://your-custom-anyspend-api.com
310
+ ```
311
+
312
+ ### Network Configuration
313
+
314
+ AnySpend automatically configures API endpoints based on the `isMainnet` parameter:
315
+
316
+ - **Mainnet**: `https://anyspend-mainnet.up.railway.app`
317
+ - **Testnet**: `https://anyspend-testnet.up.railway.app`
318
+
319
+ ## 💼 Common Use Cases
320
+
321
+ ### 1. Cross-Chain Token Swap
322
+
323
+ ```tsx
324
+ import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
325
+
326
+ function TokenSwap() {
327
+ return (
328
+ <AnySpend
329
+ mode="page"
330
+ recipientAddress="0x..."
331
+ onSuccess={txHash => {
332
+ console.log("Swap completed:", txHash);
333
+ // Redirect user or show success message
334
+ }}
335
+ />
336
+ );
337
+ }
338
+ ```
339
+
340
+ ### 2. NFT Marketplace Integration
341
+
342
+ ```tsx
343
+ import { AnySpendNFT } from "@b3dotfun/sdk/anyspend/react";
344
+
345
+ function NFTCard({ nft }) {
346
+ return (
347
+ <div className="nft-card">
348
+ <img src={nft.imageUrl} alt={nft.name} />
349
+ <h3>{nft.name}</h3>
350
+ <p>{nft.description}</p>
351
+ <AnySpendNFT
352
+ nftContract={nft}
353
+ recipientAddress={userAddress}
354
+ onSuccess={txHash => {
355
+ // Update UI to show NFT as owned
356
+ updateNFTOwnership(nft.id, userAddress);
357
+ }}
358
+ />
359
+ </div>
360
+ );
361
+ }
362
+ ```
363
+
364
+ ### 3. Custom Contract Interaction - Staking Example
365
+
366
+ ```tsx
367
+ import { AnySpendCustom, OrderType } from "@b3dotfun/sdk/anyspend/react";
368
+
369
+ function StakingInterface({ stakingContract }) {
370
+ return (
371
+ <AnySpendCustom
372
+ orderType={OrderType.Custom}
373
+ dstChainId={stakingContract.chainId}
374
+ dstToken={stakingContract.stakingToken}
375
+ dstAmount={stakingContract.stakeAmount}
376
+ contractAddress={stakingContract.contractAddress}
377
+ encodedData={stakingContract.stakeCalldata} // encoded stake() function call
378
+ metadata={{
379
+ action: "stake",
380
+ staking: {
381
+ contractAddress: stakingContract.contractAddress,
382
+ amount: stakingContract.stakeAmount,
383
+ duration: stakingContract.duration
384
+ }
385
+ }}
386
+ header={({ anyspendPrice }) => (
387
+ <div className="staking-header">
388
+ <h2>Stake {stakingContract.stakingToken.symbol}</h2>
389
+ <p>
390
+ Amount: {stakingContract.stakeAmountFormatted} {stakingContract.stakingToken.symbol}
391
+ </p>
392
+ <p>Duration: {stakingContract.duration} days</p>
393
+ </div>
394
+ )}
395
+ onSuccess={txHash => {
396
+ console.log("Staking completed:", txHash);
397
+ // Update UI to show staked amount
398
+ }}
399
+ />
400
+ );
401
+ }
402
+ ```
403
+
404
+ ### 4. Fiat to Crypto Onramp
405
+
406
+ ```tsx
407
+ import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
408
+
409
+ function FiatOnramp() {
410
+ return (
411
+ <AnySpend
412
+ defaultActiveTab="fiat"
413
+ destinationTokenAddress="0x..." // Target token to buy
414
+ destinationTokenChainId={8333}
415
+ recipientAddress="0x..."
416
+ onSuccess={txHash => {
417
+ console.log("Fiat purchase completed:", txHash);
418
+ }}
419
+ />
420
+ );
421
+ }
422
+ ```
423
+
424
+ ## ⚠️ Error Handling
425
+
426
+ ### Order Status Types
427
+
428
+ AnySpend orders go through various states:
429
+
430
+ ```typescript
431
+ enum OrderStatus {
432
+ // Preparation
433
+ ScanningDepositTransaction = "scanning_deposit_transaction",
434
+ WaitingStripePayment = "waiting_stripe_payment",
435
+ ObtainToken = "obtain_token",
436
+
437
+ // Execution
438
+ SendingTokenFromVault = "sending_token_from_vault",
439
+ Relay = "relay",
440
+ Executed = "executed",
441
+
442
+ // Failure/Refund
443
+ ObtainFailed = "obtain_failed",
444
+ Expired = "expired",
445
+ Refunding = "refunding",
446
+ Refunded = "refunded",
447
+ Failure = "failure"
448
+ }
449
+ ```
450
+
451
+ ### Common Error Codes
452
+
453
+ | Error Code | Description | Recovery Strategy |
454
+ | ---------------------- | --------------------------------- | ------------------------------------ |
455
+ | `SLIPPAGE` | Price movement exceeded tolerance | Retry with higher slippage tolerance |
456
+ | `INSUFFICIENT_BALANCE` | User doesn't have enough tokens | Request user to add funds |
457
+ | `NETWORK_ERROR` | RPC or network issues | Retry after a delay |
458
+ | `QUOTE_EXPIRED` | Price quote is no longer valid | Get a fresh quote |
459
+
460
+ ### Error Handling Best Practices
461
+
462
+ ```tsx
463
+ import { useAnyspendCreateOrder } from "@b3dotfun/sdk/anyspend";
464
+
465
+ const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({
466
+ onError: error => {
467
+ switch (error.message) {
468
+ case "SLIPPAGE":
469
+ toast.error("Price moved unfavorably. Please try again.");
470
+ break;
471
+ case "INSUFFICIENT_BALANCE":
472
+ toast.error("Insufficient balance. Please add funds to your wallet.");
473
+ break;
474
+ default:
475
+ toast.error("Transaction failed. Please try again or contact support.");
476
+ }
477
+
478
+ // Log for debugging
479
+ console.error("Order creation failed:", error);
480
+
481
+ // Optional: Send to error tracking service
482
+ // errorTracking.captureException(error);
483
+ }
484
+ });
485
+ ```
486
+
487
+ ### Order Monitoring
488
+
489
+ ```tsx
490
+ import { useAnyspendOrderAndTransactions, OrderStatus } from "@b3dotfun/sdk/anyspend";
491
+
492
+ function OrderTracker({ orderId }) {
493
+ const { orderAndTransactions } = useAnyspendOrderAndTransactions(true, orderId);
494
+
495
+ if (!orderAndTransactions) return <div>Loading...</div>;
496
+
497
+ const { order, depositTxs, executeTx, refundTxs } = orderAndTransactions.data;
498
+
499
+ const getStatusMessage = (status: OrderStatus) => {
500
+ switch (status) {
501
+ case OrderStatus.ScanningDepositTransaction:
502
+ return "Waiting for payment confirmation...";
503
+ case OrderStatus.Relay:
504
+ return "Processing your transaction...";
505
+ case OrderStatus.Executed:
506
+ return "Transaction completed successfully!";
507
+ case OrderStatus.Failure:
508
+ return "Transaction failed. You will be refunded automatically.";
509
+ case OrderStatus.Refunded:
510
+ return "Refund processed successfully.";
511
+ default:
512
+ return "Processing...";
513
+ }
514
+ };
515
+
516
+ return (
517
+ <div className="order-status">
518
+ <h3>Order Status: {order.status}</h3>
519
+ <p>{getStatusMessage(order.status)}</p>
520
+
521
+ {order.errorDetails && (
522
+ <div className="error-details">
523
+ <strong>Error:</strong> {order.errorDetails}
524
+ </div>
525
+ )}
526
+
527
+ {executeTx && (
528
+ <a href={`https://explorer.b3.fun/tx/${executeTx.txHash}`} target="_blank" rel="noopener noreferrer">
529
+ View Transaction
530
+ </a>
531
+ )}
532
+ </div>
533
+ );
534
+ }
535
+ ```
536
+
537
+ ## 🌐 Platform Support
538
+
539
+ | Feature | React Web | React Native |
540
+ | ----------------- | --------- | ------------ |
541
+ | Core AnySpend | ✅ | ✅ |
542
+ | React Components | ✅ | ✅ |
543
+ | Fiat Onramp | ✅ | ❌ |
544
+ | NFT Components | ✅ | ✅ |
545
+ | Service Functions | ✅ | ✅ |
546
+
547
+ ## 🐛 Troubleshooting
548
+
549
+ ### Common Issues
550
+
551
+ **Q: "Get rate error" appears when trying to swap**
552
+
553
+ ```
554
+ A: This usually means:
555
+ 1. Invalid token addresses
556
+ 2. Unsupported token pair
557
+ 3. Amount too small/large
558
+ 4. Network connectivity issues
559
+
560
+ Check that both tokens are supported and try with a different amount.
561
+ ```
562
+
563
+ **Q: Order stuck in "scanning_deposit_transaction" status**
564
+
565
+ ```
566
+ A: This means AnySpend is waiting for your deposit transaction to be confirmed.
567
+ Check that:
568
+ 1. You sent the correct amount
569
+ 2. Transaction was confirmed on-chain
570
+ 3. You sent to the correct address
571
+
572
+ Orders will auto-refund after 30 minutes if no deposit is detected.
573
+ ```
574
+
575
+ **Q: React Native build issues**
576
+
577
+ ```
578
+ A: Make sure you're importing from the correct entry point:
579
+
580
+ // ✅ Correct
581
+ import { anyspendService } from "@b3dotfun/sdk/anyspend";
582
+
583
+ // ❌ Incorrect for React Native
584
+ import { AnySpend } from "@b3dotfun/sdk/anyspend/react";
585
+ ```
586
+
587
+ ### Debug Mode
588
+
589
+ Enable debug logging to troubleshoot issues:
590
+
591
+ ```typescript
592
+ // Add to your app initialization
593
+ localStorage.setItem("debug", "anyspend:*");
594
+
595
+ // Or in React Native
596
+ import { anyspendService } from "@b3dotfun/sdk/anyspend";
597
+
598
+ // Service calls will now log detailed information
599
+ const quote = await anyspendService.getQuote(true, quoteRequest);
600
+ ```
601
+
602
+ ### Support Channels
603
+
604
+ - **Documentation**: [https://docs.b3.fun](https://docs.b3.fun)
605
+ - **GitHub Issues**: [https://github.com/b3-fun/b3/issues](https://github.com/b3-fun/b3/issues)
606
+ - **Discord**: [https://discord.gg/b3dotfun](https://discord.gg/b3dotfun)
607
+
608
+ ## 🤝 Contributing
609
+
610
+ We welcome contributions! Here's how to get started:
611
+
612
+ 1. **Fork the repository**
613
+ 2. **Create a feature branch**: `git checkout -b feature/amazing-feature`
614
+ 3. **Install dependencies**: `pnpm install`
615
+ 4. **Run tests**: `pnpm test`
616
+ 5. **Build the SDK**: `pnpm sdk:build`
617
+ 6. **Test your changes** in the example apps
618
+ 7. **Submit a pull request**
619
+
620
+ ### Development Setup
621
+
622
+ ```bash
623
+ # Clone the repo
624
+ git clone https://github.com/b3-fun/b3.git
625
+ cd b3
626
+
627
+ # Install dependencies
628
+ pnpm install
629
+
630
+ # Start development
631
+ pnpm dev
632
+
633
+ # Build the SDK
634
+ pnpm sdk:build
635
+ ```