Пример #1
0
        public void PaymentOperation()
        {
            // GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
            KeyPair source = KeyPair.FromSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
            // GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
            KeyPair destination = KeyPair.FromSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");

            Stellar.Generated.Asset asset = Stellar.Asset.Native();
            long amount = 1000;

            PaymentOperation operation = new PaymentOperation.Builder(destination, asset, amount)
                                         .SetSourceAccount(source)
                                         .Build();

            Stellar.Generated.Operation xdr             = operation.ToXdr();
            PaymentOperation            parsedOperation = (PaymentOperation)Operation.FromXdr(xdr);

            Assert.AreEqual(source.Address, parsedOperation.SourceAccount.Address);
            Assert.AreEqual(destination.Address, parsedOperation.Destination.Address);
            //Assert.IsTrue(parsedOperation.Asset instanceof AssetTypeNative);
            Assert.AreEqual(amount, parsedOperation.Amount);

            Assert.AreEqual(
                "AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAEAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAAAAAAAAAAA+g=",
                operation.ToXdrBase64());
        }
Пример #2
0
        public void TestPaymentOperation()
        {
            // GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
            var source = KeyPair.FromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
            // GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
            var destination = KeyPair.FromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");

            Asset asset  = new AssetTypeNative();
            var   amount = "1000";

            var operation = new PaymentOperation.Builder(destination, asset, amount)
                            .SetSourceAccount(source)
                            .Build();

            var xdr             = operation.ToXdr();
            var parsedOperation = (PaymentOperation)Operation.FromXdr(xdr);

            Assert.AreEqual(10000000000L, xdr.Body.PaymentOp.Amount.InnerValue);
            Assert.AreEqual(source.AccountId, parsedOperation.SourceAccount.AccountId);
            Assert.AreEqual(destination.AccountId, parsedOperation.Destination.AccountId);
            Assert.IsTrue(parsedOperation.Asset is AssetTypeNative);
            Assert.AreEqual(amount, parsedOperation.Amount);

            Assert.AreEqual(
                "AAAAAQAAAAC7JAuE3XvquOnbsgv2SRztjuk4RoBVefQ0rlrFMMQvfAAAAAEAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAAAAAAAlQL5AA=",
                operation.ToXdrBase64());
        }
Пример #3
0
        static void PaymentFromMaster(KeyPair kp, long amount)
        {
            // get master
            var     master       = KeyPair.Master();
            Account masterSource = new Account(master, 1);

            // load asset
            Stellar.Generated.Asset asset = Stellar.Asset.Native();

            var operation =
                new PaymentOperation.Builder(kp, asset, amount)
                .SetSourceAccount(masterSource.KeyPair)
                .Build();

            masterSource.IncrementSequenceNumber();

            Stellar.Transaction transaction =
                new Stellar.Transaction.Builder(masterSource)
                .AddOperation(operation)
                .Build();

            transaction.Sign(masterSource.KeyPair);

            string message = transaction.ToEnvelopeXdrBase64();

            string response = GetResult(message);

            Console.WriteLine(response);
        }
Пример #4
0
        static void MultiSignPayment(KeyPair from, KeyPair to, KeyPair fromm, long amount)
        {
            Account source  = new Account(from, GetSequenceNum(from.Address));
            Account sourcee = new Account(fromm);

            // load asset
            Asset asset = new Asset();

            var operation =
                new PaymentOperation.Builder(to, asset, amount)
                .SetSourceAccount(from)
                .Build();

            source.IncrementSequenceNumber();

            Stellar.Transaction transaction =
                new Stellar.Transaction.Builder(source)
                .AddOperation(operation)
                .Build();

            transaction.Sign(source.KeyPair);
            transaction.Sign(sourcee.KeyPair);

            var tx = transaction.ToEnvelopeXdrBase64();

            var response = PostResult(tx);

            Console.WriteLine(response.ReasonPhrase);
        }
Пример #5
0
        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);
            }
        }
Пример #6
0
        public ITransactionBuilder AddPayment(string destinationAddress, double amount)
        {
            KeyPair keyPair = KeyPair.FromAccountId(destinationAddress);

            PaymentOperation.Builder builder = new PaymentOperation.Builder(keyPair, NativeAsset, amount.ToString(CultureInfo.InvariantCulture));
            builder.SetSourceAccount(_baseKeyPair);
            return(this);
        }
