コード例 #1
0
        private async Task DoExternalSpendOffer()
        {
            string externalSpendOffer = JwtProviderBuilder.Spend
                                        .AddOffer("spendit", "111")
                                        .AddSender(UserId, "speeend it", "block chain sutff isn't coded yet lawl, i'm neva goonna spend")
                                        .Jwt;

            OpenOrder createExternalSpendOffer =
                await _marketPlaceClient.CreateExternalOffer(externalSpendOffer).ConfigureAwait(false);

            Order submitSpendOffer =
                await _marketPlaceClient.SubmitOrder(createExternalSpendOffer.Id).ConfigureAwait(false);

            SubmitTransactionResponse submitTransactionResponse = await _blockChainHandler.SendPayment(_keyPair,
                                                                                                       submitSpendOffer.BlockChainData.RecipientAddress,
                                                                                                       submitSpendOffer.Amount, submitSpendOffer.Id).ConfigureAwait(false);


            Order finishedOrder = await WaitForOrderCompletion(UserId, submitSpendOffer.Id).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(finishedOrder?.Result?.Jwt))
            {
                SecurityToken token = _marketPlaceJwtProvider.ValidateJwtToken(finishedOrder?.Result?.Jwt);
            }
        }
コード例 #2
0
        public async Task DoP2POffer(string toUserId = null)
        {
            string p2POffer = JwtProviderBuilder.P2P
                              .AddOffer("p2p-" + toUserId, "1")
                              .AddSender(UserId, "p2p", "to myself")
                              .AddRecipient(toUserId ?? UserId, "p2p", "to him?")
                              .Jwt;

            OpenOrder createExternalP2POffer =
                await _marketPlaceClient.CreateExternalOffer(p2POffer).ConfigureAwait(false);

            Order submitP2POffer =
                await _marketPlaceClient.SubmitOrder(createExternalP2POffer.Id).ConfigureAwait(false);

            SubmitTransactionResponse submitTransactionResponse = await _blockChainHandler.SendPayment(_keyPair,
                                                                                                       submitP2POffer.BlockChainData.RecipientAddress,
                                                                                                       submitP2POffer.Amount, submitP2POffer.Id).ConfigureAwait(false);

            Order finishedOrder = await WaitForOrderCompletion(UserId, submitP2POffer.Id).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(finishedOrder?.Result?.Jwt))
            {
                SecurityToken token = _marketPlaceJwtProvider.ValidateJwtToken(finishedOrder?.Result?.Jwt);
            }
        }
コード例 #3
0
        public async Task TestSubmitTransactionSuccess()
        {
            var json = File.ReadAllText(Path.Combine("responses", "testdata", "serverSuccess.json"));

            When().Returns(ResponseMessage(HttpOk, json));

            SubmitTransactionResponse response = await _server.SubmitTransaction(BuildTransaction());

            Assert.IsTrue(response.IsSuccess());
            Assert.AreEqual(response.Ledger, 826150L);
            Assert.AreEqual(response.Hash, "2634d2cf5adcbd3487d1df042166eef53830115844fdde1588828667bf93ff42");
            Assert.IsNull(response.SubmitTransactionResponseExtras);
        }
コード例 #4
0
        public static async Task <bool> Activate(this KeyPair account)
        {
            AccountResponse accountResponse = await GetAccount(account);

            if (!HasKinAsset(accountResponse))
            {
                SubmitTransactionResponse response = await SendAllowKinTrustOperation(account, accountResponse).ConfigureAwait(false);

                return(response != null);
            }

            return(true);
        }
コード例 #5
0
 public static TxSubmitModel ToModel(this SubmitTransactionResponse accountResponse)
 {
     if (accountResponse == null)
     {
         return(null);
     }
     return(new TxSubmitModel
     {
         Hash = accountResponse.Hash,
         IsSuccess = accountResponse.IsSuccess(),
         ResultXdr = accountResponse.ResultXdr
     });
 }
 public SubmitTransactionResponseViewModel(SubmitTransactionResponse domain)
 {
     this.ApiVersion                = Const.MERCHANT_API_VERSION;
     this.Timestamp                 = domain.Timestamp;
     this.Txid                      = domain.Txid;
     this.ReturnResult              = domain.ReturnResult ?? ""; // return empty strings instead of nulls
     this.ResultDescription         = domain.ResultDescription ?? "";
     this.MinerId                   = domain.MinerId ?? "";
     this.CurrentHighestBlockHash   = domain.CurrentHighestBlockHash;
     this.CurrentHighestBlockHeight = domain.CurrentHighestBlockHeight;
     this.TxSecondMempoolExpiry     = domain.TxSecondMempoolExpiry;
     this.ConflictedWith            = domain.ConflictedWith?.Select(t => new SubmitTransactionConflictedTxResponseViewModel(t)).ToArray();
 }
