Beispiel #1
0
        public async Task <AmountAndPrice> GetConvertedAmountAndPriceAsync(string fromAssetId, string toAssetId, double fromAmount)
        {
            if (string.IsNullOrEmpty(fromAssetId))
            {
                throw new ArgumentNullException(nameof(fromAssetId));
            }

            if (string.IsNullOrEmpty(toAssetId))
            {
                throw new ArgumentNullException(nameof(toAssetId));
            }

            if (fromAssetId == toAssetId)
            {
                return(new AmountAndPrice(fromAmount, 1, 1));
            }

            var toAsset = await _assetsDict.GetItemAsync(toAssetId);

            var assetPair = (await _assetPairsDict.Values()).PairWithAssets(fromAssetId, toAssetId);

            var feedData = await _bestPriceRepository.GetAsync(assetPair.Id);

            var price         = (assetPair.BaseAssetId == fromAssetId ? feedData.Ask : 1 / feedData.Ask).TruncateDecimalPlaces(assetPair.Accuracy);
            var invertedPrice = (assetPair.BaseAssetId == fromAssetId ? 1 / feedData.Ask : feedData.Ask).TruncateDecimalPlaces(assetPair.InvertedAccuracy);

            return(new AmountAndPrice((price * fromAmount).TruncateDecimalPlaces(toAsset.Accuracy), price, invertedPrice));
        }
Beispiel #2
0
        public async Task <IEnumerable <ApiAssetPairRateModel> > GetRate()
        {
            var assetPairsIds = (await _assetPairDictionary.Values()).Where(x => !x.IsDisabled).Select(x => x.Id);

            var marketProfile = await _marketProfileService.GetMarketProfileAsync();

            marketProfile.Profile = marketProfile.Profile.Where(x => assetPairsIds.Contains(x.Asset));
            return(marketProfile.ToApiModel());
        }
        public async Task <AssetPair> GetAssetPairAsync(string baseAssetId, string quotingAssetId)
        {
            if (string.IsNullOrEmpty(baseAssetId) || string.IsNullOrEmpty(quotingAssetId))
            {
                return(null);
            }

            var cachedValues = await _assetPairsCache.Values();

            return(cachedValues.FirstOrDefault(x => x.BaseAssetId == baseAssetId && x.QuotingAssetId == quotingAssetId));
        }
        public async Task <IEnumerable <IOrderBook> > GetAllAsync()
        {
            var assetPairs = await _assetPairsDict.Values();

            var orderBooks = new List <IOrderBook>();

            foreach (var pair in assetPairs)
            {
                var buyBookJson  = _distributedCache.GetStringAsync(_settings.CacheSettings.GetOrderBookKey(pair.Id, true));
                var sellBookJson = _distributedCache.GetStringAsync(_settings.CacheSettings.GetOrderBookKey(pair.Id, false));

                var buyBook = (await buyBookJson)?.DeserializeJson <OrderBook>();
                if (buyBook != null)
                {
                    orderBooks.Add(buyBook);
                }

                var sellBook = (await sellBookJson)?.DeserializeJson <OrderBook>();
                if (sellBook != null)
                {
                    orderBooks.Add(sellBook);
                }
            }

            return(orderBooks);
        }
