metapro
  • 🤝Welcome!
  • 💻metapro market
    • Set your account
    • Connect wallet + web3 login
    • Side panel
      • Transfer NFT
        • Multiple transfer (Airdrop NFT)
          • Import CSV List
      • Sell NFT
        • Initial NFT Selling (INS)
          • How to setup INS auction
          • How to buy on INS auction
        • Buy Now
          • How to setup Buy Now auction
          • How to buy on Buy Now auction
        • Auction (Bidding)
          • How to setup Auction
          • How to buy on Auction
      • All NFT assets
    • Buy Crypto
    • Top Menu
      • Profile
        • Profile Marketplace
        • My games
        • My assets
          • Royalty
        • Activities
      • Referral Panel
        • Register your downline
        • Downline wallets
        • My referral link
      • Profile Settings
      • Developer Portal
      • Logout
    • Assets
      • Marketplace
        • Auction Card
      • Most favorite
      • Newest assets
        • Asset Card
    • Games
      • Show all games
    • Leaderboard
    • Create asset (minter)
      • Gaming asset specification
      • How to create (mint) asset
        • 1. Setup NFT token
        • 2. Setup metadata
        • 3. Add meta asset
        • 4. Mint meta asset
        • 5. Meta asset created
    • Developers Portal
      • Create team
      • Create game
      • Developers Portal Panel
      • Unity Plugin
      • How to list game on metapro market?
    • Creators
    • Teams
    • Users
    • Wallet App
    • Launcher
    • Market and auction component fees
  • 🚀METAPRO LAUNCHER
    • What is metapro launcher?
    • Download launcher
    • Set your account
      • Login to launcher
    • Home
    • Games
      • Game card on launcher
        • Assets in this game
      • Install game on launcher
      • Update game on launcher
    • My games
      • Installed
      • Not installed
      • Wishlist
    • My assets
      • Collected assets
      • Created assets
      • Wishlist
    • NODEs app
  • 📱metapro one
    • About non-custodial wallet
    • Download & set up
      • Create new metapro wallet
      • Import existing wallet
    • Settings
      • Avatar
      • Multiple wallets
      • Wallet name
      • Private Key
        • Protect Private Key
        • How to find my Private Key
      • Recovery Phrases
        • Protect Recovery Phrases
        • How to find my Recovery Phrases
      • Application version
    • Network switch
    • Deposit (Tokens and Collectibles)
    • Send (Tokens and Collectibles)
      • Send Tokens
      • Send Collectibles (NFT)
    • Buy (Buy and Sell Crypto)
    • Browser
    • My assets
      • Tokens
        • Asset view
        • Adding Tokens
        • Activities
      • Collectibles (NFT)
      • Game assets (NFTma)
    • Explore
      • Apps
      • Collections (NFT)
      • Game assets (NFTma)
    • How to claim Airdrop
    • How to import wallet from MetaMask to metapro
    • Supported devices
  • ⛓️metapro protocol
    • API
      • Users service
      • Teams service
      • Apps service
      • Nft service
      • Nft events service
    • Meta asset
    • Metadata structure
    • Protocole structure
    • Unity Plugin
      • About metapro Unity plugin
      • What's new
      • Guides
        • Installation
        • Requirements
        • Package samples
        • Quick start
          • 1. Editor
            • Access tool
            • Import game key
            • Download resources
            • App data object
            • Change game key
            • Use app data in script
          • 2. Play mode (PC)
            • Enable Web3 in your game
            • Choose provider
            • Connect wallet
            • Login with Web3
            • Display user data
            • Show app tokens
            • Use user and app data from script
          • 3. Play mode (Mobile)
            • Enable Web3 in Your game
            • Choose provider
            • Connect wallet
            • Login with Web3
        • AFP (Additional Features Packages)
          • 1. Safe token transfer
          • 2. Phoenix
        • Troubleshooting
      • Reference
        • MetaproAPPSetup
        • Editor Window
        • Plugin Manager
        • Web3 connection providers
          • metapro
          • Wallet Connect
          • MetaMask
        • WindowController
        • AFP (Additional Features Packages)
          • SafeTransferFrom
          • Phoenix
  • 🛠️WALLET CONNECTOR
    • Introduction
    • Basic informations
      • Next 13 integration
      • React integration
      • Manual installation
  • 👨‍💻Developer Documentation
    • Introduction to Developer Documentation
      • What is a Meta asset?
      • What are the Benefits of Using Tokens as Access Keys for the Game Application
      • Why should I Choose the Meta Assets as the Access Keys for the Game Application?
      • How Does It Work, Exactly?
    • Available Environments
    • Blockchain Communication and information retrieval
      • How can we verify/distinguish a user?
      • How can we track a user's transactions?
      • What information can we obtain?
    • Integration with the Leaderboard service
    • Integration for in-Wallet Apps
    • Integration for Telegram Mini Apps
      • Integration Architecture and Configuration
      • Authorization and Session Management
      • Example Integration and Features
      • Code Examples from the Repository
      • Summary and Appendices
    • Developer documentation for the Construct 3 Plugin
      • Construct 3 - Install plugin
      • Plugin Configuration
      • User onboarding and authorization
      • User Management
      • Score System
      • Leaderboard System
      • Referral System
      • Gameplay
      • Smart Contract Interactions
      • User NFTs
      • Error Handling
      • Additional Getters for Plugin Properties
    • Integration Web3 with Your Game
      • What is Web3
      • Blockchain Basics
      • Differences between chains
      • What is a NFT
      • Advantages of Web3 Gaming
      • Examples of Web3 Games
    • Onboarding the Web3 Player
      • Value for Players
      • Explanation of Cryptocurrency Wallet
      • Rewards for Tournament Participation
      • Reselling Owned Assets
      • Integration of Metapro Wallet Connector
      • Displaying Data for Unlogged Users
      • How to Get Authorization Data
      • User Authorization Benefits
    • Creating Your First Meta Asset
      • The Difference between NFT and Meta Asset
      • Security and Transparency
      • Concept and Value of Meta Assets
      • How and Where to Create Your Meta Asset
        • Step-by-Step Guide on How to Create Your Asset
        • Explanation of URI (Metadata structure)
        • Explanation of the Meta Asset Data taken from our Back End
    • Implementing Meta Assets into Your Game
      • Integrate your Meta Asset to your game using Unity
      • Verify User Tokens Ownership
      • Displaying All User-Owned Tokens
      • Displaying All Assets Assigned to the Game on the Metapro Market
    • Smart Contracts
      • MetaproINS
        • Read Contract
        • Write Contract
      • MetaproBuyNow
        • Read Contract
        • Write Contract
      • MetaproAuction
        • Read Contract
        • Write Contract
      • MetaproMetaAsset
        • Read Contract
        • Write Contract
      • MetaproRoyalty
        • Read Contract
        • Write Contract
      • MetaproReferral
        • Read Contract
        • Write Contract
      • MetaproAirdrop
        • Read Contract
        • Write Contract
    • Universal Links & App Links with WalletConnect
  • 🔎General information
    • Blockchain
    • Blockchain Network Fee
    • Blockchain Native Token
    • Token ERC-1155 vs ERC-721
  • 📄Release Notes
    • Introduction to the Release Notes
    • Marketplace Updates
      • Release 07.03.2024
      • Release 06.03.2024
      • Release 04.03.2024
      • Release 19.02.2024
      • Release 24.01.2024
      • Release 09.01.2024
      • Release 03.01.2024
      • Release 21.12.2023
      • Release 18.12.2023
      • Release 13.12.2023
      • Release 12.12.2023
      • Release 02.12.2023
      • Release 30.11.2023
      • Release 24.11.2023
      • Release 22.11.2023
      • Release 17.11.2023
      • Release 13.11.2023
      • Release 09.11.2023
      • Release 08.11.2023
      • Release 07.11.2023
      • Release 31.10.2023
      • Release 26.10.2023
      • Release 25.10.2023
      • Release 24.10.2023
      • Release 18.10.2023
      • Release 05.10.2023
      • Release 03.10.2023
      • Release 29.09.2023
      • Release 18.09.2023
      • Release 14.09.2023
      • Release 12.09.2023
      • Release 06.09.2023
      • Release 25.08.2023
      • Release 17.08.2023
      • Release 04.08.2023
      • Release 31.07.2023
      • Release 21.07.2023
      • Release 18.07.2023
      • Release 13.07.2023
    • Games Launcher Updates
      • Release 13.03.2024
      • Release 24.01.2024
      • Release 04.01.2024
      • Release 22.11.2023
      • Release 03.10.2023
      • Release 31.07.2023
      • Release 27.07.2023
      • Release 20.07.2023
      • Release 13.07.2023
    • Wallet Updates
      • Release 04.03.2024
      • Release 03.10.2023
      • Release 29.09.2023
      • Release 15.09.2023
      • Release 30.08.2023
      • Release 18.07.2023
