public void TestDeserializeTransactionPreProtocol13()
        {
            var json        = File.ReadAllText(Path.Combine("testdata", "transactionTransaction.json"));
            var transaction = JsonSingleton.GetInstance <TransactionResponse>(json);

            var transaction2 = new TransactionResponse(transaction.Hash, transaction.Ledger, transaction.CreatedAt, transaction.SourceAccount,
                                                       transaction.Successful, transaction.PagingToken, transaction.SourceAccountSequence, transaction.FeeCharged, transaction.OperationCount,
                                                       transaction.EnvelopeXdr, transaction.ResultXdr, transaction.ResultMetaXdr, transaction.Memo, transaction.Links);


            Assert.AreEqual(transaction.Hash, transaction2.Hash);
            Assert.AreEqual(transaction.Ledger, transaction2.Ledger);
            Assert.AreEqual(transaction.Successful, transaction.Successful);
            Assert.AreEqual(transaction.SourceAccount, transaction2.SourceAccount);
            Assert.AreEqual(transaction.FeeAccount, transaction2.FeeAccount);
            Assert.AreEqual(transaction.SourceAccountSequence, transaction2.SourceAccountSequence);
            Assert.AreEqual(transaction.FeeCharged, transaction2.FeeCharged);
            Assert.AreEqual(transaction.OperationCount, transaction2.OperationCount);
        }
        public void TestDeserialize()
        {
            var json           = File.ReadAllText(Path.Combine("responses", "testdata", "operationPage.json"));
            var operationsPage = JsonSingleton.GetInstance <Page <OperationResponse> >(json);

            CreateAccountOperationResponse createAccountOperation = (CreateAccountOperationResponse)operationsPage.Records[0];

            Assert.AreEqual(createAccountOperation.StartingBalance, "10000.0");
            Assert.AreEqual(createAccountOperation.PagingToken, "3717508943056897");
            Assert.AreEqual(createAccountOperation.Account.AccountId, "GDFH4NIYMIIAKRVEJJZOIGWKXGQUF3XHJG6ZM6CEA64AMTVDN44LHOQE");
            Assert.AreEqual(createAccountOperation.Funder.AccountId, "GBS43BF24ENNS3KPACUZVKK2VYPOZVBQO2CISGZ777RYGOPYC2FT6S3K");

            PaymentOperationResponse paymentOperation = (PaymentOperationResponse)operationsPage.Records[4];

            Assert.AreEqual(paymentOperation.Amount, "10.123");
            Assert.AreEqual(paymentOperation.Asset, new AssetTypeNative());
            Assert.AreEqual(paymentOperation.From.AccountId, "GCYK67DDGBOANS6UODJ62QWGLEB2A7JQ3XUV25HCMLT7CI23PMMK3W6R");
            Assert.AreEqual(paymentOperation.To.AccountId, "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H");
        }
