Skip to content

Commit

Permalink
feat(node services): add explicit operators to convert from `IAlgoApi…
Browse files Browse the repository at this point in the history
…Client` to dotnet SDK APIs

- add `UnityHttpMessageHandler`
- add `UnityHttpClient`
- add explicit operators `AlgodClient` <-> Algorand.Algod APIs
- add explicit operators `IndexerClient` <-> Algorand.Indexer APIs

fix #157, fix #158
  • Loading branch information
jasonboukheir committed Nov 19, 2022
1 parent 2bc3cfc commit 6a657fc
Show file tree
Hide file tree
Showing 94 changed files with 603 additions and 931 deletions.
56 changes: 47 additions & 9 deletions Runtime/Algorand.Unity/Http/UnityHttpClient.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,72 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net.Http;

namespace Algorand.Unity
{
public class UnityHttpClient : HttpClient
{
public readonly UnityHttpMessageHandler MessageHandler;

protected UnityHttpClient(UnityHttpMessageHandler messageHandler)
: base(messageHandler)
{
MessageHandler = messageHandler;
}

public UnityHttpClient(
string address
)
: base(new UnityHttpMessageHandler())
: this(address, System.Threading.Timeout.InfiniteTimeSpan)
{
}

public UnityHttpClient(
string address,
TimeSpan timeout
)
: this(new UnityHttpMessageHandler())
{
BaseAddress = FormatAddress(address);
Timeout = timeout;
}

public UnityHttpClient(
string address,
params (string header, string value)[] headers
)
: base(new UnityHttpMessageHandler())
: this(address, System.Threading.Timeout.InfiniteTimeSpan, headers)
{
}

public UnityHttpClient(
string address,
TimeSpan timeout,
params (string header, string value)[] headers
)
: this(new UnityHttpMessageHandler())
{
BaseAddress = FormatAddress(address);
Timeout = timeout;

if (headers == null)
{
return;
}

foreach (var (key, value) in headers)
{
DefaultRequestHeaders.Add(key, value);
}
}

private static Uri FormatAddress(string address)
{
if (!address.EndsWith('/'))
address = address + '/';
address += '/';
var addressUri = new Uri(address);
if (!addressUri.IsAbsoluteUri)
throw new ArgumentException("Given host must be an absolute path.", nameof(address));
if (headers == null)
throw new ArgumentNullException(nameof(headers));
return addressUri;
}
}
}
}
35 changes: 21 additions & 14 deletions Runtime/Algorand.Unity/Http/UnityHttpMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
Expand All @@ -8,11 +6,14 @@
using UnityEngine;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;

namespace Algorand.Unity
{
public class UnityHttpMessageHandler : HttpMessageHandler
{
public UnityWebRequestAsyncOperation LastSentRequest { get; protected set; }

protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
Expand All @@ -38,29 +39,35 @@ CancellationToken cancellationToken
unityWebRequest.SetRequestHeader(key, value);
}

Debug.Log("Sent webrequest");
await unityWebRequest.SendWebRequest().WithCancellation(cancellationToken);
var responseMessage = new HttpResponseMessage((HttpStatusCode)unityWebRequest.responseCode)
{
Content = new ByteArrayContent(unityWebRequest.downloadHandler.data)
};
var sentRequest = unityWebRequest.SendWebRequest();
LastSentRequest = sentRequest;
await sentRequest.WithCancellation(cancellationToken);
var responseCode = (HttpStatusCode)unityWebRequest.responseCode;
var responseContent = new ByteArrayContent(unityWebRequest.downloadHandler.data);
var responseMessage = new HttpResponseMessage(responseCode) { Content = responseContent };
foreach (var header in unityWebRequest.GetResponseHeaders())
{
try
{
var headerLower = header.Key.ToLower();
if (headerLower is not "content-type" && headerLower is not "content-length")
responseMessage.Headers.Add(header.Key, header.Value);
else
if (IsContentHeader(header))
responseMessage.Content.Headers.Add(header.Key, header.Value);
else
responseMessage.Headers.Add(header.Key, header.Value);
}
catch
catch (System.Exception ex)
{
Debug.LogError($"Issue with header: {header}");
var aggregate = new System.Exception($"Issue with header: {header}", ex);
Debug.LogException(aggregate);
throw;
}
}
return responseMessage;
}

