[AVLE] Tron Balance and Total Asset Value

AVLE에서는 트론 잔액도 표시하려고 합니다. 이번에는 트론 관련 구현 내용과 전체 자산 가치를 계산해서 표시했습니다.
image.png

막 증인 노드를 돌리고 나서 한국 커뮤니티 여러분들의 투표해주셔서 대단히 감사합니다.
증인 노드 관련글은 다음 글을 참고해주세요.
이타인클럽(@etainclub) 증인투표 부탁드립니다
증인투표: https://steemitwallet.com/~witnesses (@etainclub, 44위)


트론 잔액을 얻으려면 트론 계정(지갑 주소)를 알아 낸 후, 이 계정 정보를 통해서 잔액을 알아내야 합니다. 뭔가 좀 번거롭게 되어 있습니다. 트론 관련 자료는 거의 없는거 같아 제가 구현한 내용을 코드와 함께 정리해서 공유합니다.

트론 계정

먼저 스팀 계정과 연결된 트론 계정 정보를 얻어야 합니다. 다음과 같이 얻을 수 있습니다.

static const tronRewardEndpoint = 'https://steemitwallet.com/api/v1/tron/tron_user?username='
Future<dynamic> fetchUserReward({required String account}) async {
// account에 자신의 스팀 계정을 입력
 var response = await Dio().get('${BlockchainConst.tronRewardEndpoint}$account');
      // printWarning('fetchUserReward. response: ${response.data}');
      final result = jsonDecode(response.data);
      if (result['status'] == 'ok') {
        return result['result'];
      }
}

트론 계정 변환 (base58 -> hex)

스팀 계정인 etainclub과 연동된 트론 계정이 얻어집니다. TG4JuyjQr9PEpodWc2FpBkYKhehL2p19S5

이 계정은 base58 (10진수, 16진수 처럼 58진수로 표시된 값)로 되어 있는 것입니다. 이것을 hex로 변환하여 별도의 api로 계정 정보를 요청해야 합니다.

   final response = await tronClient.fetchUserReward(account: account);
   final address = response['tron_addr'];
   // pending reward관련 필드도 있지만 값은 0으로 비어 있음.
   final reward = response['pending_claim_tron_reward'];

   // decode the base58
   var buffer = base58.decode(address);
  final hexDecimal = hex.encode(buffer);

   // convert to this base58 to hex
   final hexDecimal = hex.encode(buffer);

    // remove the last 8 characters
    final hexAddr = hexDecimal.substring(0, hexDecimal.length - 8);

base58 주소값을 hex 주소값으로 얻어오는 게 좀 복잡합니다. 이렇게 하면 hex 스트링으로 된 주소가 나옵니다.
제 경우엔 이렇습니다. 4142c7c51b21fca6bbcddca6f35360321f308291ae

트론 잔액 조회

이제 이 hex 스트링 주소로 트론 계정 정보를 요청하면 잔액을 조회할 수 있습니다.

  static const tronAccountEndpoint = 'https://api.trongrid.io/walletsolidity/getaccount';

Future<dynamic> fetchAccount(
      {required String account, required String address}) async {
    print('address: $address');
    final body = {
      'address': address,
    };
     var response = await Dio().post(BlockchainConst.tronAccountEndpoint, data: body);
      return response.data;
  }

이렇게 하면 결과에 balance 필드에 트론 잔액이 있습니다. 이 값에 10e-7을 곱해야 합니다.

image.png

Tron Reward

그리고, claim rewards를 보면 트론 pending reward도 있습니다. 이게 여기저기 뒤져봐도 통 정보가 없었습니다. 알고봤더니 sp 보상과 거의 동일하게 보상이 나오는 구조입니다.

image.png

다음과 같이 계산합니다.

  final vestingToSteemContant = totalVestingFundSteem / totalVestingShares
 // calculate tron reward based sp reward
      const vestsPerTrx = 1913.0; // 이 값은 tron config api로 얻어올 수 있음.
      final reward = double.parse(rewardSp) /
          (accountBalance.vestingToSteemContant * vestsPerTrx);
      final rewardTron = reward.toStringAsFixed(3);

참고로, vestsPerTrx 값은 다음과 같이 얻을 수 있습니다.

  static const tronConfigEndpoint = 'https://steemitwallet.com/api/v1/tron/get_config';

Future<dynamic> fetchConfig() async {
    try {
      final tronConfig =
          await Dio().get('${tronConfigEndpoint}');
      printWarning('tronConfig: $tronConfig');
    } catch (error) {
      printError('failed to fetch tron config. $error');
    }
  }

내 자산 가치

전체 자산 가치를 표시하려면 스팀, 스달, 트론 시세 정보를 알아야 합니다.
coin gecko에서 다음과 같이 얻어올 수 있습니다.

스팀, 스달은 한번에 다음과 같이 얻어올 수 있습니다.

  final response = await Dio().get('https://api.coingecko.com/api/v3/simple/price?ids=steem,steem-dollars,snax-token&vs_currencies=usd&include_24hr_change=true');
      final sbd = response.data['steem-dollars']['usd'],
      final sbdChange = response.data['steem-dollars']['usd_24h_change'],
      final steem = response.data['steem']['usd'],
      final steemChange = response.data['steem']['usd_24h_change'],

트론 가격은 다음과 같이 얻어옵니다.

final response = await Dio().get('https://api.coingecko.com/api/v3/simple/price?ids=tron&vs_currencies=usd&include_24hr_change=true');
final tronPrice = response.data['tron'];

이제 각 코인 수량과 시세를 곱해서 총 가치를 계산합니다.

결과는 아래처럼 $9,612 입니다.
image.png

스팀잇 지갑에서 확인해보니, 조금 차이가 납니다. 시세를 가져오는 방법이 조금 다른거 같습니다.
image.png

위 화면을 보면, 트론 보상, 잔액도 잘 나타나고 있습니다.

트론에 대한 정보가 별로 없어서 좀 고생했습니다. 개발에 참고가 되면 좋겠습니다.

증인 투표 및 리스팀 부탁드립니다.

https://steemitwallet.com/~witnesses

아래 링크를 누르면 키 입력후 바로 투표 됩니다.
https://steemyy.com/witness-voting/?witness=etainclub&action=approve
(현재 44입니다. 투표시 액티브키가 필요합니다.)

Make Steem Great Again!

Thank you for your support.

cc.
@steemcurator01

Sort:  

Upvoted! Thank you for supporting witness @jswit.
default.jpg

This post has been featured in the latest edition of Steem News...

Coin Marketplace

STEEM 0.36
TRX 0.12
JST 0.039
BTC 70112.96
ETH 3549.99
USDT 1.00
SBD 4.71