Ethereum Unity3D Boilerplate Questions

Hi fam,

Thanks for your amazing work !

creating a marketplace where people could buy displayed ERC1155 NFTs with specific ERC20 tokens.

I couldnā€™t find a working solution for that.
Do you have any direction for that ?
For now, I managed to:

  • authentificate
  • show custom token balance
  • send custom token to specific address
  • show owned nfts

Thanks in advance.

1 Like

Trying it myself ā€¦

It worked for me. From Android Studio log:

2022-03-03 07:48:17.540 13840-13871/com.DefaultCompany.v108 I/Unity: Already Owns Mug.
    UnityEngine.StackTraceUtility:ExtractStackTrace () (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/StackTrace.cs:37)
    UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
    UnityEngine.Logger:Log (UnityEngine.LogType,object)
    UnityEngine.Debug:Log (object)
    AwardableController/<Update>d__6:MoveNext () (at F:/projects/unity/v108/Assets/MoralisWeb3ApiSdk/Example/Scripts/AwardableController.cs:101)

This debug statement only happens if the Web3Api call returns and the result contains the target TokenId

Since you are using custom code in the sample you sent:

  1. is address non-null?
  2. Is tokenAddress non-null?
  3. Has MoralisInterface been initialized prior to calling your test method?

Are you creating this using Unity for game?

ok, there should be two safeTransferFrom function :thinking: ?
i saw two on erc 721, i took the parameter byte with the other normal parameters, the other one did not take it but took the other normal parameters

There is only one ā€¦
There is one called safeBatchTransferFrom, but takes in the same inputsā€¦

I made this test method and it worked for me:

   public async static Task TransferNft()
    {
        // Need the user for the wallet address
        MoralisUser user = await MoralisInterface.GetUserAsync();

        string addr = user.authData["moralisEth"]["id"].ToString();

        BigInteger bi = 0;

        if (BigInteger.TryParse(Constants.MUG_TOKEN_ID, out bi))
        {
            // Convert token id to hex as this is what the contract call expects
            object[] pars = new object[] { 
                // from
                addr, 
                // to
                "0xc539a39719Ad4D2DE7bf6f1e16F86383B6FF59C6", 
                // Token Id
                bi.ToString(),
                // Amount (count)
                (new HexBigInteger(1)).ToString(),
                // data
                new byte[] {0}
            };

            // Set gas estimate
            HexBigInteger gas = new HexBigInteger(30000);

            try
            {
                // Call the contract to transfer the NFT.
                string resp = await MoralisInterface.SendEvmTransactionAsync("Rewards", "mumbai", "safeTransferFrom", addr, gas, new HexBigInteger("0x0"), pars);

                Debug.Log($"$Send Transaction respo: {resp}");
            }
            catch (Exception exp)
            {
                Debug.Log($"Send transaction failed: {exp.Message}");
            }
        }
    }

This is non-WebGL

2 Likes

Yes I am :slight_smile:

1 Like

Yeayyy this worksss !! Thanks x1000 @dgoodrich and @0xprof.
Made my day.

Just a note:
Why does the nft still appears on my metamask app like I still own it ?
Is this coming from them ?

Thanks again for your amazing support guys.

Double check using the etherscan associated with the chain you are targeting and look at the transactions for you wallet.

Did the transaction actually succeed? If so I do not know why metamask still shows that address still owns the NFT.

also try logging out and into the wallet to see if that clears it up .

Oh yes Iā€™m sure it did go through ! Thanks!!
Itā€™s showing well on polygonscan, so probably just metamask being metamask :slight_smile:

Curious why it doesnā€™t show who the receiver is. Thinking itā€™s probably just mumbai polygonscan

1 Like

Yes I have tested where address is non-null, token address is non-null.
And I think MoralisInterface has been initialized because before calling GetNFTsForContract(), I am fetching address using
var user = await MoralisInterface.GetUserAsync();
address = user.authData[ā€œmoralisEthā€][ā€œidā€].ToString();
And getting proper address.

Can you please test it on android real device ?

public async void MoralisTest()
    {
        var user = await MoralisInterface.GetUserAsync();
        address = user.authData["moralisEth"]["id"].ToString();
        NftOwnerCollection noc =
                         await MoralisInterface.GetClient().Web3Api.Account.GetNFTsForContract(address.ToLower(),
                       swordTokenAddress,
                       ChainList.rinkeby);
    }
