Beispiel #1
0
        public async Task <AssetPairRate> Get(string assetPairId)
        {
            var response = await _marketProfileService.ApiMarketProfileByPairCodeGetAsync(assetPairId);

            if (response is ErrorModel error)
            {
                throw new ApiRequestException(error.Message, error.Code?.ToString());
            }

            if (response is AssetPairModel assetPairRate)
            {
                IReadOnlyDictionary <string, AssetPair> assetPairs = await _assetPairsCache.GetDictionaryAsync();

                var assetPair = assetPairs.ContainsKey(assetPairId) ? assetPairs[assetPairId] : null;

                if (assetPair == null)
                {
                    throw new Exception($"Asset pair {assetPairId} doesn't exist");
                }

                return(new AssetPairRate
                {
                    AssetPairId = assetPair.Id,
                    Ask = (decimal)assetPairRate.AskPrice,
                    Bid = (decimal)assetPairRate.BidPrice,
                    Accuracy = assetPair.Accuracy
                });
            }

            throw new Exception("Unknown MarketProfile API response");
        }
Beispiel #2
0
        /// <summary>
        /// Request money transfer referral link - reserved for version 2
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[HttpPost("giftCoinLinks")] - for v2
        //[SwaggerOperation("RequestGiftCoinsReferralLink")]
        //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.BadRequest)]
        //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.NotFound)]
        //[ProducesResponseType(typeof(RequestRefLinkResponse), (int)HttpStatusCode.Created)]
        private async Task <IActionResult> RequestGiftCoinsReferralLink([FromBody] GiftCoinsReferralLinkRequest request)
        {
            if (request == null)
            {
                return(await LogAndReturnBadRequest("", ControllerContext, Phrases.InvalidRequest));
            }

            if (request.Amount <= 0)
            {
                return(await LogAndReturnBadRequest(request, ControllerContext, Phrases.InvalidAmount));
            }

            if (String.IsNullOrEmpty(request.SenderClientId))
            {
                return(await LogAndReturnBadRequest(request, ControllerContext, Phrases.InvalidSenderClientId));
            }

            var asset = (await _assets.GetDictionaryAsync()).Values.FirstOrDefault(v => v.Id == request.Asset);

            if (String.IsNullOrEmpty(request.Asset) || asset == null)
            {
                return(await LogAndReturnBadRequest(request, ControllerContext, Phrases.InvalidAsset));
            }

            var clientBalances = await _balancesClient.GetClientBalances(request.SenderClientId);

            if (clientBalances == null)
            {
                return(await LogAndReturnNotFound(request, ControllerContext, $"Cant get clientBalance of asset {asset.Name} for client id {request.SenderClientId}."));
            }

            var balance = clientBalances.FirstOrDefault(x => x.AssetId == asset.Id)?.Balance;

            if (!balance.HasValue || balance.Value < request.Amount)
            {
                return(await LogAndReturnBadRequest(request, ControllerContext, Phrases.InvalidTreesAmount));
            }

            var referralLink = await _referralLinksService.CreateGiftCoinsLink(request);

            await LogInfo(request, ControllerContext, referralLink.ToJson());

            return(Created(uri: $"api/referralLinks/{referralLink.Id}", value: new RequestRefLinkResponse {
                RefLinkId = referralLink.Id, RefLinkUrl = referralLink.Url
            }));
        }
Beispiel #3
0
        /// <summary>
        /// Create offchain transfer to Lykke wallet
        /// </summary>
        /// <returns></returns>
        //[HttpPost("transferToLykkeWallet")] --reserved for version 2
        //[SwaggerOperation("TransferToLykkeWallet")]
        //[ProducesResponseType(typeof(OffchainTradeRespModel), (int)HttpStatusCode.OK)]
        //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.BadRequest)]
        //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.NotFound)]
        private async Task <IActionResult> TransferToLykkeWallet([FromBody] TransferToLykkeWallet model)
        {
            var clientId = model.ClientId;
            var refLink  = await _referralLinksService.GetReferralLinkById(model.ReferralLinkId);

            if (refLink == null)
            {
                return(await LogAndReturnBadRequest(model, ControllerContext, "Ref link Id not found ot missing"));
            }

            var asset = (await _assets.GetDictionaryAsync()).Values.FirstOrDefault(v => v.Id == refLink.Asset);

            if (asset == null)
            {
                return(await LogAndReturnBadRequest(model, ControllerContext, $"Specified asset id {refLink.Asset} in reflink id {refLink.Id} not found "));
            }

            await CheckOffchain(clientId);

            if (await _srvKycForAsset.IsKycNeeded(clientId, asset.Id))
            {
                return(await LogAndReturnBadRequest(model, ControllerContext, $"KYC needed for sender client id {model.ClientId} before sending asset {refLink.Asset}"));
            }

            try
            {
                var response = await _offchainService.CreateDirectTransfer(clientId, asset.Id, (decimal)refLink.Amount, model.PrevTempPrivateKey);

                var exchangeOpResult = await _exchangeOperationsService.StartTransferAsync(
                    response.TransferId,
                    _settings.ReferralLinksService.LykkeReferralClientId, //send to shared lykke wallet where coins will be temporary stored until claimed by the recipient
                    clientId,
                    TransferType.Common.ToString()
                    );

                await LogInfo(new
                {
                    Method = "StartTransferAsync",
                    response.TransferId,
                    SourceClientId = clientId
                }, ControllerContext, exchangeOpResult.ToJson());

                return(Ok(new OffchainTradeRespModel
                {
                    TransferId = response.TransferId,
                    TransactionHex = response.TransactionHex,
                    OperationResult = response.OperationResult
                }));
            }
            catch (OffchainException ex)
            {
                return(await LogOffchainExceptionAndReturn(model, ControllerContext, ex));
            }
            catch (Exception ex)
            {
                return(await LogAndReturnNotFound(model, ControllerContext, ex.Message));
            }
        }
        private async Task <IReadOnlyDictionary <string, AssetPair> > GetAssetPairs()
        {
            if (_assetPairValues == null)
            {
                _assetPairValues = await _assetPairs.GetDictionaryAsync();
            }

            return(_assetPairValues);
        }