コード例 #7
0
        public async Task TestSubmitTransactionFail()
        {
            var json = File.ReadAllText(Path.Combine("responses", "testdata", "serverFailure.json"));

            When().Returns(ResponseMessage(HttpBadRequest, json));

            SubmitTransactionResponse response = await _server.SubmitTransaction(BuildTransaction());

            Assert.IsFalse(response.IsSuccess());
            Assert.IsNull(response.Ledger);
            Assert.IsNull(response.Hash);
            Assert.AreEqual(response.SubmitTransactionResponseExtras.EnvelopeXdr, "AAAAAK4Pg4OEkjGmSN0AN37K/dcKyKPT2DC90xvjjawKp136AAAAZAAKsZQAAAABAAAAAAAAAAEAAAAJSmF2YSBGVFchAAAAAAAAAQAAAAAAAAABAAAAAG9wfBI7rRYoBlX3qRa0KOnI75W5BaPU6NbyKmm2t71MAAAAAAAAAAABMS0AAAAAAAAAAAEKp136AAAAQOWEjL+Sm+WP2puE9dLIxWlOibIEOz8PsXyG77jOCVdHZfQvkgB49Mu5wqKCMWWIsDSLFekwUsLaunvmXrpyBwQ=");
            Assert.AreEqual(response.SubmitTransactionResponseExtras.ResultXdr, "AAAAAAAAAGT/////AAAAAQAAAAAAAAAB////+wAAAAA=");
            Assert.IsNotNull(response.SubmitTransactionResponseExtras);
            Assert.AreEqual("tx_failed", response.SubmitTransactionResponseExtras.ExtrasResultCodes.TransactionResultCode);
            Assert.AreEqual("op_no_destination", response.SubmitTransactionResponseExtras.ExtrasResultCodes.OperationsResultCodes[0]);
        }
コード例 #8
0
        public async Task <SubmitTransactionResponse> SendPayment(KeyPair sourceKeyPair, string destinationAddress,
                                                                  double amount, string marketPlaceOrderId = null)
        {
            KeyPair         destinationKeyPair = KeyPair.FromAccountId(destinationAddress);
            AccountResponse sourceAccount      = await GetAccount(sourceKeyPair);

            AccountResponse destinationAccount = await GetAccount(destinationKeyPair);

            if (HasKinAsset(sourceAccount, true, amount) && HasKinAsset(destinationAccount))
            {
                SubmitTransactionResponse response =
                    await SendPaymentOperation(sourceKeyPair, destinationKeyPair, sourceAccount, amount,
                                               marketPlaceOrderId).ConfigureAwait(false);

                return(response);
            }

            return(null);
        }
コード例 #9
0
 public ActionResult <CreateAccountResponse> Get(string addr)
 {
     try
     {
         SubmitTransactionResponse txResponse = GetCreateAccountTransaction(addr).GetAwaiter().GetResult();
         return(Ok(new CreateAccountResponse()
         {
             Message = txResponse != null ? null : "Transaction failed to submit",
             Success = txResponse != null,
             TxResponse = txResponse
         }));
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message, e);
         return(Ok(new CreateAccountResponse()
         {
             Message = e.Message,
             Success = false
         }));
     }
 }
コード例 #10
0
ファイル: Server.cs プロジェクト: mocolicious/kin-csharp-sdk
        public async Task <SubmitTransactionResponse> SubmitTransaction(string transactionEnvelopeBase64)
        {
            Uri transactionUri = new UriBuilder(_serverUri).SetPath("/transactions").Uri;

            List <KeyValuePair <string, string> > paramsPairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("tx", transactionEnvelopeBase64)
            };

            HttpResponseMessage response =
                await HttpClient.PostAsync(transactionUri, new FormUrlEncodedContent(paramsPairs.ToArray()));

            if (response.Content != null)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                SubmitTransactionResponse submitTransactionResponse =
                    JsonSingleton.GetInstance <SubmitTransactionResponse>(responseString);
                return(submitTransactionResponse);
            }

            return(null);
        }
コード例 #11
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());
            }
        }
コード例 #12
0
        // [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}"));
        }