internal TransactionBuilder(Account sourceAccount, KeyPair baseKeyPair, KeyPair channelKeyPair = null) { _transactionBuilder = new Transaction.Builder(sourceAccount); _baseKeyPair = baseKeyPair; _channelKeyPair = channelKeyPair; _operations = new List <Operation>(); }
public async Task <IActionResult> Send(string issuerSeed, string receiverSeed, string amount) { Network.UseTestNetwork(); Server server = new Server("https://horizon-testnet.stellar.org"); KeyPair issuingKeys = KeyPair.FromSecretSeed(issuerSeed); KeyPair receivingKeys = KeyPair.FromSecretSeed(receiverSeed); Asset eCoin = Asset.CreateNonNativeAsset("eCoin", issuingKeys.Address); AccountResponse issuing = await server.Accounts.Account(issuingKeys.Address); Transaction sendECoin = new Transaction.Builder(issuing) .AddOperation( new PaymentOperation.Builder(receivingKeys, eCoin, amount).Build()) .Build(); sendECoin.Sign(issuingKeys); try { var response = await server.SubmitTransaction(sendECoin); return(Ok(response)); } catch (Exception e) { return(BadRequest(e.Message)); } }
private async void SendPayment(string accountId, string amount, string memo) { var toAccount = KeyPair.FromAccountId(accountId); var accountInfo = await _server.Accounts.Account(_keyPair); var fromAccount = new Account(_keyPair, accountInfo.SequenceNumber); if (toAccount.AccountId == fromAccount.KeyPair.AccountId) { return; } var transaction = new Transaction.Builder(fromAccount) .AddOperation(new PaymentOperation.Builder( toAccount, new AssetTypeNative(), amount).Build()) .AddMemo(Memo.Text(memo)) .Build(); transaction.Sign(_keyPair); try { var response = await _server.SubmitTransaction(transaction); AppSettings.Logger.Information($"Payment was sent successfully. Ledger: {response.Ledger}"); } catch (Exception e) { AppSettings.Logger.Error($"Payment was not sent successfully. Error was: \n {e.Message}"); } }
//创建随机账户 static KeyPair CreateRandomAccount(Account source, long nativeAmount) { var dest = KeyPair.Random(); var operation = new CreateAccountOperation.Builder(dest, nativeAmount) .SetSourceAccount(source.KeyPair) .Build(); source.IncrementSequenceNumber(); Transaction transaction = new Transaction.Builder(source) .AddOperation(operation) .Build(); transaction.Sign(source.KeyPair); var tx = transaction.ToEnvelopeXdrBase64(); var response = PostResult(tx); Console.WriteLine("response:" + response.ReasonPhrase); Console.WriteLine(dest.Address); Console.WriteLine(dest.Seed); Random rd = new Random(); System.IO.StreamWriter sw = new System.IO.StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "\\syslog" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + rd.Next(99999) + ".txt"); sw.WriteLine("公钥地址:" + dest.Address); sw.WriteLine("私钥密码:" + dest.Seed); sw.Close(); return(dest); }
public async Task <IActionResult> CreateTrustline(string issuerSeed, string receiverSeed) { Network.UseTestNetwork(); Server server = new Server("https://horizon-testnet.stellar.org"); KeyPair issuingKeys = KeyPair.FromSecretSeed(issuerSeed); KeyPair receivingKeys = KeyPair.FromSecretSeed(receiverSeed); Asset eCoin = Asset.CreateNonNativeAsset("eCoin", issuingKeys.Address); AccountResponse receiving = await server.Accounts.Account(receivingKeys.Address); Transaction allowECoin = new Transaction.Builder(receiving) .AddOperation(new ChangeTrustOperation.Builder(eCoin, "1000").Build()) .Build(); allowECoin.Sign(receivingKeys); var response = await server.SubmitTransaction(allowECoin); if (response.IsSuccess()) { return(Ok(response)); } else { return(BadRequest(response)); } }
public void TestVerifyChallengeTransactionThrowsIfOperationDataIsNotBase64Encoded() { var serverKeypair = KeyPair.Random(); var clientKeypair = KeyPair.Random(); var anchorName = "NET"; Network.UseTestNetwork(); var now = DateTimeOffset.Now; var nonce = new byte[64]; var tx = new Transaction .Builder(new Account(serverKeypair.AccountId, -1)) .AddOperation( new ManageDataOperation .Builder("NET auth", nonce) .SetSourceAccount(clientKeypair) .Build()) .Build(); tx.Sign(clientKeypair); Assert.ThrowsException <InvalidWebAuthenticationException>(() => { WebAuthentication.VerifyChallengeTransaction(tx, serverKeypair.AccountId, now: now); }); }
public async Task MakePayment(KeyPair destAccountKeyPair, string amount) { var destAccount = server.Accounts.Account(destAccountKeyPair); var sourceKeypair = KeyPair.FromSecretSeed(AccountSeed); var sourceAccountResp = await server.Accounts.Account(sourceKeypair); var sourceAccount = new Account(sourceKeypair, sourceAccountResp.SequenceNumber); var operation = new PaymentOperation.Builder(destAccountKeyPair, new AssetTypeNative(), amount).Build(); var transaction = new Transaction.Builder(sourceAccount).AddOperation(operation).AddMemo(Memo.Text("sample payment")).Build(); transaction.Sign(sourceKeypair); try { var resp = await server.SubmitTransaction(transaction); if (resp.IsSuccess()) { Console.WriteLine("transaction completed successfully!"); await GetAccountBalance(destAccountKeyPair); } else { Console.WriteLine("transaction failed."); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public async Task <bool> SubmitTransaction(string exchangeAccount, string destinationAddress, int amountLumens) { // Update transaction state to 'sending' so it won't be resubmitted in case of the failure. var customerId = DB.CustomerId(exchangeAccount); DB.UpdateTransactionState(customerId, destinationAddress, amountLumens, "sending"); try { // Check if the destination address exists var destinationKeyPair = KeyPair.FromAccountId(destinationAddress); // If so, continue by submitting a transaction to the destination Asset asset = new AssetTypeNative(); KeyPair sourceKeypair = KeyPair.FromSecretSeed(BaseAccountSecret); AccountResponse sourceAccountResponse = await server.Accounts.Account(sourceKeypair); Account sourceAccount = new Account(sourceAccountResponse.KeyPair, sourceAccountResponse.SequenceNumber); PaymentOperation operation = new PaymentOperation.Builder(destinationKeyPair, asset, amountLumens.ToString()).SetSourceAccount(sourceAccount.KeyPair).Build(); Transaction transact = new Transaction.Builder(sourceAccount).AddOperation(operation).Build(); // Sign the transaction transact.Sign(sourceKeypair); //Try to send the transaction try { await server.SubmitTransaction(transact); } catch (Exception exception) { Console.WriteLine("Send Transaction Failed:" + exception.Message); } } catch (Exception e) { Console.WriteLine("Account does not exist:" + e.Message); }; try { // Submit the transaction created DB.UpdateTransactionState(customerId, destinationAddress, amountLumens, "done"); } catch (Exception e) { // set transaction state to 'error' DB.UpdateTransactionState(customerId, destinationAddress, amountLumens, "error"); Console.WriteLine("error:" + e.Message); } return(true); }
private async Task SendPayment(KeyPair from, KeyPair to, int amount, Server stellarServer) { AccountResponse senderAccount = await stellarServer.Accounts.Account(from); Operation payment = new PaymentOperation.Builder(to, new AssetTypeNative(), amount.ToString()).Build(); Transaction transaction = new Transaction.Builder(senderAccount) .AddOperation(payment) .Build(); transaction.Sign(from); await stellarServer.SubmitTransaction(transaction); }
public async Task <Response> Handle(DepositOrWithdrawRequest request, CancellationToken cancellationToken) { Account account = default; if (request.Amount == 0) { return(new NotFoundResult($"Amount not to be zero")); } if (request.Id == Guid.Empty) { return(new NotFoundResult($"Id not to be null")); } if (request.typeTransaction == TypeTransaction.Payment) { return(new NotFoundResult($"invalid Transaction")); } account = await _accountRepository.GetById(request.Id); if (account == null) { return(new NotFoundResult($"Account not found to Account Id: {request.Id}")); } else { if (account.DepositOrWithdraw(request.Amount, request.typeTransaction)) { var transation = new Transaction.Builder() .FromAccountId(account.AccountId) .ToAccountId(account.AccountId) .WithTypeTransaction(request.typeTransaction) .WithAmount(request.Amount) .InTheTime(DateTime.Now) .Build(); if (!transation.IsValid()) { return(new NotFoundResult($"Invalid Transaction")); } await _transactionRepository.Add(transation); } else { return(new NotFoundResult($"Invalid Transaction")); } } await _unitOfWork.SaveChangesAsync(); return(new OkResult("")); }
public static async Task <SubmitTransactionResponse> DoPayment(KeyPair source, KeyPair destination, string amount, Server server) { var operation = new PaymentOperation.Builder(destination, new AssetTypeNative(), amount) .SetSourceAccount(source) .Build(); var xdr = operation.ToXdr(); var account = new Account(source, GetSequence(source.Address)); var transaction = new Transaction.Builder(account).AddOperation(operation).AddMemo(Memo.Text("New memo wohoooo")).Build(); transaction.Sign(source); var response = await server.SubmitTransaction(transaction); return(response); }
private static async Task <SubmitTransactionResponse> SendAllowKinTrustOperation(KeyPair account, AccountResponse accountResponse) { ChangeTrustOperation.Builder changeTrustOperationBuilder = new ChangeTrustOperation.Builder((AssetTypeCreditAlphaNum)KinAsset, TRUST_NO_LIMIT_VALUE).SetSourceAccount(account); ChangeTrustOperation changeTrustOperation = changeTrustOperationBuilder.Build(); Transaction.Builder allowKinTrustTransaction = new Transaction.Builder(new Account(account, accountResponse.SequenceNumber)).AddOperation(changeTrustOperation); Transaction transaction = allowKinTrustTransaction.Build(); transaction.Sign(account); return(await Server.SubmitTransaction(transaction).ConfigureAwait(false)); }
private async void RunAsync() { Server server = UStellarManager.GetServer(); KeyPair sourceKeyPair = KeyPair.FromSecretSeed(source); //Check if the destination account exists in the server. Log("Checking if destination account exists in server", 0); await server.Accounts.Account(destination); Log("Done"); //Load up to date information in source account await server.Accounts.Account(sourceKeyPair.AccountId); AccountResponse sourceAccountResponse = await server.Accounts.Account(sourceKeyPair.AccountId); Account sourceAccount = new Account(sourceAccountResponse.AccountId, sourceAccountResponse.SequenceNumber); //Create the Asset to send and put the amount we are going to send. Asset asset = new AssetTypeNative(); string amount = "1"; PaymentOperation operation = new PaymentOperation.Builder(KeyPair.FromAccountId(destination), asset, amount).SetSourceAccount(sourceAccount.KeyPair).Build(); Transaction transaction = new Transaction.Builder(sourceAccount).AddOperation(operation).Build(); //Sign Transaction Log("Signing Transaction", 2); transaction.Sign(KeyPair.FromSecretSeed(source)); Log("Done"); //Try to send the transaction try { Log("Sending Transaction", 2); await server.SubmitTransaction(transaction); Log("Success!", 1); } catch (Exception exception) { Log("Something went wrong", 2); Log("Exception: " + exception.Message, 1); // If the result is unknown (no response body, timeout etc.) we simply resubmit // already built transaction: // SubmitTransactionResponse response = server.submitTransaction(transaction); } }
public async Task SendPQTPayment(string FromSecret, string ToAccount, double amount) { Network network = new Network("Public Global Stellar Network ; September 2015"); Server server = new Server("https://horizon.stellar.org"); Network.UsePublicNetwork(); KeyPair fromKeypair = KeyPair.FromSecretSeed(FromSecret); KeyPair destinationKeyPair = KeyPair.FromAccountId(ToAccount); AccountResponse issuerAccountResponse = null; var t = Task.Run(async() => { issuerAccountResponse = await server.Accounts.Account(fromKeypair); }); t.Wait(); Account fromAccount = new Account(issuerAccountResponse.KeyPair, issuerAccountResponse.SequenceNumber); KeyPair issuerKeypair = KeyPair.FromAccountId(asset_issuer); Asset asset = new AssetTypeCreditAlphaNum4(asset_code, issuerKeypair); PaymentOperation operation = new PaymentOperation.Builder(destinationKeyPair, asset, amount.ToString()).SetSourceAccount(fromAccount.KeyPair).Build(); Transaction transaction = new Transaction.Builder(fromAccount).AddOperation(operation).Build(); //Try to send the transaction try { transaction.Sign(fromKeypair); var tSign = Task.Run(async() => { await server.SubmitTransaction(transaction); }); tSign.Wait(); } catch (Exception exception) { Console.WriteLine("Send Transaction Failed"); Console.WriteLine("Exception: " + exception.Message); } }
public Transaction BuildTransaction() { var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source, 2908908335136768L); var builder = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .AddMemo(Memo.Text("Hello world!")); Assert.AreEqual(1, builder.OperationsCount); var transaction = builder.Build(); Assert.AreEqual(2908908335136769L, transaction.SequenceNumber); Assert.AreEqual(2908908335136769L, account.SequenceNumber); transaction.Sign(source); return(transaction); }
public void TestSetOptionsOperationPreAuthTxSigner() { Network.UseTestNetwork(); // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var sequenceNumber = 2908908335136768L; var account = new Account(source, sequenceNumber); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); // GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF var opSource = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK"); var operation = new SetOptionsOperation.Builder() .SetSigner(Signer.PreAuthTx(transaction), 10) .SetSourceAccount(opSource) .Build(); var xdr = operation.ToXdr(); var parsedOperation = (SetOptionsOperation)Operation.FromXdr(xdr); Assert.AreEqual(null, parsedOperation.InflationDestination); Assert.AreEqual(null, parsedOperation.ClearFlags); Assert.AreEqual(null, parsedOperation.SetFlags); Assert.AreEqual(null, parsedOperation.MasterKeyWeight); Assert.AreEqual(null, parsedOperation.LowThreshold); Assert.AreEqual(null, parsedOperation.MediumThreshold); Assert.AreEqual(null, parsedOperation.HighThreshold); Assert.AreEqual(null, parsedOperation.HomeDomain); Assert.IsTrue(transaction.Hash().SequenceEqual(parsedOperation.Signer.PreAuthTx.InnerValue)); Assert.AreEqual(10, parsedOperation.SignerWeight); Assert.AreEqual(opSource.AccountId, parsedOperation.SourceAccount.AccountId); Assert.AreEqual( "AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAB1vRBIRC3w7ZH5rQa17hIBKUwZTvBP4kNmSP7jVyw1fQAAAAK", operation.ToXdrBase64()); }
//I DO NOT RECOMMEND SENDING SECRET SEEDS OVER A NETWORK (ESPECIALLY UNENCRYPTED), THIS IS JUST AN EXAMPLE OF HOW YOU MIGHT FORM AN API USING THE SDK public async Task <IActionResult> SetInflationDestination([FromBody] SetInflationDestinationRequest request) { try { Network.UseTestNetwork(); var source = KeyPair.FromAccountId(request.AccountId); var signer = KeyPair.FromSecretSeed(request.Seed); var inflationDestination = KeyPair.FromAccountId(request.InflationDestination); //For Livenet use https://horizon.stellar.org using (var server = new Server("https://horizon-testnet.stellar.org")) { AccountResponse sourceAccount = await server.Accounts.Account(source); var sequenceNumber = sourceAccount.SequenceNumber; var account = new Account(source, sequenceNumber); var operation = new SetOptionsOperation.Builder() .SetInflationDestination(inflationDestination) .SetSourceAccount(source) .Build(); var memo = Memo.Text("Sample Memo"); Transaction transaction = new Transaction.Builder(account).AddOperation(operation).AddMemo(memo).Build(); var transactionXDR = transaction.ToUnsignedEnvelopeXdr(); transaction.Sign(signer); var test = transaction.ToEnvelopeXdrBase64(); await server.SubmitTransaction(test); return(Ok()); } } catch (Exception Ex) { return(StatusCode(500, "Something went wrong")); } }
static async Task <Transaction> BuildTransaction(KeyPair keyPair, double amount, string appendedMemo = "") { amount = amount / 100; var destinationKeyPair = KeyPair.FromAccountId("GDL6CWJER7TOXIWMFTOLVUZU4GKT547OCTNPOTXISJGI4SSOPEQTC3HT"); PaymentOperation.Builder paymentOperationBuilder = new PaymentOperation.Builder(destinationKeyPair, _asset, amount.ToString(CultureInfo.InvariantCulture)) .SetSourceAccount(keyPair); PaymentOperation paymentOperation = paymentOperationBuilder.Build(); var accountResponse = await _server.Accounts.Account(keyPair); Transaction.Builder paymentTransaction = new Transaction.Builder(new Account(keyPair, accountResponse.SequenceNumber)).AddOperation(paymentOperation); paymentTransaction.AddMemo(new MemoText($"1-rced-{appendedMemo}")); var transaction = paymentTransaction.Build(); transaction.Sign(keyPair); return(transaction); }
async Task CreateSurveyAsset(string asset_code) { Network network = new Network("Public Global Stellar Network ; September 2015"); Server server = new Server("https://horizon.stellar.org"); Network.UsePublicNetwork(); KeyPair issuerKeypair = KeyPair.FromAccountId("SEED"); KeyPair destinationKeyPair = KeyPair.FromSecretSeed("PUBLIC"); AccountResponse destinationAccountResponse = null; var t = Task.Run(async() => { destinationAccountResponse = await server.Accounts.Account(destinationKeyPair); }); t.Wait(); Account destinationAccount = new Account(destinationAccountResponse.KeyPair, destinationAccountResponse.SequenceNumber); Asset asset = new AssetTypeCreditAlphaNum12(asset_code, issuerKeypair); ChangeTrustOperation operation = new ChangeTrustOperation.Builder(asset, "100000000000").Build(); Transaction transaction = new Transaction.Builder(destinationAccount).AddOperation(operation).Build(); try { transaction.Sign(destinationKeyPair); var tSign = Task.Run(async() => { await server.SubmitTransaction(transaction); }); tSign.Wait(); // await GetCoinsFromIssuer(asset_code,100); } catch (Exception exception) { Console.WriteLine("Send Transaction Failed"); Console.WriteLine("Exception: " + exception.Message); } }
private async Task <SubmitTransactionResponse> GetCreateAccountTransaction(string destinationAddress) { KeyPair destinationKeyPair = KeyPair.FromAccountId(destinationAddress); AccountResponse sourceAccount = null; AccountResponse destinationAccount = null; try { sourceAccount = await GetAccount(_keyPair).ConfigureAwait(false); destinationAccount = await GetAccount(destinationKeyPair).ConfigureAwait(false); } catch (Exception ex) {} if (sourceAccount == null) { throw new Exception("Source account doesn't exists"); } if (destinationAccount != null) { throw new Exception("Account already exists"); } CreateAccountOperation.Builder createAccountOperationBuilder = new CreateAccountOperation.Builder(destinationKeyPair, "0"); createAccountOperationBuilder.SetSourceAccount(_keyPair); Transaction.Builder transactionBuilder = new Transaction.Builder(new Account(_keyPair, sourceAccount.SequenceNumber)); transactionBuilder.AddOperation(createAccountOperationBuilder.Build()); transactionBuilder.AddMemo(new MemoText($"1-{_app_id}")); Transaction transaction = transactionBuilder.Build(); transaction.Sign(_keyPair); return(await _server.SubmitTransaction(transaction).ConfigureAwait(false)); }
public async Task Transfer(KeyPair source, List <KeyPair> signers, string destinationAddress, decimal amount) { //get source account - check existance var mainAccount = await server.Accounts.Account(source); //create stellar transaction var tx = new Transaction.Builder(mainAccount).AddOperation( new PaymentOperation.Builder(KeyPair.FromAccountId(destinationAddress), new AssetTypeNative(), amount.ToString()).Build()) .Build(); foreach (var signer in signers) { tx.Sign(signer); } var response = await server.SubmitTransaction(tx); if (response.SubmitTransactionResponseExtras != null && response.SubmitTransactionResponseExtras.ExtrasResultCodes.TransactionResultCode == "tx_failed") { throw new Exception("Transaction failed : " + response.SubmitTransactionResponseExtras.ExtrasResultCodes?.TransactionResultCode); } }
private async Task <SubmitTransactionResponse> SendPaymentOperation(KeyPair sourceKeyPair, KeyPair destinationKeyPair, AccountResponse sourceAccount, double amount, string marketPlaceOrderId = null) { PaymentOperation.Builder paymentOperationBuilder = new PaymentOperation.Builder(destinationKeyPair, _kinAsset, amount.ToString(CultureInfo.InvariantCulture)) .SetSourceAccount(sourceKeyPair); PaymentOperation paymentOperation = paymentOperationBuilder.Build(); Transaction.Builder paymentTransaction = new Transaction.Builder(new Account(sourceKeyPair, sourceAccount.SequenceNumber)).AddOperation( paymentOperation); string toAppend = string.IsNullOrEmpty(marketPlaceOrderId) ? "p2p" : marketPlaceOrderId; paymentTransaction.AddMemo(new MemoText($"1-test-{toAppend}")); Transaction transaction = paymentTransaction.Build(); transaction.Sign(sourceKeyPair); return(await _server.SubmitTransaction(transaction).ConfigureAwait(false)); }
public async Task MultisigTest() { using (var stellarServer = new Server(StellarNodeUri)) { KeyPair multisigAccount = KeyPair.FromSecretSeed(MultisigAccountSecretSeed); KeyPair account1 = KeyPair.FromSecretSeed(Account1SecretSeed); KeyPair account2 = KeyPair.FromSecretSeed(Account2SecretSeed); AccountResponse senderAccount = await stellarServer.Accounts.Account(multisigAccount); Operation payment = new PaymentOperation.Builder(account1, new AssetTypeNative(), "1").Build(); Transaction transaction = new Transaction.Builder(senderAccount) .AddOperation(payment) .Build(); transaction.Sign(account1); transaction.Sign(account2); SubmitTransactionResponse result = await stellarServer.SubmitTransaction(transaction); Assert.IsTrue(result.IsSuccess()); } }
public async Task CreateAccount(KeyPair destAccount) { var sourceKeypair = KeyPair.FromSecretSeed(AccountSeed); var sourceAccountResp = await server.Accounts.Account(sourceKeypair); var sourceAccount = new Account(sourceKeypair, sourceAccountResp.SequenceNumber); var operation = new CreateAccountOperation.Builder(destAccount, "20").SetSourceAccount(sourceKeypair).Build(); var transaction = new Transaction.Builder(sourceAccount).AddOperation(operation).AddMemo(Memo.Text("Hello Memo")).Build(); transaction.Sign(sourceKeypair); try { var resp = await server.SubmitTransaction(transaction); if (resp.IsSuccess()) { Console.WriteLine("transaction completed successfully!"); await GetAccountBalance(destAccount); } else { Console.WriteLine("transaction failed."); var c = resp.SubmitTransactionResponseExtras.ExtrasResultCodes; Console.WriteLine(c.TransactionResultCode); foreach (var x in c.OperationsResultCodes) { Console.WriteLine(x); } } } catch (Exception e) { Console.WriteLine(e.Message); } }
// [ValidateAntiForgeryToken] public async Task <string> Create([Bind("ID,TokenName,Amount,Destination,SendStart")] Send send) { send.Destination = send.Destination.ToUpper(); send.TokenName = send.TokenName.ToUpper(); if (send.Destination[0] != 'G' || send.Destination.Length != 56) { ModelState.AddModelError("Address", "Address is not in a proper format (begins with a G and is 56 characters long"); } string[] tokenNames = { "XLM", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "YEAR", "MASLOW1", "MASLOW2", "MASLOW3", "MASLOW4", "MASLOW5" }; if (!(tokenNames.Contains(send.TokenName))) { ModelState.AddModelError("TokenName", "Token is not supported."); } if (!(send.Amount > 0)) { ModelState.AddModelError("Amount", "The amount sent has to be a positive integer."); } Network.UsePublicNetwork(); var server = new Server("https://horizon.stellar.org"); KeyPair source = KeyPair.FromSecretSeed(Environment.GetEnvironmentVariable("SECRET_KEY_" + send.TokenName)); KeyPair destination = KeyPair.FromAccountId(send.Destination); send.Source = Environment.GetEnvironmentVariable("SECRET_KEY_" + send.TokenName); await server.Accounts.Account(destination); AccountResponse sourceAccount = await server.Accounts.Account(source); var sendingAccountPubKey = Environment.GetEnvironmentVariable("PUBLIC_KEY_" + send.TokenName); AccountsRequestBuilder accReqBuilder = new AccountsRequestBuilder(new Uri("https://horizon.stellar.org/accounts/" + sendingAccountPubKey)); var accountResponse = await accReqBuilder.Account(new Uri("https://horizon.stellar.org/accounts/" + sendingAccountPubKey)); Asset tst; if (send.TokenName == "XLM") { // TODO implement this in the future tst = new AssetTypeNative(); // https://elucidsoft.github.io/dotnet-stellar-sdk/api/stellar_dotnetcore_sdk.AssetTypeNative.html } else if (send.TokenName.Length <= 4) { tst = new AssetTypeCreditAlphaNum4(send.TokenName, KeyPair.FromAccountId(Environment.GetEnvironmentVariable("ISSUER_KEY_" + send.TokenName))); } else { tst = new AssetTypeCreditAlphaNum12(send.TokenName, KeyPair.FromAccountId(Environment.GetEnvironmentVariable("ISSUER_KEY_" + send.TokenName))); } Transaction transaction = new Transaction.Builder(new stellar_dotnetcore_sdk.Account(KeyPair.FromAccountId(sendingAccountPubKey), accountResponse.SequenceNumber)) .AddOperation(new PaymentOperation.Builder(destination, tst, Convert.ToString(send.Amount)).Build()) .AddMemo(Memo.Text("Test Transaction")) .Build(); transaction.Sign(source); string status = ""; try { if (ModelState.IsValid) { SubmitTransactionResponse response = await server.SubmitTransaction(transaction); status += "Success!"; return(HtmlEncoder.Default.Encode($"SendsController POST CREATE {status} 1 {source} 2 3 4 ")); } } catch (Exception e) { status += "ERROR" + e.Message; } return(HtmlEncoder.Default.Encode($"INVALID {send.ID}, {send.TokenName}")); }
private static async void SendPayment(string accountId, string amount, string memo) { Server server; var keyPair = KeyPair.FromSecretSeed(AppSettings.WalletPrivateKey); if (AppSettings.IsProduction) { AppSettings.Logger.Information("Connected to the public Stellar network."); Network.UsePublicNetwork(); server = new Server("https://horizon.stellar.org"); Console.WriteLine("Server is: PROD"); } else { AppSettings.Logger.Information("Connected to the TEST Stellar network."); Network.UseTestNetwork(); server = new Server("https://horizon-testnet.stellar.org"); Console.WriteLine("Server is: DEV"); } var toAccount = KeyPair.FromAccountId(accountId); var accountInfo = await server.Accounts.Account(keyPair); var fromAccount = new Account(keyPair, accountInfo.SequenceNumber); if (toAccount.AccountId == fromAccount.KeyPair.AccountId) { return; } var transaction = new Transaction.Builder(fromAccount) .AddOperation(new PaymentOperation.Builder( toAccount, new AssetTypeNative(), amount).Build()) .AddMemo(Memo.Text(memo)) .Build(); transaction.Sign(keyPair); try { var response = await server.SubmitTransaction(transaction); AppSettings.Logger.Information($"Payment was sent successfully to {accountId}. Ledger: {response.Ledger}"); } catch (Exception e) { AppSettings.Logger.Error($"Payment was not sent successfully to {accountId}. Error was: \n {e.Message}"); try { var message = new MimeMessage(); message.From.Add(new MailboxAddress("DeathRaffle.com Error Notification", "*****@*****.**")); message.To.Add(new MailboxAddress("DeathRaffle Support", "*****@*****.**")); message.Subject = "Message From DeathRaffle.com Payment Error Notification!"; message.Body = new TextPart("plain") { Text = $@" There was an error sending a winning payment to: Customer Address: {accountId} Amount to Send: {amount} Error was: {e.Message} " }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 465, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.Authenticate("*****@*****.**", "ownlraesbvstthqb"); client.Send(message); client.Disconnect(true); } } catch (Exception ex) { var message = $@" There was an error sending a winning payment to: Customer Address: {accountId} Amount to Send: {amount} Error was: {e.Message}"; AppSettings.Logger.Error($"Could not email about error: {message} {Environment.NewLine} Error was: {ex.Message}"); } } }
public static async void Payout(decimal InflationAmount) { Network.UseTestNetwork(); //Get the number of votes you have var votes = GetTotalVotes(); //Get the accounts that voted for you and what you owe them var accounts = GetVoterAccounts(InflationAmount, votes); decimal sum = 0; decimal percentage = 0; KeyPair PoolSource = KeyPair.FromSecretSeed(Configuration["INFLATION_POOL_SECRET"]); //KeyPair PoolSource = KeyPair.FromSecretSeed(Environment.GetEnvironmentVariable("INFLATION_POOL_SECRET")); AccountResponse sourceAccount = await server.Accounts.Account(PoolSource); var sequenceNumber = sourceAccount.SequenceNumber; Account PoolAccount = new Account(PoolSource, sequenceNumber); Transaction.Builder BatchTransaction = new Transaction.Builder(PoolAccount); List <Transaction> Transactions = new List <Transaction>(); int batch = 0; foreach (var account in accounts) { //we can only have 100 operations per transaction, this means we need to split up our payouts every 100 people //Rounding down because we're greedy pigs that want to keep every last stroop var payout = RoundDown(account.Payout, 7); var payoutPercent = RoundDown(account.Percentage, 7); //Create the payment operation, we are pulling the 100 stroop fee out of the receipients end. //The lowest amount a voting account could possibly contain is 1 lumen //1 lumen will earn 0.0001923 lumens per week, so we don't have to worry about the fee being larger than a potential earning! var operation = new PaymentOperation.Builder(KeyPair.FromAccountId(account.AccountId), new AssetTypeNative(), (payout - .0000100m).ToString()) .SetSourceAccount(PoolSource) .Build(); BatchTransaction.AddOperation(operation); Console.WriteLine($" Account: {account.AccountId} Earned: {payout}XLM (%{payoutPercent})"); //totalling up our payout/percentages sum += payout; percentage += payoutPercent; if (batch == 99 || account.Equals(accounts.LastOrDefault())) { //This batch is full! we sign it with a memo and our private key and add it to the list of to be processed outgoing transactions. var t = BatchTransaction.AddMemo(Memo.Text($"Sample Memo")).Build(); t.Sign(PoolSource); Transactions.Add(t); BatchTransaction = new Transaction.Builder(PoolAccount); } //Reset the batch batch = batch == 99 ? 0 : ++batch; } Console.WriteLine("Submitting batches to the stellar network..."); foreach (var t in Transactions) { //Submit each transaction to the network Console.WriteLine($"Submitting batch: {Transactions.IndexOf(t) + 1}..."); var response = await server.SubmitTransaction(t); Console.WriteLine($"Batch submitted."); //Console.WriteLine($"Envelope XDR is:"); //Console.WriteLine($"{response.EnvelopeXdr}"); } Console.WriteLine($"Payed out: {sum} (%{percentage})"); //Exists the console app after it has found inflation and payed out. Console.WriteLine("Exiting"); Environment.Exit(0); }
public async Task SendNativeAssets() { //Set network and server Network network = new Network("Test SDF Network ; September 2015"); Server server = new Server("https://horizon-testnet.stellar.org"); KeyPair keypair = KeyPair.Random(); Network.UseTestNetwork(); var sourceaccID = keypair.AccountId; using (var server1 = new Server("https://horizon-testnet.stellar.org")) { var friendBot = await server.TestNetFriendBot .FundAccount(sourceaccID) .Execute().ConfigureAwait(true); } //Source keypair from the secret seed KeyPair sourceKeypair = KeyPair.FromSecretSeed(keypair.SecretSeed); var SourceaccTest = await server.Accounts.Account(sourceaccID); //Load source account data AccountResponse sourceAccountResponse = await server.Accounts.Account(sourceKeypair.AccountId); //Create source account object Account sourceAccount = new Account(sourceKeypair.AccountId, sourceAccountResponse.SequenceNumber); //Create asset object with specific amount //You can use native or non native ones. Asset asset = new AssetTypeNative(); string amount = "30"; //Load des account data AccountResponse descAccountResponse = await server.Accounts.Account("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT"); //Destination keypair from the account id KeyPair destinationKeyPair = KeyPair.FromAccountId("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT"); var transactions = await server.Transactions .ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT") .Execute().ConfigureAwait(true); var abc = new TransactionResponse(); var test = new test.MyTestApp(); test.Main(); var tranDetail = server.Transactions.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT").Cursor("now"); var paymentDetail = server.Payments.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT"); //paymentDetail.Stream(operationres); //OnhresholdReached?.Invoke(this, new OperationResponse()); Program1 abcd = new Program1(); abcd.OnhresholdReached += Abcd_OnhresholdReached; abcd.OnhresholdReached += new EventHandler <OperationResponse>(this.Abcd_OnhresholdReached); var OperateDetail = server.Operations.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT"); //Create payment operation PaymentOperation operation = new PaymentOperation.Builder(destinationKeyPair, asset, amount).SetSourceAccount(sourceAccount.KeyPair).Build(); //Create transaction and add the payment operation we created Transaction transaction = new Transaction.Builder(sourceAccount).AddOperation(operation).Build(); //Sign Transaction transaction.Sign(sourceKeypair); //Try to send the transaction try { Console.WriteLine("Sending Transaction"); await server.SubmitTransaction(transaction).ConfigureAwait(true); Console.WriteLine("Success!"); } catch (Exception exception) { Console.WriteLine("Send Transaction Failed"); Console.WriteLine("Exception: " + exception.Message); } }
/// Generates a multi-signed transaction /// and transfer amount to a 3rd account, if signed correctly public async Task MultiSigTransfer() { // Horizon settings Network.UseTestNetwork(); Server server = new Server(HorizonUrl); // master account Console.WriteLine("Generating key pairs..."); KeyPair masterKeyPair = KeyPair.FromSecretSeed(MasterSecret); AccountResponse masterAccountResponse = await server.Accounts.Account(masterKeyPair); Account masterAccount = new Account(masterAccountResponse.KeyPair, masterAccountResponse.SequenceNumber); // generating keypairs KeyPair signerKeyPair = KeyPair.FromAccountId(SignerAccount); KeyPair signerSecretKeyPair = KeyPair.FromSecretSeed(SignerSecret);; KeyPair destinationKeyPair = KeyPair.FromAccountId(DestinationAccount); var signerKey = stellar_dotnet_sdk.Signer.Ed25519PublicKey(signerKeyPair); // set signer operation SetOptionsOperation signerOperation = new SetOptionsOperation.Builder().SetSigner(signerKey, 1).Build(); // set flag // for clearing flags -> SetOptionsOperation flagOperation = new SetOptionsOperation.Builder().SetClearFlags(1).Build(); SetOptionsOperation flagOperation = new SetOptionsOperation.Builder().SetSetFlags(1).Build(); // set medium threshold SetOptionsOperation thresholdOperation = new SetOptionsOperation.Builder().SetMediumThreshold(2).Build(); // payment operation string amountToTransfer = "35"; Asset asset = new AssetTypeNative(); PaymentOperation paymentOperation = new PaymentOperation.Builder(destinationKeyPair, asset, amountToTransfer).SetSourceAccount(masterKeyPair).Build(); // create transaction Transaction transaction = new Transaction.Builder(masterAccount) .AddOperation(flagOperation) .AddOperation(thresholdOperation) .AddOperation(signerOperation) .AddOperation(paymentOperation) .Build(); // sign Transaction transaction.Sign(masterKeyPair); transaction.Sign(signerSecretKeyPair); // try to send transaction try { Console.WriteLine("Sending Transaction..."); await server.SubmitTransaction(transaction); Console.WriteLine("Success!"); await this.GetBalance(MasterAccount); await this.GetBalance(SignerAccount); await this.GetBalance(DestinationAccount); } catch (Exception exception) { Console.WriteLine("Send Transaction Failed"); Console.WriteLine("Exception: " + exception.Message); } }