private static bool IsContentHeader(KeyValuePair<string, string> header)
{
var headerKeyLower = header.Key.ToLower();
return headerKeyLower == "content-type" || headerKeyLower == "content-length";
}
}
}
13 changes: 9 additions & 4 deletions Runtime/CareBoo.AlgoSdk.Crypto/Ed25519.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public struct SecretKeyHandle
{
public const int KeySize = (32 + 32);

SecureMemoryHandle handle;
private SecureMemoryHandle handle;

public IntPtr Ptr => handle.Ptr;

Expand Down Expand Up @@ -80,10 +80,10 @@ public Signature Sign<TMessage>(TMessage message)
crypto_sign_ed25519_detached(
&signature,
message.GetUnsafePtr(),
(UIntPtr)message.Length,
(UIntPtr)message.Length,
Ptr);
#else
crypto_sign_ed25519_detached(
var errorCode = crypto_sign_ed25519_detached(
&signature,
out _,
message.GetUnsafePtr(),
Expand Down Expand Up @@ -143,7 +143,12 @@ public KeyPair ToKeyPair()
int error = crypto_sign_ed25519_seed_keypair(
&pk,
sk.Ptr,
seedPtr);
seedPtr
);
if (error > 0)
{
throw new System.Exception($"error code {error} when converting to KeyPair");
}
}
return new KeyPair(sk, pk);
}
Expand Down
6 changes: 3 additions & 3 deletions Runtime/CareBoo.AlgoSdk/Accounts/Account.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public interface IAccount
, IAsyncSigner
, IAsyncSignerWithProgress
{
readonly PrivateKey privateKey;
private readonly PrivateKey privateKey;

readonly Address address;
private readonly Address address;

readonly bool isRekeyed;
private readonly bool isRekeyed;

/// <inheritdoc />
public Address Address => address;
Expand Down
6 changes: 2 additions & 4 deletions Runtime/CareBoo.AlgoSdk/Blockchain/AppliedSignedTxn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ public partial struct AppliedSignedTxn
: IEquatable<AppliedSignedTxn>
, IAppliedSignedTxn<AppliedSignedTxn>
{
[SerializeField]
SignedTxn txn;
[SerializeField] private SignedTxn txn;

[SerializeField]
ApplyData<AppliedSignedTxn> applyData;
[SerializeField] private ApplyData<AppliedSignedTxn> applyData;

/// <inheritdoc />
[AlgoApiField("sig")]
Expand Down
16 changes: 8 additions & 8 deletions Runtime/CareBoo.AlgoSdk/Blockchain/ApplyData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,28 +57,28 @@ public struct ApplyData<TTxn>
where TTxn : IAppliedSignedTxn<TTxn>
{
[SerializeField, Tooltip("Closing amount for transaction.")]
MicroAlgos closingAmount;
private MicroAlgos closingAmount;

[SerializeField, Tooltip("Closing amount for asset transaction.")]
ulong assetClosingAmount;
private ulong assetClosingAmount;

[SerializeField, Tooltip("Rewards applied to Sender account.")]
MicroAlgos senderRewards;
private MicroAlgos senderRewards;

[SerializeField, Tooltip("Rewards applied to Receiver account.")]
MicroAlgos receiverRewards;
private MicroAlgos receiverRewards;

[SerializeField, Tooltip("Rewards applied to CloseRemainderTo account.")]
MicroAlgos closeRewards;
private MicroAlgos closeRewards;

[SerializeField, Tooltip("Application global and local state delta.")]
EvalDelta<TTxn> evalDelta;
private EvalDelta<TTxn> evalDelta;

[SerializeField, Tooltip("If an asset is configured or created, the id used.")]
AssetIndex configAsset;
private AssetIndex configAsset;

[SerializeField, Tooltip("If an app is called, the id used.")]
AppIndex applicationId;
private AppIndex applicationId;

/// <inheritdoc />
public MicroAlgos ClosingAmount
Expand Down
2 changes: 1 addition & 1 deletion Runtime/CareBoo.AlgoSdk/Blockchain/BlockHash.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public partial struct BlockHash
: IByteArray
, IEquatable<BlockHash>
{
[SerializeField] Sha512_256_Hash hash;
[SerializeField] private Sha512_256_Hash hash;

public byte this[int index] { get => hash[index]; set => hash[index] = value; }

Expand Down
12 changes: 6 additions & 6 deletions Runtime/CareBoo.AlgoSdk/Blockchain/BlockRewards.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,27 +43,27 @@ public partial struct BlockRewards
{
[SerializeField]
[Tooltip("accepts transaction fees, it can only spend to the incentive pool.")]
Address feeSink;
private Address feeSink;

[SerializeField]
[Tooltip("number of leftover MicroAlgos after the distribution of rewards-rate MicroAlgos for every reward unit in the next round.")]
ulong rewardsCalculationRound;
private ulong rewardsCalculationRound;

[SerializeField]
[Tooltip("How many rewards, in MicroAlgos, have been distributed to each RewardUnit of MicroAlgos since genesis.")]
ulong rewardsLevel;
private ulong rewardsLevel;

[SerializeField]
[Tooltip("accepts periodic injections from the fee-sink and continually redistributes them as rewards.")]
Address rewardsPool;
private Address rewardsPool;

[SerializeField]
[Tooltip("Number of new MicroAlgos added to the participation stake from rewards at the next round.")]
ulong rewardsRate;
private ulong rewardsRate;

[SerializeField]
[Tooltip("Number of leftover MicroAlgos after the distribution of RewardsRate/rewardUnits MicroAlgos for every reward unit in the next round.")]
ulong rewardsResidue;
private ulong rewardsResidue;

[AlgoApiField("fee-sink")]
public Address FeeSink
Expand Down
9 changes: 3 additions & 6 deletions Runtime/CareBoo.AlgoSdk/Blockchain/BlockTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,11 @@ public partial struct BlockTransaction
: IEquatable<BlockTransaction>
, IBlockTransaction
{
[SerializeField]
AppliedSignedTxn txn;
[SerializeField] private AppliedSignedTxn txn;

[SerializeField]
Optional<bool> hasGenesisId;
[SerializeField] private Optional<bool> hasGenesisId;

[SerializeField]
Optional<bool> hasGenesisHash;
[SerializeField] private Optional<bool> hasGenesisHash;

/// <inheritdoc />
[AlgoApiField("sig")]
Expand Down
10 changes: 5 additions & 5 deletions Runtime/CareBoo.AlgoSdk/Blockchain/BlockUpgradeState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,23 @@ public partial struct BlockUpgradeState
{
[SerializeField]
[Tooltip("The current protocol version.")]
FixedString128Bytes currentProtocol;
private FixedString128Bytes currentProtocol;

[SerializeField]
[Tooltip("The next proposed protocol version.")]
FixedString128Bytes nextProtocol;
private FixedString128Bytes nextProtocol;

[SerializeField]
[Tooltip("Number of blocks which approved the protocol upgrade.")]
ulong nextProtocolApprovals;
private ulong nextProtocolApprovals;

[SerializeField]
[Tooltip("Round on which the protocol upgrade will take effect.")]
ulong nextProtocolSwitchOn;
private ulong nextProtocolSwitchOn;

[SerializeField]
[Tooltip("Deadline round for this protocol upgrade (No votes will be consider after this round).")]
ulong nextProtocolVoteBefore;
private ulong nextProtocolVoteBefore;

[AlgoApiField("current-protocol")]
public FixedString128Bytes CurrentProtocol
Expand Down
6 changes: 3 additions & 3 deletions Runtime/CareBoo.AlgoSdk/Blockchain/BlockUpgradeVote.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ public partial struct BlockUpgradeVote
{
[SerializeField]
[Tooltip("Indicates a yes vote for the current proposal.")]
Optional<bool> upgradeApprove;
private Optional<bool> upgradeApprove;

[SerializeField]
[Tooltip("Indicates the time between acceptance and execution.")]
ulong upgradeDelay;
private ulong upgradeDelay;

[SerializeField]
[Tooltip("Indicates a proposed upgrade.")]
Address upgradePropose;
private Address upgradePropose;

[AlgoApiField("upgrade-approve")]
public Optional<bool> UpgradeApprove
Expand Down
2 changes: 1 addition & 1 deletion Runtime/CareBoo.AlgoSdk/Blockchain/GenesisHash.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public partial struct GenesisHash
: IByteArray
, IEquatable<GenesisHash>
{
[SerializeField] Sha512_256_Hash hash;
[SerializeField] private Sha512_256_Hash hash;

public byte this[int index] { get => hash[index]; set => hash[index] = value; }

Expand Down
3 changes: 1 addition & 2 deletions Runtime/CareBoo.AlgoSdk/Blockchain/MicroAlgos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ public partial struct MicroAlgos
/// </summary>
public const ulong PerAlgo = 1_000_000;

[SerializeField]
ulong amount;
[SerializeField] private ulong amount;

public ulong Amount
{
Expand Down
Loading

0 comments on commit 6a657fc

Please sign in to comment.