Exemple #3
0
        public void TestDeserializeAccountResponse()
        {
            var json    = File.ReadAllText(Path.Combine("responses", "testdata", "account.json"));
            var account = JsonSingleton.GetInstance <AccountResponse>(json);

            Assert.AreEqual(account.KeyPair.AccountId, "GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7");
            Assert.AreEqual(account.PagingToken, "1");
            Assert.AreEqual(account.SequenceNumber, 2319149195853854);
            Assert.AreEqual(account.SubentryCount, 0);
            Assert.AreEqual(account.InflationDestination, "GAGRSA6QNQJN2OQYCBNQGMFLO4QLZFNEHIFXOMTQVSUTWVTWT66TOFSC");
            Assert.AreEqual(account.HomeDomain, "stellar.org");

            Assert.AreEqual(account.Thresholds.LowThreshold, 10);
            Assert.AreEqual(account.Thresholds.MedThreshold, 20);
            Assert.AreEqual(account.Thresholds.HighThreshold, 30);

            Assert.AreEqual(account.Flags.AuthRequired, false);
            Assert.AreEqual(account.Flags.AuthRevocable, true);

            Assert.AreEqual(account.Balances[0].AssetType, "credit_alphanum4");
            Assert.AreEqual(account.Balances[0].AssetCode, "ABC");
            Assert.AreEqual(account.Balances[0].AssetIssuer.AccountId, "GCRA6COW27CY5MTKIA7POQ2326C5ABYCXODBN4TFF5VL4FMBRHOT3YHU");
            Assert.AreEqual(account.Balances[0].BalanceString, "1001.0000000");
            Assert.AreEqual(account.Balances[0].Limit, "12000.4775807");

            Assert.AreEqual(account.Balances[1].AssetType, "native");
            Assert.AreEqual(account.Balances[1].BalanceString, "20.0000300");
            Assert.AreEqual(account.Balances[1].Limit, null);

            Assert.AreEqual(account.Signers[0].AccountId, "GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7");
            Assert.AreEqual(account.Signers[0].Weight, 0);
            Assert.AreEqual(account.Signers[1].AccountId, "GCR2KBCIU6KQXSQY5F5GZYC4WLNHCHCKW4NEGXNEZRYWLTNZIRJJY7D2");
            Assert.AreEqual(account.Signers[1].Weight, 1);

            Assert.AreEqual(account.Data["TestKey"], "VGVzdFZhbHVl");

            Assert.AreEqual(account.Links.Effects.Href, "/accounts/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7/effects{?cursor,limit,order}");
            Assert.AreEqual(account.Links.Offers.Href, "/accounts/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7/offers{?cursor,limit,order}");
            Assert.AreEqual(account.Links.Operations.Href, "/accounts/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7/operations{?cursor,limit,order}");
            Assert.AreEqual(account.Links.Self.Href, "/accounts/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7");
            Assert.AreEqual(account.Links.Transactions.Href, "/accounts/GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7/transactions{?cursor,limit,order}");
        }
Exemple #4
0
        public void TestDeserializeSetOptionsOperation()
        {
            var json     = File.ReadAllText(Path.Combine("responses", "testdata", "operationSetOptions.json"));
            var instance = JsonSingleton.GetInstance <OperationResponse>(json);

            //There is a JsonConverter called OperationDeserializer that instantiates the type based on the json type_i element...
            Assert.IsTrue(instance is SetOptionsOperationResponse);
            var operation = (SetOptionsOperationResponse)instance;

            Assert.AreEqual(operation.SignerKey.AccountId, "GD3ZYXVC7C3ECD5I4E5NGPBFJJSULJ6HJI2FBHGKYFV34DSIWB4YEKJZ");
            Assert.AreEqual(operation.SignerWeight, 1);
            Assert.AreEqual(operation.HomeDomain, "stellar.org");
            Assert.AreEqual(operation.InflationDestination.AccountId, "GBYWSY4NPLLPTP22QYANGTT7PEHND64P4D4B6LFEUHGUZRVYJK2H4TBE");
            Assert.AreEqual(operation.LowThreshold, 1);
            Assert.AreEqual(operation.MedThreshold, 2);
            Assert.AreEqual(operation.HighThreshold, 3);
            Assert.AreEqual(operation.MasterKeyWeight, 4);
            Assert.AreEqual(operation.SetFlags[0], "auth_required_flag");
            Assert.AreEqual(operation.ClearFlags[0], "auth_revocable_flag");
        }
