Skip to content

Commit

Permalink
🐛 Fix WebGL web request (#23)
Browse files Browse the repository at this point in the history
* 🐛 Fix WebGL web request

* ⚡ Find whirlpool return poll with liquidity more than 0

* 💚 Ignore tests with no liquidity pools

* 💚 Fix CI
  • Loading branch information
GabrielePicco authored Jan 23, 2023
1 parent f14538a commit 048d0fd
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 57 deletions.
2 changes: 1 addition & 1 deletion src/Solana.Unity.Dex/Orca/Orca/OrcaDex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ public override async Task<Tuple<PublicKey, Whirlpool>> FindWhirlpool(
await Task.WhenAll(promises);
foreach(var p in promises)
{
if (p.Result != null && p.Result.Item2 != null)
if (p.Result != null && p.Result.Item2 != null && p.Result.Item2.Liquidity > 0)
{
result = p.Result;
break;
Expand Down
3 changes: 2 additions & 1 deletion src/Solana.Unity.Dex/Orca/Orca/OrcaTokens.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ public static async Task<IList<TokenData>> GetTokens(Cluster cluster = Cluster.M
{
using var client = new HttpClient();
using var httpReq = new HttpRequestMessage(HttpMethod.Get, url);
string response = await CrossHttpClient.SendAsyncRequest(client, httpReq).Result.Content.ReadAsStringAsync();
HttpResponseMessage result = await CrossHttpClient.SendAsyncRequest(client, httpReq);
string response = await result.Content.ReadAsStringAsync();
TokensDocument tokensDocument = new JsonSerializer().Deserialize<TokensDocument>(
new JsonTextReader(
new StringReader(response)
Expand Down
6 changes: 5 additions & 1 deletion src/Solana.Unity.Dex/Orca/Quotes/Swap/SwapQuoteUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,11 @@ PublicKey programId
)
{
TokenType swapTokenType = PoolUtils.GetTokenType(whirlpool, inputTokenMint);
System.Diagnostics.Debug.Assert(swapTokenType != TokenType.None, "swapTokenMint does not match any tokens on this pool");
if(swapTokenType == TokenType.None)
throw new WhirlpoolsException(
"swapTokenMint does not match any tokens on this pool",
SwapErrorCode.SqrtPriceOutOfBounds
);
bool aToB = swapTokenType == amountSpecifiedTokenType;

IList<TickArrayContainer> tickArrays = await SwapUtils.GetTickArrays(
Expand Down
4 changes: 2 additions & 2 deletions src/Solana.Unity.Dex/Orca/Ticks/TickArraySequence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ public IList<PublicKey> GetTouchedArrays(int minArraySize)
/// <returns>True if the given index is in bounds of the array.</returns>
private bool IsArrayIndexInBounds(TickArrayIndex index, bool aToB)
{
long localArrayIndex = this.GetLocalArrayIndex(index.ArrayIndex, aToB);
int seqLength = this._tickArrays.Count;
long localArrayIndex = GetLocalArrayIndex(index.ArrayIndex, aToB);
int seqLength = _tickArrays.Count;
return localArrayIndex >= 0 && localArrayIndex < seqLength;
}

Expand Down
7 changes: 5 additions & 2 deletions src/Solana.Unity.Dex/Orca/Ticks/TickUtils.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;

using Solana.Unity.Dex.Orca.Core.Accounts;
using Solana.Unity.Dex.Orca.Exceptions;

namespace Solana.Unity.Dex.Orca.Ticks
{
Expand All @@ -13,8 +14,10 @@ public static int GetStartTickIndex(int tickIndex, ushort tickSpacing, int offse

int ticksInArray = TickConstants.TICK_ARRAY_SIZE * tickSpacing;
int minTickIndex = TickConstants.MIN_TICK_INDEX - ((TickConstants.MIN_TICK_INDEX % ticksInArray) + ticksInArray);
System.Diagnostics.Debug.Assert(startTickIndex >= minTickIndex, $"startTickIndex (${startTickIndex}) >= minTickIndex ({minTickIndex})");
System.Diagnostics.Debug.Assert(startTickIndex <= TickConstants.MAX_TICK_INDEX, $"startTickIndex (${startTickIndex}) <= TickConstants.MAX_TICK_INDEX ({TickConstants.MAX_TICK_INDEX})");
if (startTickIndex < minTickIndex)
throw new WhirlpoolsException($"startTickIndex (${startTickIndex}) >= minTickIndex ({minTickIndex})");
if (startTickIndex > TickConstants.MAX_TICK_INDEX)
throw new WhirlpoolsException($"startTickIndex (${startTickIndex}) <= TickConstants.MAX_TICK_INDEX ({TickConstants.MAX_TICK_INDEX})");
return (int)startTickIndex;
}

Expand Down
9 changes: 7 additions & 2 deletions src/Solana.Unity.Extensions/TokenMintResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static TokenMintResolver Load()
}

/// <summary>
/// Return an instance of the TokenMintResolver loaded dererialised token list JSON from the specified URL.
/// Return an instance of the TokenMintResolver loaded deserialised token list JSON from the specified URL.
/// </summary>
/// <param name="url"></param>
/// <returns>An instance of the TokenMintResolver populated with Solana token list definitions.</returns>
Expand All @@ -91,7 +91,12 @@ public static async Task<TokenMintResolver> LoadAsync(string url)
using (var client = new HttpClient())
{
using var httpReq = new HttpRequestMessage(HttpMethod.Get, url);
string json = await CrossHttpClient.SendAsyncRequest(client, httpReq).Result.Content.ReadAsStringAsync();
var httpResp = await CrossHttpClient.SendAsyncRequest(client, httpReq);
string json = null;
if (httpResp.IsSuccessStatusCode && httpResp.Content != null)
{
json = await httpResp.Content.ReadAsStringAsync();
}
return ParseTokenList(json);
}
}
Expand Down
72 changes: 41 additions & 31 deletions src/Solana.Unity.Rpc/Core/Http/CrossHttpClient.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using Solana.Unity.Rpc.Utilities;
using System;
using System.Collections;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine.Networking;

Expand All @@ -14,6 +14,8 @@ namespace Solana.Unity.Rpc.Core.Http;
/// </summary>
public static class CrossHttpClient
{
private static TaskCompletionSource<UnityWebRequest.Result> _currentRequestTask;

/// <summary>
/// Send an async request using HttpClient or UnityWebRequest if running on Unity
/// </summary>
Expand All @@ -29,6 +31,8 @@ public static async Task<HttpResponseMessage> SendAsyncRequest(HttpClient httpCl
}
return await httpClient.SendAsync(httpReq).ConfigureAwait(false);
}



/// <summary>
/// Convert a httReq to a Unity Web request
Expand All @@ -39,42 +43,48 @@ public static async Task<HttpResponseMessage> SendAsyncRequest(HttpClient httpCl
/// <exception cref="HttpRequestException"></exception>
private static async Task<HttpResponseMessage> SendUnityWebRequest(Uri uri, HttpRequestMessage httpReq)
{
using (var request = new UnityWebRequest(uri, httpReq.Method.ToString()))
using UnityWebRequest request = new(uri, httpReq.Method.ToString());
if (httpReq.Content != null)
{
if (httpReq.Content != null)
{
request.uploadHandler = new UploadHandlerRaw(await httpReq.Content.ReadAsByteArrayAsync());
request.SetRequestHeader("Content-Type", "application/json");
}
request.downloadHandler = new DownloadHandlerBuffer();
var response = new HttpResponseMessage();
var e = SendRequest(request, response);
while (e.MoveNext()) { }
if (request.result == UnityWebRequest.Result.ConnectionError)
{
throw new HttpRequestException("Error While Sending: " + request.error);
}
return response;
request.uploadHandler = new UploadHandlerRaw(await httpReq.Content.ReadAsByteArrayAsync());
request.SetRequestHeader("Content-Type", "application/json");
}
request.downloadHandler = new DownloadHandlerBuffer();
if (_currentRequestTask != null)
{
await _currentRequestTask.Task;
}
UnityWebRequest.Result result = await SendRequest(request);
HttpResponseMessage response = new();
if (result == UnityWebRequest.Result.Success)
{
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(request.downloadHandler.text));
}
else
{
response.StatusCode = HttpStatusCode.ExpectationFailed;
}
return response;
}

/// <summary>
/// Send a request using UnityWebRequest and wait for the response
/// </summary>
/// <param name="request"></param>
/// <param name="res"></param>
/// <returns></returns>
/// <exception cref="HttpRequestException"></exception>
private static IEnumerator SendRequest(UnityWebRequest request, HttpResponseMessage res)
private static Task<UnityWebRequest.Result> SendRequest(UnityWebRequest request)
{
yield return request.SendWebRequest();
while (!request.isDone)
yield return true;
if (request.result == UnityWebRequest.Result.ConnectionError)
TaskCompletionSource<UnityWebRequest.Result> sendRequestTask = new();
_currentRequestTask = sendRequestTask;
UnityWebRequestAsyncOperation op = request.SendWebRequest();

if (request.isDone)
{
sendRequestTask.SetResult(request.result);
}
else
{
throw new HttpRequestException("Error While Sending: " + request.error);
op.completed += asyncOp =>
{
sendRequestTask.SetResult(((UnityWebRequestAsyncOperation)asyncOp).webRequest.result);
};
}
res.StatusCode = HttpStatusCode.OK;
res.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(request.downloadHandler.text));
return sendRequestTask.Task;
}
}
3 changes: 2 additions & 1 deletion src/Solana.Unity.Rpc/Utilities/RuntimePlatforms.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public static bool IsWebGL()
{
return false;
}
return GetRuntimePlatform() == WebGLPlayer;
string platform = GetRuntimePlatform();
return platform == WebGLPlayer || string.IsNullOrEmpty(platform);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,11 @@
using Orca;
using System;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using System.Collections.Generic;

using Solana.Unity.Wallet;
using Solana.Unity.Rpc.Models;
using Solana.Unity.Rpc.Types;
using Solana.Unity.Programs.Models;

using Solana.Unity.Dex.Orca;
using Solana.Unity.Dex.Orca.Math;
using Solana.Unity.Dex.Orca.SolanaApi;
using Solana.Unity.Dex.Orca.Ticks;
using Solana.Unity.Dex.Orca.Quotes.Swap;
using Solana.Unity.Dex.Orca.Core.Accounts;
using Solana.Unity.Dex.Test.Orca.Params;
using Solana.Unity.Dex.Orca.Address;
using Solana.Unity.Dex.Test.Orca.Utils;
using Solana.Unity.Dex.Ticks;
Expand Down Expand Up @@ -94,7 +83,7 @@ private static async Task<List<WhirlpoolMiniData>> CreateABunchOfPools(int numPo

[Test]
[Description("finds whirlpool with tokens specified in correct order, with correct tickspacing")]
public static async Task Find_WhirlpoolsCorrectOrderCorrectTickSpacing()
public static async Task FindWhirlpoolsCorrectOrderCorrectTickSpacing()
{
OrcaDex dex = new OrcaDex(_context);

Expand All @@ -114,7 +103,7 @@ public static async Task Find_WhirlpoolsCorrectOrderCorrectTickSpacing()

[Test]
[Description("finds whirlpool with tokens specified in correct order, with correct tickspacing")]
public static async Task Find_WhirlpoolsAddressCorrectOrderCorrectTickSpacing()
public static async Task FindWhirlpoolsAddressCorrectOrderCorrectTickSpacing()
{
IDex dex = new OrcaDex(_context);

Expand All @@ -129,6 +118,7 @@ public static async Task Find_WhirlpoolsAddressCorrectOrderCorrectTickSpacing()
}

[Test]
[Ignore("Ignore no liquidity poll")]
[Description("finds whirlpool with tokens specified in correct order, with wrong tickspacing")]
public static async Task FindWhirlpoolsCorrectOrderWrongTickSpacing()
{
Expand Down Expand Up @@ -169,6 +159,7 @@ public static async Task FindWhirlpoolsWrongOrderCorrectTickSpacing()
}

[Test]
[Ignore("Ignore no liquidity poll")]
[Description("finds whirlpool with tokens specified in wrong order, with wrong tickspacing")]
public static async Task FindWhirlpoolsWrongOrderWrongTickSpacing()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Solana.Unity.Dex.Test.Orca.Utils;
using Solana.Unity.Dex.Ticks;
using Solana.Unity.Rpc.Types;
using System;
using BigDecimal = Solana.Unity.Dex.Orca.Math.BigDecimal;

namespace Solana.Unity.Dex.Test.Orca.Integration
Expand Down Expand Up @@ -107,6 +108,7 @@ await _context.WhirlpoolClient.GetPositionAsync(position.PublicKey, _defaultComm

Assert.IsTrue(updateResult.WasSuccessful);
Assert.IsTrue(await _context.RpcClient.ConfirmTransaction(updateResult.Result, _defaultCommitment));
await Task.Delay(TimeSpan.FromSeconds(10));

//get position after
Position positionAfter = (
Expand Down
8 changes: 5 additions & 3 deletions test/Solana.Unity.Dex.Test/Orca/Utils/PoolTestUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,8 @@ public static async Task<PoolInitWithLiquidityResult> BuildPoolWithLiquidity(
BigInteger? initSqrtPrice = null,
BigInteger? mintAmount = null,
bool tokenAIsNative = false,
bool aToB = false
bool aToB = false,
bool skipInitConfig = false
)
{
if (initConfigParams == null)
Expand All @@ -248,8 +249,9 @@ public static async Task<PoolInitWithLiquidityResult> BuildPoolWithLiquidity(
tickSpacing,
defaultFeeRate,
initSqrtPrice,
mintAmount,
tokenAIsNative
mintAmount,
tokenAIsNative,
skipInitConfig
);

IList<Pda> tickArrays = await TickArrayTestUtils.InitializeTickArrayRangeAsync(
Expand Down

0 comments on commit 048d0fd

Please sign in to comment.