Basic Web3

Multi-Chain Token Operations Guide

Ensure proper environment variables are set for both chains:

  • ETH_PROVIDER_URL for Ethereum operations

  • SOL_PROVIDER_URL for Solana operations

1. Basic Token Manager Setup

using UnityEngine;
using NAREON.Core;
using System.Numerics;

public class MultiChainTokenManager : MonoBehaviour
{
    [SerializeField]
    private NAREONTokenManager tokenManager;
    
    private void Awake()
    {
        // Verify connection to both networks
        tokenManager.VerifyConnections();
    }
}

2. Token Transfers

Ethereum (ERC20) Transfer

public class EthereumTokenExample : MonoBehaviour
{
    public NAREONTokenManager tokenManager;

    [ContextMenu("Transfer ERC20")]
    public async void TransferERC20Tokens()
    {
        try
        {
            // "GoldCoin" must match the tokenName in NAREONSettings
            BigInteger amount = 50;
            string playerAddress = "0xPlayerAddress";
            
            await tokenManager.TransferErc20Token(
                tokenName: "GoldCoin",
                recipientAddress: playerAddress,
                amount: amount
            );
            
            Debug.Log($"ERC20 transfer complete to {playerAddress}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"ERC20 transfer failed: {ex.Message}");
        }
    }
}

Solana (SPL) Transfer

public class SolanaTokenExample : MonoBehaviour
{
    public NAREONTokenManager tokenManager;

    [ContextMenu("Transfer SPL")]
    public async void TransferSPLTokens()
    {
        try
        {
            // "GoldCoin" must match the tokenName in NAREONSettings
            ulong amount = 50;
            string playerAddress = "playerPubKey";
            
            // Create associated token account if needed
            await tokenManager.CreateAssociatedTokenAccountIfNeeded(
                "GoldCoin",
                playerAddress
            );
            
            await tokenManager.TransferSPLToken(
                tokenName: "GoldCoin",
                recipientAddress: playerAddress,
                amount: amount,
                commitment: "confirmed"
            );
            
            Debug.Log($"SPL transfer complete to {playerAddress}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"SPL transfer failed: {ex.Message}");
        }
    }
}

3. NFT Operations

Ethereum (ERC721) NFT Minting

public class EthereumNFTExample : MonoBehaviour
{
    public NAREONTokenManager tokenManager;

    [ContextMenu("Mint ERC721")]
    public async void MintERC721()
    {
        try
        {
            string playerAddress = "0xPlayerAddress";
            BigInteger tokenId = 999;
            
            await tokenManager.MintErc721(
                tokenName: "DragonNFT",
                recipientAddress: playerAddress,
                tokenId: tokenId
            );
            
            Debug.Log($"ERC721 NFT minted to {playerAddress}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"ERC721 minting failed: {ex.Message}");
        }
    }
}

Solana (Metaplex) NFT Minting

public class SolanaNFTExample : MonoBehaviour
{
    public NAREONTokenManager tokenManager;

    [ContextMenu("Mint Metaplex NFT")]
    public async void MintMetaplexNFT()
    {
        try
        {
            string playerAddress = "playerPubKey";
            
            var metadata = new MetaplexMetadata
            {
                name = "Dragon NFT",
                symbol = "DRGN",
                uri = "https://your-metadata-uri.com/dragon.json",
                sellerFeeBasisPoints = 500, // 5% royalty
                creators = new[]
                {
                    new Creator
                    {
                        address = tokenManager.GetProgramAddress(),
                        verified = true,
                        share = 100
                    }
                }
            };
            
            await tokenManager.MintMetaplexNFT(
                tokenName: "DragonNFT",
                recipientAddress: playerAddress,
                metadata: metadata,
                useCompression: false
            );
            
            Debug.Log($"Metaplex NFT minted to {playerAddress}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Metaplex NFT minting failed: {ex.Message}");
        }
    }
}

4. Universal Token Operations

Chain-Agnostic Token Transfer

public class UniversalTokenExample : MonoBehaviour
{
    public NAREONTokenManager tokenManager;

