Skip to content

Commit

Permalink
get utxos and get balance using blockcore api
Browse files Browse the repository at this point in the history
  • Loading branch information
noescape00 committed Oct 17, 2022
1 parent a380749 commit e067049
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 205 deletions.
90 changes: 90 additions & 0 deletions Src/NFTWallet/Assets/Code/BlockCoreApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand Down Expand Up @@ -36,6 +37,50 @@ public async Task<List<OwnedNFTItem>> GetOwnedNFTIds(string ownerAddress)
return allItems;
}

public async Task<List<UTXOModel>> GetUTXOsAsync(string address)
{
List<UTXOModel> allItems = new List<UTXOModel>();

int limit = 50;

for (int offset = 0; offset < int.MaxValue; offset += limit)
{
string endpoint = baseUri + "query/address/" + address + "/transactions/unspent?confirmations=1&offset=" + offset + "&limit=" + limit;

HttpResponseMessage response = await client.GetAsync(endpoint);

var totalString = response.Headers.GetValues("pagination-total").First();
int total = int.Parse(totalString);

string result = await response.Content.ReadAsStringAsync();
List<RootUtxos> rootCollection = JsonConvert.DeserializeObject<List<RootUtxos>>(result);

foreach (RootUtxos utxoData in rootCollection)
{
allItems.Add(new UTXOModel()
{
Hash = utxoData.outpoint.transactionId,
N = utxoData.outpoint.outputIndex,
Satoshis = utxoData.value
});
}

if (total < offset + limit)
break;
}

return allItems;
}

public async Task<long> GetBalanceAsync(string address)
{
string result = await this.client.GetStringAsync(baseUri + "query/address/" + address);
AddressInfoModel root = JsonConvert.DeserializeObject<AddressInfoModel>(result);

return root.balance;
}

#region GetOwnedNFTIds models
public class OwnedNFTItem
{
public long id { get; set; }
Expand All @@ -54,4 +99,49 @@ public class OwnedNFTIdsRoot
public int total { get; set; }
public List<OwnedNFTItem> items { get; set; }
}
#endregion

#region utxos models
public class UTXOModel
{
public string Hash { get; set; }

public int N { get; set; }

public long Satoshis { get; set; }
}

public class Outpoint
{
public string transactionId { get; set; }
public int outputIndex { get; set; }
}

public class RootUtxos
{
public Outpoint outpoint { get; set; }
public string address { get; set; }
public string scriptHex { get; set; }
public long value { get; set; }
public int blockIndex { get; set; }
public bool coinBase { get; set; }
public bool coinStake { get; set; }
}
#endregion

