Add message signing

This commit is contained in:
Ivan Yaremenchuk 2022-04-04 22:34:52 +02:00
parent 79f57f273d
commit b97acab586
3 changed files with 86 additions and 0 deletions

View File

@ -1,14 +1,24 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.JsonRpc.Client;
using Nethereum.JsonRpc.Client.RpcMessages;
using Newtonsoft.Json;
using NftFaucet.Components;
using NftFaucet.Constants;
using NftFaucet.Extensions;
using NftFaucet.Models.Enums;
using Serilog;
using RpcError = Nethereum.JsonRpc.Client.RpcError;
namespace NftFaucet.Pages;
public class Step1Component : BasicComponent
{
[Inject]
protected IJSRuntime JsRuntime { get; set; }
protected string NameErrorMessage { get; set; }
protected string DescriptionErrorMessage { get; set; }
protected string ImageErrorMessage { get; set; }
@ -122,4 +132,24 @@ public class Step1Component : BasicComponent
return false;
}
public async Task<string> SignAsync(string message)
{
var rpcJsonResponse = await JsRuntime.InvokeAsync<string>("NethereumMetamaskInterop.Sign", message.ToHexUTF8());
var response = JsonConvert.DeserializeObject<RpcResponseMessage>(rpcJsonResponse);
if (response.HasError)
{
var rpcError = new RpcError(response.Error.Code, response.Error.Message, response.Error.Data);
throw new RpcResponseException(rpcError);
}
try
{
return response.GetResult<string>();
}
catch (FormatException formatException)
{
throw new RpcResponseFormatException("Invalid format found in RPC response", formatException);
}
}
}

View File

@ -0,0 +1,55 @@
async function metamaskRequest(parsedMessage) {
try {
const response = await ethereum.request(parsedMessage);
let rpcResponse = {
jsonrpc: "2.0",
result: response,
id: parsedMessage.id,
error: null
}
return rpcResponse;
} catch (e) {
console.log(e);
let rpcResonseError = {
jsonrpc: "2.0",
id: parsedMessage.id,
error: e
}
return rpcResonseError;
}
}
async function getSelectedAddress() {
let accountsReponse = await getAddresses();
if (accountsReponse.error !== null) throw accountsReponse.error;
return accountsReponse.result[0];
}
async function getAddresses() {
return await metamaskRequest({ method: 'eth_requestAccounts' });
}
window.NethereumMetamaskInterop = {
Sign: async (utf8HexMsg) => {
try {
const from = await getSelectedAddress();
const params = [utf8HexMsg, from];
const method = 'personal_sign';
const rpcResponse = await metamaskRequest({
method,
params,
from
});
return JSON.stringify(rpcResponse);
} catch (e) {
console.log(e);
let rpcResponseError = {
jsonrpc: "2.0",
id: parsedMessage.id,
error: e
}
return JSON.stringify(rpcResponseError);
}
}
}

View File

@ -31,6 +31,7 @@
<script src="_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js"></script>
<script src="_content/BlazorMonaco/jsInterop.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="NethereumMetamask.js"></script>
</body>
</html>