Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: interaction with some smart contract functions is broken in WebGL #19

Merged
merged 5 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ mergeInto(LibraryManager.library, {
// Call the method using the provided function
let result = await callFn(_web3ModalConfig, methodName, parameterObj);

if (!result) {
if (result === undefined || result === null) {
{{{makeDynCall('viii', 'callbackPtr')}}} (id, undefined, undefined);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public string BalanceSymbol
private NetworkController _networkController;
private BlockchainApiController _blockchainApiController;

private UnityHttpClient _httpClient = new();
private readonly UnityHttpClient _httpClient = new();

private string _address;
private string _accountId;
Expand All @@ -87,9 +87,11 @@ public async Task InitializeAsync(ConnectorController connectorController, Netwo
_connectorController = connectorController ?? throw new ArgumentNullException(nameof(connectorController));
_networkController = networkController ?? throw new ArgumentNullException(nameof(networkController));
_blockchainApiController = blockchainApiController ?? throw new ArgumentNullException(nameof(blockchainApiController));


#if !UNITY_WEBGL || UNITY_EDITOR
_connectorController.AccountConnected += ConnectorAccountConnectedHandler;
_connectorController.AccountChanged += ConnectorAccountChangedHandler;
#endif
Comment on lines +91 to +94

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these features not supported on WebGL?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These event handler update ENS name, avatar, and account balance in native Unity UI. In WebGL @web3modal/wagmi takes care of that, so these handler were just making duplicate requests to the blockchain api.

}

private async void ConnectorAccountConnectedHandler(object sender, Connector.AccountConnectedEventArgs e)
Expand Down Expand Up @@ -124,6 +126,9 @@ await Task.WhenAll(

public async Task UpdateProfile()
{
if (string.IsNullOrWhiteSpace(Address))
return;

var identity = await _blockchainApiController.GetIdentityAsync(Address);
ProfileName = string.IsNullOrWhiteSpace(identity.Name)
? Address.Truncate()
Expand Down Expand Up @@ -151,8 +156,19 @@ public async Task UpdateProfile()

public async Task UpdateBalance()
{
if (string.IsNullOrWhiteSpace(Address))
return;

var response = await _blockchainApiController.GetBalanceAsync(Address);
var balance = response.Balances.FirstOrDefault(x => x.chainId == ChainId && string.IsNullOrWhiteSpace(x.address));

if (response.Balances.Length == 0)
{
Balance = "0.000";
BalanceSymbol = _networkController.ActiveChain.NativeCurrency.symbol;
return;
}

var balance = Array.Find(response.Balances,x => x.chainId == ChainId && string.IsNullOrWhiteSpace(x.address));

if (string.IsNullOrWhiteSpace(balance.quantity.numeric))
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using WalletConnect.Web3Modal.Http;
Expand All @@ -24,6 +25,9 @@ public class BlockchainApiController

public async Task<GetIdentityResponse> GetIdentityAsync(string address)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentNullException(nameof(address));

var projectId = ProjectConfiguration.Load().Id;
var path = $"identity/{address}?projectId={projectId}";

Expand All @@ -45,6 +49,9 @@ public async Task<GetIdentityResponse> GetIdentityAsync(string address)

public async Task<GetBalanceResponse> GetBalanceAsync(string address)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentNullException(nameof(address));

var projectId = ProjectConfiguration.Load().Id;
return await _httpClient.GetAsync<GetBalanceResponse>($"account/{address}/balance?projectId={projectId}&currency=usd", headers: _getBalanceHeaders);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using Newtonsoft.Json;
using WalletConnectSharp.Common.Utils;

namespace WalletConnect.Web3Modal.Utils
{
/// <summary>
/// Converts byte array to hex string and vice versa.
/// </summary>
/// <remarks>
/// The default behavior of Newtonsoft.Json is to convert byte arrays to base64 strings.
/// </remarks>
public class ByteArrayJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(byte[]);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;

if (reader.TokenType == JsonToken.String)
{
var hexString = (string)reader.Value;
return hexString.HexToByteArray();
}

throw new JsonSerializationException("Expected byte array object value");
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}

var byteArray = (byte[])value;
var hexString = byteArray.ToHex(true);

writer.WriteValue(hexString);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using AOT;
using Newtonsoft.Json;
using UnityEngine;
using WalletConnect.Web3Modal.Utils;

namespace WalletConnect.Web3Modal.WebGl
{
Expand All @@ -15,6 +16,11 @@ public class InteropService

private readonly ExternalMethod _externalMethod;

private readonly JsonConverter[] _jsonConverts =
{
new ByteArrayJsonConverter()
};

public InteropService(ExternalMethod externalMethod)
{
_externalMethod = externalMethod;
Expand Down Expand Up @@ -46,9 +52,13 @@ public async Task<TRes> InteropCallAsync<TReq, TRes>(string methodName, TReq req
if (!Equals(requestParameter, default(TReq)))
{
if (typeof(TReq) == typeof(string))
{
paramStr = requestParameter as string;
}
else
paramStr = JsonConvert.SerializeObject(requestParameter);
{
paramStr = JsonConvert.SerializeObject(requestParameter, _jsonConverts);
}
}

_externalMethod(id, methodName, paramStr, TcsCallback);
Expand Down
42 changes: 4 additions & 38 deletions Samples/W3M Basic Sample/Assets/Scripts/Dapp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public async void OnPersonalSignButton()
{
var account = await Web3Modal.GetAccountAsync();

const string message = "Hello from the service!";
const string message = "Hello from Unity!";
var signature = await Web3Modal.Evm.SignMessageAsync(message);
var isValid = await Web3Modal.Evm.VerifyMessageSignatureAsync(account.Address, message, signature);

Expand Down Expand Up @@ -305,42 +305,8 @@ private TypedData<Domain> GetMailTypedDefinition()
};
}


public const string CryptoPunksAbi = @"[{""constant"":true,""inputs"":[],""name"":""name"",""outputs"":[{""name"":"""",""type"":""string""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[{""name"":"""",""type"":""uint256""}],""name"":""punksOfferedForSale"",""outputs"":[{""name"":""isForSale"",""type"":""bool""},{""name"":""punkIndex"",""type"":""uint256""},{""name"":""seller"",""type"":""address""},{""name"":""minValue"",""type"":""uint256""},{""name"":""onlySellTo"",""type"":""address""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""}],""name"":""enterBidForPunk"",""outputs"":[],""payable"":true,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""totalSupply"",""outputs"":[{""name"":"""",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""},{""name"":""minPrice"",""type"":""uint256""}],""name"":""acceptBidForPunk"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""decimals"",""outputs"":[{""name"":"""",""type"":""uint8""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""addresses"",""type"":""address[]""},{""name"":""indices"",""type"":""uint256[]""}],""name"":""setInitialOwners"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[],""name"":""withdraw"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""imageHash"",""outputs"":[{""name"":"""",""type"":""string""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""nextPunkIndexToAssign"",""outputs"":[{""name"":"""",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[{""name"":"""",""type"":""uint256""}],""name"":""punkIndexToAddress"",""outputs"":[{""name"":"""",""type"":""address""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""standard"",""outputs"":[{""name"":"""",""type"":""string""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[{""name"":"""",""type"":""uint256""}],""name"":""punkBids"",""outputs"":[{""name"":""hasBid"",""type"":""bool""},{""name"":""punkIndex"",""type"":""uint256""},{""name"":""bidder"",""type"":""address""},{""name"":""value"",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[{""name"":"""",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""name"":"""",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[],""name"":""allInitialOwnersAssigned"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""allPunksAssigned"",""outputs"":[{""name"":"""",""type"":""bool""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""}],""name"":""buyPunk"",""outputs"":[],""payable"":true,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""to"",""type"":""address""},{""name"":""punkIndex"",""type"":""uint256""}],""name"":""transferPunk"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""symbol"",""outputs"":[{""name"":"""",""type"":""string""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""}],""name"":""withdrawBidForPunk"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""to"",""type"":""address""},{""name"":""punkIndex"",""type"":""uint256""}],""name"":""setInitialOwner"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""},{""name"":""minSalePriceInWei"",""type"":""uint256""},{""name"":""toAddress"",""type"":""address""}],""name"":""offerPunkForSaleToAddress"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""punksRemainingToAssign"",""outputs"":[{""name"":"""",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""},{""name"":""minSalePriceInWei"",""type"":""uint256""}],""name"":""offerPunkForSale"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""}],""name"":""getPunk"",""outputs"":[],""payable"":false,""type"":""function""},
{""constant"":true,""inputs"":[{""name"":"""",""type"":""address""}],""name"":""pendingWithdrawals"",""outputs"":[{""name"":"""",""type"":""uint256""}],""payable"":false,""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""punkIndex"",""type"":""uint256""}],""name"":""punkNoLongerForSale"",""outputs"":[],""payable"":false,""type"":""function""},
{""inputs"":[],""payable"":true,""type"":""constructor""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""to"",""type"":""address""},{""indexed"":false,""name"":""punkIndex"",""type"":""uint256""}],""name"":""Assign"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""from"",""type"":""address""},{""indexed"":true,""name"":""to"",""type"":""address""},{""indexed"":false,""name"":""value"",""type"":""uint256""}],""name"":""Transfer"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""from"",""type"":""address""},{""indexed"":true,""name"":""to"",""type"":""address""},{""indexed"":false,""name"":""punkIndex"",""type"":""uint256""}],""name"":""PunkTransfer"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""punkIndex"",""type"":""uint256""},{""indexed"":false,""name"":""minValue"",""type"":""uint256""},{""indexed"":true,""name"":""toAddress"",""type"":""address""}],""name"":""PunkOffered"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""punkIndex"",""type"":""uint256""},{""indexed"":false,""name"":""value"",""type"":""uint256""},{""indexed"":true,""name"":""fromAddress"",""type"":""address""}],""name"":""PunkBidEntered"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""punkIndex"",""type"":""uint256""},{""indexed"":false,""name"":""value"",""type"":""uint256""},{""indexed"":true,""name"":""fromAddress"",""type"":""address""}],""name"":""PunkBidWithdrawn"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""punkIndex"",""type"":""uint256""},{""indexed"":false,""name"":""value"",""type"":""uint256""},{""indexed"":true,""name"":""fromAddress"",""type"":""address""},{""indexed"":true,""name"":""toAddress"",""type"":""address""}],""name"":""PunkBought"",""type"":""event""},
{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""punkIndex"",""type"":""uint256""}],""name"":""PunkNoLongerForSale"",""type"":""event""}]";
public const string CryptoPunksAbi =
@"[{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""name"":""balance"",""type"":""uint256""}],""payable"":false,""stateMutability"":""view"",""type"":""function""},
{""constant"":true,""inputs"":[],""name"":""name"",""outputs"":[{""name"":"""",""type"":""string""}],""payable"":false,""stateMutability"":""view"",""type"":""function""}]";
}
}