Skip to content

Commit

Permalink
Buy With Fiat API // Scene_Pay (#178)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xFirekeeper authored May 14, 2024
1 parent 69ca41f commit 4b24a66
Show file tree
Hide file tree
Showing 32 changed files with 2,523 additions and 175 deletions.
12 changes: 9 additions & 3 deletions Assets/Thirdweb/Core/Scripts/Pay/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ public static class Constants
{
public const string THIRDWEB_PAY_BASE_URL = "https://pay.thirdweb.com";

public const string THIRDWEB_PAY_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/quote/v1";
public const string THIRDWEB_PAY_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/status/v1";
public const string THIRDWEB_PAY_HISTORY_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/history/v1";
public const string THIRDWEB_PAY_CRYPTO_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/quote/v1";
public const string THIRDWEB_PAY_CRYPTO_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/status/v1";

public const string THIRDWEB_PAY_FIAT_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/quote/v1";
public const string THIRDWEB_PAY_FIAT_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/status/v1";

public const string THIRDWEB_PAY_FIAT_CURRENCIES_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/currency/v1";

public const string THIRDWEB_PAY_HISTORY_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/wallet/history/v1";
}
}
31 changes: 31 additions & 0 deletions Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithFiat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;
using UnityEngine;

namespace Thirdweb.Pay
{
public static partial class ThirdwebPay
{
/// <summary>
/// Buy crypto with fiat using the onramp link from the quote and get a quote ID to poll for the onramp status.
/// </summary>
/// <param name="buyWithFiatQuote">Quote containing onramp details</param>
/// <param name="sdk">Optional SDK instance, defaults to ThirdwebManager instance</param>
/// <returns>Quote ID to poll for the onramp status</returns>
public static string BuyWithFiat(BuyWithFiatQuoteResult buyWithFiatQuote, ThirdwebSDK sdk = null)
{
sdk ??= ThirdwebManager.Instance.SDK;

if (string.IsNullOrEmpty(buyWithFiatQuote.OnRampLink))
{
throw new Exception("OnRampLink is required to buy with fiat.");
}

var onRampLink = buyWithFiatQuote.OnRampLink;

Application.OpenURL(onRampLink);

return buyWithFiatQuote.IntentId;
}
}
}
11 changes: 11 additions & 0 deletions Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithFiat.cs.meta

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 @@ -10,16 +10,16 @@ namespace Thirdweb.Pay
public static partial class ThirdwebPay
{
/// <summary>
/// Get swap history, supports cursor and pagination.
/// Get buy history, supports cursor and pagination.
/// </summary>
/// <param name="walletAddress">User wallet address to get swap history for</param>
/// <param name="walletAddress">User wallet address to get buy history for</param>
/// <param name="start">Offset for the records</param>
/// <param name="count">Number of records to retrieve</param>
/// <param name="cursor">Cursor for paging through the history</param>
/// <param name="pageSize">Swap statuses to query for</param>
/// <returns>Swap history object <see cref="BuyWithCryptoHistoryResult"/></returns>
/// <param name="pageSize">Buy statuses to query for</param>
/// <returns>Buy history object <see cref="BuyHistoryResult"/></returns>
/// <exception cref="Exception"></exception>
public static async Task<BuyWithCryptoHistoryResult> GetBuyWithCryptoHistory(string walletAddress, int start, int count, string cursor = null, int? pageSize = null)
public static async Task<BuyHistoryResult> GetBuyHistory(string walletAddress, int start, int count, string cursor = null, int? pageSize = null)
{
if (string.IsNullOrEmpty(Utils.GetClientId()))
{
Expand Down Expand Up @@ -83,7 +83,8 @@ public static async Task<BuyWithCryptoHistoryResult> GetBuyWithCryptoHistory(str
}

var content = request.downloadHandler.text;
var data = JsonConvert.DeserializeObject<SwapHistoryResponse>(content);
ThirdwebDebug.Log($"GetBuyHistory response: {content}");
var data = JsonConvert.DeserializeObject<BuyHistoryResponse>(content);
return data.Result;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,12 @@ public static async Task<BuyWithCryptoQuoteResult> GetBuyWithCryptoQuote(BuyWith
{ "toTokenAddress", buyWithCryptoParams.ToTokenAddress },
{ "toAmount", buyWithCryptoParams.ToAmount },
{ "toAmountWei", buyWithCryptoParams.ToAmountWei },
{ "maxSlippageBPS", buyWithCryptoParams.MaxSlippageBPS?.ToString() }
{ "maxSlippageBPS", buyWithCryptoParams.MaxSlippageBPS?.ToString() },
{ "intentId", buyWithCryptoParams.IntentId }
};

var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
var url = $"{Constants.THIRDWEB_PAY_QUOTE_ENDPOINT}?{queryStringFormatted}";
var url = $"{Constants.THIRDWEB_PAY_CRYPTO_QUOTE_ENDPOINT}?{queryStringFormatted}";

using var request = UnityWebRequest.Get(url);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static async Task<BuyWithCryptoStatusResult> GetBuyWithCryptoStatus(strin
var queryString = new Dictionary<string, string> { { "transactionHash", transactionHash } };

var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
var url = $"{Constants.THIRDWEB_PAY_STATUS_ENDPOINT}?{queryStringFormatted}";
var url = $"{Constants.THIRDWEB_PAY_CRYPTO_STATUS_ENDPOINT}?{queryStringFormatted}";

using var request = UnityWebRequest.Get(url);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.Linq;
using System.Threading.Tasks;
using Thirdweb.Redcode.Awaiting;

namespace Thirdweb.Pay
{
public static partial class ThirdwebPay
{
/// <summary>
/// Get supported fiat currencies for Buy with Fiat.
/// </summary>
/// <returns>List of supported Fiat currency symbols.</returns>
public static async Task<List<string>> GetBuyWithFiatCurrencies()
{
if (string.IsNullOrEmpty(Utils.GetClientId()))
{
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
}

var url = $"{Constants.THIRDWEB_PAY_FIAT_CURRENCIES_ENDPOINT}";

using var request = UnityWebRequest.Get(url);

request.SetRequestHeader("x-sdk-name", "UnitySDK");
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
request.SetRequestHeader("x-sdk-platform", "unity");
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
request.SetRequestHeader("x-client-id", ThirdwebManager.Instance.SDK.Session.Options.clientId);
if (!Utils.IsWebGLBuild())
request.SetRequestHeader("x-bundle-id", ThirdwebManager.Instance.SDK.Session.Options.bundleId);

await request.SendWebRequest();

if (request.result != UnityWebRequest.Result.Success)
{
ErrorResponse error;
try
{
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
}
catch
{
error = new ErrorResponse
{
Error = new ErrorDetails
{
Message = "Unknown error",
Reason = "Unknown",
Code = "Unknown",
Stack = "Unknown",
StatusCode = (int)request.responseCode
}
};
}

throw new Exception(
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
);
}

var content = request.downloadHandler.text;
var data = JsonConvert.DeserializeObject<FiatCurrenciesResponse>(content);
return data.Result.FiatCurrencies;
}
}
}

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
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.Linq;
using Thirdweb.Redcode.Awaiting;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Thirdweb.Pay
{
public static partial class ThirdwebPay
{
/// <summary>
/// Get a quote containing an onramp link for a fiat to crypto swap.
/// </summary>
/// <param name="buyWithFiatParams">Fiat onramp parameters <see cref="BuyWithFiatQuoteParams"/></param>
/// <returns>Fiat quote object <see cref="BuyWithFiatQuoteResult"/></returns>
public static async Task<BuyWithFiatQuoteResult> GetBuyWithFiatQuote(BuyWithFiatQuoteParams buyWithFiatParams)
{
if (string.IsNullOrEmpty(Utils.GetClientId()))
{
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
}

var queryString = new Dictionary<string, string>
{
{ "fromCurrencySymbol", buyWithFiatParams.FromCurrencySymbol },
{ "fromAmount", buyWithFiatParams.FromAmount },
{ "fromAmountUnits", buyWithFiatParams.FromAmountUnits },
{ "toAddress", buyWithFiatParams.ToAddress },
{ "toChainId", buyWithFiatParams.ToChainId },
{ "toTokenAddress", buyWithFiatParams.ToTokenAddress },
{ "toAmount", buyWithFiatParams.ToAmount },
{ "toAmountWei", buyWithFiatParams.ToAmountWei },
{ "maxSlippageBPS", buyWithFiatParams.MaxSlippageBPS?.ToString() }
};

var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
var url = $"{Constants.THIRDWEB_PAY_FIAT_QUOTE_ENDPOINT}?{queryStringFormatted}";
url += buyWithFiatParams.IsTestMode ? "&isTestMode=true" : "&isTestMode=false";

using var request = UnityWebRequest.Get(url);

request.SetRequestHeader("x-sdk-name", "UnitySDK");
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
request.SetRequestHeader("x-sdk-platform", "unity");
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
request.SetRequestHeader("x-client-id", Utils.GetClientId());
if (!Utils.IsWebGLBuild())
request.SetRequestHeader("x-bundle-id", Utils.GetBundleId());

await request.SendWebRequest();

if (request.result != UnityWebRequest.Result.Success)
{
ErrorResponse error;
try
{
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
}
catch
{
error = new ErrorResponse
{
Error = new ErrorDetails
{
Message = "Unknown error",
Reason = "Unknown",
Code = "Unknown",
Stack = "Unknown",
StatusCode = (int)request.responseCode
}
};
}

throw new Exception(
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
);
}

var content = request.downloadHandler.text;
var data = JsonConvert.DeserializeObject<GetFiatQuoteResponse>(content);
return data.Result;
}
}
}

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
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.Linq;
using System.Threading.Tasks;
using Thirdweb.Redcode.Awaiting;

namespace Thirdweb.Pay
{
public static partial class ThirdwebPay
{
/// <summary>
/// Get onramp status for a quote id.
/// </summary>
/// <param name="intentId">Intent ID to get onramp status for</param>
/// <returns>Onramp status object <see cref="BuyWithFiatStatusResult"/></returns>
public static async Task<BuyWithFiatStatusResult> GetBuyWithFiatStatus(string intentId)
{
if (string.IsNullOrEmpty(Utils.GetClientId()))
{
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
}

if (string.IsNullOrEmpty(intentId))
{
throw new ArgumentNullException(nameof(intentId));
}

var queryString = new Dictionary<string, string> { { "intentId", intentId } };

var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
var url = $"{Constants.THIRDWEB_PAY_FIAT_STATUS_ENDPOINT}?{queryStringFormatted}";

using var request = UnityWebRequest.Get(url);

request.SetRequestHeader("x-sdk-name", "UnitySDK");
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
request.SetRequestHeader("x-sdk-platform", "unity");
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
request.SetRequestHeader("x-client-id", ThirdwebManager.Instance.SDK.Session.Options.clientId);
if (!Utils.IsWebGLBuild())
request.SetRequestHeader("x-bundle-id", ThirdwebManager.Instance.SDK.Session.Options.bundleId);

await request.SendWebRequest();

if (request.result != UnityWebRequest.Result.Success)
{
ErrorResponse error;
try
{
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
}
catch
{
error = new ErrorResponse
{
Error = new ErrorDetails
{
Message = "Unknown error",
Reason = "Unknown",
Code = "Unknown",
Stack = "Unknown",
StatusCode = (int)request.responseCode
}
};
}

throw new Exception(
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
);
}

var content = request.downloadHandler.text;
var data = JsonConvert.DeserializeObject<OnRampStatusResponse>(content);
return data.Result;
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 4b24a66

Please sign in to comment.