Skip to content

Commit 635d781

Browse files
authored
Thirdweb Pay, Buy with Crypto Scene/Prefab Examples, Cross-Platform Support (#165)
1 parent e12c16d commit 635d781

29 files changed

+3650
-31
lines changed

Assets/Thirdweb/Core/Scripts/Pay.meta

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace Thirdweb.Pay
2+
{
3+
public static class Constants
4+
{
5+
public const string THIRDWEB_PAY_BASE_URL = "https://pay.thirdweb.com";
6+
7+
public const string THIRDWEB_PAY_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/quote/v1";
8+
public const string THIRDWEB_PAY_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/status/v1";
9+
public const string THIRDWEB_PAY_HISTORY_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/history/v1";
10+
}
11+
}

Assets/Thirdweb/Core/Scripts/Pay/Constants.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System.Threading.Tasks;
2+
3+
namespace Thirdweb.Pay
4+
{
5+
public static partial class ThirdwebPay
6+
{
7+
/// <summary>
8+
/// Send a quoted swap transaction.
9+
/// </summary>
10+
/// <param name="buyWithCryptoQuote">Swap quote containing the transaction request</param>
11+
/// <param name="sdk">Optional SDK instance, defaults to ThirdwebManager instance</param>
12+
/// <returns></returns>
13+
public static async Task<string> BuyWithCrypto(BuyWithCryptoQuoteResult buyWithCryptoQuote, ThirdwebSDK sdk = null)
14+
{
15+
sdk ??= ThirdwebManager.Instance.SDK;
16+
17+
if (buyWithCryptoQuote.Approval != null)
18+
{
19+
ThirdwebDebug.Log("Approving ERC20...");
20+
var erc20ToApprove = sdk.GetContract(buyWithCryptoQuote.Approval.TokenAddress);
21+
var approvalRes = await erc20ToApprove.ERC20.SetAllowance(buyWithCryptoQuote.Approval.SpenderAddress, buyWithCryptoQuote.Approval.AmountWei.ToEth());
22+
ThirdwebDebug.Log($"Approval transaction receipt: {approvalRes}");
23+
}
24+
25+
ThirdwebDebug.Log("Sending swap transaction...");
26+
var hash = await sdk.Wallet.SendRawTransaction(
27+
new Thirdweb.TransactionRequest()
28+
{
29+
from = buyWithCryptoQuote.TransactionRequest.From,
30+
to = buyWithCryptoQuote.TransactionRequest.To,
31+
data = buyWithCryptoQuote.TransactionRequest.Data,
32+
value = buyWithCryptoQuote.TransactionRequest.Value,
33+
gasLimit = buyWithCryptoQuote.TransactionRequest.GasLimit,
34+
gasPrice = buyWithCryptoQuote.TransactionRequest.GasPrice,
35+
}
36+
);
37+
ThirdwebDebug.Log($"Swap transaction hash: {hash}");
38+
39+
return hash;
40+
}
41+
}
42+
}

Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using UnityEngine.Networking;
4+
using Newtonsoft.Json;
5+
using System.Threading.Tasks;
6+
using System.Linq;
7+
8+
namespace Thirdweb.Pay
9+
{
10+
public static partial class ThirdwebPay
11+
{
12+
/// <summary>
13+
/// Get swap history, supports cursor and pagination.
14+
/// </summary>
15+
/// <param name="walletAddress">User wallet address to get swap history for</param>
16+
/// <param name="start">Offset for the records</param>
17+
/// <param name="count">Number of records to retrieve</param>
18+
/// <param name="cursor">Cursor for paging through the history</param>
19+
/// <param name="pageSize">Swap statuses to query for</param>
20+
/// <returns>Swap history object <see cref="BuyWithCryptoHistoryResult"/></returns>
21+
/// <exception cref="Exception"></exception>
22+
public static async Task<BuyWithCryptoHistoryResult> GetBuyWithCryptoHistory(string walletAddress, int start, int count, string cursor = null, int? pageSize = null)
23+
{
24+
if (string.IsNullOrEmpty(Utils.GetClientId()))
25+
{
26+
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
27+
}
28+
29+
var queryString = new Dictionary<string, string>
30+
{
31+
{ "walletAddress", walletAddress },
32+
{ "start", start.ToString() },
33+
{ "count", count.ToString() },
34+
{ "cursor", cursor },
35+
{ "pageSize", pageSize?.ToString() }
36+
};
37+
38+
var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
39+
var url = $"{Constants.THIRDWEB_PAY_HISTORY_ENDPOINT}?{queryStringFormatted}";
40+
41+
using var request = UnityWebRequest.Get(url);
42+
43+
request.SetRequestHeader("x-sdk-name", "UnitySDK");
44+
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
45+
request.SetRequestHeader("x-sdk-platform", "unity");
46+
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
47+
request.SetRequestHeader("x-client-id", Utils.GetClientId());
48+
if (!Utils.IsWebGLBuild())
49+
request.SetRequestHeader("x-bundle-id", Utils.GetBundleId());
50+
51+
var operation = request.SendWebRequest();
52+
53+
while (!operation.isDone)
54+
{
55+
await Task.Delay(100);
56+
}
57+
58+
if (request.result != UnityWebRequest.Result.Success)
59+
{
60+
ErrorResponse error;
61+
try
62+
{
63+
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
64+
}
65+
catch
66+
{
67+
error = new ErrorResponse
68+
{
69+
Error = new ErrorDetails
70+
{
71+
Message = "Unknown error",
72+
Reason = "Unknown",
73+
Code = "Unknown",
74+
Stack = "Unknown",
75+
StatusCode = (int)request.responseCode
76+
}
77+
};
78+
}
79+
80+
throw new Exception(
81+
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
82+
);
83+
}
84+
85+
var content = request.downloadHandler.text;
86+
var data = JsonConvert.DeserializeObject<SwapHistoryResponse>(content);
87+
return data.Result;
88+
}
89+
}
90+
}

Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.GetBuyWithCryptoHistory.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using UnityEngine.Networking;
4+
using Newtonsoft.Json;
5+
using System.Linq;
6+
using Thirdweb.Redcode.Awaiting;
7+
using System.Threading.Tasks;
8+
9+
namespace Thirdweb.Pay
10+
{
11+
public static partial class ThirdwebPay
12+
{
13+
/// <summary>
14+
/// Get a quote containing a TransactionRequest for swapping any token pair.
15+
/// </summary>
16+
/// <param name="buyWithCryptoParams">Swap parameters <see cref="BuyWithCryptoQuoteParams"/></param>
17+
/// <returns>Swap quote object <see cref="BuyWithCryptoQuoteResult"/></returns>
18+
/// <exception cref="Exception"></exception>
19+
public static async Task<BuyWithCryptoQuoteResult> GetBuyWithCryptoQuote(BuyWithCryptoQuoteParams buyWithCryptoParams)
20+
{
21+
if (string.IsNullOrEmpty(Utils.GetClientId()))
22+
{
23+
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
24+
}
25+
26+
var queryString = new Dictionary<string, string>
27+
{
28+
{ "fromAddress", buyWithCryptoParams.FromAddress },
29+
{ "fromChainId", buyWithCryptoParams.FromChainId?.ToString() },
30+
{ "fromTokenAddress", buyWithCryptoParams.FromTokenAddress },
31+
{ "fromAmount", buyWithCryptoParams.FromAmount },
32+
{ "fromAmountWei", buyWithCryptoParams.FromAmountWei },
33+
{ "toChainId", buyWithCryptoParams.ToChainId?.ToString() },
34+
{ "toTokenAddress", buyWithCryptoParams.ToTokenAddress },
35+
{ "toAmount", buyWithCryptoParams.ToAmount },
36+
{ "toAmountWei", buyWithCryptoParams.ToAmountWei },
37+
{ "maxSlippageBPS", buyWithCryptoParams.MaxSlippageBPS?.ToString() }
38+
};
39+
40+
var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
41+
var url = $"{Constants.THIRDWEB_PAY_QUOTE_ENDPOINT}?{queryStringFormatted}";
42+
43+
using var request = UnityWebRequest.Get(url);
44+
45+
request.SetRequestHeader("x-sdk-name", "UnitySDK");
46+
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
47+
request.SetRequestHeader("x-sdk-platform", "unity");
48+
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
49+
request.SetRequestHeader("x-client-id", Utils.GetClientId());
50+
if (!Utils.IsWebGLBuild())
51+
request.SetRequestHeader("x-bundle-id", Utils.GetBundleId());
52+
53+
await request.SendWebRequest();
54+
55+
if (request.result != UnityWebRequest.Result.Success)
56+
{
57+
ErrorResponse error;
58+
try
59+
{
60+
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
61+
}
62+
catch
63+
{
64+
error = new ErrorResponse
65+
{
66+
Error = new ErrorDetails
67+
{
68+
Message = "Unknown error",
69+
Reason = "Unknown",
70+
Code = "Unknown",
71+
Stack = "Unknown",
72+
StatusCode = (int)request.responseCode
73+
}
74+
};
75+
}
76+
77+
throw new Exception(
78+
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
79+
);
80+
}
81+
82+
var content = request.downloadHandler.text;
83+
var data = JsonConvert.DeserializeObject<GetSwapQuoteResponse>(content);
84+
return data.Result;
85+
}
86+
}
87+
}

Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.GetBuyWithCryptoQuote.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using UnityEngine.Networking;
4+
using Newtonsoft.Json;
5+
using System.Linq;
6+
using System.Threading.Tasks;
7+
using Thirdweb.Redcode.Awaiting;
8+
9+
namespace Thirdweb.Pay
10+
{
11+
public static partial class ThirdwebPay
12+
{
13+
/// <summary>
14+
/// Get swap status for a transaction hash.
15+
/// </summary>
16+
/// <param name="transactionHash">Transaction hash to get swap status for</param>
17+
/// <returns>Swap status object <see cref="BuyWithCryptoStatusResult"/></returns>
18+
public static async Task<BuyWithCryptoStatusResult> GetBuyWithCryptoStatus(string transactionHash)
19+
{
20+
if (string.IsNullOrEmpty(Utils.GetClientId()))
21+
{
22+
throw new Exception("Client ID is not set. Please set it in the ThirdwebManager.");
23+
}
24+
25+
if (string.IsNullOrEmpty(transactionHash))
26+
{
27+
throw new ArgumentNullException(nameof(transactionHash));
28+
}
29+
30+
var queryString = new Dictionary<string, string> { { "transactionHash", transactionHash } };
31+
32+
var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
33+
var url = $"{Constants.THIRDWEB_PAY_STATUS_ENDPOINT}?{queryStringFormatted}";
34+
35+
using var request = UnityWebRequest.Get(url);
36+
37+
request.SetRequestHeader("x-sdk-name", "UnitySDK");
38+
request.SetRequestHeader("x-sdk-os", Utils.GetRuntimePlatform());
39+
request.SetRequestHeader("x-sdk-platform", "unity");
40+
request.SetRequestHeader("x-sdk-version", ThirdwebSDK.version);
41+
request.SetRequestHeader("x-client-id", ThirdwebManager.Instance.SDK.Session.Options.clientId);
42+
if (!Utils.IsWebGLBuild())
43+
request.SetRequestHeader("x-bundle-id", ThirdwebManager.Instance.SDK.Session.Options.bundleId);
44+
45+
await request.SendWebRequest();
46+
47+
if (request.result != UnityWebRequest.Result.Success)
48+
{
49+
ErrorResponse error;
50+
try
51+
{
52+
error = JsonConvert.DeserializeObject<ErrorResponse>(request.downloadHandler.text);
53+
}
54+
catch
55+
{
56+
error = new ErrorResponse
57+
{
58+
Error = new ErrorDetails
59+
{
60+
Message = "Unknown error",
61+
Reason = "Unknown",
62+
Code = "Unknown",
63+
Stack = "Unknown",
64+
StatusCode = (int)request.responseCode
65+
}
66+
};
67+
}
68+
69+
throw new Exception(
70+
$"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"
71+
);
72+
}
73+
74+
var content = request.downloadHandler.text;
75+
var data = JsonConvert.DeserializeObject<SwapStatusResponse>(content);
76+
return data.Result;
77+
}
78+
}
79+
}

Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.GetBuyWithCryptoStatus.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)