    [ContextMenu("Universal Transfer")]
    public async void TransferTokens(string tokenName, string recipientAddress, decimal amount)
    {
        try
        {
            var tokenConfig = NAREONSettings.Instance.GetTokenConfig(tokenName);
            
            switch (tokenConfig.network.ToLower())
            {
                case "ethereum":
                    await tokenManager.TransferErc20Token(
                        tokenName,
                        recipientAddress,
                        new BigInteger(amount)
                    );
                    break;
                
                case "solana":
                    await tokenManager.TransferSPLToken(
                        tokenName,
                        recipientAddress,
                        (ulong)amount
                    );
                    break;
                
                default:
                    throw new System.Exception($"Unsupported network: {tokenConfig.network}");
            }
            
            Debug.Log($"Token transfer complete on {tokenConfig.network}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Token transfer failed: {ex.Message}");
        }
    }
}

5. Configuration (NAREONSettings.asset)

{
    "tokens": [
        {
            "tokenName": "GoldCoin",
            "network": "ethereum",
            "contractAddress": "0x1234...",
            "tokenType": "ERC20",
            "decimals": 18,
            "defaultAmount": 100
        },
        {
            "tokenName": "GoldCoin",
            "network": "solana",
            "mintAddress": "7xKXtg2...",
            "tokenType": "SPL",
            "decimals": 9,
            "defaultAmount": 100
        },
        {
            "tokenName": "DragonNFT",
            "network": "ethereum",
            "contractAddress": "0xABCD...",
            "tokenType": "ERC721"
        },
        {
            "tokenName": "DragonNFT",
            "network": "solana",
            "collectionAddress": "AKxZWve...",
            "tokenType": "MetaplexNFT",
            "metadataFormat": "standard"
        }
    ]
}

6. Best Practices

Gas and Fee Management

  • Ethereum

    • Implement proper gas estimation

    • Handle EIP-1559 transactions

    • Consider gas price fluctuations

  • Solana

    • Handle rent-exempt requirements

    • Manage account creation fees

    • Consider compute unit limits

Error Handling

public class TokenErrorHandler
{
    public static async Task<bool> ValidateTokenOperation(
        NAREONTokenManager manager,
        string tokenName,
        string recipientAddress)
    {
        var config = NAREONSettings.Instance.GetTokenConfig(tokenName);
        
        switch (config.network.ToLower())
        {
            case "ethereum":
                return await ValidateEthereumOperation(manager, config, recipientAddress);
            
            case "solana":
                return await ValidateSolanaOperation(manager, config, recipientAddress);
            
            default:
                return false;
        }
    }

    private static async Task<bool> ValidateEthereumOperation(
        NAREONTokenManager manager,
        TokenConfig config,
        string recipientAddress)
    {
        // Validate ETH balance for gas
        // Check contract approval status
        // Verify recipient address format
        return true;
    }

    private static async Task<bool> ValidateSolanaOperation(
        NAREONTokenManager manager,
        TokenConfig config,
        string recipientAddress)
    {
        // Check associated token account
        // Verify SOL balance for rent
        // Validate address format
        return true;
    }
}

Transaction Monitoring

public class TransactionMonitor : MonoBehaviour
{
    public async Task<bool> WaitForConfirmation(
        string transactionId,
        string network,
        int maxAttempts = 30)
    {
        switch (network.ToLower())
        {
            case "ethereum":
                return await WaitForEthereumConfirmation(transactionId, maxAttempts);
            
            case "solana":
                return await WaitForSolanaConfirmation(transactionId, maxAttempts);
            
            default:
                throw new System.Exception($"Unsupported network: {network}");
        }
    }
}

7. Testing Guidelines

  1. Test Environment Setup

    • Use testnet configurations

    • Create dedicated test tokens

    • Implement proper mocking

  2. Transaction Validation

    • Verify token balances

    • Check transaction receipts

    • Monitor event emissions

  3. Error Scenarios

    • Test insufficient funds

    • Validate invalid addresses

    • Handle network timeouts

Last updated