Beispiel #5
0
        public async Task TransferAllAssetsToAddress(string clientId, string srcAddress, string srcPrivateKey, string destAddress)
        {
            var transactionId = Guid.NewGuid().ToString("N");
            var transfer      =
                await
                _transferEventsRepository.RegisterAsync(TransferEvent.CreateNewTransferAll(clientId, transactionId, srcAddress));

            var contextData = TransferContextData.Create(new TransferContextData.TransferModel
            {
                ClientId    = clientId,
                OperationId = transfer.Id
            });

            await _bitCoinTransactionsRepository.CreateAsync(transactionId, null, contextData);

            if (_baseSettings.UsePushPrivateKeyService)
            {
                await _srvBlockchainHelper.PushPrivateKey(srcPrivateKey);

                srcPrivateKey = null;
            }

            var  assets = (await _assetsDict.Values()).ToArray();
            bool needToTransferAssets = (await _srvBlockchainReader.GetBalancesForAdress(srcAddress, assets)).Any(x => x.Balance > 0);

            if (needToTransferAssets)
            {
                var queueMsg = await _bitCoinCommandProducer.TransferAllAssetsToAddress(transactionId, srcAddress, srcPrivateKey, destAddress);

                await _bitCoinTransactionsRepository.UpdateRequestAsync(transactionId, queueMsg);
            }
        }
Beispiel #6
0
        public async Task <IActionResult> GetCandles([FromQuery] CandleSticksRequestModel request)
        {
            try
            {
                var assetPair = (await _assetPairs.Values()).FirstOrDefault(x => x.Id == request.AssetPairId);

                if (assetPair == null)
                {
                    return(NotFound("Asset pair not found"));
                }

                var candleHistoryService = _candlesServiceProvider.Get(request.Type);

                var candles = await candleHistoryService.GetCandlesHistoryAsync(
                    request.AssetPairId,
                    request.PriceType,
                    request.TimeInterval,
                    request.FromMoment,
                    request.ToMoment);

                var baseAsset = await _assetsService.AssetGetAsync(assetPair.BaseAssetId);

                var quotingAsset = await _assetsService.AssetGetAsync(assetPair.QuotingAssetId);

                return(Ok(
                           candles.ToResponseModel(
                               baseAsset.DisplayAccuracy ?? baseAsset.Accuracy,
                               quotingAsset.DisplayAccuracy ?? quotingAsset.Accuracy)));
            }
            catch (ErrorResponseException ex)
            {
                var errors = ex.Error.ErrorMessages.Values.SelectMany(s => s.Select(ss => ss));
                return(NotFound($"{string.Join(',', errors)}"));
            }
        }
        public async Task <AssetPair> TryGetAssetPairAsync(string assetId1, string assetId2)
        {
            if (string.IsNullOrEmpty(assetId1) ||
                string.IsNullOrEmpty(assetId2))
            {
                return(null);
            }

            var cachedValues = await _assetPairsCache.Values();

            return(cachedValues
                   .FirstOrDefault(
                       x =>
                       x.BaseAssetId == assetId1 && x.QuotingAssetId == assetId2 ||
                       x.BaseAssetId == assetId2 && x.QuotingAssetId == assetId1));
        }
        public async Task <IAssetPair[]> GetAssetsPairsForClient(string clientId, bool isIosDevice)
        {
            var assetsForClient = await GetAssetsForClient(clientId, isIosDevice);

            var baseAsset = await GetBaseAssetForClient(clientId, isIosDevice);

            return
                ((await _assetPairsDict.Values()).WhichHaveAssets(baseAsset.Id)
                 .WhichConsistsOfAssets(assetsForClient.Select(x => x.Id).ToArray()).ToArray());
        }
        public async Task <Asset> GetAssetByIdAsync(string assetId)
        {
            if (string.IsNullOrEmpty(assetId))
            {
                return(null);
            }

            var cachedValues = await _assetsCache.Values();

            return(cachedValues.FirstOrDefault(x => x.Id == assetId));
        }
        public async Task <IAsset[]> GetAssetsForClient(string clientId, bool isIosDevice)
        {
            var result = (await _assetsDict.Values()).Where(x => !x.IsDisabled);

            var assetIdsForClient = await _assetGroupRepository.GetAssetIdsForClient(clientId, isIosDevice);

            if (assetIdsForClient != null)
            {
                return(result.Where(x => assetIdsForClient.Contains(x.Id)).ToArray());
            }

            return(result.ToArray());
        }
        public async Task <AssetPair[]> GetAssetsPairsForClient(string clientId, bool isIosDevice, string partnerId, bool ignoreBase = false)
        {
            var assetsForClient = await GetAssetsForClient(clientId, isIosDevice, partnerId);

            var result = (await _assetPairsDictionary.Values()).Where(x => !x.IsDisabled);

            if (!ignoreBase)
            {
                result = result.WhichHaveAssets((await GetBaseAssetForClient(clientId, isIosDevice, partnerId)).Id);
            }

            return(result.WhichConsistsOfAssets(assetsForClient.Select(x => x.Id).ToArray()).ToArray());
        }
        public async Task <double> GetCapitalization(string market)
        {
            double rate = 1;

            if (market != LykkeConstants.LykkeAssetId)
            {
                var assetPairs = await _assetPairsDict.Values();

                var pair = assetPairs.PairWithAssets(LykkeConstants.LykkeAssetId, market);

                if (pair == null)
                {
                    return(0);
                }

                rate = await _srvRatesHelper.GetRate(market, pair);
            }

            CacheRecord record;
            var         asset = await _assetsDict.GetItemAsync(market);

            var cacheKey = GetMarketCapitalizationCacheKey();

            if (!_memCache.TryGetValue(cacheKey, out record))
            {
                double amount = 0;

                await _walletsRepository.GetWalletsByChunkAsync(pairs =>
                {
                    var c =
                        pairs.Select(x => x.Value?.FirstOrDefault(y => y.AssetId == LykkeConstants.LykkeAssetId))
                        .Sum(x => x?.Balance ?? 0);
                    amount += c;
                    return(Task.CompletedTask);
                });

                record = record ?? new CacheRecord();

                record.AssetId = LykkeConstants.LykkeAssetId;
                record.Dt      = DateTime.UtcNow;
                record.Amount  = amount;

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetAbsoluteExpiration(_cacheExpTime);

                _memCache.Set(cacheKey, record, cacheEntryOptions);
            }

            return((record.Amount * rate).TruncateDecimalPlaces(asset.Accuracy));
        }
        public async Task <Asset[]> GetAssetsForClient(string clientId, bool isIosDevice, string partnerId = null)
        {
            var result = await _cachedAssetsDictionary.Values();

            result = result.Where(x => !x.IsDisabled);

            if (partnerId != null)
            {
                return(result.Where(x => x.PartnerIds != null && x.PartnerIds.Contains(partnerId)).ToArray());
            }

            var assetIdsForClient = await _assetsService.ClientGetAssetIdsAsync(clientId, isIosDevice);

            if (assetIdsForClient.Any())
            {
                result = result.Where(x => assetIdsForClient.Contains(x.Id));
            }

            return(result.Where(x => !x.NotLykkeAsset).ToArray());
        }