Powered by GitBook
On this page
  1. metapro protocol
  2. Unity Plugin
  3. Reference
  4. AFP (Additional Features Packages)

SafeTransferFrom

This AFP contains a call for the safeTransferFrom function from smart contract. Most important code is in SafeTransferFrom class and TransactionEncoder class.

This package also offers scripts that deal with showing player the UI screen. All scripts are in namespace metaproSDK.Scripts.AFP.SafeTransferFrom.

Interaction with smart contract is achieved by first getting the _smartContractAddress and _functionSignature. Then using ABI specification hash of function signature is combined with encoded function parameters and sended as data in WalletConenct transaction. From parameter of the transaction is the current logged wallet address and To parameter is the smart contract address.

SafeTrasnferFrom.cs

using System;
using System.Collections;
using System.Linq;
using System.Threading.Tasks;
using metaproSDK.Scripts.AFP.SafeTransferFrom.Serialization;
using metaproSDK.Scripts.Serialization;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using WalletConnectSharp.Core.Models.Ethereum;
using WalletConnectSharp.Unity;

namespace metaproSDK.Scripts.AFP.SafeTransferFrom
{
    public class SafeTransferFrom : MonoBehaviour
    {
        [SerializeField] private string bscApiKey;
        [SerializeField] private TransferPopupView transferPopupView;
        [SerializeField] private GameObject signTransactionView;
        [SerializeField] private ErrorPopupView transactionFailedView;
        [SerializeField] private TransferSuccessPopupView transactionSucceedView;
        
