public PaymentResponse Send(string recipientWallet, decimal amount, decimal fee) { BlockchainApiSettings blockchainApiSettings = GetSettings(); var httpClient = new BlockchainHttpClient(blockchainApiSettings.ApiKey, blockchainApiSettings.ServiceUrl); using (BlockchainApiHelper apiHelper = new BlockchainApiHelper(apiCode: blockchainApiSettings.ApiKey, serviceUrl: blockchainApiSettings.ServiceUrl, serviceHttpClient: httpClient)) { try { BitcoinValue _fee = BitcoinValue.FromBtc(fee); BitcoinValue _amount = BitcoinValue.FromBtc(amount); Wallet wallet = apiHelper.InitializeWallet(blockchainApiSettings.WalletID, blockchainApiSettings.WalletPassword); PaymentResponse payment = wallet.SendAsync(recipientWallet, _amount, fee: _fee).Result; return(payment); } catch (ClientApiException e) { throw new ArgumentException("Blockchain exception: " + e.Message); } } }
/// <summary> /// Sends bitcoin from your wallet to multiple addresses. /// </summary> /// <param name="recipients">Dictionary with the structure of 'address':amount /// (string:BitcoinValue)</param> /// <param name="fromAddress">Specific address to send from</param> /// <param name="fee">Transaction fee. Must be greater than the default fee</param> /// <returns>An instance of the PaymentResponse class</returns> /// <exception cref="ServerApiException">If the server returns an error</exception> public async Task <PaymentResponse> SendManyAsync(Dictionary <string, BitcoinValue> recipients, string fromAddress = null, BitcoinValue fee = null) { if (recipients == null || recipients.Count == 0) { throw new ArgumentException("Sending bitcoin from your wallet requires at least one receipient.", nameof(recipients)); } QueryString queryString = new QueryString(); queryString.Add("password", password); string recipientsJson = JsonConvert.SerializeObject(recipients, Formatting.None, new BitcoinValueJsonConverter()); queryString.Add("recipients", recipientsJson); if (!string.IsNullOrWhiteSpace(secondPassword)) { queryString.Add("second_password", secondPassword); } if (!string.IsNullOrWhiteSpace(fromAddress)) { queryString.Add("from", fromAddress); } if (fee != null) { queryString.Add("fee", fee.ToString()); } string route = $"merchant/{identifier}/sendmany"; PaymentResponse paymentResponse = await httpClient.GetAsync <PaymentResponse>(route, queryString); return(paymentResponse); }
private void ReadFeesMemory() { foreach (Currency ccy in AvailableCryptoCurrencies) { string pth_ccy = GetPath(ccy); if (File.Exists(pth_ccy)) { List <string[]> csv = StaticLibrary.LoadCsvFile(pth_ccy); bool isHeaders = true; string[] headers = null; foreach (string[] array in csv) { if (isHeaders) { headers = array; isHeaders = false; } else { DateTime t_line = StaticLibrary.UnixTimeStampToDateTime(Convert.ToDouble(array[0])); BitcoinValue bv_line = new BitcoinValue(Convert.ToDecimal(array[2])); FeesMemory[ccy][t_line] = new Tuple <string, BitcoinValue>(array[1], bv_line); } } } } }
public async Task <ActionResult> SendPayment_SendBtc_NoFreeOutputs() { var emailaddress = Session["Email_Address"]; var walletdetails = db.AspNetUsers.Join(db.WalletDetails, u => u.Id, uir => uir.UserId, (u, uir) => new { u, uir }).Where(w => w.u.Email == emailaddress.ToString()).Select(s => new { s.uir.Address, s.uir.GuidIdentifier }).FirstOrDefault(); string WALLET_ID = walletdetails.GuidIdentifier; string Form_Address = walletdetails.Address; string WALLET_PASSWORD = "******"; string FIRST_ADDRESS = "16RQNCzpCQAyTQkj2Bp43vuBu5D822bGAn"; ServerApiException apiException = await Assert.ThrowsAsync <ServerApiException>(async() => { BlockchainHttpClient httpClient = new BlockchainHttpClient(apicode, ApiURL); using (BlockchainApiHelper apiHelper = new BlockchainApiHelper(apicode, httpClient, ApiURL, httpClient)) { Wallet wallet = apiHelper.InitializeWallet(WALLET_ID, WALLET_PASSWORD); await wallet.SendAsync(FIRST_ADDRESS, BitcoinValue.FromBtc(1), Form_Address, BitcoinValue.FromBtc(0)); } }); Assert.Contains("No free", apiException.Message); return(RedirectToAction("Index")); }
/// <summary> /// Fetches the wallet balance. Includes unconfirmed transactions /// and possibly double spends. /// </summary> /// <returns>Wallet balance</returns> /// <exception cref="ServerApiException">If the server returns an error</exception> public async Task <BitcoinValue> GetBalanceAsync() { QueryString queryString = BuildBasicQueryString(); string route = $"merchant/{identifier}/balance"; BitcoinValue bitcoinValue = await httpClient.GetAsync <BitcoinValue>(route, queryString); return(bitcoinValue); }
private async Task <decimal> GetResultOfTransaction(string transactionHash, string againstAddress) { using (var client = new BlockchainHttpClient()) { var result = await client.GetAsync <long>($"q/txresult/{transactionHash}/{againstAddress}"); return(BitcoinValue.FromSatoshis(result).GetBtc()); } }
public void BitcoinValue_ConvertMilliBits_ValidConversion() { const decimal milliBits = 1234.56789m; BitcoinValue bitcoinValue = BitcoinValue.FromMilliBits(milliBits); Assert.Equal(bitcoinValue.Satoshis, milliBits * 100000m); Assert.Equal(bitcoinValue.Bits, milliBits * 1000m); Assert.Equal(bitcoinValue.MilliBits, milliBits); Assert.Equal(bitcoinValue.Btc, milliBits / 1000m); }
public void BitcoinValue_ConverBits_ValidConversion() { const decimal bits = 1234567.89m; BitcoinValue bitcoinValue = BitcoinValue.FromBits(bits); Assert.Equal(bitcoinValue.Satoshis, bits * 100m); Assert.Equal(bitcoinValue.Bits, bits); Assert.Equal(bitcoinValue.MilliBits, bits / 1000m); Assert.Equal(bitcoinValue.Btc, bits / 1000000m); }
public async void FromBtc_ToGbp_HasValue() { using (BlockchainApiHelper apiHelper = new BlockchainApiHelper()) { var btc = new BitcoinValue(new decimal(0.4)); double btcValue = await apiHelper.exchangeRateExplorer.FromBtcAsync(btc, "GBP"); Assert.True(btcValue > 0); } }
public void BitcoinValue_ConvertSatoshis_ValidConversion() { const long satoshis = 123456789; BitcoinValue bitcoinValue = BitcoinValue.FromSatoshis(satoshis); Assert.Equal(bitcoinValue.Satoshis, satoshis); Assert.Equal(bitcoinValue.Bits, satoshis / 100m); Assert.Equal(bitcoinValue.MilliBits, satoshis / 100000m); Assert.Equal(bitcoinValue.Btc, satoshis / 100000000m); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value is long) { long satoshis = (long)reader.Value; BitcoinValue bitcoinValue = BitcoinValue.FromSatoshis(satoshis); return(bitcoinValue); } return(BitcoinValue.Zero); }
public async void SendPayment_SendBtc_NoFreeOutputs() { ServerApiException apiException = await Assert.ThrowsAsync <ServerApiException>(async() => { using (BlockchainApiHelper apiHelper = new BlockchainApiHelper()) { WalletHelper walletHelper = apiHelper.CreateWalletHelper(WalletTests.WALLET_ID, WalletTests.WALLET_PASSWORD, WalletTests.WALLET_PASSWORD2); await walletHelper.SendAsync(WalletTests.FIRST_ADDRESS, BitcoinValue.FromBtc(1)); } }); Assert.Contains("No free", apiException.Message); }
public void BitcoinValue_Add_Valid() { const decimal btc1 = 1.23456789m; const decimal btc2 = 9.87654321m; BitcoinValue value1 = BitcoinValue.FromBtc(btc1); BitcoinValue value2 = BitcoinValue.FromBtc(btc2); BitcoinValue value3 = value1 + value2; Assert.Equal(value3.Btc, btc1 + btc2); value3 = value2 + value1; Assert.Equal(value3.Btc, btc1 + btc2); }
public async Task <PaymentResponse> Send(string toAddress, BitcoinValue amount, string fromAddress = null, BitcoinValue fee = null) { if (string.IsNullOrWhiteSpace(toAddress)) { throw new ArgumentNullException(nameof(toAddress)); } if (amount.GetBtc() <= 0) { throw new ArgumentException("Amount sent must be greater than 0", nameof(amount)); } var queryString = new QueryString(); queryString.Add("password", _password); queryString.Add("to", toAddress); queryString.Add("amount", amount.Satoshis.ToString()); if (!string.IsNullOrWhiteSpace(_secondPassword)) { queryString.Add("second_password", _secondPassword); } if (!string.IsNullOrWhiteSpace(fromAddress)) { queryString.Add("from", fromAddress); } if (fee != null) { queryString.Add("fee", fee.ToString()); } string route = $"merchant/{_identifier}/payment"; PaymentResponse paymentResponse; try { paymentResponse = await _httpClient.GetAsync <PaymentResponse>(route, queryString); } catch { paymentResponse = await Task.FromResult(new PaymentResponse { Message = "sent", TxHash = "263c018582731ff54dc72c7d67e858c002ae298835501d80200f05753de0edf0", Notice = "test" }); return(paymentResponse); } return(paymentResponse); }
public static BitcoinValue GetFees(this ApiTx tx) { BitcoinValue res = new BitcoinValue(0); foreach (Input item in tx.Inputs) { res += item.PreviousOutput.Value; } foreach (Output item in tx.Outputs) { res -= item.Value; } return(res); }
public void BitcoinValue_ConvertBtc_ValidConversion() { const decimal btc = 1.23456789m; BitcoinValue bitcoinValue = BitcoinValue.FromBtc(btc); Assert.Equal(bitcoinValue.Satoshis, btc * 100000000m); Assert.Equal(bitcoinValue.Bits, btc * 1000000m); Assert.Equal(bitcoinValue.MilliBits, btc * 1000m); Assert.Equal(bitcoinValue.Btc, btc); bitcoinValue = new BitcoinValue(btc); Assert.Equal(bitcoinValue.Satoshis, btc * 100000000m); Assert.Equal(bitcoinValue.Bits, btc * 1000000m); Assert.Equal(bitcoinValue.MilliBits, btc * 1000m); Assert.Equal(bitcoinValue.Btc, btc); }
public async void SendPayment_SendMultiBtc_NoFreeOutputs() { ServerApiException apiException = await Assert.ThrowsAsync <ServerApiException>(async() => { using (BlockchainApiHelper apiHelper = new BlockchainApiHelper()) { WalletHelper walletHelper = apiHelper.CreateWalletHelper(WalletTests.WALLET_ID, WalletTests.WALLET_PASSWORD, WalletTests.WALLET_PASSWORD2); Dictionary <string, BitcoinValue> recipients = new Dictionary <string, BitcoinValue>() { { "17VYDFsDxBMovM1cKGEytgeqdijNcr4L5", BitcoinValue.FromBtc(1) } }; await walletHelper.SendManyAsync(recipients); } }); Assert.Contains("No free", apiException.Message); }
/// <summary> /// Converts a BitcoinValue object to its value in the specified currency /// </summary> /// <param name="btc">BitcoinValue representing the value to convert from</param> /// <param name="currency">Currency code (default USD)</param> /// <returns>Converted value in currency of choice</returns> public async Task <double> FromBtcAsync(BitcoinValue btc, string currency = "") { if (btc == null) { throw new ArgumentNullException(nameof(btc)); } if (btc.GetBtc() <= 0) { throw new ArgumentOutOfRangeException(nameof(btc), "BitcoinValue must represent a value higher than 0"); } QueryString queryString = new QueryString(); queryString.Add("currency", currency); queryString.Add("value", btc.Satoshis.ToString()); return(await httpClient.GetAsync <double>("frombtc", queryString)); }
public void BitcoinValue_Subtract_Valid() { const decimal btc1 = 1.23456789m; const decimal btc2 = 9.87654321m; BitcoinValue value1 = BitcoinValue.FromBtc(btc1); BitcoinValue value2 = BitcoinValue.FromBtc(btc2); BitcoinValue value3 = value1 - value2; Assert.Equal(value3.Btc, btc1 - btc2); value3 = value2 - value1; Assert.Equal(value3.Btc, btc2 - btc1); Assert.NotEqual(value3.Btc, btc1 - btc2); value3 = value1 - value1; Assert.Equal(value3.Btc, 0); }
public async void FromBtc_NegativeValue_ArgumentOutOfRangeException() { await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => { using (BlockchainApiHelper apiHelper = UnitTestUtil.GetFakeHelper()) { var btc = new BitcoinValue(new decimal(-0.4)); await apiHelper.exchangeRateExplorer.FromBtcAsync(btc); } }); await Assert.ThrowsAsync <ArgumentNullException>(async() => { using (BlockchainApiHelper apiHelper = UnitTestUtil.GetFakeHelper()) { await apiHelper.exchangeRateExplorer.FromBtcAsync(null); } }); }
public async void Send_BadParameters_ArgumentExceptions() { await Assert.ThrowsAsync <ArgumentNullException>(async() => { using (BlockchainApiHelper apiHelper = UnitTestUtil.GetFakeHelper()) { WalletHelper walletHelper = this.GetWalletHelper(apiHelper); await walletHelper.SendAsync(null, BitcoinValue.Zero); } }); await Assert.ThrowsAsync <ArgumentException>(async() => { using (BlockchainApiHelper apiHelper = UnitTestUtil.GetFakeHelper()) { WalletHelper walletHelper = this.GetWalletHelper(apiHelper); await walletHelper.SendAsync("Test", BitcoinValue.FromBtc(-1)); } }); }
/// <summary> /// Sends bitcoin from your wallet to a single address. /// </summary> /// <param name="toAddress">Recipient bitcoin address</param> /// <param name="amount">Amount to send</param> /// <param name="fromAddress">Specific address to send from</param> /// <param name="fee">Transaction fee. Must be greater than the default fee</param> /// <param name="note">Public note to include with the transaction</param> /// <returns>An instance of the PaymentResponse class</returns> /// <exception cref="ServerApiException">If the server returns an error</exception> public async Task <PaymentResponse> SendAsync(string toAddress, BitcoinValue amount, string fromAddress = null, BitcoinValue fee = null, string note = null) { if (string.IsNullOrWhiteSpace(toAddress)) { throw new ArgumentNullException(nameof(toAddress)); } if (amount.GetBtc() <= 0) { throw new ArgumentException("Amount sent must be greater than 0", nameof(amount)); } QueryString queryString = new QueryString(); queryString.Add("password", password); queryString.Add("to", toAddress); queryString.Add("amount", amount.Satoshis.ToString()); if (!string.IsNullOrWhiteSpace(secondPassword)) { queryString.Add("second_password", secondPassword); } if (!string.IsNullOrWhiteSpace(fromAddress)) { queryString.Add("from", fromAddress); } if (!string.IsNullOrWhiteSpace(note)) { queryString.Add("note", note); } if (fee != null) { queryString.Add("fee", fee.ToString()); } string route = $"merchant/{identifier}/payment"; PaymentResponse paymentResponse = await httpClient.GetAsync <PaymentResponse>(route, queryString); return(paymentResponse); }
public async Task <IHttpActionResult> SendBtc([FromBody] BitcoinRequest request) { var operations = new BitcoinOperations(WalletId, WalletPassword1, WalletPassword2); if (request == null) { throw new ArgumentNullException(nameof(request)); } BitcoinQuery query = Mapper.Map <BitcoinRequest, BitcoinQuery>(request); var bitcoinSend = await operations.Send(query.Address, BitcoinValue.FromBtc(query.Amount), WalletId); // This is fake bitcoin service but can be use as real if (bitcoinSend.TxHash != null) { await _dbExecutor.SaveTransactions(query); } return(Ok()); }
public BitcoinValue GetTransactionFees(Transaction tx, List <string> depositAddresses) { Currency ccy = tx.Received.Ccy; DateTime?timeKey = GetTransactionInMemory(tx); if (timeKey.HasValue) { return(FeesMemory[ccy][timeKey.Value].Item2); } UpdateMemory[ccy] = true; decimal res = 0; long tx_date_ref = StaticLibrary.DateTimeToUnixTimeStamp(tx.Date); DateTime?tx_date = null; foreach (string address in depositAddresses) { List <ApiTx> tx_add = GetAddressTransactions(address); foreach (ApiTx item in tx_add) { if (item.GetAmountFromAddress(address).GetBtc() == (decimal)tx.Received.Amount) { if (StaticLibrary.DateTimeDistTest(tx.Date, item.Time, 4)) { res = item.GetFees().GetBtc(); tx_date = item.Time; } } } } BitcoinValue bv = new BitcoinValue(res); if (tx_date.HasValue) { FeesMemory[ccy][tx_date.Value] = new Tuple <string, BitcoinValue>(tx.ID, bv); } return(bv); }
private async void OnClickSend(object sender, EventArgs e) { // reset value _isNumber = false; _outNumber = 0; vtp.TextColor = Color.Black; try { //For From Address ApiLogon.AddressList = await ApiLogon.Wallet.ListAddressesAsync(); foreach (var adr in ApiLogon.AddressList) { ApiLogon.Address = adr; ApiLogon.FromMyBitcoinAddress = adr.AddressStr; break; } if (string.IsNullOrWhiteSpace(ApiLogon.FromMyBitcoinAddress)) //TODO: HACK for testing { ApiLogon.FromMyBitcoinAddress = Bitcoin.APIv2Client.Models.DataLogon.AddressWallet; } } catch (Exception ex) { Debug.WriteLine($"Error from server or client! Error is: {ex}"); //Logging.Debug($"Error from server or client! Error is: {ex}"); } //For To Address if (!string.IsNullOrWhiteSpace(ValueAddress.Text)) { ApiLogon.ToBitcoinAddress = ValueAddress.Text; } else { ApiLogon.ToBitcoinAddress = ValueAddress2.Text; } //For Amount if (!string.IsNullOrWhiteSpace(vtp.Text)) { _isNumber = double.TryParse(vtp.Text, out _outNumber); } else { if (!string.IsNullOrWhiteSpace(vtp2.Text)) { _isNumber = double.TryParse(vtp2.Text, out _outNumber); } } if (_isNumber) { ApiLogon.MyAmount = _outNumber; BitcoinValue amount = new BitcoinValue((decimal)ApiLogon.MyAmount * BitcoinValue.SatoshisPerBitcoin); //for testing Debug.WriteLine($"My Amount: {(float)ApiLogon.Balance.Btc / BitcoinValue.SatoshisPerBitcoin}"); Debug.WriteLine($"My Amount: {ApiLogon.MyAmount}"); if (ApiLogon.MyAmount < 0 || string.IsNullOrWhiteSpace(ApiLogon.ToBitcoinAddress)) // TODO correct is ApiLogon.MyAmount <= 0 { await DisplayAlert("Warning", $"Amount or To Address are bad filled!", "OK"); } else if (ApiLogon.MyAmount > (float)ApiLogon.Balance.Btc / BitcoinValue.SatoshisPerBitcoin) { await DisplayAlert("Warning", $"Amount higher than Balance!", "OK"); } else { //For Test Yes or No send money bool result = await OnAlertYesNoClicked(sender, e); if (result) { try { //For SendMoney, (toAddres, Amount, fromAddress, fee=0.0001, note) ApiLogon.PayResponse = await ApiLogon.Wallet.SendAsync(ApiLogon.ToBitcoinAddress, amount, ApiLogon.FromMyBitcoinAddress, new BitcoinValue(10000), null); await DisplayAlert("Successfully", $"Send amount is: {ApiLogon.MyAmount}\n to {ApiLogon.ToBitcoinAddress}\n" + $" trans. hash is {ApiLogon.PayResponse.TxHash}\n message is {ApiLogon.PayResponse.Message}", "OK"); } catch (Exception ex) { Debug.WriteLine($"Error from server or client! Error is: {ex}"); //Logging.Debug($"Error from server or client! Error is: {ex}"); await DisplayAlert("Successfully", $"Send amount is: {ApiLogon.MyAmount}\n to {ApiLogon.ToBitcoinAddress}", "OK"); //TODO HACK for testing } } } } else { ApiLogon.MyAmount = 0; //reset value vtp.TextColor = Color.Red; await DisplayAlert("Warning", $"Amount is not number!", "OK"); } }
public void BitcoinValue_ToString_Valid() { BitcoinValue value = BitcoinValue.FromBtc(1.34567m); Assert.Equal(value.ToString(), "1.34567"); }