Beispiel #14
0
        public async Task <IEnumerable <ApiMarketData> > Get()
        {
            var marketProfile = await _marketProfileRepo.GetAsync();

            var result =
                (await _marketDataRepository.Get24HMarketsAsync()).ToApiModel(marketProfile)
                .ToList();

            var assetPairs = (await _assetPairsDictionary.Values()).Where(x => !x.IsDisabled);

            var emptyRecords =
                assetPairs.Where(
                    x => result.All(y => y.AssetPair != x.Id) && marketProfile.Profile.Any(z => z.Asset == x.Id));

            result.AddRange(emptyRecords.Select(x => new MarketData
            {
                AssetPairId = x.Id,
                Dt          = DateTime.UtcNow
            }.ToApiModel(marketProfile.Profile.First(y => y.Asset == x.Id))));

            return(result);
        }
        public async Task <IActionResult> Get()
        {
            var assetPairs = (await _assetPairs.Values()).Where(s => !s.IsDisabled);

            return(Ok(Models.AssetPairsModels.AssetPairResponseModel.Create(assetPairs.Select(itm => itm.ConvertToApiModel()).ToArray())));
        }
Beispiel #16
0
        public async Task <IEnumerable <ApiAsset> > GetDictionary()
        {
            var assets = (await _assetsDict.Values()).Where(x => !x.IsDisabled);

            return(assets.ToApiModel());
        }