Пример #7
0
        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);
        }
Пример #8
0
        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 TestDoesNotCheckDestinationMoreThanOnce()
        {
            var accountId = "GAYHAAKPAQLMGIJYMIWPDWCGUCQ5LAWY4Q7Q3IKSP57O7GUPD3NEOSEA";
            var json      = BuildAccountResponse(accountId);

            When().Returns(ServerTest.ResponseMessage(HttpStatusCode.OK, json));

            var payment = new PaymentOperation
                          .Builder(KeyPair.FromAccountId(accountId), new AssetTypeNative(), "100.500")
                          .Build();

            var tx = BuildTransaction(accountId, new Operation[] { payment });
            await _server.CheckMemoRequired(tx);
        }
        public async Task TestSkipCheckIfDestinationIsMuxedAccount()
        {
            var accountId = "GAYHAAKPAQLMGIJYMIWPDWCGUCQ5LAWY4Q7Q3IKSP57O7GUPD3NEOSEA";

            var muxed = MuxedAccountMed25519.FromMuxedAccountId(
                "MAAAAAAAAAAAJURAAB2X52XFQP6FBXLGT6LWOOWMEXWHEWBDVRZ7V5WH34Y22MPFBHUHY");

            var payment = new PaymentOperation
                          .Builder(muxed, new AssetTypeNative(), "100.500")
                          .Build();

            var tx = BuildTransaction(accountId, new Operation[] { payment }, Memo.None(), skipDefaultOp: true);
            await _server.CheckMemoRequired(tx);
        }
Пример #11
0
        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);
        }
Пример #12
0
        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);
            }
        }
Пример #13
0
        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);
            }
        }
Пример #14
0
        public async void TestSubmitTransactionMissingAmount()
        {
            StellarBase.Network.CurrentNetwork = network_passphrase;

            AccountCallBuilder accountBuilder = new AccountCallBuilder(horizon_url);

            accountBuilder.accountId("GBAB45XKXEGB74QALBHWP7HATWSWXVHWJKO7W6R3ETWJVCZN5FTASVHL");
            var t = await accountBuilder.Call();


            var     sourceKeyPair = KeyPair.FromSeed("SAEBUXJNNNZPMX3NDG4TTTV2OGUQIMFPPAHZG4FO4FQECKWK4BOSN5GZ");
            Account sourceAccount = new Account(sourceKeyPair, long.Parse(t.Sequence));

            var destinationKeyPair = KeyPair.FromAddress("GDGUDD3WNMAZD6GQXXJXZMJKMCADEZJDA74TAQJSEEPTLNL4PYHZVM4T");

            // make payment with amount > source balance
            double amount    = double.Parse(t.Balances[0].Balance);
            var    operation =
                new PaymentOperation.Builder(destinationKeyPair, new Asset(), (long)(amount * StellarBase.One.Value) + 10)
                .SetSourceAccount(sourceKeyPair)
                .Build();

            sourceAccount.IncrementSequenceNumber();
            var transaction = new StellarBase.Transaction.Builder(sourceAccount)
                              .AddOperation(operation)
                              .Build();

            transaction.Sign(sourceAccount.KeyPair);
            var txSigned = transaction.ToEnvelopeXdrBase64();

            TransactionCallBuilder txBuilder = new TransactionCallBuilder(horizon_url);

            txBuilder.submitTransaction(txSigned);
            try
            {
                var tx = await txBuilder.Call();

                Assert.Equal("Expected BadRequestException", null);
            }
            catch (BadRequestException e)
            {
                Assert.Equal(400, e.ErrorDetails.Status);
                Assert.Equal("tx_failed", e.ErrorDetails.Extras.ResultCodes.Transaction);
                Assert.Equal("op_underfunded", e.ErrorDetails.Extras.ResultCodes.Operations[0]);
            }
        }
