Skip to content

Commit

Permalink
Merge pull request #65 from CSID-DGU/feature/#48/upbit-keys
Browse files Browse the repository at this point in the history
[feat] : 업비트 키 등록 시, 검증하는 기능 추가
  • Loading branch information
bbbang105 authored Jun 10, 2024
2 parents 2b2ae74 + 93b2159 commit 41b2bc4
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 33 deletions.
3 changes: 2 additions & 1 deletion backend/src/main/java/org/dgu/backend/dto/DashBoardDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ public class DashBoardDto {
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class UserAccountResponse {
private Long account;
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal account;
}

@Builder
Expand Down
8 changes: 5 additions & 3 deletions backend/src/main/java/org/dgu/backend/dto/UpbitDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import lombok.*;
import org.dgu.backend.domain.Market;

import java.math.BigDecimal;

public class UpbitDto {
@Builder
@Getter
Expand Down Expand Up @@ -82,9 +84,9 @@ public static class CandleInfoResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Account {
private String currency;
private Double balance;
private Double locked;
private Double avgBuyPrice;
private BigDecimal balance;
private BigDecimal locked;
private BigDecimal avgBuyPrice;
private String unitCurrency;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package org.dgu.backend.repository;

import jakarta.transaction.Transactional;
import org.dgu.backend.domain.UpbitKey;
import org.dgu.backend.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

public interface UpbitKeyRepository extends JpaRepository<UpbitKey,Long> {
UpbitKey findByUser(User user);

@Transactional
@Modifying(clearAutomatically = true)
@Query("delete from UpbitKey where id = :id")
void deleteUpbitKeyById(Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
Expand Down Expand Up @@ -49,20 +50,10 @@ public DashBoardDto.UserAccountResponse getUserAccount(String authorizationHeade
if (Objects.isNull(responseBody)) {
throw new UpbitException(UpbitErrorResult.FAIL_ACCESS_USER_ACCOUNT);
}

long accountSum = 0L;
for (UpbitDto.Account account : responseBody) {
if (account.getCurrency().equals("KRW")) {
accountSum += BigDecimal.valueOf(account.getBalance()).longValue();
} else {
accountSum += BigDecimal.valueOf(account.getBalance())
.multiply(BigDecimal.valueOf(account.getAvgBuyPrice()))
.longValue();
}
}
BigDecimal accountSum = getAccountSum(responseBody);

return DashBoardDto.UserAccountResponse.builder()
.account(accountSum)
.account(accountSum.setScale(3, RoundingMode.HALF_UP))
.build();
}

Expand Down Expand Up @@ -98,8 +89,8 @@ public List<DashBoardDto.UserCoinResponse> getUserCoins(String authorizationHead

DashBoardDto.UserCoinResponse userCoinResponse = DashBoardDto.UserCoinResponse.builder()
.coinName(coinName)
.balance(BigDecimal.valueOf(account.getBalance()))
.price(BigDecimal.valueOf(account.getAvgBuyPrice()))
.balance(account.getBalance())
.price(account.getAvgBuyPrice())
.isIncrease(isIncrease)
.build();
userCoinResponses.add(userCoinResponse);
Expand All @@ -126,10 +117,25 @@ public List<DashBoardDto.RepresentativeCoinResponse> getRepresentativeCoins() {
return representativeCoinResponses;
}

// 현재 업비트 잔고를 계산하는 메서드
private BigDecimal getAccountSum(UpbitDto.Account[] responseBody) {
BigDecimal accountSum = BigDecimal.ZERO;
for (UpbitDto.Account account : responseBody) {
if (account.getCurrency().equals("KRW")) {
accountSum = accountSum.add(account.getBalance());
} else {
BigDecimal balance = account.getBalance();
BigDecimal avgBuyPrice = account.getAvgBuyPrice();
accountSum = accountSum.add(balance.multiply(avgBuyPrice));
}
}
return accountSum;
}

// 코인 가격 상승 여부를 판단하는 메서드
private boolean isBalanceIncreased(UpbitDto.Account account, UserCoin userCoin) {

return BigDecimal.valueOf(account.getBalance()).compareTo(userCoin.getBalance()) > 0;
return account.getBalance().compareTo(userCoin.getBalance()) > 0;
}

// 전체 계좌 조회 업비트 API와 통신하는 메서드
Expand Down
30 changes: 16 additions & 14 deletions backend/src/main/java/org/dgu/backend/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
import org.springframework.stereotype.Service;

import java.security.KeyPair;
import java.util.Objects;

@Service
@Transactional
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final DashBoardService dashBoardService;
private final UpbitKeyRepository upbitKeyRepository;
private final JwtUtil jwtUtil;
private final EncryptionUtil encryptionUtil;
Expand All @@ -34,6 +36,9 @@ public void addUserUpbitKeys(String authorizationHeader, UserDto.UserUpbitKeyReq
String encryptedPrivateKey = encryptionUtil.encryptPrivateKey(keyPair);

saveUpbitKey(user, encodedAccessKey, encodedSecretKey, encryptedPrivateKey, existUpbitKey);

// 업비트 키가 정상적으로 입력되었는지 확인
dashBoardService.getUserAccount(authorizationHeader);
}

// 서비스 약관 동의 여부를 등록하는 메서드
Expand All @@ -56,20 +61,17 @@ public UserDto.getUserAgreementResponse getUserAgreement(String authorizationHea

// 업비트 키 저장 메서드
private void saveUpbitKey(User user, String encodedAccessKey, String encodedSecretKey, String encryptedPrivateKey, UpbitKey existUpbitKey) {
// 기존 키 있는 경우 업데이트
if (existUpbitKey != null) {
existUpbitKey.updateAccessKey(encodedAccessKey);
existUpbitKey.updateSecretKey(encodedSecretKey);
existUpbitKey.updatePrivateKey(encryptedPrivateKey);
upbitKeyRepository.save(existUpbitKey);
} else {
UpbitKey upbitKey = UpbitKey.builder()
.user(user)
.accessKey(encodedAccessKey)
.secretKey(encodedSecretKey)
.privateKey(encryptedPrivateKey)
.build();
upbitKeyRepository.save(upbitKey);
// 기존 키가 있으면 삭제
if (!Objects.isNull(existUpbitKey)) {
upbitKeyRepository.deleteUpbitKeyById(existUpbitKey.getId());
}

UpbitKey upbitKey = UpbitKey.builder()
.user(user)
.accessKey(encodedAccessKey)
.secretKey(encodedSecretKey)
.privateKey(encryptedPrivateKey)
.build();
upbitKeyRepository.save(upbitKey);
}
}

0 comments on commit 41b2bc4

Please sign in to comment.