Beispiel #17
0
        public Task <CreateTransactionResponse> GetTransferAllTransaction(BitcoinAddress @from, BitcoinAddress to, Guid transactionId)
        {
            return(Retry.Try(async() =>
            {
                var context = _transactionBuildContextFactory.Create(_connectionParams.Network);

                var channels = await _offchainService.GetCurrentChannels(from.ToString());

                var assets = await _assetRepository.Values();

                return await context.Build(async() =>
                {
                    var builder = new TransactionBuilder();
                    var uncoloredCoins = (await _bitcoinOutputsService.GetUncoloredUnspentOutputs(from.ToString())).ToList();
                    var coloredCoins = (await _bitcoinOutputsService.GetColoredUnspentOutputs(from.ToString())).ToList();

                    if (uncoloredCoins.Count == 0 && coloredCoins.Count == 0)
                    {
                        throw new BackendException("Address has no unspent outputs", ErrorCode.NoCoinsFound);
                    }

                    async Task <IDestination> GetChangeWallet(string asset)
                    {
                        var assetSetting = await _offchainService.GetAssetSetting(asset);
                        return OpenAssetsHelper.ParseAddress(!string.IsNullOrEmpty(assetSetting.ChangeWallet) ? assetSetting.ChangeWallet
                            : assetSetting.HotWallet);
                    };

                    if (uncoloredCoins.Count > 0)
                    {
                        var hubAmount = Money.Zero;
                        IDestination hubAmountAddress = null;
                        var channel = channels.FirstOrDefault(o => o.Asset == "BTC");
                        if (channel != null)
                        {
                            hubAmount = Money.FromUnit(channel.HubAmount, MoneyUnit.BTC);
                            hubAmountAddress = await GetChangeWallet("BTC");
                        }

                        builder.AddCoins(uncoloredCoins);
                        context.AddCoins(uncoloredCoins);
                        builder.Send(to, uncoloredCoins.Sum(o => o.TxOut.Value) - hubAmount);
                        if (hubAmount > 0)
                        {
                            builder.Send(hubAmountAddress, hubAmount);
                        }
                    }
                    foreach (var assetGroup in coloredCoins.GroupBy(o => o.AssetId))
                    {
                        var asset = assets.First(o => o.BlockChainAssetId == assetGroup.Key.GetWif(_connectionParams.Network).ToString());

                        var channel = channels.FirstOrDefault(o => o.Asset == asset.Id);

                        var sum = new AssetMoney(assetGroup.Key);
                        foreach (var coloredCoin in assetGroup)
                        {
                            sum += coloredCoin.Amount;
                        }

                        var hubAmount = new AssetMoney(assetGroup.Key);
                        IDestination hubAmountAddress = null;
                        if (channel != null)
                        {
                            hubAmount = new AssetMoney(assetGroup.Key, channel.HubAmount, asset.MultiplierPower);
                            hubAmountAddress = await GetChangeWallet(asset.Id);
                        }
                        builder.AddCoins(assetGroup.ToList());
                        context.AddCoins(assetGroup.ToList());
                        builder.SendAsset(to, sum - hubAmount);
                        if (hubAmount.Quantity > 0)
                        {
                            builder.SendAsset(hubAmountAddress, hubAmount);
                        }
                    }
                    await _transactionBuildHelper.AddFee(builder, context);

                    var buildedTransaction = builder.BuildTransaction(true);

                    await _spentOutputService.SaveSpentOutputs(transactionId, buildedTransaction);

                    await SaveNewOutputs(transactionId, buildedTransaction, context);

                    foreach (var offchainChannel in channels)
                    {
                        await _offchainService.RemoveChannel(offchainChannel);
                    }

                    return new CreateTransactionResponse(buildedTransaction.ToHex(), transactionId);
                });
            }, exception => (exception as BackendException)?.Code == ErrorCode.TransactionConcurrentInputsProblem, 3, _log));
        }
 public async Task <IAssetDefinition> GetAssetDefinitionByDefUrlAsync(string url)
 {
     return((await _assetDefinitionCachedDictionary.Values()).FirstOrDefault(p => p.AssetDefinitionUrl == url));
 }
