Skip to content

Commit

Permalink
feat(errors): serializer read errors now print the full message they'…
Browse files Browse the repository at this point in the history
…re deserializing

This should make it easier to debug when reading json or msgpack
  • Loading branch information
jasonboukheir committed Mar 25, 2022
1 parent 3c500b3 commit b67db2a
Show file tree
Hide file tree
Showing 20 changed files with 77 additions and 36 deletions.
17 changes: 15 additions & 2 deletions Runtime/CareBoo.AlgoSdk.Json/JsonReadError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ public class JsonReadException : Exception
{
public JsonReadException(JsonReadError error, char c, int pos)
: base($"{error} on char '{c}' at pos: {pos}")
{
}
{ }

public JsonReadException(JsonReadError error, JsonReader context)
: base($"{error} on char '{context.Char}' at position: {context.Position} in JSON text:\n{context.Text}")
{ }
}

public static class JsonReadErrorExtensions
Expand All @@ -31,5 +34,15 @@ public static void ThrowIfError(this JsonReadError err, char c, int pos)
throw new JsonReadException(err, c, pos);
}
}

public static void ThrowIfError(this JsonReadError err, JsonReader context)
{
switch (err)
{
case JsonReadError.None: return;
default:
throw new JsonReadException(err, context);
}
}
}
}
2 changes: 2 additions & 0 deletions Runtime/CareBoo.AlgoSdk.Json/JsonReader/JsonReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public int Position

public char Char => text.Peek(offset).ToChar();

public string Text => text.ToString();

public JsonToken Peek()
{
if (offset >= text.Length)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ namespace AlgoSdk.MessagePack
{
public ref partial struct MessagePackReader
{
NotSupportedException InvalidCode(int code) => new NotSupportedException($"invalid code: {code} at position {offset}");
NotSupportedException InvalidCode(int code) => new NotSupportedException(
$"invalid code: {code} at position {offset}\nbase64 msgpack: \"{System.Convert.ToBase64String(data.ToArray())}\"");

EndOfStreamException InsufficientBuffer() => new EndOfStreamException("insufficient buffer...");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ async UniTask<JsonRpcResponse> PollUntilResponse(ulong id, CancellationToken can
catch (Exception e) when (e is JsonReadException || e is SerializationException || e is AggregateException)
{
var s = Encoding.UTF8.GetString(payloadEvent.Payload);
Debug.LogWarning($"Did not recognize payload: {s}");
Debug.LogWarning($"Did not recognize payload: {s}\n{e}");
}
}
}
Expand Down
1 change: 0 additions & 1 deletion Runtime/CareBoo.AlgoSdk.WalletConnect/JsonRpc.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using AlgoSdk.Collections;
using AlgoSdk.WalletConnect;
using AlgoSdk.WebSocket;
using Unity.Collections;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public partial struct JsonRpcResponse

private static bool @__generated__InitializeAlgoApiFormatters()
{
AlgoSdk.AlgoApiFormatterLookup.Add<AlgoSdk.WalletConnect.JsonRpcResponse>(new AlgoSdk.AlgoApiObjectFormatter<AlgoSdk.WalletConnect.JsonRpcResponse>().Assign("id", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Id, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, System.UInt64 value) => x.Id = value, false).Assign("jsonrpc", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.JsonRpc, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, System.String value) => x.JsonRpc = value, AlgoSdk.StringComparer.Instance, false).Assign("result", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Result, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, AlgoSdk.AlgoApiObject value) => x.Result = value, false).Assign("error", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Error, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, AlgoSdk.WalletConnect.JsonRpcError value) => x.Error = value, false));
AlgoSdk.AlgoApiFormatterLookup.Add<AlgoSdk.WalletConnect.JsonRpcResponse>(new AlgoSdk.AlgoApiObjectFormatter<AlgoSdk.WalletConnect.JsonRpcResponse>().Assign("id", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Id, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, AlgoSdk.Optional<System.UInt64> value) => x.Id = value, false).Assign("jsonrpc", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.JsonRpc, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, System.String value) => x.JsonRpc = value, AlgoSdk.StringComparer.Instance, false).Assign("result", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Result, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, AlgoSdk.AlgoApiObject value) => x.Result = value, false).Assign("error", null, (AlgoSdk.WalletConnect.JsonRpcResponse x) => x.Error, (ref AlgoSdk.WalletConnect.JsonRpcResponse x, AlgoSdk.WalletConnect.JsonRpcError value) => x.Error = value, false));
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public interface IJsonRpcResponse
/// The Id of the response.
/// It should be the same as the ID of the corresponding <see cref="IJsonRpcRequest"/>.
/// </summary>
ulong Id { get; set; }
Optional<ulong> Id { get; set; }

