diff --git a/packages/server/src/account/account.repository.ts b/packages/server/src/account/account.repository.ts index ba498e38..1dc4a81f 100644 --- a/packages/server/src/account/account.repository.ts +++ b/packages/server/src/account/account.repository.ts @@ -1,4 +1,4 @@ -import { DataSource, Repository } from 'typeorm'; +import { DataSource, Repository, QueryRunner } from 'typeorm'; import { Account } from './account.entity'; import { Injectable } from '@nestjs/common'; import { User } from 'src/auth/user.entity'; @@ -12,7 +12,7 @@ export class AccountRepository extends Repository { const account = new Account(); account.KRW = 300000000; account.USDT = 300000; - account.BTC = 10; + account.BTC = 0; account.user = adminUser; await this.save(account); console.log('admin 계정에 Account가 성공적으로 생성되었습니다.'); @@ -26,15 +26,27 @@ export class AccountRepository extends Repository { return account[moneyType]; } async updateAccountCurrency(typeGiven, accountBalance, accountId, queryRunner) { - try{ - const updateData = { - id: accountId, - [typeGiven]: accountBalance, - }; - - await queryRunner.manager.save(Account, updateData); - }catch(error){ - console.log(error) - } + try{ + await queryRunner.manager + .createQueryBuilder() + .update(Account) + .set({ + [typeGiven]: accountBalance, + }) + .where('id = :id', { id: accountId }) + .execute(); + }catch(error){ + console.log(error) + } + } + async updateAccountBTC(id, quantity, queryRunner){ + await queryRunner.manager + .createQueryBuilder() + .update(Account) + .set({ + BTC: quantity, + }) + .where('id = :id', { id: id }) + .execute(); } } diff --git a/packages/server/src/asset/asset.repository.ts b/packages/server/src/asset/asset.repository.ts index db320c69..57bb7678 100644 --- a/packages/server/src/asset/asset.repository.ts +++ b/packages/server/src/asset/asset.repository.ts @@ -52,7 +52,10 @@ export class AssetRepository extends Repository { await queryRunner.manager .createQueryBuilder() .update(Asset) - .set({ price: asset.price }) + .set({ + price: asset.price, + quantity: asset.quantity + }) .where('assetId = :assetId', { assetId: asset.assetId }) .execute(); } catch (e) { diff --git a/packages/server/src/auth/auth.service.ts b/packages/server/src/auth/auth.service.ts index c3e4415d..f638745c 100644 --- a/packages/server/src/auth/auth.service.ts +++ b/packages/server/src/auth/auth.service.ts @@ -88,15 +88,19 @@ export class AuthService { } async logout(userId: number): Promise<{ message: string }> { - const user = await this.userRepository.findOneBy({ id: userId }); + try{ + const user = await this.userRepository.findOneBy({ id: userId }); - if (!user) { - throw new Error('User not found'); - } + if (!user) { + throw new Error('User not found'); + } - if (user.isGuest) { - await this.userRepository.delete({ id: userId }); - return { message: 'Guest user data successfully deleted' }; + if (user.isGuest) { + await this.userRepository.delete({ id: userId }); + return { message: 'Guest user data successfully deleted' }; + } + }catch(error){ + console.error(error) } } diff --git a/packages/server/src/auth/constants.ts b/packages/server/src/auth/constants.ts index 11f765eb..06bd4fce 100644 --- a/packages/server/src/auth/constants.ts +++ b/packages/server/src/auth/constants.ts @@ -5,4 +5,4 @@ export const jwtConstants = { export const DEFAULT_KRW = 30000000; export const DEFAULT_USDT = 300000; -export const DEFAULT_BTC = 10; +export const DEFAULT_BTC = 0; diff --git a/packages/server/src/trade/trade-ask.service.ts b/packages/server/src/trade/trade-ask.service.ts index 199d7e09..7e4222dd 100644 --- a/packages/server/src/trade/trade-ask.service.ts +++ b/packages/server/src/trade/trade-ask.service.ts @@ -31,9 +31,12 @@ export class AskService implements OnModuleInit { } async calculatePercentBuy(user, moneyType: string, percent: number) { + const account = await this.accountRepository.findOne({ + where : {user: {id: user.userId}} + }) const asset = await this.assetRepository.findOne({ where:{ - account: {id: user.userId}, + account: {id: account.id}, assetName: moneyType } }) @@ -58,24 +61,10 @@ export class AskService implements OnModuleInit { code: 422, }); } - const userAsset = await this.checkCurrency(user, askDto, queryRunner); - userAsset.quantity -= askDto.receivedAmount - if(userAsset.quantity !==0){ - await this.assetRepository.updateAssetQuantity( - userAsset, - queryRunner, - ) - }else { - await this.assetRepository.delete({ - assetId: userAsset.assetId - }) - } + await this.tradeRepository.createTrade(askDto, user.userId,'sell', queryRunner); await queryRunner.commitTransaction(); - const temp = await this.assetRepository.findOne({ - where: {assetId: userAsset.assetId} - }) - console.log(temp.quantity) + return { code: 200, message: '거래가 정상적으로 등록되었습니다.', @@ -121,12 +110,16 @@ export class AskService implements OnModuleInit { userId, } = askDto; try { + const account = await this.accountRepository.findOne({ + where: { user : { id : userId } } + }) const userAsset = await this.assetRepository.findOne({ where: { - account: { id: userId }, + account: { id: account.id }, assetName: typeGiven }, }); + if(!userAsset) return; askDto.assetBalance = userAsset.quantity; askDto.asset = userAsset; const currentCoinOrderbook = @@ -138,6 +131,12 @@ export class AskService implements OnModuleInit { }); if (!tradeData) break; const result = await this.executeTrade(askDto, order, tradeData); + if(askDto.asset.quantity ===0){ + await this.assetRepository.delete({ + assetId: askDto.asset.assetId + }) + break; + } if (!result) break; } @@ -160,7 +159,9 @@ export class AskService implements OnModuleInit { userId, tradeId, asset, + typeGiven, assetBalance, + typeReceived, krw } = askDto; let result = false; @@ -168,7 +169,7 @@ export class AskService implements OnModuleInit { const buyData = { ...tradeData }; buyData.quantity = tradeData.quantity >= bid_size ? bid_size : tradeData.quantity; - buyData.price = bid_price; + buyData.price = bid_price * krw; await this.tradeHistoryRepository.createTradeHistory( userId, buyData, @@ -177,21 +178,36 @@ export class AskService implements OnModuleInit { if (assetBalance !== 0) { asset.price = - asset.price * asset.quantity - krw * buyData.quantity; + asset.price - buyData.price * buyData.quantity; + asset.quantity -= buyData.quantity; await this.assetRepository.updateAssetPrice(asset, queryRunner); + } + + const account = await this.accountRepository.findOne({ + where: { user : { id : userId } } + }) + if(typeGiven === "BTC"){ + const BTC_QUANTITY = account.BTC - buyData.quantity + await this.accountRepository.updateAccountBTC(account.id, BTC_QUANTITY, queryRunner) } + const change = account[typeReceived] + buyData.price * buyData.quantity + console.log("account : "+account[typeReceived]) + console.log("change : "+buyData.price*buyData.quantity) + console.log("result : "+change) + await this.accountRepository.updateAccountCurrency(typeReceived, change, account.id, queryRunner) + tradeData.quantity -= buyData.quantity; if (tradeData.quantity === 0) { await this.tradeRepository.deleteTrade(tradeId, queryRunner); - } else + } else{ await this.tradeRepository.updateTradeTransaction( tradeData, queryRunner, ); - + } await queryRunner.commitTransaction(); result = true; } catch (error) { @@ -233,6 +249,8 @@ export class AskService implements OnModuleInit { }); const availableTrades = await this.tradeRepository.searchSellTrade(coinPrice); availableTrades.forEach((trade) => { + const krw = coinLatestInfo.get(["KRW",trade.tradeCurrency].join("-")).trade_price; + const another = coinLatestInfo.get([trade.assetName,trade.tradeCurrency].join("-")).trade_price; const askDto = { userId: trade.user.id, typeGiven: trade.tradeCurrency, //건네주는 통화 @@ -240,7 +258,7 @@ export class AskService implements OnModuleInit { receivedPrice: trade.price, //건네받을 통화 가격 receivedAmount: trade.quantity, //건네 받을 통화 갯수 tradeId: trade.tradeId, - krw: coinLatestInfo.get(["KRW",trade.assetName].join("-")), + krw: another/krw }; this.askTradeService(askDto); }); diff --git a/packages/server/src/trade/trade-bid.service.ts b/packages/server/src/trade/trade-bid.service.ts index fb84ec61..37f531a9 100644 --- a/packages/server/src/trade/trade-bid.service.ts +++ b/packages/server/src/trade/trade-bid.service.ts @@ -89,11 +89,8 @@ export class BidService implements OnModuleInit { }); const accountBalance = userAccount[typeGiven]; const accountResult = accountBalance - givenAmount; - console.error(`accountResult : ${accountResult}`) + if (accountResult < 0){ - console.error(`매수 희망 금액 : ${givenAmount}`) - console.error(`계좌 잔액 : ${accountBalance}`) - console.error(`accountResult : ${accountResult}`) throw new UnprocessableEntityException({ message: '자산이 부족합니다.', code: 422, @@ -111,17 +108,17 @@ export class BidService implements OnModuleInit { userId, } = bidDto; try { - const account = await this.accountRepository.findOne({ - where: { - user: { id: userId }, - }, - }); - bidDto.accountBalance = account[typeGiven]; - bidDto.account = account; const currentCoinOrderbook = this.coinDataUpdaterService.getCoinOrderbookByBid(bidDto); for(const order of currentCoinOrderbook){ if (order.ask_price > receivedPrice) break; + const account = await this.accountRepository.findOne({ + where: { + user: { id: userId }, + }, + }); + bidDto.accountBalance = account[typeGiven]; + bidDto.account = account; const tradeData = await this.tradeRepository.findOne({ where: { tradeId: tradeId }, }); @@ -156,9 +153,9 @@ export class BidService implements OnModuleInit { let result = false; try { const buyData = {...tradeData}; - + buyData.quantity = buyData.quantity >= ask_size ? ask_size : buyData.quantity; - buyData.price = ask_price; + buyData.price = ask_price * krw; await this.tradeHistoryRepository.createTradeHistory( userId, @@ -167,34 +164,40 @@ export class BidService implements OnModuleInit { ); const asset = await this.assetRepository.findOne({ - where: { account: {id: account.accountId}, assetName: typeReceived }, + where: { account: {id: account.id}, assetName: typeReceived }, }); if (asset) { asset.price = - asset.price * asset.quantity + krw * buyData.quantity; + asset.price + buyData.price * buyData.quantity; asset.quantity += buyData.quantity; await this.assetRepository.updateAssetQuantityPrice(asset, queryRunner); } else { await this.assetRepository.createAsset( bidDto, - buyData.price, + buyData.price * buyData.quantity, buyData.quantity, queryRunner, ); } - + tradeData.quantity -= buyData.quantity; if (tradeData.quantity === 0) { await this.tradeRepository.deleteTrade(tradeId, queryRunner); } else await this.tradeRepository.updateTradeTransaction(tradeData, queryRunner); - const temp = await this.tradeRepository.findOne({ - where: {tradeId: tradeData.tradeId} - }) + const change = (tradeData.price - buyData.price) * buyData.quantity; const returnChange = change + account[typeGiven] + const new_asset = await this.assetRepository.findOne({ + where: {account:{id:account.id}, assetName: "BTC"} + }) + + if(typeReceived === "BTC"){ + const BTC_QUANTITY = new_asset ? asset.quantity : buyData.quantity; + await this.accountRepository.updateAccountBTC(account.id, BTC_QUANTITY, queryRunner) + } await this.accountRepository.updateAccountCurrency(typeGiven,returnChange, account.id, queryRunner); @@ -239,6 +242,8 @@ export class BidService implements OnModuleInit { }); const availableTrades = await this.tradeRepository.searchBuyTrade(coinPrice); availableTrades.forEach((trade) => { + const krw = coinLatestInfo.get(["KRW",trade.assetName].join("-")).trade_price + const another = coinLatestInfo.get([trade.tradeCurrency,trade.assetName].join("-")).trade_price const bidDto = { userId: trade.user.id, typeGiven: trade.tradeCurrency, //건네주는 통화 @@ -246,7 +251,7 @@ export class BidService implements OnModuleInit { receivedPrice: trade.price, //건네받을 통화 가격 receivedAmount: trade.quantity, //건네 받을 통화 갯수 tradeId: trade.tradeId, - krw: coinLatestInfo.get(["KRW",trade.assetName].join("-")), + krw: another/krw }; this.bidTradeService(bidDto); });