Exemple #5
0
        public void TestDeserializeTradeEffect()
        {
            var json     = File.ReadAllText(Path.Combine("responses", "testdata", "effectTrade.json"));
            var instance = JsonSingleton.GetInstance <EffectResponse>(json);

            //There is a JsonConverter called OperationDeserializer that instantiates the type based on the json type_i element...
            Assert.IsTrue(instance is TradeEffectResponse);
            var effect = (TradeEffectResponse)instance;

            Assert.AreEqual(effect.Account.AccountId, "GA6U5X6WOPNKKDKQULBR7IDHDBAQKOWPHYEC7WSXHZBFEYFD3XVZAKOO");
            Assert.AreEqual(effect.Seller.AccountId, "GCVHDLN6EHZBYW2M3BQIY32C23E4GPIRZZDBNF2Q73DAZ5VJDRGSMYRB");
            Assert.AreEqual(effect.OfferId, 1);
            Assert.AreEqual(effect.SoldAmount, "1000.0");
            Assert.AreEqual(effect.SoldAsset, Asset.CreateNonNativeAsset("EUR", KeyPair.FromAccountId("GCWVFBJ24754I5GXG4JOEB72GJCL3MKWC7VAEYWKGQHPVH3ENPNBSKWS")));
            Assert.AreEqual(effect.BoughtAmount, "60.0");
            Assert.AreEqual(effect.BoughtAsset, Asset.CreateNonNativeAsset("TESTTEST", KeyPair.FromAccountId("GAHXPUDP3AK6F2QQM4FIRBGPNGKLRDDSTQCVKEXXKKRHJZUUQ23D5BU7")));

            Assert.AreEqual(effect.Links.Operation.Href, "http://horizon-testnet.stellar.org/operations/33788507721730");
            Assert.AreEqual(effect.Links.Succeeds.Href, "http://horizon-testnet.stellar.org/effects?order=desc&cursor=33788507721730-2");
            Assert.AreEqual(effect.Links.Precedes.Href, "http://horizon-testnet.stellar.org/effects?order=asc&cursor=33788507721730-2");
        }
        public async Task <SubmitTransactionResponse> SubmitTransaction(string transactionEnvelopeBase64)
        {
            var transactionUri = new UriBuilder(_serverUri).SetPath("/transactions").Uri;

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

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

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

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

            return(null);
        }
        public void TestDeserialize()
        {
            var json   = File.ReadAllText(Path.Combine("responses", "testdata", "ledger.json"));
            var ledger = JsonSingleton.GetInstance <LedgerResponse>(json);

            Assert.AreEqual(ledger.Hash, "686bb246db89b099cd3963a4633eb5e4315d89dfd3c00594c80b41a483847bfa");
            Assert.AreEqual(ledger.PagingToken, "3860428274794496");
            Assert.AreEqual(ledger.PrevHash, "50c8695eb32171a19858413e397cc50b504ceacc819010bdf8ff873aff7858d7");
            Assert.AreEqual(ledger.Sequence, 898826);
            Assert.AreEqual(ledger.TransactionCount, 1);
            Assert.AreEqual(ledger.OperationCount, 2);
            Assert.AreEqual(ledger.ClosedAt, "2015-11-19T21:35:59Z");
            Assert.AreEqual(ledger.TotalCoins, "101343867604.8975480");
            Assert.AreEqual(ledger.FeePool, "1908.2248818");
            Assert.AreEqual(ledger.BaseFee, 100);
            Assert.AreEqual(ledger.BaseReserve, "10.0000000");
            Assert.AreEqual(ledger.MaxTxSetSize, 50);
            Assert.AreEqual(ledger.Links.Effects.Href, "/ledgers/898826/effects{?cursor,limit,order}");
            Assert.AreEqual(ledger.Links.Operations.Href, "/ledgers/898826/operations{?cursor,limit,order}");
            Assert.AreEqual(ledger.Links.Self.Href, "/ledgers/898826");
            Assert.AreEqual(ledger.Links.Transactions.Href, "/ledgers/898826/transactions{?cursor,limit,order}");
        }
        ///<Summary>
        /// Allows to stream SSE events from horizon.
        /// Certain endpoints in Horizon can be called in streaming mode using Server-Sent Events.
        /// This mode will keep the connection to horizon open and horizon will continue to return
        /// responses as ledgers close.
        /// <a href="http://www.w3.org/TR/eventsource/" target="_blank">Server-Sent Events</a>
        /// <a href="https://www.stellar.org/developers/horizon/learn/responses.html" target="_blank">Response Format documentation</a>
        /// </Summary>
        /// <param name="listener">EventListener implementation with EffectResponse type</param>
        /// <returns>EventSource object, so you can <code>close()</code> connection when not needed anymore</param>
        public IEventSource Stream(EventHandler <TResponse> listener)
        {
            if (EventSource == null)
            {
                EventSource = new SSEEventSource(BuildUri());
            }

            EventSource.Message += (sender, e) =>
            {
                var responseObject = JsonSingleton.GetInstance <TResponse>(e.Data) ?? throw new NotSupportedException("Unknown response type");

                if (responseObject is IPagingToken page)
                {
                    Cursor(page.PagingToken);
                    EventSource.Url = BuildUri();
                }

                listener?.Invoke(this, responseObject);
            };

            return(EventSource);
        }
        public void TestDeserialize()
        {
            var json      = File.ReadAllText(Path.Combine("responses", "testdata", "orderBook.json"));
            var orderBook = JsonSingleton.GetInstance <OrderBookResponse>(json);

            Assert.AreEqual(orderBook.OrderBookBase, new AssetTypeNative());
            Assert.AreEqual(orderBook.Counter, Asset.CreateNonNativeAsset("DEMO", KeyPair.FromAccountId("GBAMBOOZDWZPVV52RCLJQYMQNXOBLOXWNQAY2IF2FREV2WL46DBCH3BE")));

            Assert.AreEqual(orderBook.Bids[0].Amount, "31.4007644");
            Assert.AreEqual(orderBook.Bids[0].Price, "0.0024224");
            Assert.AreEqual(orderBook.Bids[0].PriceR.Numerator, 4638606);
            Assert.AreEqual(orderBook.Bids[0].PriceR.Denominator, 1914900241);

            Assert.AreEqual(orderBook.Bids[1].Amount, "5.9303650");
            Assert.AreEqual(orderBook.Bids[1].Price, "0.0024221");

            Assert.AreEqual(orderBook.Asks[0].Amount, "541.4550766");
            Assert.AreEqual(orderBook.Asks[0].Price, "0.0025093");

            Assert.AreEqual(orderBook.Asks[1].Amount, "121.9999600");
            Assert.AreEqual(orderBook.Asks[1].Price, "0.0025093");
        }
        public void TestDeserializeFeeBump()
        {
            var json        = File.ReadAllText(Path.Combine("testdata", "transactionFeeBump.json"));
            var transaction = JsonSingleton.GetInstance <TransactionResponse>(json);

            var transaction2 = new TransactionResponse(transaction.Hash, transaction.Ledger, transaction.CreatedAt, transaction.SourceAccount, transaction.FeeAccount,
                                                       transaction.Successful, transaction.PagingToken, transaction.SourceAccountSequence, transaction.MaxFee, 123L, transaction.OperationCount,
                                                       transaction.EnvelopeXdr, transaction.ResultXdr, transaction.ResultMetaXdr, transaction.Memo, transaction.Signatures, transaction.FeeBumpTx,
                                                       transaction.InnerTx, transaction.Links);


            Assert.AreEqual(transaction.Hash, transaction2.Hash);
            Assert.AreEqual(transaction.Ledger, transaction2.Ledger);
            Assert.AreEqual(transaction.Successful, transaction.Successful);
            Assert.AreEqual(transaction.SourceAccount, transaction2.SourceAccount);
            Assert.AreEqual(transaction.FeeAccount, transaction2.FeeAccount);
            Assert.AreEqual(transaction.SourceAccountSequence, transaction2.SourceAccountSequence);
            Assert.AreEqual(transaction.MaxFee, transaction2.MaxFee);
            Assert.AreEqual(transaction.FeeCharged, transaction2.FeeCharged);
            Assert.AreEqual(transaction.OperationCount, transaction2.OperationCount);
            CollectionAssert.AreEqual(transaction.Signatures, new List <string>()
            {
                "Hh4e"
            });

            TransactionResponse.FeeBumpTransaction feeBumpTransaction = transaction.FeeBumpTx;
            Assert.AreEqual(feeBumpTransaction.Hash, "3dfef7d7226995b504f2827cc63d45ad41e9687bb0a8abcf08ba755fedca0352");
            CollectionAssert.AreEqual(feeBumpTransaction.Signatures, new List <string>()
            {
                "Hh4e"
            });

            TransactionResponse.InnerTransaction innerTransaction = transaction.InnerTx;
            Assert.AreEqual(innerTransaction.Hash, "e98869bba8bce08c10b78406202127f3888c25454cd37b02600862452751f526");
            Assert.AreEqual(innerTransaction.MaxFee, 99L);
            CollectionAssert.AreEqual(innerTransaction.Signatures, new List <string> {
                "FBQU"
            });
        }