Пример #15
0
        public async Task <string> SendVoteToken(string pubKey, string secretKey, string memo)
        {
            //Set network and server
            Network.UseTestNetwork();
            Server server = new Server("https://horizon-testnet.stellar.org");

            var source = KeyPair.FromSecretSeed(secretKey);

            AccountResponse sourceAccountResponse = await server.Accounts.Account(source.AccountId);

            //Create source account object
            Account sourceAccount = new Account(source.AccountId, sourceAccountResponse.SequenceNumber);

            Asset asset = new AssetTypeCreditAlphaNum12(this.VoteToken, IssueAccount.PublicKey);

            //Create payment operation
            PaymentOperation operation = new PaymentOperation.Builder(KeyPair.FromAccountId(DistributionAccount.PublicKey), asset, "1").SetSourceAccount(sourceAccount.KeyPair).Build();

            Transaction innerTransaction = new TransactionBuilder(sourceAccount)
                                           .SetFee(100)
                                           .AddOperation(operation)
                                           .AddMemo(new MemoText(memo))
                                           .Build();

            innerTransaction.Sign(source);

            var feeSource = KeyPair.FromSecretSeed(DistributionAccount.SecretSeed);
            var finalTx   = TransactionBuilder.BuildFeeBumpTransaction(feeSource, innerTransaction, 100);

            finalTx.Sign(feeSource);
            //Try to send the transaction
            try
            {
                var response = await this.SubmitTransaction(finalTx.ToEnvelopeXdrBase64());

                var hash = response.Hash;
                return(hash);
            }
            catch (Exception exception)
            {
                return(string.Empty);
            }
        }
        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);
        }
Пример #17
0
        public async Task <bool> SendVoteTokenToUser(string destinationAddress)
        {
            //Set network and server
            Network.UseTestNetwork();
            Server server = new Server("https://horizon-testnet.stellar.org");

            //Sender
            var senderSource = KeyPair.FromSecretSeed(DistributionAccount.SecretSeed);

            //Destination keypair from the account id
            KeyPair destinationKeyPair = KeyPair.FromAccountId(destinationAddress);

            AccountResponse sourceAccountResponse = await server.Accounts.Account(senderSource.AccountId);

            //Create source account object
            Account sourceAccount = new Account(senderSource.AccountId, sourceAccountResponse.SequenceNumber);

            Asset asset = new AssetTypeCreditAlphaNum12(this.VoteToken, IssueAccount.PublicKey);

            //Create payment operation
            PaymentOperation operation = new PaymentOperation.Builder(destinationKeyPair, asset, "1").SetSourceAccount(sourceAccount.KeyPair).Build();

            //Create transaction and add the payment operation we created
            Transaction transaction = new TransactionBuilder(sourceAccount).AddOperation(operation).Build();

            //Sign Transaction
            transaction.Sign(senderSource);

            //Try to send the transaction
            try
            {
                var response = await server.SubmitTransaction(transaction);

                return(response.IsSuccess());
            }
            catch (Exception exception)
            {
                return(false);
            }
        }
Пример #18
0
        private Task <Transaction> GetTransaction(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-{_appId}-{toAppend}"));

            Transaction transaction = paymentTransaction.Build();

            transaction.Sign(sourceKeyPair);
            return(Task.FromResult(transaction));
        }
Пример #19
0
        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));
        }
Пример #20
0
        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());
            }
        }
Пример #21
0
        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);
        }
Пример #22
0
        /// 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);
            }
        }
Пример #23
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);
            }
        }
Пример #24
0
        public static Transaction BuildPaymentTransaction(TransactionBuilderOptions options, KeyPair destination, Asset asset, long amount)
        {
            var paymentOperation = new PaymentOperation.Builder(destination, asset, Amount.FromXdr(amount)).Build();

            return(BuildTransaction(options, paymentOperation));
        }