Beispiel #5
0
        public async Task <IEnumerable <ConversionResult> > GetMarketAmountInBase(IEnumerable <AssetWithAmount> from,
                                                                                  string assetIdTo, OrderAction orderAction)
        {
            var limitOrdersTask   = _activeLimitOrdersRepository.GetAsync();
            var assetsDictTask    = _assetsDict.GetDictionaryAsync();
            var assetPairsTask    = _assetPairsDict.Values();
            var marketProfileTask = _bestPriceRepository.GetAsync();

            var limitOrders   = await limitOrdersTask;
            var assetsDict    = await assetsDictTask;
            var assetPairs    = await assetPairsTask;
            var marketProfile = await marketProfileTask;

            return(@from.Select(item => GetMarketAmountInBase(orderAction, limitOrders, item, assetIdTo, assetsDict, assetPairs, marketProfile)));
        }
Beispiel #6
0
        public async Task <ExchangeOperationResult> TransferRewardCoins(IReferralLink refLink, bool isNewClient, string recipientClientId, string executionContext)
        {
            var request = new { RefLinkId = refLink.Id, RefLinkUrl = refLink.Url, RecipientClientId = recipientClientId, IsNewClient = isNewClient };

            try
            {
                var asset = (await _assets.GetDictionaryAsync()).Values.FirstOrDefault(v => v.Id == refLink.Asset);
                if (asset == null)
                {
                    var message = $"Asset with symbol id {refLink.Asset} not found";
                    await _log.WriteErrorAsync(executionContext, nameof(TransferRewardCoins), (new { Error = message }).ToJson(), new Exception(message));

                    return(new ExchangeOperationResult {
                        Message = message
                    });
                }

                var result = await _exchangeOperationsService.TransferAsync(
                    recipientClientId,
                    _settings.ReferralLinksService.LykkeReferralClientId,
                    refLink.Amount,
                    asset.Id,
                    TransferType.Common.ToString()
                    );

                if (!result.IsOk())
                {
                    string error;
                    if (result.Code.HasValue && Enum.IsDefined(typeof(MeStatusCodes), result.Code.Value))
                    {
                        error = $"Error: {((MeStatusCodes)result.Code.Value).ToString()}, Message: {result.Message}, TransactionId: {result.TransactionId}";
                    }
                    else
                    {
                        error = $"Error: {result.Code}, Message: {result.Message}, TransactionId: {result.TransactionId}";
                    }
                    await _log.WriteErrorAsync(executionContext, nameof(TransferRewardCoins), error, new Exception(error));

                    result.Message = error;
                    return(result);
                }
                await _log.WriteInfoAsync(executionContext, request.ToJson(), $"Transfer successfull: {result.ToJson()}");

                return(result);
            }
            catch (OffchainException ex)
            {
                await _log.WriteErrorAsync(executionContext, request.ToJson(), ex);

                throw new Exception($"ExchangeOperationsService error: Code={ex.OffchainExceptionCode}.OffchainException={ex.OffchainExceptionMessage}.Message={ex.Message}.{ex.InnerException?.Message}");
            }
            catch (ApplicationException ex)
            {
                await _log.WriteErrorAsync(executionContext, request.ToJson(), ex);

                throw new Exception($"ExchangeOperationsService error: {ex.Message}{ex.InnerException?.Message}");
            }
            catch (Exception ex)
            {
                await _log.WriteErrorAsync(executionContext, request.ToJson(), ex);

                throw new Exception($"ExchangeOperationsService error: {ex.Message}{ex.InnerException?.Message}");
            }
        }
 public async Task <IDictionary <string, IAssetScore> > GetAssetScoreDictionaryAsync()
 {
     return(await _assetScoreDictionary.GetDictionaryAsync());
 }
 public async Task <IDictionary <string, IAssetCoinholdersIndex> > GetAssetCoinholdersIndexAsync()
 {
     return(await _assetCoinholdersIndexesDictionary.GetDictionaryAsync());
 }
 public async Task <IReadOnlyDictionary <string, IAssetDefinition> > GetAssetDefinitionDictionaryAsync()
 {
     return(new ReadOnlyDictionary <string, IAssetDefinition>(await _assetDefinitionCachedDictionary.GetDictionaryAsync()));
 }