/// <summary>
/// The JsonRpc version.
Expand All @@ -40,7 +40,7 @@ public partial struct JsonRpcResponse
, IEquatable<JsonRpcResponse>
{
[AlgoApiField("id", null)]
public ulong Id { get; set; }
public Optional<ulong> Id { get; set; }

[AlgoApiField("jsonrpc", null)]
public string JsonRpc { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ public T Deserialize(ref JsonReader reader)
{
T result = default;
if (!reader.TryRead(JsonToken.ObjectBegin))
JsonReadError.IncorrectType.ThrowIfError(reader.Char, reader.Position);
JsonReadError.IncorrectType.ThrowIfError(reader);
while (reader.Peek() != JsonToken.ObjectEnd && reader.Peek() != JsonToken.None)
{
FixedString64Bytes key = default;
reader.ReadString(ref key).ThrowIfError(reader.Char, reader.Position);
reader.ReadString(ref key).ThrowIfError(reader);
try
{
if (jsonFieldMap.TryGetValue(key, out var field))
Expand All @@ -70,7 +70,7 @@ public T Deserialize(ref JsonReader reader)
}
}
if (!reader.TryRead(JsonToken.ObjectEnd))
JsonReadError.IncorrectFormat.ThrowIfError(reader.Char, reader.Position);
JsonReadError.IncorrectFormat.ThrowIfError(reader);
return result;
}

Expand Down Expand Up @@ -137,7 +137,7 @@ public AlgoApiObject Deserialize(ref JsonReader reader)
var json = new NativeText(Allocator.Temp);
try
{
reader.ReadRaw(ref json).ThrowIfError(reader.Char, reader.Position);
reader.ReadRaw(ref json).ThrowIfError(reader);
return json;
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class AddressFormatter : IAlgoApiFormatter<Address>
public Address Deserialize(ref JsonReader reader)
{
var fs = new FixedString128Bytes();
reader.ReadString(ref fs).ThrowIfError(reader.Char, reader.Position);
reader.ReadString(ref fs).ThrowIfError(reader);
return Address.FromString(fs);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public byte[] Deserialize(ref JsonReader reader)
var b64 = new NativeText(Allocator.Temp);
try
{
reader.ReadString(ref b64).ThrowIfError(reader.Char, reader.Position);
reader.ReadString(ref b64).ThrowIfError(reader);
return System.Convert.FromBase64String(b64.ToString());
}
finally
Expand Down Expand Up @@ -60,7 +60,7 @@ public TByteArray Deserialize(ref JsonReader reader)
try
{
reader.ReadString(ref text)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
TByteArray result = default;
result.CopyFromBase64(text);
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public ErrorResponse Deserialize(ref JsonReader reader)
}
}
if (!reader.TryRead(JsonToken.ObjectEnd))
JsonReadError.IncorrectFormat.ThrowIfError(reader.Char, reader.Position);
JsonReadError.IncorrectFormat.ThrowIfError(reader);
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public T Deserialize(ref JsonReader reader)
try
{
reader.ReadString(ref text)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
FixedBytesArray<T> bytes = default;
bytes.CopyFromBase64(text);
return bytes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public T Deserialize(ref JsonReader reader)
{
T result = default;
reader.ReadString(ref result)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ public T[] Deserialize(ref JsonReader reader)

var list = new List<T>();
if (!reader.TryRead(JsonToken.ArrayBegin))
JsonReadError.IncorrectType.ThrowIfError(reader.Char, reader.Position);
JsonReadError.IncorrectType.ThrowIfError(reader);
while (reader.Peek() != JsonToken.ArrayEnd && reader.Peek() != JsonToken.None)
{
var nextItem = AlgoApiFormatterCache<T>.Formatter.Deserialize(ref reader);
list.Add(nextItem);
}
if (!reader.TryRead(JsonToken.ArrayEnd))
JsonReadError.IncorrectFormat.ThrowIfError(reader.Char, reader.Position);
JsonReadError.IncorrectFormat.ThrowIfError(reader);

return list.ToArray();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public GenesisHash Deserialize(ref JsonReader reader)
{
var s = new FixedString64Bytes();
reader.ReadString(ref s)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
GenesisHash result = default;
result.CopyFromBase64(s);
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class BoolFormatter : IAlgoApiFormatter<bool>
public bool Deserialize(ref JsonReader reader)
{
reader.ReadBool(out bool val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class UInt64Formatter : IAlgoApiFormatter<ulong>
public ulong Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out ulong val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -33,7 +33,7 @@ public class UInt32Formatter : IAlgoApiFormatter<uint>
public uint Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out uint val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -58,7 +58,7 @@ public class UInt16Formatter : IAlgoApiFormatter<ushort>
public ushort Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out ushort val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -83,7 +83,7 @@ public class UInt8Formatter : IAlgoApiFormatter<byte>
public byte Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out byte val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -108,7 +108,7 @@ public class Int64Formatter : IAlgoApiFormatter<long>
public long Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out long val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -133,7 +133,7 @@ public class Int32Formatter : IAlgoApiFormatter<int>
public int Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out int val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -158,7 +158,7 @@ public class Int16Formatter : IAlgoApiFormatter<short>
public short Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out short val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand All @@ -183,7 +183,7 @@ public class Int8Formatter : IAlgoApiFormatter<sbyte>
public sbyte Deserialize(ref JsonReader reader)
{
reader.ReadNumber(out sbyte val)
.ThrowIfError(reader.Char, reader.Position);
.ThrowIfError(reader);
return val;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class TransactionIdFormatter : IAlgoApiFormatter<TransactionId>
public TransactionId Deserialize(ref JsonReader reader)
{
var fs = new FixedString64Bytes();
reader.ReadString(ref fs).ThrowIfError(reader.Char, reader.Position);
reader.ReadString(ref fs).ThrowIfError(reader);
return TransactionId.FromString(fs);
}

Expand Down
2 changes: 1 addition & 1 deletion Runtime/CareBoo.AlgoSdk/Serialization/HexFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public sealed class HexFormatter : IAlgoApiFormatter<Hex>
{
public Hex Deserialize(ref JsonReader reader)
{
reader.ReadString(out var s).ThrowIfError(reader.Char, reader.Position);
reader.ReadString(out var s).ThrowIfError(reader);
return Hex.FromString(s);
}

Expand Down
34 changes: 30 additions & 4 deletions Samples~/WalletConnect/WalletConnectManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Linq;
using AlgoSdk;
using AlgoSdk.WalletConnect;
using Cysharp.Threading.Tasks;
Expand All @@ -17,13 +16,20 @@ public class WalletConnectManager : MonoBehaviour

bool launchApp;

MicroAlgos currentBalance;

AlgorandWalletConnectSession session;

TransactionStatus txnStatus;

AlgodClient algod = new AlgodClient("https://node.testnet.algoexplorerapi.io");

IndexerClient indexer = new IndexerClient("https://algoindexer.testnet.algoexplorerapi.io");

void Start()
{
StartWalletConnect().Forget();
PollForBalance().Forget();
}

void OnGUI()
Expand Down Expand Up @@ -67,6 +73,8 @@ void OnGUI()
{
GUILayout.Label($"Connected Account: {session.Accounts[0]}");
GUILayout.Space(5);
var balanceAlgos = currentBalance / (double)MicroAlgos.PerAlgo;
GUILayout.Label($"Balance: {balanceAlgos:F} Algos");
switch (txnStatus)
{
case TransactionStatus.None:
Expand Down Expand Up @@ -94,9 +102,27 @@ async UniTaskVoid StartWalletConnect()
Debug.Log($"accounts:\n{AlgoApiSerializer.SerializeJson(session.Accounts)}");
}

async UniTaskVoid PollForBalance()
{
while (true)
{
var status = session?.ConnectionStatus ?? AlgorandWalletConnectSession.Status.Unknown;
if (status == AlgorandWalletConnectSession.Status.Connected)
{
var (err, response) = await indexer.GetAccount(session.Accounts[0]);
if (err) Debug.LogError(err);
else
{
currentBalance = response.Account.Amount;
}
}
await UniTask.Delay(1_000);
await UniTask.Yield();
}
}

async UniTaskVoid TestTransaction()
{
var algod = new AlgodClient("https://node.testnet.algoexplorerapi.io");
var (txnParamsErr, txnParams) = await algod.GetSuggestedParams();
if (txnParamsErr)
{
Expand All @@ -121,7 +147,7 @@ async UniTaskVoid TestTransaction()
var signingTransactions = session.SignTransactions(new[] { walletTxn });
if (launchApp)
WalletRegistry.PeraWallet.LaunchForSigning();
var (err, signedTxns) = await session.SignTransactions(new[] { walletTxn });
var (err, signedTxns) = await signingTransactions;
if (err)
{
txnStatus = TransactionStatus.Failed;
Expand Down Expand Up @@ -153,7 +179,7 @@ async UniTaskVoid TestTransaction()
}
while (pending.ConfirmedRound <= 0)
{
await UniTask.Delay(500);
await UniTask.Delay(1000);
(pendingErr, pending) = await algod.GetPendingTransaction(txid);
}
txnStatus = TransactionStatus.Confirmed;
Expand Down

0 comments on commit b67db2a

Please sign in to comment.