        private bool _isOpened;
        
        private const string _smartContractAddress = "0xa293D68684Be29540838Dc8A0222De0c43c6b5B4";
        private const string _functionSignature = "safeTransferFrom(address,address,uint256,uint256,bytes)";

        private SafeTransferFromState _currentState;
        private NftTokenData _nftTokenData;

        private void Start()
        {
            _currentState = SafeTransferFromState.Initial;
        }

        public void SetupTransfer(NftTokenData nftTokenData)
        {
            transferPopupView.Setup(nftTokenData);
            _nftTokenData = nftTokenData;
        }

        public void OpenView()
        {
            HideAllViews();
            switch (_currentState)
            {
                case SafeTransferFromState.Initial:
                    transferPopupView.gameObject.SetActive(true);
                    break;
                case SafeTransferFromState.Transaction_Sent:
                    signTransactionView.gameObject.SetActive(true);
                    break;
                case SafeTransferFromState.Transaction_Failed:
                    transactionFailedView.gameObject.SetActive(true);
                    break;
                case SafeTransferFromState.Transaction_Success:
                    transactionSucceedView.gameObject.SetActive(true);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(_currentState), _currentState, null);
            }

            _isOpened = true;
        }
        
        private void HideAllViews()
        {
            transferPopupView.gameObject.SetActive(false);
            signTransactionView.gameObject.SetActive(false);
            transactionFailedView.gameObject.SetActive(false);
            transactionSucceedView.gameObject.SetActive(false);
        }

        public void CloseView()
        {
            HideAllViews();
            _isOpened = false;
        }

        public void OpenClosePopup()
        {
            if (_isOpened)
            {
                CloseView();
            }
            else
            {
                OpenView();
            }
        }

        public void SetState(SafeTransferFromState newState)
        {
            _currentState = newState;
        }

        public void OpenInitialState()
        {
            _currentState = SafeTransferFromState.Initial;
            OpenView();
        }

        public void SendSelectedToken()
        {
            if (transferPopupView.CheckErrors())
            {
                return;
            }
            
            var fromAddress = WalletConnect.ActiveSession.Accounts[0];
            var toAddress = transferPopupView.ToAddress;
            var tokenId = transferPopupView.TokenId;
            var amount = transferPopupView.Amount;
            SendToken(fromAddress, toAddress, tokenId, amount);
        }