Exemple #11
0
        public void TestDeserializeCreateAccountOperation()
        {
            var json     = File.ReadAllText(Path.Combine("responses", "testdata", "operationCreateAccount.json"));
            var instance = JsonSingleton.GetInstance <OperationResponse>(json);

            //There is a JsonConverter called OperationDeserializer that instantiates the type based on the json type_i element...
            Assert.IsTrue(instance is CreateAccountOperationResponse);
            var operation = (CreateAccountOperationResponse)instance;

            Assert.AreEqual(operation.SourceAccount.AccountId, "GD6WU64OEP5C4LRBH6NK3MHYIA2ADN6K6II6EXPNVUR3ERBXT4AN4ACD");
            Assert.AreEqual(operation.PagingToken, "3936840037961729");
            Assert.AreEqual(operation.Id, 3936840037961729L);

            Assert.AreEqual(operation.Account.AccountId, "GAR4DDXYNSN2CORG3XQFLAPWYKTUMLZYHYWV4Y2YJJ4JO6ZJFXMJD7PT");
            Assert.AreEqual(operation.StartingBalance, "299454.904954");
            Assert.AreEqual(operation.Funder.AccountId, "GD6WU64OEP5C4LRBH6NK3MHYIA2ADN6K6II6EXPNVUR3ERBXT4AN4ACD");

            Assert.AreEqual(operation.Links.Effects.Href, "/operations/3936840037961729/effects{?cursor,limit,order}");
            Assert.AreEqual(operation.Links.Precedes.Href, "/operations?cursor=3936840037961729&order=asc");
            Assert.AreEqual(operation.Links.Self.Href, "/operations/3936840037961729");
            Assert.AreEqual(operation.Links.Succeeds.Href, "/operations?cursor=3936840037961729&order=desc");
            Assert.AreEqual(operation.Links.Transaction.Href, "/transactions/75608563ae63757ffc0650d84d1d13c0f3cd4970a294a2a6b43e3f454e0f9e6d");
        }