Пример #25
0
        public async Task <string> BuildTransactionAsync(Guid operationId, AddressBalance from, string toAddress, long amount)
        {
            var fromKeyPair = KeyPair.FromAddress(from.Address);
            var fromAccount = new Account(fromKeyPair, from.Sequence);

            var toKeyPair = KeyPair.FromAddress(toAddress);

            var transferableBalance = from.Balance - from.MinBalance;

            StellarBase.Operation operation;
            if (await _horizonService.AccountExists(toAddress))
            {
                if (amount <= transferableBalance)
                {
                    var asset = new StellarBase.Asset();
                    operation = new PaymentOperation.Builder(toKeyPair, asset, amount)
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
                else
                {
                    operation = new AccountMergeOperation.Builder(toKeyPair)
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
            }
            else
            {
                if (amount <= transferableBalance)
                {
                    operation = new CreateAccountOperation.Builder(toKeyPair, amount)
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
                else
                {
                    throw new BusinessException($"Currently not possible to transfer entire balance to an unused account! Use a destination in existance. transferable={transferableBalance}");
                }
            }

            fromAccount.IncrementSequenceNumber();

            var tx = new StellarBase.Transaction.Builder(fromAccount)
                     .AddOperation(operation)
                     .Build();

            var xdr    = tx.ToXDR();
            var writer = new ByteWriter();

            StellarBase.Generated.Transaction.Encode(writer, xdr);
            var xdrBase64 = Convert.ToBase64String(writer.ToArray());

            var build = new TxBuild
            {
                OperationId = operationId,
                XdrBase64   = xdrBase64
            };
            await _buildRepository.AddAsync(build);

            return(xdrBase64);
        }
Пример #26
0
        public async Task <string> BuildTransactionAsync(Guid operationId, AddressBalance from, string toAddress, string memoText, long amount)
        {
            var fromKeyPair = KeyPair.FromAccountId(from.Address);
            var fromAccount = new Account(fromKeyPair, from.Sequence);

            var toKeyPair = KeyPair.FromAccountId(toAddress);

            var transferableBalance = from.Balance - from.MinBalance;

            Operation operation;

            if (await _horizonService.AccountExists(toAddress))
            {
                if (amount <= transferableBalance)
                {
                    var asset = new AssetTypeNative();
                    operation = new PaymentOperation.Builder(toKeyPair, asset, Operation.FromXdrAmount(amount))
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
                else if (!_balanceService.IsDepositBaseAddress(from.Address))
                {
                    operation = new AccountMergeOperation.Builder(toKeyPair)
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
                else
                {
                    throw new BusinessException($"It isn't allowed to merge the entire balance from the deposit base into another account! Transfer less funds. transferable={transferableBalance}");
                }
            }
            else
            {
                if (amount <= transferableBalance)
                {
                    operation = new CreateAccountOperation.Builder(toKeyPair, Operation.FromXdrAmount(amount))
                                .SetSourceAccount(fromKeyPair)
                                .Build();
                }
                else
                {
                    throw new BusinessException($"It isn't possible to merge the entire balance into an unused account! Use a destination in existance. transferable={transferableBalance}");
                }
            }

            var builder = new TransactionBuilder(fromAccount)
                          .AddOperation(operation)
                          .SetFee(_appSettings.StellarApiService.OperationFee);

            if (!string.IsNullOrWhiteSpace(memoText))
            {
                var memo = new MemoText(memoText);
                builder = builder.AddMemo(memo);
            }

            var tx = builder.Build();

            var xdr               = tx.ToUnsignedEnvelopeXdr(TransactionBase.TransactionXdrVersion.V1);
            var expirationDate    = (DateTime.UtcNow + _transactionExpirationTime);
            var maxUnixTimeDouble = expirationDate.ToUnixTime() / 1000;//ms to seconds
            var maxTimeUnix       = (ulong)maxUnixTimeDouble;

            xdr.V1.Tx.TimeBounds = new TimeBounds()
            {
                MaxTime = new TimePoint(new Uint64(maxTimeUnix)),
                MinTime = new TimePoint(new Uint64(0)),
            };

            var writer = new XdrDataOutputStream();

            stellar_dotnet_sdk.xdr.TransactionEnvelope.Encode(writer, xdr);
            var xdrBase64 = Convert.ToBase64String(writer.ToArray());

            _log.Info("Transaction has been built", new
            {
                OperationId = operationId,
                From        = from,
                To          = toAddress,
                Memo        = memoText,
                Amount      = amount,
                Fee         = tx.Fee,
                Sequence    = tx.SequenceNumber,
                MaxTimeUnix = maxTimeUnix
            });

            var build = new TxBuild
            {
                OperationId = operationId,
                XdrBase64   = xdrBase64
            };
            await _buildRepository.AddAsync(build);

            return(xdrBase64);
        }