Beispiel #19
0
        private async Task GenerateIssueAllowedCoins()
        {
            foreach (var asset in await _assetRepostory.Values())
            {
                if (OpenAssetsHelper.IsBitcoin(asset.Id) || OpenAssetsHelper.IsLkk(asset.Id) || !asset.IssueAllowed)
                {
                    continue;
                }

                try
                {
                    var setting = await GetAssetSetting(asset.Id);

                    if (setting.HotWallet != setting.ChangeWallet)
                    {
                        continue;
                    }

                    var hotWallet = OpenAssetsHelper.ParseAddress(setting.HotWallet);
                    var assetId   = new BitcoinAssetId(asset.BlockChainAssetId).AssetId;

                    var coins = await _bitcoinOutputsService.GetColoredUnspentOutputs(setting.HotWallet, assetId);

                    var outputSize = new AssetMoney(assetId, setting.OutputSize, asset.MultiplierPower);

                    await _logger.WriteInfoAsync("GenerateOffchainOutputsFunction", "GenerateIssueAllowedCoins", "AssetId " + asset.Id, "Start process");

                    var existingCoinsCount = coins.Count(o => o.Amount <= outputSize && o.Amount * 2 > outputSize);

                    if (existingCoinsCount > setting.MinOutputsCount)
                    {
                        continue;
                    }

                    var generateCnt = setting.MaxOutputsCount - existingCoinsCount;
                    var generated   = 0;
                    while (generated < generateCnt)
                    {
                        var outputsCount = Math.Min(setting.MaxOutputsCountInTx, generateCnt - generated);

                        var context = _transactionBuildContextFactory.Create(_connectionParams.Network);

                        await context.Build(async() =>
                        {
                            var builder = new TransactionBuilder();
                            var queue   = _pregeneratedOutputsQueueFactory.Create(asset.BlockChainAssetId);
                            var coin    = await queue.DequeueCoin();

                            try
                            {
                                var issueCoin = new IssuanceCoin(coin)
                                {
                                    DefinitionUrl = new Uri(asset.DefinitionUrl)
                                };

                                builder.AddCoins(issueCoin);

                                for (var i = 0; i < outputsCount; i++)
                                {
                                    builder.IssueAsset(hotWallet, outputSize);
                                }
                                context.IssueAsset(assetId);
                                await _transactionBuildHelper.AddFee(builder, context);

                                var tr = builder.BuildTransaction(true);

                                await SignAndBroadcastTransaction(tr, context);

                                return("");
                            }
                            catch (Exception)
                            {
                                await queue.EnqueueOutputs(coin);

                                throw;
                            }
                        });

                        generated += outputsCount;
                    }
                }
                catch (Exception ex)
                {
                    await _logger.WriteWarningAsync("GenerateOffchainOutputsFunction", "GenerateIssueAllowedCoins", "AssetId " + asset.Id, ex);
                }
                finally
                {
                    await _logger.WriteInfoAsync("GenerateOffchainOutputsFunction", "GenerateIssueAllowedCoins", "AssetId " + asset.Id, "End process");
                }
            }
        }
 public Task <IEnumerable <ABI> > GetAsync()
 {
     return(_fetchCache.Values());
 }
 public Task <IEnumerable <AssetPair> > GetAllAssetPairsAsync()
 {
     return(_assetPairsCache.Values());
 }