Exemple #12
0
        /// <summary>
        /// Submit a transaction to the network.
        ///
        /// This method will check if any of the destination accounts require a memo.  Change the SkipMemoRequiredCheck
        /// options to change this behaviour.
        /// </summary>
        /// <param name="transactionEnvelopeBase64"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <SubmitTransactionResponse> SubmitTransaction(string transactionEnvelopeBase64, SubmitTransactionOptions options)
        {
            if (!options.SkipMemoRequiredCheck)
            {
                TransactionBase tx;

                if (options.FeeBumpTransaction)
                {
                    tx = FeeBumpTransaction.FromEnvelopeXdr(transactionEnvelopeBase64);
                }
                else
                {
                    tx = Transaction.FromEnvelopeXdr(transactionEnvelopeBase64);
                }

                await CheckMemoRequired(tx);
            }

            var transactionUri = new UriBuilder(_serverUri).SetPath("/transactions").Uri;

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

            var response = await _httpClient.PostAsync(transactionUri, new FormUrlEncodedContent(paramsPairs.ToArray()));

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

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

            return(null);
        }
        public async Task TestStream()
        {
            var json = File.ReadAllText(Path.Combine("testdata", "ledger.json"))
                       .Replace(Environment.NewLine, "");
            var fakeHandler = new FakeHttpMessageHandler();
            var stream      = $"event: open\ndata: hello\n\nid: 1234\ndata: {json}\n\n";

            fakeHandler.QueueResponse(FakeResponse.StartsStream(StreamAction.Write(stream)));

            var eventSource = new SSEEventSource(new Uri("http://test.com"),
                                                 builder => builder.MessageHandler(fakeHandler));

            LedgerResponse dataReceived = null;

            eventSource.Message += (sender, args) =>
            {
                dataReceived = JsonSingleton.GetInstance <LedgerResponse>(args.Data);
                eventSource.Shutdown();
            };

            await eventSource.Connect();

            LedgerDeserializeTest.AssertTestData(dataReceived);
        }
Exemple #14
0
        public void TestDeserialize()
        {
            var json       = File.ReadAllText(Path.Combine("responses", "testdata", "tradesPage.json"));
            var tradesPage = JsonSingleton.GetInstance <Page <TradeResponse> >(json);

            Assert.AreEqual(tradesPage.Links.Next.Href, "https://horizon.stellar.org/trades?base_asset_type=native&counter_asset_code=SLT&counter_asset_issuer=GCKA6K5PCQ6PNF5RQBF7PQDJWRHO6UOGFMRLK3DYHDOI244V47XKQ4GP&counter_asset_type=credit_alphanum4&cursor=68836785177763841-0&limit=2&order=desc");
            Assert.AreEqual(tradesPage.Links.Prev.Href, "https://horizon.stellar.org/trades?base_asset_type=native&counter_asset_code=SLT&counter_asset_issuer=GCKA6K5PCQ6PNF5RQBF7PQDJWRHO6UOGFMRLK3DYHDOI244V47XKQ4GP&counter_asset_type=credit_alphanum4&cursor=68836918321750017-0&limit=2&order=asc");
            Assert.AreEqual(tradesPage.Links.Self.Href, "https://horizon.stellar.org/trades?base_asset_type=native&counter_asset_code=SLT&counter_asset_issuer=GCKA6K5PCQ6PNF5RQBF7PQDJWRHO6UOGFMRLK3DYHDOI244V47XKQ4GP&counter_asset_type=credit_alphanum4&cursor=&limit=2&order=desc");

            Assert.AreEqual(tradesPage.Records[0].Id, "68836918321750017-0");
            Assert.AreEqual(tradesPage.Records[0].PagingToken, "68836918321750017-0");

            Assert.AreEqual(tradesPage.Records[0].LedgerCloseTime, "2018-02-02T00:20:10Z");
            Assert.AreEqual(tradesPage.Records[0].OfferId, "695254");
            Assert.AreEqual(tradesPage.Records[0].BaseAccount.AccountId, "GBZXCJIUEPDXGHMS64UBJHUVKV6ETWYOVHADLTBXJNJFUC7A7RU5B3GN");
            Assert.AreEqual(tradesPage.Records[0].BaseAmount, "0.1217566");
            Assert.AreEqual(tradesPage.Records[0].BaseAssetType, "native");
            Assert.AreEqual(tradesPage.Records[0].CounterAccount.AccountId, "GBHKUQDYXGK5IEYORI7DZMMXANOIEHHOF364LNT4Q7EWPUL7FOO2SP6D");
            Assert.AreEqual(tradesPage.Records[0].CounterAmount, "0.0199601");
            Assert.AreEqual(tradesPage.Records[0].CounterAssetType, "credit_alphanum4");
            Assert.AreEqual(tradesPage.Records[0].CounterAssetCode, "SLT");
            Assert.AreEqual(tradesPage.Records[0].CounterAssetIssuer, "GCKA6K5PCQ6PNF5RQBF7PQDJWRHO6UOGFMRLK3DYHDOI244V47XKQ4GP");
            Assert.AreEqual(tradesPage.Records[0].BaseIsSeller, true);
        }
Exemple #15
0
        private void ShowOperationResponse(EventSourceMessageEventArgs op)
        {
            if (op.Event == "open")
            {
                return;
            }
            var or = JsonSingleton.GetInstance <OperationResponse>(op.Message);

            SavePagingToken(or.PagingToken);

            if (or.GetType() != typeof(PaymentOperationResponse))
            {
                return;
            }
            var payment = (PaymentOperationResponse)or;

            if (payment.From.AccountId == _keyPair.AccountId)
            {
                return;
            }

            AppSettings.Logger.Information(
                $@"Transaction received: Id: {or.Id}, Source: {or.SourceAccount.AccountId}, Type: {or.Type}");

            // Need to make sure the payment was at least $10 worth of XRP
            // If it isn't enough, refund the money minus a small transaction fee.
            var paymentAmount = decimal.Parse(payment.Amount);

            if (GetMinimumLumensRequired() > paymentAmount)
            {
                AppSettings.Logger.Information(
                    $"Received underfunded pament of {paymentAmount} lumens from {payment.From.AccountId}! Refunding...");

                SendPayment(
                    payment.From.AccountId,
                    (paymentAmount - 0.0000200m).ToString("0.0000000"),
                    "Err: http://bit.ly/2FW9r0m");

                return;
            }

            AppSettings.Logger.Information("Connecting to the database to get the availale pool...");
            var poolId = _poolRepository.GetAvailablePoolByPayer(payment.From.AccountId);

            if (poolId == 0)
            {
                poolId = _poolRepository.Add(new Pool
                {
                    CreateDate = DateTime.Now
                });

                AppSettings.Logger.Information($"Created new Pool {poolId}.");
            }

            var celebId = _poolRepository.GetAvailablePoolCelebrity(poolId);

            var ticketId = _ticketRepository.Add(new Ticket
            {
                PlayerAddress = payment.From.AccountId,
                CelebrityId   = celebId,
                PoolId        = poolId
            });

            AppSettings.Logger.Information(
                "Created a new Ticket: \n " +
                $"Ticket ID: {ticketId} \n " +
                $"Player Address: {payment.From.AccountId} \n" +
                $"Celebrity ID: {celebId} \n" +
                $"Pool ID: {poolId}");

            SendPayment(
                or.SourceAccount.AccountId,
                "0.0000001",
                $"Raffle Ticket Id: {ticketId}");
        }