public class AddressInfoModel
{
public string address { get; set; }
public long balance { get; set; }
public long totalReceived { get; set; }
public int totalStake { get; set; }
public long totalMine { get; set; }
public long totalSent { get; set; }
public int totalReceivedCount { get; set; }
public int totalSentCount { get; set; }
public int totalStakeCount { get; set; }
public int totalMineCount { get; set; }
public int pendingSent { get; set; }
public int pendingReceived { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public async UniTask DisplayUntilDestBalanceChanges(string address, long current

while (true)
{
long balanceSat = await NFTWallet.Instance.StratisUnityManager.Client.GetAddressBalanceAsync(address);
long balanceSat = await NFTWallet.Instance.GetBlockCoreApi().GetBalanceAsync(address);

if (balanceSat != currentBalanceSat)
break;
Expand Down
4 changes: 2 additions & 2 deletions Src/NFTWallet/Assets/Code/NFTWallet/Windows/WalletWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ void Awake()
return;
}

long currentBalanceSat = await NFTWallet.Instance.StratisUnityManager.Client.GetAddressBalanceAsync(destAddress);
long currentBalanceSat = await NFTWallet.Instance.GetBlockCoreApi().GetBalanceAsync(destAddress);

Task<string> sendTxTask = NFTWallet.Instance.StratisUnityManager.SendTransactionAsync(destAddress, amount);

Expand Down Expand Up @@ -78,7 +78,7 @@ void Awake()

Task<string> sendTxTask = stratisUnityManager.SendTransactionAsync(destAddr, faucetAmount);

long currentBalanceSat = await NFTWallet.Instance.StratisUnityManager.Client.GetAddressBalanceAsync(destAddr);
long currentBalanceSat = await NFTWallet.Instance.GetBlockCoreApi().GetBalanceAsync(destAddr);

await NFTWalletWindowManager.Instance.WaitTransactionWindow.DisplayUntilDestBalanceChanges(destAddr, currentBalanceSat, sendTxTask);

Expand Down
7 changes: 4 additions & 3 deletions Src/NFTWallet/Assets/Code/StratisUnityManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Expand Down Expand Up @@ -58,7 +59,7 @@ public StratisUnityManager(Unity3dClient client, Network network, Mnemonic mnemo

public async Task<decimal> GetBalanceAsync()
{
long balanceSat = await Client.GetAddressBalanceAsync(this.address.ToString());
long balanceSat = await NFTWallet.Instance.GetBlockCoreApi().GetBalanceAsync(this.address.ToString());

decimal balance = new Money(balanceSat).ToUnit(MoneyUnit.BTC);

Expand Down Expand Up @@ -136,9 +137,9 @@ public async Task<string> SendOpReturnTransactionAsync(byte[] bytes)

private async Task<Coin[]> GetCoinsAsync()
{
GetUTXOsResponseModel utxos = await Client.GetUTXOsForAddressAsync(this.address.ToString());
List<BlockCoreApi.UTXOModel> utxos = await NFTWallet.Instance.GetBlockCoreApi().GetUTXOsAsync(this.address.ToString());

Coin[] coins = utxos.Utxos.Select(x => new Coin(new OutPoint(uint256.Parse(x.Hash), x.N), new TxOut(new Money(x.Satoshis), address))).ToArray();
Coin[] coins = utxos.Select(x => new Coin(new OutPoint(uint256.Parse(x.Hash), x.N), new TxOut(new Money(x.Satoshis), address))).ToArray();

return coins;
}
Expand Down
200 changes: 1 addition & 199 deletions Src/NFTWallet/Assets/Code/Unity3dApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,175 +50,7 @@ public string BaseUrl
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<GetUTXOsResponseModel> GetUTXOsForAddressAsync(string address)
{
return GetUTXOsForAddressAsync(address, System.Threading.CancellationToken.None);
}

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public async System.Threading.Tasks.Task<GetUTXOsResponseModel> GetUTXOsForAddressAsync(string address, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/Unity3d/getutxosforaddress?");
if (address != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("address") + "=").Append(System.Uri.EscapeDataString(ConvertToString(address, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
}
urlBuilder_.Length--;

var client_ = new System.Net.Http.HttpClient();
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));

PrepareRequest(client_, request_, urlBuilder_);

var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

PrepareRequest(client_, request_, url_);

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var disposeResponse_ = true;
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}

ProcessResponse(client_, response_);

var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<GetUTXOsResponseModel>(response_, headers_, cancellationToken);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
return objectResponse_.Object;
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync();
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}


/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<long> GetAddressBalanceAsync(string address)
{
return GetAddressBalanceAsync(address, System.Threading.CancellationToken.None);
}

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public async System.Threading.Tasks.Task<long> GetAddressBalanceAsync(string address, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/Unity3d/getaddressbalance?");
if (address != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("address") + "=").Append(System.Uri.EscapeDataString(ConvertToString(address, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
}
urlBuilder_.Length--;

var client_ = new System.Net.Http.HttpClient();
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));

PrepareRequest(client_, request_, urlBuilder_);

var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

PrepareRequest(client_, request_, url_);

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var disposeResponse_ = true;
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}

ProcessResponse(client_, response_);

var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<long>(response_, headers_, cancellationToken);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
return objectResponse_.Object;
}
else
if (status_ == 400)
{
var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null);
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync();
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}


/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public System.Threading.Tasks.Task<BlockHeaderModel> GetBlockHeaderAsync(string hash)
Expand Down Expand Up @@ -1492,21 +1324,6 @@ public partial class GasModel
public long Value { get; set; }


}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")]
public partial class GetUTXOsResponseModel
{
[Newtonsoft.Json.JsonProperty("balanceSat", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public long BalanceSat { get; set; }

[Newtonsoft.Json.JsonProperty("utxOs", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.Generic.ICollection<UTXOModel> Utxos { get; set; }

[Newtonsoft.Json.JsonProperty("reason", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string Reason { get; set; }


}

/// <summary>A class containing the necessary parameters to perform a local smart contract method call request.</summary>
Expand Down Expand Up @@ -1741,21 +1558,6 @@ public partial class Uint160
public int Size { get; set; }


}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")]
public partial class UTXOModel
{
[Newtonsoft.Json.JsonProperty("hash", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string Hash { get; set; }

[Newtonsoft.Json.JsonProperty("n", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public int N { get; set; }

[Newtonsoft.Json.JsonProperty("satoshis", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public long Satoshis { get; set; }


}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")]
Expand Down

0 comments on commit e067049

Please sign in to comment.