From 388fa841358f8a0b553479f4e2df90e1054cdb3b Mon Sep 17 00:00:00 2001 From: pinkhoodie Date: Thu, 13 Mar 2025 21:52:10 -0400 Subject: [PATCH 1/5] code snippets for use case examples --- .../portal/src/app/insight/use-cases/page.mdx | 424 +++++++++++++++++- 1 file changed, 417 insertions(+), 7 deletions(-) diff --git a/apps/portal/src/app/insight/use-cases/page.mdx b/apps/portal/src/app/insight/use-cases/page.mdx index 278a7812811..bdc99ec6536 100644 --- a/apps/portal/src/app/insight/use-cases/page.mdx +++ b/apps/portal/src/app/insight/use-cases/page.mdx @@ -14,49 +14,459 @@ export const metadata = createMetadata({ ## Gaming ### Show assets owned by players -In blockchain games, players often own digital assets such as in-game items or tokens. To display these assets, the events blueprint can track Transfer events of ERC-721 (NFT) or ERC-1155 tokens, allowing you to determine which assets belong to each player’s wallet. -- The Events blueprint can be used to fetch Transfer events where the player’s wallet is the recipient, showing all NFTs or in-game items acquired by the player. +In blockchain games, players often own digital assets such as in-game items or tokens. To display these assets, the events blueprint can track Transfer events of ERC-721 (NFT) or ERC-1155 tokens, allowing you to determine which assets belong to each player's wallet. +- The Events blueprint can be used to fetch Transfer events where the player's wallet is the recipient, showing all NFTs or in-game items acquired by the player. + +```typescript +const getPlayerAssets = async (playerAddress, gameContractAddress) => { + try { + // Use the events blueprint to get all Transfer events where the player is the recipient + const response = await fetch( + `https://1.insight.thirdweb.com/v1/events/${gameContractAddress}/Transfer(address,address,uint256)?to=${playerAddress}&limit=100`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const assets = await response.json(); + return assets; + } catch (error) { + console.error('Error fetching player assets:', error); + } +}; +``` ### Show users the tokens they earned -Some games reward players with tokens based on achievements or progress. Using the transactions blueprint, you can display these earned tokens by tracking transactions where the game’s smart contract sends tokens to the player’s wallet. +Some games reward players with tokens based on achievements or progress. Using the transactions blueprint, you can display these earned tokens by tracking transactions where the game's smart contract sends tokens to the player's wallet. - Transactions Blueprint: Shows all transactions where the game contract transfers tokens to players. -- Events Blueprint: Filters Transfer events from the game’s contract to list all tokens awarded to players. +- Events Blueprint: Filters Transfer events from the game's contract to list all tokens awarded to players. + +```typescript +const getPlayerTokenRewards = async (playerAddress, gameContractAddress) => { + try { + // Using transactions blueprint to see all token transfers from game contract to player + const txResponse = await fetch( + `https://1.insight.thirdweb.com/v1/transactions?from=${gameContractAddress}&to=${playerAddress}&limit=50`, + { + headers: { + 'x-client-id': '' + } + } + ); + + // Using events blueprint to get Transfer events specifically + const eventsResponse = await fetch( + `https://1.insight.thirdweb.com/v1/events/${gameContractAddress}/Transfer(address,address,uint256)?from=${gameContractAddress}&to=${playerAddress}&limit=50`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const transactions = await txResponse.json(); + const events = await eventsResponse.json(); + + return { + transactions: transactions.data, + events: events.data + }; + } catch (error) { + console.error('Error fetching player rewards:', error); + } +}; +``` ## DeFi ### Analyse Token Economics e.g. USDC 24h volume -Token economics, like daily trading volume, helps in understanding a token’s liquidity and market activity. By using the transactions blueprint users can get transactions involving USDC and then aggregating data based on timestamps, you can calculate 24-hour transaction volume. +Token economics, like daily trading volume, helps in understanding a token's liquidity and market activity. By using the transactions blueprint users can get transactions involving USDC and then aggregating data based on timestamps, you can calculate 24-hour transaction volume. - Transactions Blueprint: Retrieves all USDC transactions in the past 24 hours, enabling calculation of volume and other economic indicators. +```typescript +const getUSDC24hVolume = async () => { + try { + const usdcAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'; // USDC on Ethereum + const now = Math.floor(Date.now() / 1000); + const oneDayAgo = now - 86400; // 24 hours in seconds + + // Get all transactions involving USDC in the last 24 hours + const response = await fetch( + `https://1.insight.thirdweb.com/v1/transactions?to=${usdcAddress}&from_timestamp=${oneDayAgo}&to_timestamp=${now}&limit=1000`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const txData = await response.json(); + + // Calculate total volume by summing the value of all transactions + const totalVolume = txData.data.reduce((sum, tx) => sum + BigInt(tx.value), BigInt(0)); + + return { + volume: totalVolume.toString(), + transactionCount: txData.data.length, + startTime: oneDayAgo, + endTime: now + }; + } catch (error) { + console.error('Error calculating USDC volume:', error); + } +}; +``` + ### Optimize protocol gas efficiency DeFi protocols aim to minimize gas fees for users. Using the transactions blueprint allow users to analyze the gas consumption of different transactions, you can identify areas where gas optimization is possible by evaluating high-gas transactions or commonly used functions. - Transactions Blueprint: Summarizes gas usage across transactions for specific functions, helping to analyze and optimize protocol functions for efficiency. +```typescript +const analyzeProtocolGasUsage = async (protocolAddress, days = 7) => { + try { + const now = Math.floor(Date.now() / 1000); + const startTime = now - (days * 86400); // Convert days to seconds + + // Get all transactions for the protocol in the specified period + const response = await fetch( + `https://1.insight.thirdweb.com/v1/transactions?to=${protocolAddress}&from_timestamp=${startTime}&to_timestamp=${now}&limit=500`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const txData = await response.json(); + + // Group transactions by function signature (first 10 bytes of data) + const functionGasUsage = {}; + + txData.data.forEach(tx => { + const functionSignature = tx.data.slice(0, 10); // Get first 10 bytes + if (!functionGasUsage[functionSignature]) { + functionGasUsage[functionSignature] = { + count: 0, + totalGas: BigInt(0), + avgGas: 0, + maxGas: BigInt(0) + }; + } + + const gas = BigInt(tx.gas); + functionGasUsage[functionSignature].count += 1; + functionGasUsage[functionSignature].totalGas += gas; + functionGasUsage[functionSignature].avgGas = Number(functionGasUsage[functionSignature].totalGas) / functionGasUsage[functionSignature].count; + + if (gas > functionGasUsage[functionSignature].maxGas) { + functionGasUsage[functionSignature].maxGas = gas; + } + }); + + return { + totalTransactions: txData.data.length, + period: `${days} days`, + functionGasUsage + }; + } catch (error) { + console.error('Error analyzing gas usage:', error); + } +}; +``` + ### Analyse Token ownership Understanding who holds a token (e.g., whales, retail investors) is crucial in DeFi to gauge community health and investment risk. The events blueprint helps track token transfer events, where users can analyze the distribution and concentration of token holders. - Events Blueprint: Retrieves Transfer events to build a map of current token holders, showing distributions among wallets. +```typescript +const analyzeTokenOwnership = async (tokenAddress, limit = 1000) => { + try { + // Get Transfer events for the token + const response = await fetch( + `https://1.insight.thirdweb.com/v1/events/${tokenAddress}/Transfer(address,address,uint256)?limit=${limit}`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const events = await response.json(); + + // Build a map of token holders and their balances + const holders = {}; + + events.data.forEach(event => { + // Extract from and to addresses from topics + const fromAddress = '0x' + event.topics[1].slice(26); + const toAddress = '0x' + event.topics[2].slice(26); + const amount = BigInt(event.data); + + // Subtract from sender + if (holders[fromAddress]) { + holders[fromAddress] = holders[fromAddress] - amount; + } else { + holders[fromAddress] = BigInt(0) - amount; + } + + // Add to recipient + if (holders[toAddress]) { + holders[toAddress] = holders[toAddress] + amount; + } else { + holders[toAddress] = amount; + } + }); + + // Filter out zero balances and sort by amount + const sortedHolders = Object.entries(holders) + .filter(([_, balance]) => balance > 0) + .sort((a, b) => (b[1] > a[1] ? 1 : -1)); + + return { + totalHolders: sortedHolders.length, + topHolders: sortedHolders.slice(0, 10) // Top 10 holders + }; + } catch (error) { + console.error('Error analyzing token ownership:', error); + } +}; +``` + ## NFTs ### Get all transfers of an NFT collection To track the movement of an entire NFT collection, users can use the events blueprint to capture all Transfer events for that collection. This helps show ownership history or current trading volume for the collection. - Events Blueprint: Queries Transfer events by contract address, returning each transfer for the NFT collection. +```typescript +const getNFTCollectionTransfers = async (collectionAddress, limit = 100) => { + try { + // Get all Transfer events for the NFT collection + const response = await fetch( + `https://1.insight.thirdweb.com/v1/events/${collectionAddress}/Transfer(address,address,uint256)?limit=${limit}`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const transfers = await response.json(); + + // Process the transfers to extract relevant information + const processedTransfers = transfers.data.map(event => { + return { + tokenId: BigInt(event.data).toString(), + from: '0x' + event.topics[1].slice(26), + to: '0x' + event.topics[2].slice(26), + blockNumber: event.block_number, + timestamp: event.block_timestamp, + transactionHash: event.transaction_hash + }; + }); + + return { + collection: collectionAddress, + transfers: processedTransfers + }; + } catch (error) { + console.error('Error fetching NFT transfers:', error); + } +}; +``` + ### Get All NFTs owned by address To show all NFTs owned by a user, users can use the events blueprint to fetch Transfer events where the specified address is the recipient. This shows a complete list of NFTs in their wallet. - Events Blueprint: Retrieves Transfer events for each NFT contract where the wallet address is the recipient. +```typescript +const getNFTsOwnedByAddress = async (ownerAddress) => { + try { + // Use the tokens blueprint to get all ERC-721 tokens owned by the address + const response = await fetch( + `https://1.insight.thirdweb.com/v1/tokens/erc721/${ownerAddress}`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const nfts = await response.json(); + + // Process the results to make them more readable + const processedNFTs = nfts.map(nft => { + return { + collectionAddress: nft.collectionAddress, + tokenId: nft.tokenId, + balance: nft.balance + }; + }); + + return { + owner: ownerAddress, + nftCount: processedNFTs.length, + nfts: processedNFTs + }; + } catch (error) { + console.error('Error fetching owned NFTs:', error); + } +}; +``` + ## Wallets ### Get all transactions performed by a wallet cross chain Wallet activity often spans multiple chains. By using the transactions blueprint with the wallet address across different chain_ids, users can retrieve a cross-chain view of all transactions for that wallet. - Transactions Blueprint: Filters transactions by wallet address and chain ID, providing a history of cross-chain transactions. +```typescript +const getWalletCrossChainTransactions = async (walletAddress, limit = 100) => { + try { + // Query transactions across Ethereum, Polygon, and Arbitrum + const chainIds = [1, 137, 42161]; // Ethereum, Polygon, Arbitrum + + // Use multichain query format + const queryParams = chainIds.map(chain => `chain=${chain}`).join('&'); + + const response = await fetch( + `https://insight.thirdweb.com/v1/transactions?${queryParams}&from=${walletAddress}&limit=${limit}`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const transactions = await response.json(); + + // Group transactions by chain + const transactionsByChain = {}; + + chainIds.forEach(chainId => { + transactionsByChain[chainId] = transactions.data.filter(tx => tx.chain_id === chainId); + }); + + return { + wallet: walletAddress, + totalTransactions: transactions.data.length, + transactionsByChain + }; + } catch (error) { + console.error('Error fetching cross-chain transactions:', error); + } +}; +``` + ### Get all ERC-20 tokens owned by a wallet This allows users to see all ERC-20 tokens they own. By using the events blueprint to find Transfer events where the wallet address is the recipient, you can list each ERC-20 token held by that wallet. - Events Blueprint: Tracks Transfer events of ERC-20 tokens to the wallet address, providing a list of token balances. +```typescript +const getERC20TokensOwnedByWallet = async (walletAddress) => { + try { + // Use the tokens blueprint to get all ERC-20 tokens owned by the address + const response = await fetch( + `https://1.insight.thirdweb.com/v1/tokens/erc20/${walletAddress}`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const tokens = await response.json(); + + // Process the results to make them more readable + const processedTokens = tokens.map(token => { + return { + tokenAddress: token.tokenAddress, + balance: token.balance + }; + }); + + return { + wallet: walletAddress, + tokenCount: processedTokens.length, + tokens: processedTokens + }; + } catch (error) { + console.error('Error fetching owned ERC-20 tokens:', error); + } +}; +``` + ### Detect wallet staking activity (e.g. AAVE) -To identify staking activity in AAVE or any DeFi protocol, users can use the events blueprint to watch for staking-related events, such as Deposit or Stake events on any protocol e.g. AAVE’s smart contracts. This helps monitor which wallets are actively staking assets. -- Events Blueprint: Filters by staking events on AAVE’s staking contracts for the wallet address, providing insights into wallet staking activity. +To identify staking activity in AAVE or any DeFi protocol, users can use the events blueprint to watch for staking-related events, such as Deposit or Stake events on any protocol e.g. AAVE's smart contracts. This helps monitor which wallets are actively staking assets. +- Events Blueprint: Filters by staking events on AAVE's staking contracts for the wallet address, providing insights into wallet staking activity. + +```typescript +const detectAAVEStakingActivity = async (walletAddress) => { + try { + // AAVE staking contract address (for example purposes) + const aaveStakingAddress = '0x4da27a545c0c5B758a6BA100e3a049001de870f5'; + + // Get Stake events where the wallet is involved + const stakeResponse = await fetch( + `https://1.insight.thirdweb.com/v1/events/${aaveStakingAddress}/Stake(address,address,uint256,uint256)?user=${walletAddress}&limit=50`, + { + headers: { + 'x-client-id': '' + } + } + ); + + // Get Redeem events where the wallet is involved + const redeemResponse = await fetch( + `https://1.insight.thirdweb.com/v1/events/${aaveStakingAddress}/Redeem(address,address,uint256)?user=${walletAddress}&limit=50`, + { + headers: { + 'x-client-id': '' + } + } + ); + + const stakeEvents = await stakeResponse.json(); + const redeemEvents = await redeemResponse.json(); + + // Process stake events + const stakes = stakeEvents.data.map(event => { + // Parse event data based on AAVE staking event structure + return { + type: 'stake', + amount: BigInt(event.data).toString(), + blockNumber: event.block_number, + timestamp: event.block_timestamp, + transactionHash: event.transaction_hash + }; + }); + + // Process redeem events + const redeems = redeemEvents.data.map(event => { + // Parse event data based on AAVE staking event structure + return { + type: 'redeem', + amount: BigInt(event.data).toString(), + blockNumber: event.block_number, + timestamp: event.block_timestamp, + transactionHash: event.transaction_hash + }; + }); + + // Combine and sort all events by timestamp + const allEvents = [...stakes, ...redeems].sort((a, b) => a.timestamp - b.timestamp); + + return { + wallet: walletAddress, + stakingActivity: allEvents, + totalStakeEvents: stakes.length, + totalRedeemEvents: redeems.length + }; + } catch (error) { + console.error('Error detecting AAVE staking activity:', error); + } +}; +``` From 6f087b5870b3c8d27145ca3e374b77c2977572ba Mon Sep 17 00:00:00 2001 From: pinkhoodie Date: Tue, 18 Mar 2025 13:30:32 -0400 Subject: [PATCH 2/5] FAQ pages for Ecosystem and In-App Wallets --- apps/portal/src/app/connect/sidebar.tsx | 8 +++ .../app/connect/wallet/ecosystem/faq/page.mdx | 58 +++++++++++++++++++ .../src/app/connect/wallet/faq/page.mdx | 57 ------------------ .../connect/wallet/in-app-wallet/faq/page.mdx | 32 ++++++++++ 4 files changed, 98 insertions(+), 57 deletions(-) create mode 100644 apps/portal/src/app/connect/wallet/ecosystem/faq/page.mdx create mode 100644 apps/portal/src/app/connect/wallet/in-app-wallet/faq/page.mdx diff --git a/apps/portal/src/app/connect/sidebar.tsx b/apps/portal/src/app/connect/sidebar.tsx index ad6bacd3ef7..d15262cc5c1 100644 --- a/apps/portal/src/app/connect/sidebar.tsx +++ b/apps/portal/src/app/connect/sidebar.tsx @@ -75,6 +75,10 @@ export const sidebar: SideBar = { name: "Guest Mode", href: `${walletSlug}/sign-in-methods/guest`, }, + { + name: "FAQ", + href: `${walletSlug}/in-app-wallet/faq`, + }, { name: "Custom Authentication", links: [ @@ -130,6 +134,10 @@ export const sidebar: SideBar = { name: "Register with WalletConnect", href: `${walletSlug}/ecosystem/register-walletconnect`, }, + { + name: "FAQ", + href: `${walletSlug}/ecosystem/faq`, + }, ], }, //Account abstraction diff --git a/apps/portal/src/app/connect/wallet/ecosystem/faq/page.mdx b/apps/portal/src/app/connect/wallet/ecosystem/faq/page.mdx new file mode 100644 index 00000000000..c94bd9c47db --- /dev/null +++ b/apps/portal/src/app/connect/wallet/ecosystem/faq/page.mdx @@ -0,0 +1,58 @@ +import { createMetadata } from "@doc"; + +export const metadata = createMetadata({ + title: "Ecosystem Wallet FAQs", + description: "Frequently asked questions about thirdweb's Ecosystem Wallet", + image: { + title: "FAQs for thirdweb Ecosystem Wallet", + icon: "wallets", + }, +}); + +# Ecosystem Wallet FAQs + +### What is an Ecosystem Wallet? + +An ecosystem wallet is a managed in-app wallet service that allows platforms to create a branded wallet and login system, manage their partners, and allow any number of partners to spin up in-app wallets. End users that create in-app wallets through your partner applications (either with email, phone number, passkey, or socials) will receive **one account and wallet address** that they can access across the entire ecosystem. + +### How do Ecosystem Wallets work? + +Ecosystem Wallets are a fully managed and containerized in-app wallet backend service that is white labeled to your application. By giving you access to this backend service, you can power any application with in-app wallets just like thirdweb does for over 70,000 developers. + +### What is an Ecosystem Partner? + +Ecosystem partners are games or applications that you have permissioned to spin up in-app wallets underneath your brand. They will have access to the same account (funds, assets, etc.) for any end users that 1) use your branded login system or 2) log in with your wallet. + +You can manage ecosystem partners in the Permissions tab of your Ecosystem Wallet dashboard. + +### Which login providers can display my Ecosystem Wallet? + +thirdweb Connect, with WalletConnect and any wagmi- or viem-based login providers coming soon. + +### How can Partners integrate my Ecosystem Wallet? + +Partners can integrate your Ecosystem Wallet in three different ways: + +**Login System** + +Partners can install thirdweb SDK and use the Partner ID you created for them to display your branded sign in flow. All login options in this sign in flow will create an in-app wallet. + +**Branded Wallet Connector** + +Partners can add your wallet as a wallet connector option in their existing sign in flow on any domains they've whitelisted by calling the follow endpoint from their application. + +**WalletConnect (Coming Soon)** + +Partners using WalletConnect will automatically display your wallet as a WalletConnect option on any domains they've whitelisted. + +### What is the difference between Anyone and Allowlist scopes for Ecosystem Wallet? + +The **Anyone** scope allows any developer to integrate your ecosystem wallet, even if you have not given them permission. Any developer with thirdweb Connect, for example, would now display your wallet as a login option. + +The **Allowlist** scope allows developers that you have explicitly added to your list of Partners to display your wallet as a login option. + +You can manage scope in the Permissions tab of your Ecosystem Wallet dashboard. + +### How does billing work for Ecosystem Wallets? + +As the ecosystem admin, you will be billed $250 monthly for your Ecosystem Wallet. This allows any application or game in your ecosystem generate in-app wallets. Each month, we allow you and your ecosystem partners to generate 30,000 wallets for free. Once you've generated 30,000 wallets, you will be charged $0.02 per in-app wallet. At the end of each month, we will provide you with an invoice with a usage breakdown across all partners. \ No newline at end of file diff --git a/apps/portal/src/app/connect/wallet/faq/page.mdx b/apps/portal/src/app/connect/wallet/faq/page.mdx index 7a8b865c34b..45ffecbac4b 100644 --- a/apps/portal/src/app/connect/wallet/faq/page.mdx +++ b/apps/portal/src/app/connect/wallet/faq/page.mdx @@ -57,63 +57,6 @@ Currently, users will rely on the built-in recovery of their auth method. Refer Users can also link their account to a different auth method (e.g. email, phone, or social). All linked methods will be able to be used to access their accounts, providing an alternate recovery method in the case where one is lost. -# In App Wallet FAQs - -### How do users connect to their in-app wallet in a third-party app? - -Users can access it by doing a manual connection via wallet connect. They will then have to use the connect button or embed and select manage wallet -> connect an App. - -### How is pricing calculated for in-app wallets? - -In-app wallets are billed based on "monthly active wallets". An active wallet is defined as a wallet where a user logs in during the billing period. In-app wallets are completely free up to 1,000 monthly active wallets, and $0.02 per wallet after that. - -# Ecosystem Wallet FAQs - -### What is an Ecosystem Wallet? - -An ecosystem wallet is a managed in-app wallet service that allows you to create a branded wallet and login system, manage your partners, and allow any number of partners to spin up in-app wallets. End users that create in-app wallets through your partner applications (either with email, phone number, passkey, or socials) will receive **one account and wallet address** that they can access across the entire ecosystem. - -### How do Ecosystem Wallets work? - -Ecosystem Wallets are a fully managed and containerized in-app wallet backend service that is white labeled to your application. By giving you access to this backend service, you can power any application with in-app wallets just like thirdweb does for over 70,000 developers. - -### What is an Ecosystem Partner? - -Ecosystem partners are games or applications that you have permissioned to spin up in-app wallets underneath your brand. They will have access to the same account (funds, assets, etc.) for any end users that 1) use your branded login system or 2) log in with your wallet. - -You can manage ecosystem partners in the Permissions tab of your Ecosystem Wallet dashboard. - -### Which login providers can display my Ecosystem Wallet? - -thirdweb Connect, with WalletConnect and any wagmi- or viem-based login providers coming soon. - -### How can Partners integrate my Ecosystem Wallet? - -Partners can integrate your Ecosystem Wallet in three different ways: - -**Login System** - -Partners can install thirdweb SDK and use the Partner ID you created for them to display your branded sign in flow. All login options in this sign in flow will create an in-app wallet. - -**Branded Wallet Connector** - -Partners can add your wallet as a wallet connector option in their existing sign in flow on any domains they've whitelisted by calling the follow endpoint from their application. - -**WalletConnect (Coming Soon)** - -Partners using WalletConnect will automatically display your wallet as a WalletConnect option on any domains they've whitelisted. - -### What is the difference between Anyone and Allowlist scopes for Ecosystem Wallet? - -The **Anyone** scope allows any developer to integrate your ecosystem wallet, even if you have not given them permission. Any developer with thirdweb Connect, for example, would now display your wallet as a login option. - -The **Allowlist** scope allows developers that you have explicitly added to your list of Partners to display your wallet as a login option. - -You can manage scope in the Permissions tab of your Ecosystem Wallet dashboard. - -### How does billing work for Ecosystem Wallets? - -As the ecosystem admin, you will be billed $250 monthly for your Ecosystem Wallet. This allows any application or game in your ecosystem generate in-app wallets. Each month, we allow you and your ecosystem partners to generate 30,000 wallets for free. Once you’ve generated 30,000 wallets, you will be charged $0.02 per in-app wallet. At the end of each month, we will provide you with an invoice with a usage breakdown across all partners. # Security FAQs diff --git a/apps/portal/src/app/connect/wallet/in-app-wallet/faq/page.mdx b/apps/portal/src/app/connect/wallet/in-app-wallet/faq/page.mdx new file mode 100644 index 00000000000..e3762468af3 --- /dev/null +++ b/apps/portal/src/app/connect/wallet/in-app-wallet/faq/page.mdx @@ -0,0 +1,32 @@ +import { createMetadata } from "@doc"; + +export const metadata = createMetadata({ + title: "In-App Wallet FAQs", + description: "Frequently asked questions about thirdweb's In-App Wallet", + image: { + title: "FAQs for thirdweb In-App Wallet", + icon: "wallets", + }, +}); + +# In-App Wallet FAQs + +### How do users connect to their in-app wallet in a third-party app? + +Users can access it by doing a manual connection via wallet connect. They will then have to use the connect button or embed and select manage wallet -> connect an App. + +### How is pricing calculated for in-app wallets? + +In-app wallets are billed based on "monthly active wallets". An active wallet is defined as a wallet where a user logs in during the billing period. In-app wallets are completely free up to 1,000 monthly active wallets, and $0.02 per wallet after that. + +### What security measures should users take when connecting their in-app wallet? + +Users should always verify they are connecting to legitimate websites by checking the URL carefully. Never connect to unverified or suspicious websites. The connection process should only be initiated through the official WalletConnect interface or trusted dApp integrations. + +### Can developers integrate both in-app wallets and external wallets in the same application? + +Yes, developers can build a unified experience that supports both in-app wallets and external wallets (like MetaMask) using the same code base. The SDK provides a wallet signer that handles how all wallet types interact with signatures and smart contracts consistently, though the initial connection flow will differ by wallet type. + +### What blockchain networks are supported for in-app wallet connections? + +In-app wallets are fully EVM (Ethereum Virtual Machine) compatible and support all EVM chains. This includes major networks like Ethereum Mainnet, Polygon, Optimism, Base, and other EVM-compatible blockchains. \ No newline at end of file From 268c7ef52faff3d94b30f5c6f8b44bda6cc3e5b5 Mon Sep 17 00:00:00 2001 From: pinkhoodie Date: Tue, 18 Mar 2025 13:33:50 -0400 Subject: [PATCH 3/5] Pay -> Universal Bridge --- apps/portal/src/app/connect/pay/get-started/page.mdx | 2 +- apps/portal/src/app/connect/pay/testing-pay/page.mdx | 2 +- apps/portal/src/app/dotnet/pay/quickstart/page.mdx | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/portal/src/app/connect/pay/get-started/page.mdx b/apps/portal/src/app/connect/pay/get-started/page.mdx index c631050fb09..8d597f85ff8 100644 --- a/apps/portal/src/app/connect/pay/get-started/page.mdx +++ b/apps/portal/src/app/connect/pay/get-started/page.mdx @@ -46,7 +46,7 @@ Log in to [the thirdweb dashboard](https://thirdweb.com/team). Navigate to the * ## Option 1: ConnectButton -Pay is available by default with our `ConnectButton` component. When users log in with Connect, they'll be able to onramp and purchase crypto directly from the logged in Connect interface. You can read more about `ConnectButton` [in this guide](/connect/sign-in/ConnectButton). +Universal Bridge is available by default with our `ConnectButton` component. When users log in with Connect, they'll be able to onramp and purchase crypto directly from the logged in Connect interface. You can read more about `ConnectButton` [in this guide](/connect/sign-in/ConnectButton). ```tsx import { ThirdwebProvider, ConnectButton } from "thirdweb/react"; diff --git a/apps/portal/src/app/connect/pay/testing-pay/page.mdx b/apps/portal/src/app/connect/pay/testing-pay/page.mdx index 1d9dede41b3..1d88ab73481 100644 --- a/apps/portal/src/app/connect/pay/testing-pay/page.mdx +++ b/apps/portal/src/app/connect/pay/testing-pay/page.mdx @@ -3,7 +3,7 @@ import { createMetadata, Callout } from "@doc"; export const metadata = createMetadata({ image: { - title: "thirdweb Pay - Test Mode", + title: "thirdweb Universal Bridge - Test Mode", icon: "thirdweb", }, title: "Enable Test Mode for Universal bridge — thirdweb docs", diff --git a/apps/portal/src/app/dotnet/pay/quickstart/page.mdx b/apps/portal/src/app/dotnet/pay/quickstart/page.mdx index a834b4b82b6..8cfadfed4cb 100644 --- a/apps/portal/src/app/dotnet/pay/quickstart/page.mdx +++ b/apps/portal/src/app/dotnet/pay/quickstart/page.mdx @@ -1,17 +1,17 @@ import { Details, createMetadata } from "@doc"; export const metadata = createMetadata({ - title: "Thirdweb Pay Quickstart | thirdweb .NET SDK", - description: "End to end examples for using the Thirdweb Pay SDK.", + title: "Thirdweb Universal Bridge Quickstart | thirdweb .NET SDK", + description: "End to end examples for using the Thirdweb Universal Bridge SDK.", }); # Quickstart -Thirdweb Pay is a powerful service that allows you to easily integrate fiat onramps and cross-chain crypto purchases. +Thirdweb Universal Bridge is a powerful service that allows you to easily integrate fiat onramps and cross-chain crypto purchases. ## Cross-Chain Swaps -This example demonstrates how to perform a cross-chain swap using the Thirdweb Pay SDK. +This example demonstrates how to perform a cross-chain swap using the Thirdweb Universal Bridge SDK. ```csharp using Thirdweb.Pay; @@ -45,7 +45,7 @@ while (currentSwapStatus is not SwapStatus.COMPLETED and not SwapStatus.FAILED) ## Fiat Onramps -This example demonstrates how to use the Thirdweb Pay SDK to initiate a fiat onramp. +This example demonstrates how to use the Thirdweb Universal Bridge SDK to initiate a fiat onramp. ```csharp // Get a Buy with Fiat quote @@ -80,4 +80,4 @@ while (currentOnRampStatus is not OnRampStatus.ON_RAMP_TRANSFER_COMPLETED and no ## Learn More -Please refer to our official [Thirdweb Pay](/connect/pay/overview) documentation for more general information. +Please refer to our official [Thirdweb Universal Bridge](/connect/pay/overview) documentation for more general information. From 57894be424b09098eb4369daac65d918acf9f8be Mon Sep 17 00:00:00 2001 From: pinkhoodie Date: Wed, 19 Mar 2025 13:26:39 -0400 Subject: [PATCH 4/5] Update page.mdx --- .../app/connect/wallet/get-started/page.mdx | 545 +++++++++++++++++- 1 file changed, 536 insertions(+), 9 deletions(-) diff --git a/apps/portal/src/app/connect/wallet/get-started/page.mdx b/apps/portal/src/app/connect/wallet/get-started/page.mdx index 762456e59ec..9af20553b3c 100644 --- a/apps/portal/src/app/connect/wallet/get-started/page.mdx +++ b/apps/portal/src/app/connect/wallet/get-started/page.mdx @@ -1,4 +1,4 @@ -import { Callout, OpenSourceCard, createMetadata, InstallTabs, SDKCard, Grid, ArticleIconCard } from "@doc"; +import { Callout, OpenSourceCard, createMetadata, InstallTabs, SDKCard, Grid, ArticleIconCard, Tabs, TabsList, TabsTrigger, TabsContent } from "@doc"; import { ReactIcon, TypeScriptIcon, @@ -17,19 +17,29 @@ export const metadata = createMetadata({ description: "Get started with thirdweb Wallet", }); -# Get Started +# Get Started with thirdweb Wallet -thirdweb offers multiple ways to add wallets to your application. Choose the method that best suits your needs: +thirdweb Wallet offers multiple ways to integrate wallet functionality in your application: 1. **External Wallets** - Connect to existing wallets like MetaMask, Coinbase Wallet, etc. 2. **In-App Wallets** - Create wallets with social/email login. -3. **Ecosystem Wallets** - Create wallets with social/email login that is shareable across various aplications. +3. **Ecosystem Wallets** - Create wallets with social/email login that is shareable across various applications. These methods can be used independently or together in the same application to provide the best experience for your users. +## Get your Client ID + +To use wallet features in your applications, you will need a client ID. Generate one for free at [your thirdweb dashboard](https://thirdweb.com/create-api-key). + +This client ID will be used to authenticate your application with thirdweb's services. + + + Keep your client ID safe. You can generate different client IDs for development and production environments. + + ## Live Playground -Check out the playground that lets you see all the various capabilities of Connect. +Before diving into the implementation, check out our playground to see all the various capabilities of Connect: -## Get your client ID +## Choose Your Framework/Language + + + + TypeScript + React + React Native + Unity + .NET + Unreal Engine + + + + ### Installation + + Install the thirdweb SDK in your TypeScript project: + + ```bash + npm install thirdweb + # or + yarn add thirdweb + # or + pnpm add thirdweb + ``` + + ### Setup the Client + + First, create a client instance to connect with thirdweb services: + + ```typescript + import { createThirdwebClient } from "thirdweb"; + + const client = createThirdwebClient({ + clientId: "YOUR_CLIENT_ID", // Get from your thirdweb dashboard + }); + ``` + + ### Connect External Wallets + + Enable users to connect their existing wallets: + + ```typescript + import { createThirdwebClient, walletConnect } from "thirdweb"; + + // Create the client + const client = createThirdwebClient({ + clientId: "YOUR_CLIENT_ID", + }); + + // Connect WalletConnect + const wallet = walletConnect({ + projectId: "YOUR_WALLETCONNECT_PROJECT_ID", // Get from WalletConnect dashboard + }); + + // Connect the wallet + const walletInstance = wallet.connect(); + const address = await walletInstance.getAddress(); + console.log("Connected to:", address); + ``` + + ### Setup In-App Wallet + + Create wallets with email or social login: + + ```typescript + import { createThirdwebClient, embeddedWallet } from "thirdweb"; + + // Create the client + const client = createThirdwebClient({ + clientId: "YOUR_CLIENT_ID", + }); + + // Initialize embedded wallet + const wallet = embeddedWallet({ + client, + }); + + // Connect with email + const emailWallet = await wallet.connect({ + strategy: "email", + email: "user@example.com", + }); + + // Connect with social login + const googleWallet = await wallet.connect({ + strategy: "google", + }); + ``` + + ### Setup Ecosystem Wallet + + Create shareable wallets across multiple applications: + + ```typescript + import { createThirdwebClient, ecosystemWallet } from "thirdweb"; + + // Create the client + const client = createThirdwebClient({ + clientId: "YOUR_CLIENT_ID", + }); + + // Initialize ecosystem wallet + const wallet = ecosystemWallet({ + client, + ecosystemId: "YOUR_ECOSYSTEM_ID", // Get from your ecosystem dashboard + }); + + // Connect with email + const emailWallet = await wallet.connect({ + strategy: "email", + email: "user@example.com", + }); + ``` + + + + ### Installation + + Install the thirdweb SDK in your React project: + + ```bash + npm install thirdweb + # or + yarn add thirdweb + # or + pnpm add thirdweb + ``` + + ### Setup the Provider + + Wrap your application with the ThirdwebProvider: + + ```tsx + import { ThirdwebProvider } from "thirdweb/react"; + + function App() { + return ( + + + + ); + } + ``` + + ### Connect Button Component + + Use the pre-built ConnectButton for a complete wallet connection UI: + + ```tsx + import { ConnectButton } from "thirdweb/react"; + + function YourApp() { + return ( +
+

My dApp

+ +
+ ); + } + ``` + + ### Connection Hooks + + For more customized implementations, use the connection hooks: + + ```tsx + import { useConnect, useDisconnect, useWallet } from "thirdweb/react"; + + function CustomConnectButton() { + const connect = useConnect(); + const disconnect = useDisconnect(); + const wallet = useWallet(); + + return ( +
+ {wallet ? ( +
+

Connected: {wallet.getAddress()}

+ +
+ ) : ( + + )} +
+ ); + } + ``` + + ### Using In-App Wallets + + Enable email or social login with the `useEmbeddedWallet` hook: + + ```tsx + import { useEmbeddedWallet } from "thirdweb/react"; + + function EmailLoginButton() { + const embeddedWallet = useEmbeddedWallet(); + const [email, setEmail] = useState(""); + + const handleLogin = async () => { + try { + await embeddedWallet.connect({ + strategy: "email", + email, + }); + } catch (error) { + console.error("Failed to login:", error); + } + }; + + return ( +
+ setEmail(e.target.value)} + placeholder="Enter your email" + /> + +
+ ); + } + ``` +
+ + + ### Installation + + Install the thirdweb SDK in your React Native project: + + ```bash + npm install thirdweb + # or + yarn add thirdweb + # or + pnpm add thirdweb + ``` + + ### Setup the Provider + + Wrap your application with the ThirdwebProvider: + + ```tsx + import { ThirdwebProvider } from "thirdweb/react-native"; + + function App() { + return ( + + + + ); + } + ``` + + ### Connect Button Component + + Use the pre-built ConnectButton for a complete wallet connection UI: + + ```tsx + import { ConnectButton } from "thirdweb/react-native"; + + function YourApp() { + return ( + + My Mobile dApp + + + ); + } + ``` + + ### Using In-App Wallets + + Enable email or social login for mobile: + + ```tsx + import { useEmbeddedWallet } from "thirdweb/react-native"; + import { useState } from "react"; + import { View, TextInput, Button, Alert } from "react-native"; + + function EmailLoginButton() { + const embeddedWallet = useEmbeddedWallet(); + const [email, setEmail] = useState(""); + + const handleLogin = async () => { + try { + await embeddedWallet.connect({ + strategy: "email", + email, + }); + } catch (error) { + Alert.alert("Login Failed", error.message); + } + }; + + return ( + + + ) : ( )} @@ -248,9 +294,13 @@ Before diving into the implementation, check out our playground to see all the v ```tsx import { useEmbeddedWallet } from "thirdweb/react"; + import { useState } from "react"; + import { client } from "./thirdwebClient"; function EmailLoginButton() { - const embeddedWallet = useEmbeddedWallet(); + const embeddedWallet = useEmbeddedWallet({ + client, + }); const [email, setEmail] = useState(""); const handleLogin = async () => { @@ -292,16 +342,39 @@ Before diving into the implementation, check out our playground to see all the v pnpm add thirdweb ``` + + You cannot use Expo Go with thirdweb because native modules are required. + Use an Expo development build (`npx expo prebuild`) or React Native CLI app. + + + ### Create a Client + + Create a client file for reuse throughout your app: + + ```typescript + // thirdwebClient.ts + import { createThirdwebClient } from "thirdweb"; + + export const client = createThirdwebClient({ + clientId: "YOUR_CLIENT_ID", // Configure in your app's env or constants + }); + ``` + + + When creating your client ID on the thirdweb dashboard, allowlist your mobile app's bundle ID (e.g., com.yourcompany.app) for security. + + ### Setup the Provider Wrap your application with the ThirdwebProvider: ```tsx - import { ThirdwebProvider } from "thirdweb/react-native"; + import { ThirdwebProvider } from "thirdweb/react"; + import { client } from "./thirdwebClient"; function App() { return ( - + ); @@ -313,13 +386,15 @@ Before diving into the implementation, check out our playground to see all the v Use the pre-built ConnectButton for a complete wallet connection UI: ```tsx - import { ConnectButton } from "thirdweb/react-native"; + import { ConnectButton } from "thirdweb/react"; + import { client } from "./thirdwebClient"; + import { View, Text } from "react-native"; function YourApp() { return ( My Mobile dApp - + ); } @@ -330,12 +405,15 @@ Before diving into the implementation, check out our playground to see all the v Enable email or social login for mobile: ```tsx - import { useEmbeddedWallet } from "thirdweb/react-native"; + import { useEmbeddedWallet } from "thirdweb/react"; import { useState } from "react"; import { View, TextInput, Button, Alert } from "react-native"; + import { client } from "./thirdwebClient"; function EmailLoginButton() { - const embeddedWallet = useEmbeddedWallet(); + const embeddedWallet = useEmbeddedWallet({ + client, + }); const [email, setEmail] = useState(""); const handleLogin = async () => { @@ -367,9 +445,17 @@ Before diving into the implementation, check out our playground to see all the v ### Installation - 1. Download the latest [thirdweb Unity SDK](https://github.com/thirdweb-dev/unity-sdk/releases) + 1. Download the latest [thirdweb Unity SDK](https://github.com/thirdweb-dev/unity-sdk/releases) (.unitypackage file) 2. Import the package into your Unity project via Assets > Import Package > Custom Package + ### Configure Client ID + + After importing the SDK: + + 1. Go to Project Settings > Thirdweb + 2. Enter your Client ID from the thirdweb dashboard + 3. Allowlist your game's Bundle ID on the thirdweb dashboard for security + ### Initialize the SDK Create a new script to manage wallet connections: @@ -387,6 +473,7 @@ Before diving into the implementation, check out our playground to see all the v void Start() { + // Client ID is set in Project Settings > Thirdweb sdk = new ThirdwebSDK("ethereum"); // Or any supported chain connectButton.onClick.AddListener(ConnectWallet); } @@ -394,8 +481,9 @@ Before diving into the implementation, check out our playground to see all the v public async void ConnectWallet() { try { + // Connect with an external wallet like Coinbase Wallet string address = await sdk.wallet.Connect(new WalletConnection() { - provider = WalletProvider.CoinbaseWallet, // Or other providers + provider = WalletProvider.CoinbaseWallet, chainId = 1 // Ethereum Mainnet }); @@ -432,6 +520,10 @@ Before diving into the implementation, check out our playground to see all the v }); walletAddressText.text = "Connected: " + address; + + // Read wallet balance + var balance = await sdk.wallet.GetBalance(); + Debug.Log($"Balance: {balance.DisplayValue} {balance.Symbol}"); } catch (System.Exception e) { Debug.LogError("Error connecting wallet: " + e.Message); @@ -443,7 +535,7 @@ Before diving into the implementation, check out our playground to see all the v ### Installation - Install the thirdweb .NET SDK: + Install the thirdweb .NET SDK using NuGet: ```bash dotnet add package Thirdweb @@ -456,11 +548,17 @@ Before diving into the implementation, check out our playground to see all the v ```csharp using Thirdweb; - // Initialize the SDK + // For client-side applications: var sdk = new ThirdwebSDK("ethereum", new ThirdwebSDK.Options { - ClientId = "YOUR_CLIENT_ID" + ClientId = "YOUR_CLIENT_ID" // From thirdweb dashboard }); + + // For server-side applications: + // var sdk = new ThirdwebSDK("ethereum", new ThirdwebSDK.Options + // { + // SecretKey = Environment.GetEnvironmentVariable("THIRDWEB_SECRET_KEY") + // }); ``` ### Connect External Wallets @@ -469,12 +567,16 @@ Before diving into the implementation, check out our playground to see all the v ```csharp // For server-side applications or wallet management - var privateKey = "YOUR_PRIVATE_KEY"; // Be careful with private keys + var privateKey = Environment.GetEnvironmentVariable("WALLET_PRIVATE_KEY"); // Never hardcode var wallet = new PrivateKeyWallet(privateKey); await sdk.SetWallet(wallet); var address = await sdk.Wallet.GetAddress(); Console.WriteLine($"Connected wallet address: {address}"); + + // Read wallet balance + var balance = await sdk.Wallet.GetBalance(); + Console.WriteLine($"Balance: {balance.DisplayValue} {balance.Symbol}"); ``` ### Using In-App Wallets @@ -495,19 +597,43 @@ Before diving into the implementation, check out our playground to see all the v // Authenticate and get the wallet address await wallet.Authenticate(); var address = await sdk.Wallet.GetAddress(); + Console.WriteLine($"Connected with embedded wallet: {address}"); + ``` + + ### Reading Contract Data + + Interact with smart contracts: + + ```csharp + // Get a contract instance + var contract = await ThirdwebContract.Create( + client: sdk.Client, + address: "0x...", + chain: Chain.Ethereum + ); + + // Read a value from the contract + var name = await contract.Read("name"); + Console.WriteLine($"Contract name: {name}"); ``` ### Installation - 1. Download the latest [thirdweb Unreal Engine SDK](https://github.com/thirdweb-dev/unreal-sdk/releases) + 1. Download the thirdweb Unreal Engine plugin from the [Unreal Engine Marketplace](https://www.unrealengine.com/marketplace/en-US/product/thirdweb) 2. Add the plugin to your Unreal project 3. Enable the plugin in your project settings - ### Initialize the SDK + ### Configure Client ID + + 1. Go to Edit > Project Settings > Thirdweb + 2. Enter your Client ID from the thirdweb dashboard + 3. Enter your Bundle ID (must match what was allowlisted on the thirdweb dashboard) + + ### Initialize the SDK (C++) - Create a new Blueprint or C++ class to manage wallet connections: + Create a new class to manage wallet connections: ```cpp #include "ThirdwebManager.h" @@ -519,8 +645,8 @@ Before diving into the implementation, check out our playground to see all the v // Get the Thirdweb subsystem UThirdwebSubsystem* ThirdwebSubsystem = GEngine->GetEngineSubsystem(); - // Initialize with your client ID - ThirdwebSubsystem->Initialize("YOUR_CLIENT_ID", "ethereum"); + // Initialize with your client ID (configured in project settings) + ThirdwebSubsystem->Initialize("ethereum"); } void AMyGameController::ConnectWallet() @@ -529,10 +655,11 @@ Before diving into the implementation, check out our playground to see all the v // Configure wallet connection FWalletConnection WalletOptions; - WalletOptions.Provider = EWalletProvider::MetaMask; + WalletOptions.Provider = EWalletProvider::EmbeddedWallet; + WalletOptions.Email = "user@example.com"; WalletOptions.ChainId = 1; // Ethereum Mainnet - // Connect wallet + // Connect wallet asynchronously ThirdwebSubsystem->ConnectWallet(WalletOptions, FOnWalletConnected::CreateUObject(this, &AMyGameController::OnWalletConnected)); } @@ -541,25 +668,52 @@ Before diving into the implementation, check out our playground to see all the v if (Error.IsEmpty()) { UE_LOG(LogTemp, Display, TEXT("Wallet connected: %s"), *Address); + + // Get balance + UThirdwebSubsystem* ThirdwebSubsystem = GEngine->GetEngineSubsystem(); + ThirdwebSubsystem->GetWalletBalance(FOnWalletBalanceReceived::CreateUObject(this, &AMyGameController::OnBalanceReceived)); } else { UE_LOG(LogTemp, Error, TEXT("Failed to connect wallet: %s"), *Error); } } + + void AMyGameController::OnBalanceReceived(const FString& Balance, const FString& Symbol) + { + UE_LOG(LogTemp, Display, TEXT("Balance: %s %s"), *Balance, *Symbol); + } ``` - ### UI Integration + ### Using Blueprints - Create a widget blueprint with buttons to trigger wallet connections: + Alternatively, use Blueprint nodes provided by the Thirdweb plugin: - 1. Create a new Widget Blueprint - 2. Add a button for connecting wallets - 3. Bind the button's OnClicked event to your ConnectWallet function - 4. Add text elements to display the connected wallet address + 1. Create a new Blueprint class + 2. Add a component for user interface (like widget blueprint) + 3. Use the Thirdweb nodes found in the node palette + 4. Connect nodes for wallet login, balance checking, etc.
+## Performance Considerations + +Optimize your wallet implementation: + +1. **Create Client Once** + - Initialize the thirdweb client once and reuse it + - Avoid recreating the client for each operation + +2. **Caching** + - Use built-in React query capabilities + - Avoid polling or constant refetching + - Implement proper state management + +3. **Lazy Loading** + - The SDK loads wallet connectors on demand + - Modularity reduces bundle size + - Only import what you need + ## Next Steps After setting up wallet functionality, explore these advanced topics: