Esempio n. 1
0
            public async Task <Result <GetHistoryResponse> > GetHistory(GetHistoryRequest request)
            {
                const string api    = "api/Document/GetHistory";
                var          result = await _owner.PostAsync <GetHistoryRequest, GetHistoryResponse>(api, request);

                return(result);
            }
Esempio n. 2
0
        // messages.getHistory#92a1df2f peer:InputPeer offset:int max_id:int limit:int = messages.Messages;
        public async Task <MessagesMessages> GetHistory(InputPeer inputPeer, int offset, int limit, int maxId = -1)
        {
            var request = new GetHistoryRequest(inputPeer, offset, maxId, limit);

            await SendRpcRequest(request);

            return(request.messages);
        }
Esempio n. 3
0
        public async Task <List <Message> > GetMessagesHistoryForContact(int user_id, int offset, int limit, int max_id = -1)
        {
            var request = new GetHistoryRequest(new InputPeerContactConstructor(user_id), offset, max_id, limit);
            await _sender.Send(request);

            await _sender.Recieve(request);

            return(request.messages);
        }
Esempio n. 4
0
        public async Task <ActionResult <IList <EntranceHistoryModel> > > GetHistoryAsync(
            int officeId,
            int doorId,
            [FromQuery] GetHistoryRequest request)
        {
            var door = await GetAndEnsureDoorAsync(officeId, doorId);

            var logs = await _entranceLogRepository.GetLastForDoorAsync(door.Id, request.Count);

            var history = _mapper.Map <List <EntranceHistoryModel> >(logs);

            return(Ok(history));
        }
Esempio n. 5
0
        public Task <GetHistoryResult> GetHistory(GetHistoryRequest body)
        {
            return(Task.Run(() =>
            {
                var request = FilterRequestForWPS(Request);
                if (!request.Status)
                {
                    return new GetHistoryResult {
                        code = request.code, msg = request.msg
                    };
                }
                // 从数据库查询用户、文件信息等......

                // 创建时间和修改时间默认全是现在
                var now = TimestampHelper.GetCurrentTimestamp();

                // 不需要使用历史版本功能的此处也请返回,如果此接口不通时,文档加载会报错:“GetFileInfoFailed”
                var result = new GetHistoryResult
                {
                    histories = new List <HistroyModel>
                    {
                        new HistroyModel
                        {
                            id = request.FileId,
                            name = "文件名",
                            size = 1024, // 单位B
                            version = 1,
                            download_url = "文件下载链接",
                            create_time = now,
                            modify_time = now,
                            creator = new UserModel
                            {
                                id = "创建者ID",
                                name = "创建者名",
                                avatar_url = "创建者头像url"
                            },
                            modifier = new UserModel
                            {
                                id = "修改者ID",
                                name = "修改者名",
                                avatar_url = "修改者头像url"
                            }
                        }
                    }
                };
                return result;
            }));
        }
        public GetHistoryResponse GetHistory(GetHistoryRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Must have the documentId you'd like to add annotations to.
            // If you only have the document cache URI, DocumentFactory.LoadFromUri needs to be called.
            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentNullException("documentId");
            }

            IList <DocumentHistoryItem> items = null;

            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                // Ensure we have the document.
                DocumentHelper.CheckLoadFromCache(document);

                DocumentHistory history = document.History;
                items = history.GetItems();

                if (items != null && request.ClearHistory)
                {
                    history.Clear();
                    document.SaveToCache();
                }
            }

            if (_loggingDocumentHistory)
            {
                ShowHistory(request.DocumentId, items);
            }

            DocumentHistoryItem[] itemsArray = new DocumentHistoryItem[items.Count];
            items.CopyTo(itemsArray, 0);
            GetHistoryResponse response = new GetHistoryResponse
            {
                Items = itemsArray
            };

            return(response);
        }
Esempio n. 7
0
        public async Task <List <Release> > GetHistory(string name, int max, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            GetHistoryRequest request = new GetHistoryRequest()
            {
                Max  = max,
                Name = name
            };

            var response = await this.client.GetHistoryAsync(request, this.GetDefaultHeaders(), cancellationToken : cancellationToken);

            return(response.Releases.ToList());
        }
Esempio n. 8
0
        /// <summary>
        /// Возвращает коллекцию сообщений по указанным параметрам.
        /// </summary>
        /// <param name="offset">Смещение для выборки определенного множества.</param>
        /// <param name="count">Количество элементов для выборки.</param>
        /// <param name="startMessageID"></param>
        private async Task <List <VKMessage> > GetMessagesWithParameters(int offset, uint count, long startMessageID = 0, bool rev = false)
        {
            var request = new GetHistoryRequest
            {
                Offset         = offset,
                Count          = count,
                StartMessageID = startMessageID,
                Reverse        = rev ? VKBoolean.True : VKBoolean.False
            };

            if (IsChat)
            {
                request.ChatID = ChatID;
            }
            else
            {
                request.UserID = UserID;
            }

            List <VKMessage> result = null;

            var response = await request.ExecuteAsync();

            if (response.Error.ErrorType == VKErrors.None)
            {
                Skipped    = response.Response.Skipped;
                Unread     = response.Response.Unread;
                totalCount = response.Response.Count;

                if (response.Response.Items.Count == 0)
                {
                    return(new List <VKMessage>());
                }

                try { await UsersService.SetUsers(response.Response.Items); }
                catch (Exception) { return(null); }

                result = response.Response.Items;
            }

            return(result);
        }
        public void GetHistoryWithValidModelWithoutTransactionSpendingDetailsReturnsWalletHistoryModel()
        {
            ulong gasPrice             = SmartContractMempoolValidator.MinGasPrice;
            int   vmVersion            = 1;
            var   gasLimit             = (Stratis.SmartContracts.RuntimeObserver.Gas)(SmartContractFormatLogic.GasLimitMaximum / 2);
            var   contractTxData       = new ContractTxData(vmVersion, gasPrice, gasLimit, new byte[] { 0, 1, 2, 3 });
            var   callDataSerializer   = new CallDataSerializer(new ContractPrimitiveSerializer(new SmartContractsRegTest()));
            var   contractCreateScript = new Script(callDataSerializer.Serialize(contractTxData));

            string          walletName        = "myWallet";
            HdAddress       address           = WalletTestsHelpers.CreateAddress();
            TransactionData normalTransaction = WalletTestsHelpers.CreateTransaction(new uint256(1), new Money(500000), 1);
            TransactionData createTransaction = WalletTestsHelpers.CreateTransaction(new uint256(1), new Money(500000), 1);

            createTransaction.SpendingDetails = new SpendingDetails
            {
                BlockHeight   = 100,
                CreationTime  = DateTimeOffset.Now,
                TransactionId = uint256.One,
                Payments      = new List <PaymentDetails>
                {
                    new PaymentDetails
                    {
                        Amount = new Money(100000),
                        DestinationScriptPubKey = contractCreateScript
                    }
                }
            };

            address.Transactions.Add(normalTransaction);
            address.Transactions.Add(createTransaction);

            var addresses = new List <HdAddress> {
                address
            };

            Features.Wallet.Wallet wallet = WalletTestsHelpers.CreateWallet(walletName);
            var account = new HdAccount {
                ExternalAddresses = addresses
            };

            wallet.AccountsRoot.Add(new AccountRoot()
            {
                Accounts = new List <HdAccount> {
                    account
                }
            });

            List <FlatHistory> flat = addresses.SelectMany(s => s.Transactions.Select(t => new FlatHistory {
                Address = s, Transaction = t
            })).ToList();

            var accountsHistory = new List <AccountHistory> {
                new AccountHistory {
                    History = flat, Account = account
                }
            };

            this.walletManager.Setup(w => w.GetHistory(walletName, It.IsAny <string>())).Returns(accountsHistory);
            this.walletManager.Setup(w => w.GetWalletByName(walletName)).Returns(wallet);
            this.walletManager.Setup(w => w.GetAccounts(walletName)).Returns(new List <HdAccount> {
                account
            });

            var receipt = new Receipt(null, 12345, new Log[0], null, null, null, uint160.Zero, true, null, null, 2, 100000);

            this.receiptRepository.Setup(x => x.RetrieveMany(It.IsAny <IList <uint256> >()))
            .Returns(new List <Receipt> {
                receipt
            });
            this.callDataSerializer.Setup(x => x.Deserialize(It.IsAny <byte[]>()))
            .Returns(Result.Ok(new ContractTxData(0, 0, (Stratis.SmartContracts.RuntimeObserver.Gas) 0, new uint160(0), null, null)));

            var controller = new SmartContractWalletController(
                this.broadcasterManager.Object,
                this.callDataSerializer.Object,
                this.connectionManager.Object,
                this.loggerFactory.Object,
                this.network,
                this.receiptRepository.Object,
                this.walletManager.Object,
                this.smartContractTransactionService.Object);

            var request = new GetHistoryRequest
            {
                Address    = address.Address,
                WalletName = walletName
            };

            IActionResult result = controller.GetHistory(request);

            JsonResult viewResult = Assert.IsType <JsonResult>(result);
            var        model      = viewResult.Value as IEnumerable <ContractTransactionItem>;

            Assert.NotNull(model);
            Assert.Single(model);

            ContractTransactionItem resultingTransaction = model.ElementAt(0);

            ContractTransactionItem resultingCreate = model.ElementAt(0);

            Assert.Equal(ContractTransactionItemType.ContractCreate, resultingTransaction.Type);
            Assert.Equal(createTransaction.SpendingDetails.TransactionId, resultingTransaction.Hash);
            Assert.Equal(createTransaction.SpendingDetails.Payments.First().Amount.ToUnit(MoneyUnit.Satoshi), resultingTransaction.Amount);
            Assert.Equal(uint160.Zero.ToBase58Address(this.network), resultingTransaction.To);
            Assert.Equal(createTransaction.SpendingDetails.BlockHeight, resultingTransaction.BlockHeight);
            Assert.Equal((createTransaction.Amount - createTransaction.SpendingDetails.Payments.First().Amount).ToUnit(MoneyUnit.Satoshi), resultingTransaction.TransactionFee);
            Assert.Equal(receipt.GasPrice * receipt.GasUsed, resultingTransaction.GasFee);
        }
        public void GetHistoryWithValidModelWithSkipAndTakeReturnsWalletHistoryModel()
        {
            ulong gasPrice             = SmartContractMempoolValidator.MinGasPrice;
            int   vmVersion            = 1;
            var   gasLimit             = (Stratis.SmartContracts.RuntimeObserver.Gas)(SmartContractFormatLogic.GasLimitMaximum / 2);
            var   contractTxData       = new ContractTxData(vmVersion, gasPrice, gasLimit, new byte[] { 0, 1, 2, 3 });
            var   callDataSerializer   = new CallDataSerializer(new ContractPrimitiveSerializer(new SmartContractsRegTest()));
            var   contractCreateScript = new Script(callDataSerializer.Serialize(contractTxData));

            string    walletName = "myWallet";
            HdAddress address    = WalletTestsHelpers.CreateAddress();

            const int totalHistoryLength = 100;
            const int toSkip             = 10;
            const int toTake             = 10;

            for (int i = 0; i < totalHistoryLength; i++)
            {
                TransactionData createTransaction = WalletTestsHelpers.CreateTransaction(new uint256((ulong)i), new Money(500000), 100 + i);
                createTransaction.SpendingDetails = new SpendingDetails
                {
                    BlockHeight   = 100 + i,
                    CreationTime  = DateTimeOffset.Now,
                    TransactionId = new uint256((ulong)i),
                    Payments      = new List <PaymentDetails>
                    {
                        new PaymentDetails
                        {
                            Amount = new Money(100000),
                            DestinationScriptPubKey = contractCreateScript
                        }
                    }
                };

                address.Transactions.Add(createTransaction);
            }

            var addresses = new List <HdAddress> {
                address
            };

            Features.Wallet.Wallet wallet = WalletTestsHelpers.CreateWallet(walletName);
            var account = new HdAccount {
                ExternalAddresses = addresses
            };

            wallet.AccountsRoot.Add(new AccountRoot()
            {
                Accounts = new List <HdAccount> {
                    account
                }
            });

            List <FlatHistory> flat = addresses.SelectMany(s => s.Transactions.Select(t => new FlatHistory {
                Address = s, Transaction = t
            })).ToList();

            var accountsHistory = new List <AccountHistory> {
                new AccountHistory {
                    History = flat, Account = account
                }
            };

            this.walletManager.Setup(w => w.GetHistory(walletName, It.IsAny <string>())).Returns(accountsHistory);
            this.walletManager.Setup(w => w.GetWalletByName(walletName)).Returns(wallet);
            this.walletManager.Setup(w => w.GetAccounts(walletName)).Returns(new List <HdAccount> {
                account
            });

            var receipt     = new Receipt(null, 12345, new Log[0], null, null, null, uint160.Zero, true, null, null, 2, 100000);
            var receiptList = new List <Receipt>();

            for (int i = 0; i < totalHistoryLength; i++)
            {
                receiptList.Add(receipt);
            }

            this.receiptRepository.Setup(x => x.RetrieveMany(It.IsAny <IList <uint256> >()))
            .Returns(receiptList);
            this.callDataSerializer.Setup(x => x.Deserialize(It.IsAny <byte[]>()))
            .Returns(Result.Ok(new ContractTxData(0, 0, (Stratis.SmartContracts.RuntimeObserver.Gas) 0, new uint160(0), null, null)));

            var controller = new SmartContractWalletController(
                this.broadcasterManager.Object,
                this.callDataSerializer.Object,
                this.connectionManager.Object,
                this.loggerFactory.Object,
                this.network,
                this.receiptRepository.Object,
                this.walletManager.Object,
                this.smartContractTransactionService.Object);

            var request = new GetHistoryRequest
            {
                Address    = address.Address,
                WalletName = walletName,
                Skip       = toSkip,
                Take       = toTake
            };

            IActionResult result = controller.GetHistory(request);

            JsonResult viewResult = Assert.IsType <JsonResult>(result);
            var        model      = viewResult.Value as IEnumerable <ContractTransactionItem>;

            Assert.NotNull(model);
            Assert.Equal(toTake, model.Count());
            Assert.Equal(new uint256(toSkip), model.ElementAt(toTake - 1).Hash);
            Assert.Equal(new uint256(toSkip + toTake - 1), model.ElementAt(0).Hash);
        }
Esempio n. 11
0
        public IActionResult GetHistory(GetHistoryRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.WalletName))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided"));
            }

            if (string.IsNullOrWhiteSpace(request.Address))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided"));
            }

            try
            {
                var transactionItems = new List <ContractTransactionItem>();

                HdAccount account = this.walletManager.GetAccounts(request.WalletName).First();

                // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them.
                IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(request.WalletName, account.Name, null);

                // Wallet manager returns only 1 when an account name is specified.
                AccountHistory accountHistory = accountsHistory.First();

                List <FlatHistory> items = accountHistory.History.Where(x => x.Address.Address == request.Address).ToList();

                // Represents a sublist of transactions associated with receive addresses + a sublist of already spent transactions associated with change addresses.
                // In effect, we filter out 'change' transactions that are not spent, as we don't want to show these in the history.
                List <FlatHistory> history = items.Where(t => !t.Address.IsChangeAddress() || (t.Address.IsChangeAddress() && t.Transaction.IsSpent())).ToList();

                // TransactionData in history is confusingly named. A "TransactionData" actually represents an input, and the outputs that spend it are "SpendingDetails".
                // There can be multiple "TransactionData" which have the same "SpendingDetails".
                // For SCs we need to group spending details by their transaction ID, to get all the inputs related to the same outputs.
                // Each group represents 1 SC transaction.
                // Each item.Transaction in a group is an input.
                // Each item.Transaction.SpendingDetails in the group represent the outputs, and they should all be the same so we can pick any one.
                var scTransactions = history
                                     .Where(item => item.Transaction.SpendingDetails != null)
                                     .Where(item => item.Transaction.SpendingDetails.Payments.Any(x => x.DestinationScriptPubKey.IsSmartContractExec()))
                                     .GroupBy(item => item.Transaction.SpendingDetails.TransactionId)
                                     .Skip(request.Skip ?? 0)
                                     .Take(request.Take ?? history.Count)
                                     .Select(g => new
                {
                    TransactionId = g.Key,
                    InputAmount   = g.Sum(i => i.Transaction.Amount),                 // Sum the inputs to the SC transaction.
                    Outputs       = g.First().Transaction.SpendingDetails.Payments,   // Each item in the group will have the same outputs.
                    OutputAmount  = g.First().Transaction.SpendingDetails.Payments.Sum(o => o.Amount),
                    BlockHeight   = g.First().Transaction.SpendingDetails.BlockHeight // Each item in the group will have the same block height.
                })
                                     .ToList();

                // Get all receipts in one transaction
                IList <Receipt> receipts = this.receiptRepository.RetrieveMany(scTransactions.Select(x => x.TransactionId).ToList());

                for (int i = 0; i < scTransactions.Count; i++)
                {
                    var     scTransaction = scTransactions[i];
                    Receipt receipt       = receipts[i];

                    // Consensus rules state that each transaction can have only one smart contract exec output.
                    PaymentDetails scPayment = scTransaction.Outputs.First(x => x.DestinationScriptPubKey.IsSmartContractExec());

                    // This will always give us a value - the transaction has to be serializable to get past consensus.
                    Result <ContractTxData> txDataResult = this.callDataSerializer.Deserialize(scPayment.DestinationScriptPubKey.ToBytes());
                    ContractTxData          txData       = txDataResult.Value;

                    // If the receipt is not available yet, we don't know how much gas was consumed so use the full gas budget.
                    ulong gasFee = receipt != null
                        ? receipt.GasUsed * receipt.GasPrice
                        : txData.GasCostBudget;

                    long  totalFees      = scTransaction.InputAmount - scTransaction.OutputAmount;
                    Money transactionFee = Money.FromUnit(totalFees, MoneyUnit.Satoshi) - Money.FromUnit(txData.GasCostBudget, MoneyUnit.Satoshi);

                    var result = new ContractTransactionItem
                    {
                        Amount         = scPayment.Amount.ToUnit(MoneyUnit.Satoshi),
                        BlockHeight    = scTransaction.BlockHeight,
                        Hash           = scTransaction.TransactionId,
                        TransactionFee = transactionFee.ToUnit(MoneyUnit.Satoshi),
                        GasFee         = gasFee
                    };

                    if (scPayment.DestinationScriptPubKey.IsSmartContractCreate())
                    {
                        result.Type = ContractTransactionItemType.ContractCreate;
                        result.To   = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? string.Empty;
                    }
                    else if (scPayment.DestinationScriptPubKey.IsSmartContractCall())
                    {
                        result.Type = ContractTransactionItemType.ContractCall;
                        result.To   = txData.ContractAddress.ToBase58Address(this.network);
                    }

                    transactionItems.Add(result);
                }

                return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? Int32.MaxValue)));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
 /// <summary>
 /// 消息记录下载:get_history
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public async Task <GetHistoryResult> GetHistoryAsync(GetHistoryRequest request)
 {
     return(await RequestAsync <GetHistoryRequest, GetHistoryResult>(ServiceName, "get_history", request));
 }
        public JsonResult GetHistory(GetHistoryRequest body)
        {
            _log.WriteInfo("开始请求接口【file/history】");
            GetHistoryResult result = new GetHistoryResult();

            try
            {
                var request = GetFilterRequest.GetParams(HttpContext.ApplicationInstance.Request);
                if (!request.Status)
                {
                    result.code    = request.code;
                    result.message = request.message;
                    result.details = request.details;
                    result.hint    = request.hint;
                }
                else
                {
                    // 从数据库查询用户、文件信息等......

                    // 创建时间和修改时间默认全是现在
                    //var now = TimestampHelper.GetCurrentTimestamp();

                    var startNow = TimestampHelper.ConvertToTimeStamp(DateTime.Now.AddHours(-10));
                    // 不需要使用历史版本功能的此处也请返回,如果此接口不通时,文档加载会报错:“GetFileInfoFailed”
                    result.histories = new List <HistroyModel>
                    {
                        new HistroyModel
                        {
                            id           = "1001",
                            name         = "TestFile_v1.docx",
                            size         = FileHelper.FileSize(Server.MapPath("/Files/TestFile_v1.docx")), // 单位B
                            version      = 1,
                            download_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Files/TestFile_v1.docx",
                            create_time  = startNow,
                            modify_time  = startNow,
                            creator      = new UserModel
                            {
                                id         = "1001",
                                name       = "兆丰",
                                avatar_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Images/photo2.jpg"
                            },
                            modifier = new UserModel
                            {
                                id         = "1001",
                                name       = "兆丰",
                                avatar_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Images/photo2.jpg"
                            }
                        },
                        new HistroyModel
                        {
                            id           = "1002",
                            name         = "TestFile_v2.docx",
                            size         = FileHelper.FileSize(Server.MapPath("/Files/TestFile_v2.docx")), // 单位B
                            version      = 2,
                            download_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Files/TestFile_v2.docx",
                            create_time  = startNow,
                            modify_time  = startNow,
                            creator      = new UserModel
                            {
                                id         = "1002",
                                name       = "丫丫",
                                avatar_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Images/photo3.jpg"
                            },
                            modifier = new UserModel
                            {
                                id         = "1002",
                                name       = "丫丫",
                                avatar_url = $"{ConfigurationManager.AppSettings["WPSTokenUrl"]}/Images/photo3.jpg"
                            }
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                _log.WriteError("【系统异常】-【" + ex.Message + "】", ex);
                result.code    = (int)Enumerator.ErrorCode.ServerError;
                result.message = Enumerator.ErrorCode.ServerError.ToString();
                result.details = result.hint = EnumExtension.GetDescription(Enumerator.ErrorCode.ServerError);
            }

            _log.WriteInfo("请求接口【file/history】完成,返回数据:" + JsonConvert.SerializeObject(result));
            return(Json(result));
        }
Esempio n. 14
0
        public IActionResult GetHistory(GetHistoryRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.WalletName))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided"));
            }

            if (string.IsNullOrWhiteSpace(request.Address))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided"));
            }

            try
            {
                var transactionItems = new List <ContractTransactionItem>();

                HdAccount account = this.walletManager.GetAccounts(request.WalletName).First();

                // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them.
                IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(request.WalletName, account.Name, null, offset: request.Skip ?? 0, limit: request.Take ?? int.MaxValue, accountAddress: request.Address, forSmartContracts: true);

                // Wallet manager returns only 1 when an account name is specified.
                AccountHistory accountHistory = accountsHistory.First();

                var scTransactions = accountHistory.History.Select(h => new
                {
                    TransactionId      = uint256.Parse(h.Id),
                    Fee                = h.Fee,
                    SendToScriptPubKey = Script.FromHex(h.SendToScriptPubkey),
                    OutputAmount       = h.Amount,
                    BlockHeight        = h.BlockHeight
                }).ToList();

                // Get all receipts in one transaction
                IList <Receipt> receipts = this.receiptRepository.RetrieveMany(scTransactions.Select(x => x.TransactionId).ToList());

                for (int i = 0; i < scTransactions.Count; i++)
                {
                    var     scTransaction = scTransactions[i];
                    Receipt receipt       = receipts[i];

                    // This will always give us a value - the transaction has to be serializable to get past consensus.
                    Result <ContractTxData> txDataResult = this.callDataSerializer.Deserialize(scTransaction.SendToScriptPubKey.ToBytes());
                    ContractTxData          txData       = txDataResult.Value;

                    // If the receipt is not available yet, we don't know how much gas was consumed so use the full gas budget.
                    ulong gasFee = receipt != null
                        ? receipt.GasUsed * receipt.GasPrice
                        : txData.GasCostBudget;

                    long  totalFees      = scTransaction.Fee;
                    Money transactionFee = Money.FromUnit(totalFees, MoneyUnit.Satoshi) - Money.FromUnit(txData.GasCostBudget, MoneyUnit.Satoshi);

                    var result = new ContractTransactionItem
                    {
                        Amount         = new Money(scTransaction.OutputAmount).ToUnit(MoneyUnit.Satoshi),
                        BlockHeight    = scTransaction.BlockHeight,
                        Hash           = scTransaction.TransactionId,
                        TransactionFee = transactionFee.ToUnit(MoneyUnit.Satoshi),
                        GasFee         = gasFee
                    };

                    if (scTransaction.SendToScriptPubKey.IsSmartContractCreate())
                    {
                        result.Type = ContractTransactionItemType.ContractCreate;
                        result.To   = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? string.Empty;
                    }
                    else if (scTransaction.SendToScriptPubKey.IsSmartContractCall())
                    {
                        result.Type = ContractTransactionItemType.ContractCall;
                        result.To   = txData.ContractAddress.ToBase58Address(this.network);
                    }

                    transactionItems.Add(result);
                }

                return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? int.MaxValue)));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Esempio n. 15
0
 public virtual GetHistoryResult GetHistory(GetHistoryRequest request)
 {
     return(Request <GetHistoryResult>("open_msg_svc", "get_history", request));
 }
Esempio n. 16
0
 public Response <HistoryData> GetHistory <T>(GetHistoryRequest request) where T : DeletableEntity
 {
     return(ExecuteCustomQuery <GetHistoryQuery <T>, GetHistoryRequest, HistoryData>(request));
 }