1 Like

I did. I have a Pixel 4 and tested it on that.
I had it connected to my PC with android studio which is how I captured the log.

check if the nft moved :sweat_smile: and where it moved to

1 Like

Is there error because of async function, because I think async works differently on each OS.
Or what should be wrong ? What should I check now. I am stuck with this for more than 48 hours.

1 Like

I do not know as it worked on an Android device for me. The call I made was async and awaited.

Send me the actual address, and contract address and I can try.

I also just realized I assumed that you are building for Android and not WebGL. Is this correct?

Also what version of Unity are you building with?

1 Like

public address : 0xB65f5Ac5eAD9598f7Ec61c8C89033B970dA7B77D
contract address : 0x81437356a6143f7c344d8569a09607e294ef17a4
on rinkeby testnet.
Unity version : 2021.2.9f1
Yes I am building for Android OS.

Hmmā€¦ Still no luck with getting the callbacks to fire. Can you think of anything else I should look at?

Hereā€™s the full context of the code:

     public class PlayerData : MoralisObject
     {
         public long TokenCount { get; set; }
         public string WalletAddress { get; set; }
         public PlayerData() : base("PlayerData") { }
     }

    private async void Start()
    {
        var user = await MoralisInterface.GetUserAsync();

        if (WalletConnect.Instance.Connected && user != null)
        {
            setupPlayer(user);
            monitorPlayerData();
        }
    }
    private async void setupPlayer(MoralisUser user)
    {
        var walletAddress = user.authData["moralisEth"]["id"].ToString();
        var playerDataQuery = await MoralisInterface.GetClient().Query<PlayerData>();

        playerDataQuery = playerDataQuery.WhereEqualTo("WalletAddress", walletAddress);

        var queryResult = await playerDataQuery.FindAsync();

        PlayerData playerData = queryResult.FirstOrDefault();

        if (playerData == null)
        {
            playerData = MoralisInterface.GetClient().Create<PlayerData>();
            playerData.WalletAddress = walletAddress;
            playerData.TokenCount = 0;
            await playerData.SaveAsync();
        }

        TokensCollected = playerData.TokenCount;
        OnTokenCountChanged?.Invoke(TokensCollected);
    }

   private async void monitorPlayerData()
    {
        var query = await MoralisInterface.GetClient().Query<PlayerData>();

        MoralisLiveQueryCallbacks<PlayerData> callbacks = new MoralisLiveQueryCallbacks<PlayerData>();

        callbacks.OnConnectedEvent += (() => { Console.WriteLine("Connection Established."); });
        callbacks.OnSubscribedEvent += ((requestId) => { Console.WriteLine($"Subscription {requestId} created."); });
        callbacks.OnUnsubscribedEvent += ((requestId) => { Console.WriteLine($"Unsubscribed from {requestId}."); });
        callbacks.OnErrorEvent += ((ErrorMessage em) =>
        {
            Debug.Log($"***** ERROR: code: {em.code}, msg: {em.error}, requestId: {em.requestId}");
        });
        callbacks.OnCreateEvent += ((item, requestId) =>
        {
            Debug.Log($"***** Created");
        });
        callbacks.OnUpdateEvent += ((item, requestId) =>
        {
            Debug.Log($"***** Updated");
        });
        callbacks.OnDeleteEvent += ((item, requestId) =>
        {
            Debug.Log($"***** Deleted");
        });
        callbacks.OnGeneralMessageEvent += ((text) =>
        {
            Debug.Log($"***** Websocket message: {text}");
        });

        MoralisLiveQueryController.AddSubscription<PlayerData>("PlayerData", query, callbacks);
    }

1 Like

Hi guys !

Everything working smoothly on desktop and android ! Thank you!

However it isnā€™t working for iOSā€¦
When I try to authenticate, WalletConnect donā€™t seem to do the job and get stuck on this screen:

Any idea why is that ?
Thanks!

1 Like

did you select wallets in the ios gameobject in unity
there will be a choice to select wallets, that you want your users to use.
and if there is an error, you can show us

well, idk if this is correct, but you are only calling the function onStart, is anything supposed to be fired then ? i assume you will want to keep this in an update so it will be running throughout the life span of your game and be constantly check if any event is been fired