Skip to content

Commit

Permalink
Merge pull request #19 from WalletConnect/fix/webgl-solidity-data-types
Browse files Browse the repository at this point in the history
fix: interaction with some smart contract functions is broken in WebGL
  • Loading branch information
skibitsky authored Aug 2, 2024
2 parents cda06d2 + 3921a9a commit d55882e
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 51 deletions.
4 changes: 2 additions & 2 deletions Packages/com.walletconnect.web3modal/Plugins/Web3Modal.jslib
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 Expand Up @@ -69,7 +69,7 @@ mergeInto(LibraryManager.library, {
const enableOnramp = parameters.enableOnramp;

// Load the scripts and initialize the configuration
import("https://cdn.jsdelivr.net/npm/@web3modal/[email protected].1/dist/wagmi.js").then(CDNW3M => {
import("https://cdn.jsdelivr.net/npm/@web3modal/[email protected].11/dist/wagmi.js").then(CDNW3M => {
const WagmiCore = CDNW3M['WagmiCore'];
const Chains = CDNW3M['Chains'];
const Web3modal = CDNW3M['Web3modal'];
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
}

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
Expand Up @@ -89,6 +89,11 @@ public Task<string> WriteContractAsync(string contractAddress, string contractAb
return WriteContractAsync(contractAddress, contractAbi, methodName, default, default, arguments);
}

public Task<string> WriteContractAsync(string contractAddress, string contractAbi, string methodName, BigInteger gas = default, params object[] arguments)
{
return WriteContractAsyncCore(contractAddress, contractAbi, methodName, default, gas, arguments);
}

public Task<string> WriteContractAsync(string contractAddress, string contractAbi, string methodName, BigInteger value = default, BigInteger gas = default, params object[] arguments)
{
return WriteContractAsyncCore(contractAddress, contractAbi, methodName, value, gas, arguments);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,12 @@ protected override async Task<string> WriteContractAsyncCore(string contractAddr
var contract = Web3.Eth.GetContract(contractAbi, contractAddress);
var function = contract.GetFunction(methodName);

var receipt = await function.SendTransactionAndWaitForReceiptAsync(
from: null, // will be automatically filled by interceptor
gas: new HexBigInteger(gas),
value: new HexBigInteger(value),
receiptRequestCancellationToken: CancellationToken.None,
return await function.SendTransactionAsync(
null, // will be automatically filled by interceptor
new HexBigInteger(gas),
new HexBigInteger(value),
arguments
);

return receipt.TransactionHash;
}


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""}]";
}
}

0 comments on commit d55882e

Please sign in to comment.