        public void SendToken(string fromAddress, string toAddress, int tokenId, int amount)
        {
            var transactionHash = "";
            transactionHash += TransactionEncoder.EncodeFunction(_functionSignature);
            var fromWalletAddress = new WalletAddress();
            fromWalletAddress.value = fromAddress;
            transactionHash += TransactionEncoder.EncodeParam(fromWalletAddress);
            var toWalletAddress = new WalletAddress();
            toWalletAddress.value = toAddress;
            transactionHash += TransactionEncoder.EncodeParam(toWalletAddress);
            transactionHash += TransactionEncoder.EncodeParam(tokenId);
            transactionHash += TransactionEncoder.EncodeParam(amount);
            transactionHash += TransactionEncoder.EncodeLastBytes();
            StartCoroutine(TransactionRequest(transactionHash));
        }
        
        private IEnumerator TransactionRequest(string transactionHashData)
        {
            SetState(SafeTransferFromState.Transaction_Sent);
            OpenView();
            TransactionData data = new TransactionData();

            data.from = WalletConnect.ActiveSession.Accounts[0];
            data.to = _smartContractAddress;
            data.data = transactionHashData;

            var task = Task.Run(async () => await WalletConnect.ActiveSession.EthSendTransaction(data));
            
            yield return new WaitUntil(() => task.IsCompleted);
            if (task.IsFaulted)
            {
                foreach (var innerException in task.Exception.InnerExceptions)
                {
                    Debug.LogWarning(innerException.Message);
                }
                SetState(SafeTransferFromState.Transaction_Failed);
                transactionFailedView.SetupView(task.Exception.InnerExceptions[0].Message);
                OpenView();
                yield break;
            }
            Debug.Log(task.Result);

            if (bscApiKey == "")
            {
                Debug.LogWarning("BSC api key not found");
                yield break;
            }
            
            var txHash = task.Result;
            var requestUrl = $"https://api.bscscan.com/api?module=transaction" +
                             $"&action=getstatus" +
                             $"&txhash={txHash}" +
                             $"&apikey={bscApiKey}";
            var request = UnityWebRequest.Get(requestUrl);
            yield return request.SendWebRequest();
            
            Debug.Log($"Transaction hash: {request.result}");
            var apiResponse = JsonConvert.DeserializeObject<BSCApiRespone>(request.downloadHandler.text);

            if (apiResponse != null && apiResponse.result.isError == "1")
            {
                Debug.LogWarning("Transaction occured an error");
                SetState(SafeTransferFromState.Transaction_Failed);
                transactionFailedView.SetupView(apiResponse.result.errDescription);
                OpenView();
                yield break;
            }
            
            SetState(SafeTransferFromState.Transaction_Success);
            transactionSucceedView.Setup(_nftTokenData, transferPopupView.ToAddress, transferPopupView.Amount, "https://bscscan.com/tx/" + txHash);
            OpenView();
        }

        public void CloseSafeTransfer()
        {
            Destroy(gameObject);
        }
    }
}

TransactionEncoder.cs

using System.Text;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Utilities.Encoders;

namespace metaproSDK.Scripts.AFP.SafeTransferFrom
{
    public class TransactionEncoder
    {
        public static string EncodeFunction(string functionWithParams)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(functionWithParams);
            KeccakDigest keccakDigest = new KeccakDigest(256);
            byte[] outputBytes = new byte[keccakDigest.GetDigestSize()];
            keccakDigest.BlockUpdate(inputBytes, 0, inputBytes.Length);
            keccakDigest.DoFinal(outputBytes, 0);
            return Hex.ToHexString(outputBytes)[..8]; //return first 4 bytes of hash 
        }

        private static string SimpleStringEncoding(string input)
        {
            string result = "";

            for (int i = 0; i < 64 - input.Length; i++)
            {
                result += "0";
            }
            result += input;
            return result.ToLower();
        }
        
        public static string EncodeParam(WalletAddress walletAddress)
        {
            return SimpleStringEncoding(walletAddress.value.Substring(2));
        }
        
        public static string EncodeParam(int integer)
        {
            string hexValue = integer.ToString("X");
            return SimpleStringEncoding(hexValue);
        }

        public static string EncodeLastBytes()
        {
            return "00000000000000000000000000000000000000000000000000000000000000a0" +
                   "0000000000000000000000000000000000000000000000000000000000000001" +
                   "0000000000000000000000000000000000000000000000000000000000000000";
        }
    }
}

PreviousAFP (Additional Features Packages)NextPhoenix

Last updated 7 months ago

⛓️