Exemple #16
0
        public async Task BalanceService_UpdateWallets_SkipErrorMemo()
        {
            // Arrange

            Mock <IBlockchainAssetsService> blockchainAssetsService = new Mock <IBlockchainAssetsService>();
            Mock <IHorizonService>          horizonService          = new Mock <IHorizonService>();
            Mock <IKeyValueStoreRepository> keyValueStoreRepository = new Mock <IKeyValueStoreRepository>();
            Mock <IObservationRepository <BalanceObservation> > observationRepository =
                new Mock <IObservationRepository <BalanceObservation> >();
            Mock <IWalletBalanceRepository> walletBalanceRepository = new Mock <IWalletBalanceRepository>();
            string depositBaseAddress = "CX...";
            string memo = "http://stellar-win.me/";

            string[]           explorerUrlFormats = new [] { "" };
            Mock <ILog>        l1  = new Mock <ILog>();
            Mock <ILogFactory> log = new Mock <ILogFactory>();

            log.Setup(x => x.CreateLog(It.IsAny <object>())).Returns(l1.Object);

            horizonService.Setup(x => x.GetMemo(It.IsAny <TransactionResponse>())).Returns(memo);
            walletBalanceRepository
            .Setup(x => x.RecordOperationAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>(), It.IsAny <long>()))
            .Returns((string a, string b, long c, long d, string e, long f) => Task.CompletedTask)
            .Verifiable();
            walletBalanceRepository
            .Setup(x => x.RefreshBalance(It.IsAny <IEnumerable <(string, string)> >()))
            .Returns((IEnumerable <(string, string)> a) => Task.CompletedTask)
            .Verifiable();

            horizonService.Setup(x => x.GetTransactions(depositBaseAddress,
                                                        OrderDirection.ASC,
                                                        null,
                                                        It.IsAny <int>()))
            .ReturnsAsync(new EditableList <TransactionResponse>()
            {
                new TransactionResponse("hash", 1, DateTime.UtcNow.ToString(), "", true, "", 1, 1000, 1,
                                        "AAAAAAdlB/ts6RCzHAoU/FjtFBGyu66ibVPVoQuJh9CPgAueAAABk" +
                                        "AClxo0AAAABAAAAAAAAAAEAAAAcc3RlbGwwNV81Yjk5MmUwZDAzOW" +
                                        "I5NS4wMjQzNwAAAAQAAAABAAAAAIJL979+ksErfRfiXWlzB+rQZdH" +
                                        "2j4pZdur2OwL02RfxAAAAAQAAAAAr5Jq3XoimudpnjzcQbriV22rX" +
                                        "httVbubwIx31oPeU1AAAAAFGWU9VAAAAAHC5SBVcvtgAfFcLHrI8q" +
                                        "ouvob0F0uxHhlP9otowVtJvAAAAAAAIi4AAAAABAAAAAIJL979+ks" +
                                        "ErfRfiXWlzB+rQZdH2j4pZdur2OwL02RfxAAAAAQAAAABHY0WsIeN" +
                                        "z8/GVG6ienwp48nk2H0ec8UagsCoFsnd+0wAAAAFGWU9VAAAAAHC5" +
                                        "SBVcvtgAfFcLHrI8qouvob0F0uxHhlP9otowVtJvAAAAAAAAnEAAA" +
                                        "AABAAAAAIJL979+ksErfRfiXWlzB+rQZdH2j4pZdur2OwL02RfxAA" +
                                        "AAAQAAAAAW1fr/5UFFVCSXQSIaRg+Bhgg6pYuTcsIiB0a+PA7cNAA" +
                                        "AAAFGWU9VAAAAAHC5SBVcvtgAfFcLHrI8qouvob0F0uxHhlP9otow" +
                                        "VtJvAAAAAAAB1MAAAAABAAAAAIJL979+ksErfRfiXWlzB+rQZdH2j" +
                                        "4pZdur2OwL02RfxAAAAAQAAAAAW1fr/5UFFVCSXQSIaRg+Bhgg6pYu" +
                                        "TcsIiB0a+PA7cNAAAAAFGWU9VAAAAAHC5SBVcvtgAfFcLHrI8qouvo" +
                                        "b0F0uxHhlP9otowVtJvAAAAAAABOIAAAAAAAAAAAvTZF/EAAABAX/d" +
                                        "mfgcuMq0sTlNhvq4RIFtSNRe+RdNsmantkMWKqcfWjTWNO8YSW26ct" +
                                        "Kens8g9EIiD0RJZUr8oGBAoILCrBY+AC54AAABAEoGfpIrRlugsk0" +
                                        "F5Br3Q7tInzScxEDgoYOKIKoBy3f3nWemHz6puW48rjPlFMs+ovx7X" +
                                        "w" +
                                        "hZnOS27iloMkVzeDA==",
                                        "", "", Memo.Text(memo), null)
            });

            horizonService.Setup(x => x.GetTransactionOperations(It.IsAny <string>()))
            .ReturnsAsync(new List <OperationResponse>
            {
                JsonSingleton.GetInstance <PaymentOperationResponse>("{\"id\": \"5375855945584641\",\n  \"paging_token\": \"5375855945584641\",\n  \"source_account\": \"GD5BZDV2RPSIEXFA5G6L3GECLKEBQ4C3ZZYT57XM5IWW7NJGXI7NIBPQ\",\n  \"type\": \"payment\",\n  \"type_i\": 1,\n  \"created_at\": \"2018-12-18T07:35:38Z\",\n  \"transaction_hash\": \"97da6620df28655cfb42f25e988f5727c3f54fbd09df35f0fa56f88c7ef9572c\",\n  \"asset_type\": \"native\",\n  \"from\": \"GD5BZDV2RPSIEXFA5G6L3GECLKEBQ4C3ZZYT57XM5IWW7NJGXI7NIBPQ\",\n  \"to\": \"GD5BZDV2RPSIEXFA5G6L3GECLKEBQ4C3ZZYT57XM5IWW7NJGXI7NIBPQ\",\n  \"amount\": \"9.9990000\"}")
            });

            blockchainAssetsService.Setup(x => x.GetNativeAsset())
            .Returns(new Asset("XLM", "", "Stellar Lumen", "native", 7));

            BalanceService balanceService = new BalanceService(horizonService.Object,
                                                               keyValueStoreRepository.Object,
                                                               observationRepository.Object,
                                                               walletBalanceRepository.Object,
                                                               depositBaseAddress,
                                                               explorerUrlFormats,
                                                               log.Object,
                                                               blockchainAssetsService.Object);

            // Act

            await balanceService.UpdateWalletBalances();

            // Assert

            walletBalanceRepository.Verify(
                x => x.RecordOperationAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>(), It.IsAny <long>()),
                Times.Never
                );

            walletBalanceRepository.Verify(
                x => x.RefreshBalance(It.Is <IEnumerable <(string, string)> >(v => v.Count() == 0)),
                Times.Exactly(1)
                );
        }
        public void TestUnknownEffect()
        {
            var json = File.ReadAllText(Path.Combine("testdata", "effectUnknown.json"));

            Assert.ThrowsException <JsonSerializationException>(() => JsonSingleton.GetInstance <EffectResponse>(json));
        }