### Project Setup and Execution Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/nextjs/README.md Steps to clone the repository, install dependencies, configure environment variables, and start the Next.js development server. ```bash git clone https://github.com/yourusername/evmauth.git cd evmauth/examples/nextjs pnpm install # Create .env.local from .env.example and set contract address/RPC URL pnpm dev ``` -------------------------------- ### Quick Start with EVMAuth TypeScript SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md A basic example demonstrating how to initialize the EVMAuth SDK with a provider for read operations and with a signer for write operations, including reading token metadata and purchasing a token. ```typescript import { ethers } from 'ethers'; import { EVMAuth } from 'evmauth'; // Replace with your EVMAuth contract address const contractAddress = '0x1234567890abcdef1234567890abcdef12345678'; // Connect to an EVM network provider const provider = new ethers.JsonRpcProvider('YOUR_RPC_URL'); // Create an SDK instance const evmAuth = new EVMAuth(contractAddress, provider); // Read token metadata const tokenId = 1; evmAuth.metadataOf(tokenId) .then(metadata => console.log('Token Metadata:', metadata)) .catch(console.error); // Connect with a signer for write operations const privateKey = 'YOUR_PRIVATE_KEY'; const signer = new ethers.Wallet(privateKey, provider); const evmAuthSigner = evmAuth.connect(signer); // Purchase a token evmAuthSigner.purchase('0xRECIPIENT', tokenId, 1, ethers.parseEther('0.1')) .then(tx => console.log('Transaction hash:', tx.hash)) .catch(console.error); ``` -------------------------------- ### Start Express Server Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/express/README.md Command to start the Express.js server after dependencies are installed and code is built. ```sh pnpm start ``` -------------------------------- ### Setup Project Dependencies and Build Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/express/README.md Commands to set up the Express.js project. This includes copying the environment file, installing Node.js dependencies using PNPM, and compiling the TypeScript code. ```sh cp .env.example .env pnpm install pnpm build ``` -------------------------------- ### Install EVMAuth TypeScript SDK (Bash) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Instructions for installing the EVMAuth TypeScript SDK and its peer dependency, ethers. This command should be run in your project's terminal. ```bash npm install evmauth ethers ``` -------------------------------- ### Client-Side Protected Content Fetching Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/nextjs/README.md An example of how a client-side component can fetch data from a protected API route. It handles responses indicating token purchase requirements (402 status) and successful data retrieval. ```tsx async function fetchProtectedContent(walletAddress) { const response = await fetch(`/api/protected?address=${walletAddress}`); if (response.status === 402) { // Token purchase required const paymentDetails = await response.json(); // Show payment UI... return; } if (!response.ok) { // Handle other errors return; } // Success - protected content accessible const data = await response.json(); // Show protected content... } ``` -------------------------------- ### EVMAuth Token-Gated API Route Logic Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/nextjs/README.md Describes the functionality of protected API routes within the Next.js example. These routes are secured by middleware that checks for token ownership. If ownership is insufficient, a 402 Payment Required status is returned, prompting the user to acquire the necessary token. ```APIDOC API Endpoint: /api/protected Method: GET Description: Accesses protected resources that require token ownership. Middleware Logic: 1. Intercepts requests to protected routes. 2. Verifies if the wallet address associated with the request possesses the required token balance. 3. If token balance is sufficient, allows the request to proceed to the handler. 4. If token balance is insufficient, returns a 402 Payment Required response. Parameters: - address (query parameter): The wallet address to check for token ownership. Responses: - 200 OK: Returns protected content upon successful token validation. - 402 Payment Required: Returned when the wallet address does not have sufficient token balance. The response body may contain details for token acquisition. - Other Error Codes: For network issues, invalid requests, etc. Related Concepts: - Next.js Middleware: Used to enforce access control before reaching route handlers. - Token Validation: The core mechanism checking token balance against access requirements. ``` -------------------------------- ### Error Handling Example Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Demonstrates how to catch and handle potential errors during contract interactions. It shows checking for specific error messages like 'AccessControlUnauthorizedAccount' to provide user-friendly feedback. ```typescript try { await evmAuth.issue(recipientAddress, tokenId, amount); console.log('Tokens minted successfully'); } catch (error) { if (error.message.includes('AccessControlUnauthorizedAccount')) { console.error('Error: You do not have the TOKEN_MINTER_ROLE'); } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Test API Endpoints with Curl Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/express/README.md Examples using curl to test the public and protected API endpoints. The protected endpoint requires an address query parameter to check for token ownership. ```sh curl -X GET http://localhost:3000/ curl -X GET http://localhost:3000/paid-content curl -X GET "http://localhost:3000/paid-content?address=0x..." ``` -------------------------------- ### EVMAuth Express.js API Endpoints Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/express/README.md Defines the available API endpoints for the EVMAuth Express.js example. It includes a public endpoint and a protected endpoint requiring token ownership. ```APIDOC API Endpoints: GET http://localhost:3000/ Description: A public endpoint that requires no authorization. Parameters: None Returns: Standard HTTP response. GET http://localhost:3000/paid-content Description: A protected endpoint that requires the purchase of token ID '0'. Access is granted if the provided address owns the token. Parameters: - address (query string, optional): The wallet address of the user to check for authorization. If not provided, the server might default to a check or return an unauthorized status. Returns: - On success (token owned): JSON object with a success message. - On failure (token not owned or address missing): Unauthorized status code (e.g., 401 or 403). Example Success Response: { "message": "This is a paid content route; you should only see this if you purchased the required token." } ``` -------------------------------- ### Initialize EVMAuth SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Demonstrates different ways to initialize the EVMAuth SDK. It can be initialized with just a provider for read-only access or with a signer for both read and write operations. An existing instance can also be connected to a signer. ```typescript // With provider (read-only) const provider = new ethers.JsonRpcProvider('https://rpc.example.com'); const evmAuth = new EVMAuth(contractAddress, provider); // With signer (read & write) const signer = new ethers.Wallet(privateKey, provider); const evmAuthSigner = new EVMAuth(contractAddress, signer); // Or connect a signer to an existing instance const evmAuthSigner = evmAuth.connect(signer); ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/evmauth/evmauth-ts/blob/main/CONTRIBUTING.md Essential Git and package manager commands for contributing to the EVMAuth project. This includes cloning the repository, creating branches, and running checks. ```git git clone https://github.com/your-username/evmauth-ts.git ``` ```git git checkout -b my-feature ``` ```pnpm pnpm check ``` ```pnpm pnpm test ``` -------------------------------- ### Manage Blacklist with EVMAuth SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Provides methods for managing blacklisted accounts. You can check if an account is blacklisted, add accounts to the blacklist (requires BLACKLIST_MANAGER_ROLE), and remove accounts from the blacklist. ```typescript // Check if an account is blacklisted const isBlacklisted = await evmAuth.isBlacklisted(accountAddress); // Add to blacklist (requires BLACKLIST_MANAGER_ROLE) await evmAuth.addToBlacklist(accountAddress); await evmAuth.addBatchToBlacklist([address1, address2, address3]); // Remove from blacklist await evmAuth.removeFromBlacklist(accountAddress); await evmAuth.removeBatchFromBlacklist([address1, address2, address3]); ``` -------------------------------- ### Manage Roles with EVMAuth SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Explains how to manage roles within the EVMAuth system using the SDK. This includes checking for existing roles, granting new roles (like Token Minter or Token Burner), and revoking roles. Role management typically requires administrative privileges. ```typescript import { roles } from 'evmauth'; // Check roles const hasMinterRole = await evmAuth.hasRole(roles.tokenMinter, accountAddress); // Grant roles (requires admin role) await evmAuth.grantRole(roles.tokenMinter, accountAddress); await evmAuth.grantRoles([roles.tokenMinter, roles.tokenBurner], accountAddress); // Revoke roles await evmAuth.revokeRole(roles.tokenMinter, accountAddress); await evmAuth.revokeRoles([roles.tokenMinter, roles.tokenBurner], accountAddress); ``` -------------------------------- ### Read Token Data with EVMAuth SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Shows how to retrieve various data points related to tokens using the EVMAuth SDK. This includes metadata, active status, burnability, transferability, sale status, price, TTL, expiration, and balance details. ```typescript // Get token metadata const metadata = await evmAuth.metadataOf(tokenId); console.log(metadata); // { id: 0n, active: true, burnable: true, transferable: false, price: 100000000000000000n, ttl: 2592000n } // Check token status const isActive = await evmAuth.active(tokenId); const isBurnable = await evmAuth.burnable(tokenId); const isTransferable = await evmAuth.transferable(tokenId); const isForSale = await evmAuth.forSale(tokenId); // Get token price and TTL const price = await evmAuth.priceOf(tokenId); const ttl = await evmAuth.ttlOf(tokenId); const expiration = await evmAuth.expirationFor(tokenId); // Get token balance const balance = await evmAuth.balanceOf(accountAddress, tokenId); // Get detailed balance including expiration const balanceDetailsOf = await evmAuth.balanceDetailsOf(accountAddress, tokenId); console.log(balanceDetailsOf); // [{ balance: 1n, expiresAt: 1714583142n }] ``` -------------------------------- ### Perform Token Operations with EVMAuth SDK (TypeScript) Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Details on performing core token management operations such as minting, burning, purchasing, and transferring tokens. These operations typically require specific roles or conditions to be met. ```typescript // Mint tokens (requires TOKEN_MINTER_ROLE) await evmAuth.issue(recipientAddress, tokenId, amount); // Burn tokens (requires TOKEN_BURNER_ROLE) await evmAuth.burn(accountAddress, tokenId, amount); // Purchase tokens await evmAuth.purchase(recipientAddress, tokenId, amount, price); // Transfer tokens (if transferable) await evmAuth.safeTransferFrom(fromAddress, toAddress, tokenId, amount); ``` -------------------------------- ### Admin: Wallet for Receiving Funds Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Allows retrieval and setting of the wallet address designated for receiving funds within the contract. This is crucial for managing payouts and financial operations. ```typescript // Get/set wallet for receiving funds const wallet = await evmAuth.wallet(); await evmAuth.setWallet(newWalletAddress); ``` -------------------------------- ### Token Configuration: Update Price Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Allows updating the price of a single token or multiple tokens simultaneously. This is useful for dynamic pricing strategies or bulk updates. ```typescript // Update token price await evmAuth.setPriceOf(tokenId, ethers.parseEther('0.2')); await evmAuth.setPriceOfBatch([token1, token2], [price1, price2]); ``` -------------------------------- ### Admin: Contract Ownership Transfer Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Manages the ownership of the contract. The transfer is a two-step process: first, initiate the transfer to a new address, and then the new admin must accept it. This ensures a secure handover. ```typescript // Transfer ownership (two-step process) await evmAuth.beginDefaultAdminTransfer(newAdminAddress); // Later, as the new admin: await evmAuth.acceptDefaultAdminTransfer(); ``` -------------------------------- ### Pull Request Template Selection Source: https://github.com/evmauth/evmauth-ts/blob/main/CONTRIBUTING.md How to specify a particular template when creating a pull request on GitHub for EVMAuth contributions, allowing for specialized PRs for features, bug fixes, or documentation. ```github-pr https://github.com/radiustech/evmauth-ts/compare/main...your-branch?template=feature.md ``` -------------------------------- ### Token Configuration: Update URI Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Sets the base URI for token metadata. This URI is typically appended with the token ID to fetch its specific metadata, often used in NFT standards. ```typescript // Update URI await evmAuth.setURI('https://metadata.example.com/{id}.json'); ``` -------------------------------- ### Token Configuration: Update Metadata Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Updates the metadata for a specific token, including its active status, burnability, transferability, price, and time-to-live (TTL). This allows fine-grained control over token properties. ```typescript await evmAuth.setMetadata( tokenId, true, // active true, // burnable false, // transferable ethers.parseEther('0.1'), // price 60 * 60 * 24 * 30 // ttl: 30 days in seconds ); ``` -------------------------------- ### Listen for Token Purchases Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Subscribes to token purchase events. You can filter events by the purchaser's wallet address or the specific token ID being purchased. Returns a function to unsubscribe from the event listener. ```typescript const unsubscribe = evmAuth.onTokenPurchased( (event) => { console.log('Purchase:', event); }, accountFilter, // optional: filter by purchaser wallet address tokenIdFilter // optional: filter by token ID ); // Stop listening unsubscribe(); ``` -------------------------------- ### Conventional Commits Specification Source: https://github.com/evmauth/evmauth-ts/blob/main/CONTRIBUTING.md The standard format for commit messages used in the EVMAuth project, promoting consistency and clarity in the commit history. Includes types like feat, fix, docs, style, refactor, test, and chore. ```conventional-commits (): [optional body] [optional footer] Types: - feat: New features - fix: Bug fixes - docs: Documentation only - style: Code style changes - refactor: Non-bug-fixing code changes - test: Test updates - chore: Build process updates ``` -------------------------------- ### Token Configuration: Update TTL Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Sets or updates the time-to-live (TTL) for a specific token, determining how long it remains valid or active. This can be used for time-limited offers or access. ```typescript // Update token TTL await evmAuth.setTTL(tokenId, 60 * 60 * 24 * 7); // 7 days in seconds ``` -------------------------------- ### Listen for ERC-1155 Token Transfers Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Subscribes to ERC-1155 single token transfer events. Allows filtering by sender or receiver addresses, with a zero address filter for minting or burning events respectively. Returns an unsubscribe function to stop listening. ```typescript const unsubscribe = evmAuth.onTransferSingle( (event) => { console.log('Transfer:', event); }, fromFilter, // optional: filter by sender address (use zero address for token minting events) toFilter // optional: filter by receiver address (use zero address for token burning events) ); // Stop listening unsubscribe(); ``` -------------------------------- ### Admin: Withdraw Funds Source: https://github.com/evmauth/evmauth-ts/blob/main/README.md Provides a mechanism to withdraw funds that may have been accidentally sent directly to the contract address. This function helps recover misplaced assets. ```typescript // Withdraw funds accidentally sent to the contract address await evmAuth.withdraw(); ``` -------------------------------- ### Protected Content Response Source: https://github.com/evmauth/evmauth-ts/blob/main/examples/express/README.md The JSON response received when accessing a protected endpoint successfully, indicating that the user has purchased the required token. ```json { "message": "This is a paid content route; you should only see this if you purchased the required token." } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.