@ledgerhq/coin-tron 0.2.2 → 0.2.3-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +7 -0
  3. package/lib/bridge/broadcast.js +3 -12
  4. package/lib/bridge/broadcast.js.map +1 -1
  5. package/lib/bridge/estimateMaxSpendable.js +9 -12
  6. package/lib/bridge/estimateMaxSpendable.js.map +1 -1
  7. package/lib/bridge/getEstimateFees.js +7 -17
  8. package/lib/bridge/getEstimateFees.js.map +1 -1
  9. package/lib/bridge/getTransactionStatus.js +18 -26
  10. package/lib/bridge/getTransactionStatus.js.map +1 -1
  11. package/lib/bridge/preload.js +3 -12
  12. package/lib/bridge/preload.js.map +1 -1
  13. package/lib/bridge/prepareTransaction.js +4 -13
  14. package/lib/bridge/prepareTransaction.js.map +1 -1
  15. package/lib/bridge/serialization.js +8 -8
  16. package/lib/bridge/serialization.js.map +1 -1
  17. package/lib/bridge/signOperation.js +39 -53
  18. package/lib/bridge/signOperation.js.map +1 -1
  19. package/lib/bridge/synchronization.integ.test.js +10 -15
  20. package/lib/bridge/synchronization.integ.test.js.map +1 -1
  21. package/lib/bridge/synchronization.js +25 -23
  22. package/lib/bridge/synchronization.js.map +1 -1
  23. package/lib/bridge/transaction.js +20 -4
  24. package/lib/bridge/transaction.js.map +1 -1
  25. package/lib/logic/utils.test.js +21 -10
  26. package/lib/logic/utils.test.js.map +1 -1
  27. package/lib/network/format.js +4 -5
  28. package/lib/network/format.js.map +1 -1
  29. package/lib/network/index.integ.test.js +3 -12
  30. package/lib/network/index.integ.test.js.map +1 -1
  31. package/lib/network/index.js +296 -321
  32. package/lib/network/index.js.map +1 -1
  33. package/lib/network/index.test.js +4 -14
  34. package/lib/network/index.test.js.map +1 -1
  35. package/lib/signer/getAddress.js +4 -13
  36. package/lib/signer/getAddress.js.map +1 -1
  37. package/lib/test/bridgeDatasetTest.js +33 -7
  38. package/lib/test/bridgeDatasetTest.js.map +1 -1
  39. package/lib/test/cli.js +7 -2
  40. package/lib/test/cli.js.map +1 -1
  41. package/lib-es/bridge/broadcast.js +3 -12
  42. package/lib-es/bridge/broadcast.js.map +1 -1
  43. package/lib-es/bridge/estimateMaxSpendable.js +9 -12
  44. package/lib-es/bridge/estimateMaxSpendable.js.map +1 -1
  45. package/lib-es/bridge/getEstimateFees.js +7 -17
  46. package/lib-es/bridge/getEstimateFees.js.map +1 -1
  47. package/lib-es/bridge/getTransactionStatus.js +18 -26
  48. package/lib-es/bridge/getTransactionStatus.js.map +1 -1
  49. package/lib-es/bridge/preload.js +3 -12
  50. package/lib-es/bridge/preload.js.map +1 -1
  51. package/lib-es/bridge/prepareTransaction.js +4 -13
  52. package/lib-es/bridge/prepareTransaction.js.map +1 -1
  53. package/lib-es/bridge/serialization.js +8 -8
  54. package/lib-es/bridge/serialization.js.map +1 -1
  55. package/lib-es/bridge/signOperation.js +39 -53
  56. package/lib-es/bridge/signOperation.js.map +1 -1
  57. package/lib-es/bridge/synchronization.integ.test.js +10 -15
  58. package/lib-es/bridge/synchronization.integ.test.js.map +1 -1
  59. package/lib-es/bridge/synchronization.js +25 -23
  60. package/lib-es/bridge/synchronization.js.map +1 -1
  61. package/lib-es/bridge/transaction.js +20 -4
  62. package/lib-es/bridge/transaction.js.map +1 -1
  63. package/lib-es/logic/utils.test.js +21 -10
  64. package/lib-es/logic/utils.test.js.map +1 -1
  65. package/lib-es/network/format.js +4 -5
  66. package/lib-es/network/format.js.map +1 -1
  67. package/lib-es/network/index.integ.test.js +3 -12
  68. package/lib-es/network/index.integ.test.js.map +1 -1
  69. package/lib-es/network/index.js +296 -321
  70. package/lib-es/network/index.js.map +1 -1
  71. package/lib-es/network/index.test.js +4 -14
  72. package/lib-es/network/index.test.js.map +1 -1
  73. package/lib-es/signer/getAddress.js +4 -13
  74. package/lib-es/signer/getAddress.js.map +1 -1
  75. package/lib-es/test/bridgeDatasetTest.js +33 -7
  76. package/lib-es/test/bridgeDatasetTest.js.map +1 -1
  77. package/lib-es/test/cli.js +7 -2
  78. package/lib-es/test/cli.js.map +1 -1
  79. package/package.json +4 -4
  80. package/tsconfig.json +0 -1
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { hours, makeLRUCache } from "@ledgerhq/live-network/cache";
11
2
  import network from "@ledgerhq/live-network";
12
3
  import { promiseAllBatched } from "@ledgerhq/live-promise";
@@ -25,71 +16,65 @@ import { decode58Check, encode58Check, formatTrongridTrc20TxResponse, formatTron
25
16
  import { isMalformedTransactionTronAPI, isTransactionTronAPI, } from "./types";
26
17
  import { stringify } from "querystring";
27
18
  const getBaseApiUrl = () => getCoinConfig().explorer.url;
28
- function post(endPoint, body) {
29
- return __awaiter(this, void 0, void 0, function* () {
30
- const { data } = yield network({
31
- method: "POST",
32
- url: `${getBaseApiUrl()}${endPoint}`,
33
- data: body,
34
- });
35
- // Ugly but trongrid send a 200 status event if there are errors
36
- if ("Error" in data) {
37
- log("tron-error", stringify(data.Error), {
38
- endPoint,
39
- body,
40
- });
41
- throw new Error(stringify(data.Error));
42
- }
43
- return data;
19
+ async function post(endPoint, body) {
20
+ const { data } = await network({
21
+ method: "POST",
22
+ url: `${getBaseApiUrl()}${endPoint}`,
23
+ data: body,
44
24
  });
25
+ // Ugly but trongrid send a 200 status event if there are errors
26
+ if ("Error" in data) {
27
+ log("tron-error", stringify(data.Error), {
28
+ endPoint,
29
+ body,
30
+ });
31
+ throw new Error(stringify(data.Error));
32
+ }
33
+ return data;
45
34
  }
46
- function fetch(endPoint) {
47
- return __awaiter(this, void 0, void 0, function* () {
48
- return fetchWithBaseUrl(`${getBaseApiUrl()}${endPoint}`);
49
- });
35
+ async function fetch(endPoint) {
36
+ return fetchWithBaseUrl(`${getBaseApiUrl()}${endPoint}`);
50
37
  }
51
- function fetchWithBaseUrl(url) {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- const { data } = yield network({ url });
54
- // Ugly but trongrid send a 200 status event if there are errors
55
- if ("Error" in data) {
56
- log("tron-error", stringify(data.Error), {
57
- url,
58
- });
59
- throw new Error(stringify(data.Error));
60
- }
61
- return data;
62
- });
38
+ async function fetchWithBaseUrl(url) {
39
+ const { data } = await network({ url });
40
+ // Ugly but trongrid send a 200 status event if there are errors
41
+ if ("Error" in data) {
42
+ log("tron-error", stringify(data.Error), {
43
+ url,
44
+ });
45
+ throw new Error(stringify(data.Error));
46
+ }
47
+ return data;
63
48
  }
64
- export const freezeTronTransaction = (account, transaction) => __awaiter(void 0, void 0, void 0, function* () {
49
+ export const freezeTronTransaction = async (account, transaction) => {
65
50
  const txData = {
66
51
  frozen_balance: transaction.amount.toNumber(),
67
52
  resource: transaction.resource,
68
53
  owner_address: decode58Check(account.freshAddress),
69
54
  };
70
55
  const url = `/wallet/freezebalancev2`;
71
- const result = yield post(url, txData);
56
+ const result = await post(url, txData);
72
57
  return result;
73
- });
74
- export const unfreezeTronTransaction = (account, transaction) => __awaiter(void 0, void 0, void 0, function* () {
58
+ };
59
+ export const unfreezeTronTransaction = async (account, transaction) => {
75
60
  const txData = {
76
61
  owner_address: decode58Check(account.freshAddress),
77
62
  resource: transaction.resource,
78
63
  unfreeze_balance: transaction.amount.toNumber(),
79
64
  };
80
65
  const url = `/wallet/unfreezebalancev2`;
81
- const result = yield post(url, txData);
66
+ const result = await post(url, txData);
82
67
  return result;
83
- });
84
- export const withdrawExpireUnfreezeTronTransaction = (account, _transaction) => __awaiter(void 0, void 0, void 0, function* () {
68
+ };
69
+ export const withdrawExpireUnfreezeTronTransaction = async (account, _transaction) => {
85
70
  const txData = {
86
71
  owner_address: decode58Check(account.freshAddress),
87
72
  };
88
73
  const url = `/wallet/withdrawexpireunfreeze`;
89
- const result = yield post(url, txData);
74
+ const result = await post(url, txData);
90
75
  return result;
91
- });
92
- export const unDelegateResourceTransaction = (account, transaction) => __awaiter(void 0, void 0, void 0, function* () {
76
+ };
77
+ export const unDelegateResourceTransaction = async (account, transaction) => {
93
78
  const txData = {
94
79
  balance: transaction.amount.toNumber(),
95
80
  resource: transaction.resource,
@@ -97,41 +82,39 @@ export const unDelegateResourceTransaction = (account, transaction) => __awaiter
97
82
  receiver_address: decode58Check(transaction.recipient),
98
83
  };
99
84
  const url = `/wallet/undelegateresource`;
100
- const result = yield post(url, txData);
85
+ const result = await post(url, txData);
101
86
  return result;
102
- });
103
- export const legacyUnfreezeTronTransaction = (account, transaction) => __awaiter(void 0, void 0, void 0, function* () {
87
+ };
88
+ export const legacyUnfreezeTronTransaction = async (account, transaction) => {
104
89
  const txData = {
105
90
  resource: transaction.resource,
106
91
  owner_address: decode58Check(account.freshAddress),
107
92
  receiver_address: transaction.recipient ? decode58Check(transaction.recipient) : undefined,
108
93
  };
109
94
  const url = `/wallet/unfreezebalance`;
110
- const result = yield post(url, txData);
95
+ const result = await post(url, txData);
111
96
  return result;
112
- });
113
- export function getDelegatedResource(account, transaction, resource) {
114
- return __awaiter(this, void 0, void 0, function* () {
115
- const url = `/wallet/getdelegatedresourcev2`;
116
- const { delegatedResource = [], } = yield post(url, {
117
- fromAddress: decode58Check(account.freshAddress),
118
- toAddress: decode58Check(transaction.recipient),
119
- });
120
- const { frozen_balance_for_bandwidth, frozen_balance_for_energy } = delegatedResource.reduce((accum, cur) => {
121
- if (cur.frozen_balance_for_bandwidth) {
122
- accum.frozen_balance_for_bandwidth += cur.frozen_balance_for_bandwidth;
123
- }
124
- if (cur.frozen_balance_for_energy) {
125
- accum.frozen_balance_for_energy += cur.frozen_balance_for_energy;
126
- }
127
- return accum;
128
- }, { frozen_balance_for_bandwidth: 0, frozen_balance_for_energy: 0 });
129
- const amount = resource === "BANDWIDTH" ? frozen_balance_for_bandwidth : frozen_balance_for_energy;
130
- return new BigNumber(amount);
97
+ };
98
+ export async function getDelegatedResource(account, transaction, resource) {
99
+ const url = `/wallet/getdelegatedresourcev2`;
100
+ const { delegatedResource = [], } = await post(url, {
101
+ fromAddress: decode58Check(account.freshAddress),
102
+ toAddress: decode58Check(transaction.recipient),
131
103
  });
104
+ const { frozen_balance_for_bandwidth, frozen_balance_for_energy } = delegatedResource.reduce((accum, cur) => {
105
+ if (cur.frozen_balance_for_bandwidth) {
106
+ accum.frozen_balance_for_bandwidth += cur.frozen_balance_for_bandwidth;
107
+ }
108
+ if (cur.frozen_balance_for_energy) {
109
+ accum.frozen_balance_for_energy += cur.frozen_balance_for_energy;
110
+ }
111
+ return accum;
112
+ }, { frozen_balance_for_bandwidth: 0, frozen_balance_for_energy: 0 });
113
+ const amount = resource === "BANDWIDTH" ? frozen_balance_for_bandwidth : frozen_balance_for_energy;
114
+ return new BigNumber(amount);
132
115
  }
133
116
  // Send trx or trc10/trc20 tokens
134
- export const createTronTransaction = (account, transaction, subAccount) => __awaiter(void 0, void 0, void 0, function* () {
117
+ export const createTronTransaction = async (account, transaction, subAccount) => {
135
118
  const [tokenType, tokenId] = subAccount && subAccount.type === "TokenAccount"
136
119
  ? drop(subAccount.token.id.split("/"), 1)
137
120
  : [undefined, undefined];
@@ -147,7 +130,7 @@ export const createTronTransaction = (account, transaction, subAccount) => __awa
147
130
  owner_address: decode58Check(account.freshAddress),
148
131
  };
149
132
  const url = `/wallet/triggersmartcontract`;
150
- const { transaction: preparedTransaction } = yield post(url, txData);
133
+ const { transaction: preparedTransaction } = await post(url, txData);
151
134
  return extendTronTxExpirationTimeBy10mn(preparedTransaction);
152
135
  }
153
136
  else {
@@ -159,11 +142,11 @@ export const createTronTransaction = (account, transaction, subAccount) => __awa
159
142
  asset_name: tokenId && Buffer.from(tokenId).toString("hex"),
160
143
  };
161
144
  const url = subAccount ? `/wallet/transferasset` : `/wallet/createtransaction`;
162
- const preparedTransaction = yield post(url, txData);
145
+ const preparedTransaction = await post(url, txData);
163
146
  // for the ledger Vault we need to increase the expiration
164
147
  return extendTronTxExpirationTimeBy10mn(preparedTransaction);
165
148
  }
166
- });
149
+ };
167
150
  function extendTronTxExpirationTimeBy10mn(preparedTransaction) {
168
151
  const VAULT_EXPIRATION_TIME = 600;
169
152
  const HttpProvider = TronWeb.providers.HttpProvider;
@@ -174,114 +157,102 @@ function extendTronTxExpirationTimeBy10mn(preparedTransaction) {
174
157
  //FIXME: test it and rewrite it
175
158
  return tronWeb.transactionBuilder.extendExpiration(preparedTransaction, VAULT_EXPIRATION_TIME);
176
159
  }
177
- export const broadcastTron = (trxTransaction) => __awaiter(void 0, void 0, void 0, function* () {
178
- const result = yield post(`/wallet/broadcasttransaction`, trxTransaction);
160
+ export const broadcastTron = async (trxTransaction) => {
161
+ const result = await post(`/wallet/broadcasttransaction`, trxTransaction);
179
162
  if (result.code === "TRANSACTION_EXPIRATION_ERROR") {
180
163
  throw new TronTransactionExpired();
181
164
  }
182
165
  return result;
183
- });
184
- export function fetchTronAccount(addr) {
185
- return __awaiter(this, void 0, void 0, function* () {
186
- try {
187
- const data = yield fetch(`/v1/accounts/${addr}`);
188
- return data.data;
189
- }
190
- catch (e) {
191
- return [];
192
- }
193
- });
166
+ };
167
+ export async function fetchTronAccount(addr) {
168
+ try {
169
+ const data = await fetch(`/v1/accounts/${addr}`);
170
+ return data.data;
171
+ }
172
+ catch (e) {
173
+ return [];
174
+ }
194
175
  }
195
- export function fetchCurrentBlockHeight() {
196
- return __awaiter(this, void 0, void 0, function* () {
197
- const data = yield fetch(`/wallet/getnowblock`);
198
- return data.block_header.raw_data.number;
199
- });
176
+ export async function fetchCurrentBlockHeight() {
177
+ const data = await fetch(`/wallet/getnowblock`);
178
+ return data.block_header.raw_data.number;
200
179
  }
201
180
  // For the moment, fetching transaction info is the only way to get fees from a transaction
202
- function fetchTronTxDetail(txId) {
203
- return __awaiter(this, void 0, void 0, function* () {
204
- const { fee, blockNumber, withdraw_amount, unfreeze_amount } = yield fetch(`/wallet/gettransactioninfobyid?value=${encodeURIComponent(txId)}`);
205
- return {
206
- fee,
207
- blockNumber,
208
- withdraw_amount,
209
- unfreeze_amount,
210
- };
211
- });
181
+ async function fetchTronTxDetail(txId) {
182
+ const { fee, blockNumber, withdraw_amount, unfreeze_amount } = await fetch(`/wallet/gettransactioninfobyid?value=${encodeURIComponent(txId)}`);
183
+ return {
184
+ fee,
185
+ blockNumber,
186
+ withdraw_amount,
187
+ unfreeze_amount,
188
+ };
212
189
  }
213
- function getAllTransactions(initialUrl, shouldFetchMoreTxs, getTxs) {
214
- return __awaiter(this, void 0, void 0, function* () {
215
- let all = [];
216
- let url = initialUrl;
217
- while (url && shouldFetchMoreTxs(all)) {
218
- const { nextUrl, results } = yield getTxs(url);
219
- url = nextUrl;
220
- all = all.concat(results);
221
- }
222
- return all;
223
- });
190
+ async function getAllTransactions(initialUrl, shouldFetchMoreTxs, getTxs) {
191
+ let all = [];
192
+ let url = initialUrl;
193
+ while (url && shouldFetchMoreTxs(all)) {
194
+ const { nextUrl, results } = await getTxs(url);
195
+ url = nextUrl;
196
+ all = all.concat(results);
197
+ }
198
+ return all;
224
199
  }
225
- const getTransactions = (cacheTransactionInfoById) => (url) => __awaiter(void 0, void 0, void 0, function* () {
226
- var _a, _b;
227
- const transactions = yield fetchWithBaseUrl(url);
228
- const nextUrl = (_b = (_a = transactions.meta.links) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.replace(/https:\/\/api(\.[a-z]*)?.trongrid.io/, getBaseApiUrl());
229
- const results = yield promiseAllBatched(3, transactions.data || [], (tx) => __awaiter(void 0, void 0, void 0, function* () {
200
+ const getTransactions = (cacheTransactionInfoById) => async (url) => {
201
+ const transactions = await fetchWithBaseUrl(url);
202
+ const nextUrl = transactions.meta.links?.next?.replace(/https:\/\/api(\.[a-z]*)?.trongrid.io/, getBaseApiUrl());
203
+ const results = await promiseAllBatched(3, transactions.data || [], async (tx) => {
230
204
  if (isMalformedTransactionTronAPI(tx)) {
231
205
  return tx;
232
206
  }
233
207
  const txID = tx.txID;
234
- const detail = cacheTransactionInfoById[txID] || (yield fetchTronTxDetail(txID));
208
+ const detail = cacheTransactionInfoById[txID] || (await fetchTronTxDetail(txID));
235
209
  cacheTransactionInfoById[txID] = detail;
236
- return Object.assign(Object.assign({}, tx), { detail });
237
- }));
210
+ return { ...tx, detail };
211
+ });
238
212
  return {
239
213
  results,
240
214
  nextUrl,
241
215
  };
242
- });
243
- const getTrc20 = (url) => __awaiter(void 0, void 0, void 0, function* () {
244
- var _a, _b;
245
- const transactions = yield fetchWithBaseUrl(url);
216
+ };
217
+ const getTrc20 = async (url) => {
218
+ const transactions = await fetchWithBaseUrl(url);
246
219
  return {
247
220
  results: transactions.data,
248
- nextUrl: (_b = (_a = transactions.meta.links) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.replace(/https:\/\/api(\.[a-z]*)?.trongrid.io/, getBaseApiUrl()),
221
+ nextUrl: transactions.meta.links?.next?.replace(/https:\/\/api(\.[a-z]*)?.trongrid.io/, getBaseApiUrl()),
249
222
  };
250
- });
251
- export function fetchTronAccountTxs(addr, shouldFetchMoreTxs, cacheTransactionInfoById) {
252
- return __awaiter(this, void 0, void 0, function* () {
253
- const entireTxs = (yield getAllTransactions(`${getBaseApiUrl()}/v1/accounts/${addr}/transactions?limit=100`, shouldFetchMoreTxs, getTransactions(cacheTransactionInfoById)))
254
- .filter((tx) => isTransactionTronAPI(tx))
255
- .filter(tx => {
256
- // custom smart contract tx has internal txs
257
- const hasInternalTxs = tx.txID && tx.internal_transactions && tx.internal_transactions.length > 0;
258
- // and also a duplicated malformed tx that we have to ignore
259
- const isDuplicated = tx.tx_id;
260
- const type = tx.raw_data.contract[0].type;
261
- if (hasInternalTxs) {
262
- // log once
263
- log("tron-error", `unsupported transaction ${tx.txID}`);
264
- }
265
- return !isDuplicated && !hasInternalTxs && type !== "TriggerSmartContract";
266
- })
267
- .map(tx => formatTrongridTxResponse(tx));
268
- // we need to fetch and filter trc20 transactions from another endpoint
269
- const entireTrc20Txs = (yield getAllTransactions(`${getBaseApiUrl()}/v1/accounts/${addr}/transactions/trc20?get_detail=true`, shouldFetchMoreTxs, getTrc20)).map(tx => formatTrongridTrc20TxResponse(tx));
270
- const txInfos = compact(entireTxs.concat(entireTrc20Txs)).sort((a, b) => b.date.getTime() - a.date.getTime());
271
- return txInfos;
272
- });
223
+ };
224
+ export async function fetchTronAccountTxs(addr, shouldFetchMoreTxs, cacheTransactionInfoById) {
225
+ const entireTxs = (await getAllTransactions(`${getBaseApiUrl()}/v1/accounts/${addr}/transactions?limit=100`, shouldFetchMoreTxs, getTransactions(cacheTransactionInfoById)))
226
+ .filter((tx) => isTransactionTronAPI(tx))
227
+ .filter(tx => {
228
+ // custom smart contract tx has internal txs
229
+ const hasInternalTxs = tx.txID && tx.internal_transactions && tx.internal_transactions.length > 0;
230
+ // and also a duplicated malformed tx that we have to ignore
231
+ const isDuplicated = tx.tx_id;
232
+ const type = tx.raw_data.contract[0].type;
233
+ if (hasInternalTxs) {
234
+ // log once
235
+ log("tron-error", `unsupported transaction ${tx.txID}`);
236
+ }
237
+ return !isDuplicated && !hasInternalTxs && type !== "TriggerSmartContract";
238
+ })
239
+ .map(tx => formatTrongridTxResponse(tx));
240
+ // we need to fetch and filter trc20 transactions from another endpoint
241
+ const entireTrc20Txs = (await getAllTransactions(`${getBaseApiUrl()}/v1/accounts/${addr}/transactions/trc20?get_detail=true`, shouldFetchMoreTxs, getTrc20)).map(tx => formatTrongridTrc20TxResponse(tx));
242
+ const txInfos = compact(entireTxs.concat(entireTrc20Txs)).sort((a, b) => b.date.getTime() - a.date.getTime());
243
+ return txInfos;
273
244
  }
274
- export const getContractUserEnergyRatioConsumption = (address) => __awaiter(void 0, void 0, void 0, function* () {
275
- const result = yield fetchTronContract(address);
245
+ export const getContractUserEnergyRatioConsumption = async (address) => {
246
+ const result = await fetchTronContract(address);
276
247
  if (result) {
277
248
  const { consume_user_resource_percent } = result;
278
249
  return consume_user_resource_percent;
279
250
  }
280
251
  return 0;
281
- });
282
- export const fetchTronContract = (addr) => __awaiter(void 0, void 0, void 0, function* () {
252
+ };
253
+ export const fetchTronContract = async (addr) => {
283
254
  try {
284
- const data = yield post(`/wallet/getcontract`, {
255
+ const data = await post(`/wallet/getcontract`, {
285
256
  value: decode58Check(addr),
286
257
  });
287
258
  return Object.keys(data).length !== 0 ? data : undefined;
@@ -289,9 +260,9 @@ export const fetchTronContract = (addr) => __awaiter(void 0, void 0, void 0, fun
289
260
  catch (e) {
290
261
  return undefined;
291
262
  }
292
- });
293
- export const getTronAccountNetwork = (address) => __awaiter(void 0, void 0, void 0, function* () {
294
- const result = yield fetch(`/wallet/getaccountresource?address=${encodeURIComponent(decode58Check(address))}`);
263
+ };
264
+ export const getTronAccountNetwork = async (address) => {
265
+ const result = await fetch(`/wallet/getaccountresource?address=${encodeURIComponent(decode58Check(address))}`);
295
266
  const { freeNetUsed = 0, freeNetLimit = 0, NetUsed = 0, NetLimit = 0, EnergyUsed = 0, EnergyLimit = 0, } = result;
296
267
  return {
297
268
  family: "tron",
@@ -302,10 +273,10 @@ export const getTronAccountNetwork = (address) => __awaiter(void 0, void 0, void
302
273
  energyUsed: new BigNumber(EnergyUsed),
303
274
  energyLimit: new BigNumber(EnergyLimit),
304
275
  };
305
- });
306
- export const validateAddress = (address) => __awaiter(void 0, void 0, void 0, function* () {
276
+ };
277
+ export const validateAddress = async (address) => {
307
278
  try {
308
- const result = yield post(`/wallet/validateaddress`, {
279
+ const result = await post(`/wallet/validateaddress`, {
309
280
  address: decode58Check(address),
310
281
  });
311
282
  return result.result || false;
@@ -317,61 +288,68 @@ export const validateAddress = (address) => __awaiter(void 0, void 0, void 0, fu
317
288
  });
318
289
  return false;
319
290
  }
320
- });
291
+ };
321
292
  // cache for account names (name is unchanged over time)
322
- const accountNamesCache = makeLRUCache((addr) => __awaiter(void 0, void 0, void 0, function* () { return getAccountName(addr); }), (addr) => addr, hours(3, 300));
293
+ const accountNamesCache = makeLRUCache(async (addr) => getAccountName(addr), (addr) => addr, hours(3, 300));
323
294
  // cache for super representative brokerages (brokerage is unchanged over time)
324
- const srBrokeragesCache = makeLRUCache((addr) => __awaiter(void 0, void 0, void 0, function* () { return getBrokerage(addr); }), (addr) => addr, hours(3, 300));
325
- export const getAccountName = (addr) => __awaiter(void 0, void 0, void 0, function* () {
326
- const tronAcc = yield fetchTronAccount(addr);
295
+ const srBrokeragesCache = makeLRUCache(async (addr) => getBrokerage(addr), (addr) => addr, hours(3, 300));
296
+ export const getAccountName = async (addr) => {
297
+ const tronAcc = await fetchTronAccount(addr);
327
298
  const acc = tronAcc[0];
328
299
  const accountName = acc && acc.account_name ? hexToAscii(acc.account_name) : undefined;
329
300
  accountNamesCache.hydrate(addr, accountName); // put it in cache
330
301
  return accountName;
331
- });
332
- export const getBrokerage = (addr) => __awaiter(void 0, void 0, void 0, function* () {
333
- const { brokerage } = yield fetch(`/wallet/getBrokerage?address=${encodeURIComponent(addr)}`);
302
+ };
303
+ export const getBrokerage = async (addr) => {
304
+ const { brokerage } = await fetch(`/wallet/getBrokerage?address=${encodeURIComponent(addr)}`);
334
305
  srBrokeragesCache.hydrate(addr, brokerage); // put it in cache
335
306
  return brokerage;
336
- });
337
- const superRepresentativesCache = makeLRUCache(() => __awaiter(void 0, void 0, void 0, function* () {
338
- const superRepresentatives = yield fetchSuperRepresentatives();
307
+ };
308
+ const superRepresentativesCache = makeLRUCache(async () => {
309
+ const superRepresentatives = await fetchSuperRepresentatives();
339
310
  log("tron/superRepresentatives", "loaded " + superRepresentatives.length + " super representatives");
340
311
  return superRepresentatives;
341
- }), () => "", hours(1, 300));
342
- export const getTronSuperRepresentatives = () => __awaiter(void 0, void 0, void 0, function* () {
343
- return yield superRepresentativesCache();
344
- });
312
+ }, () => "", hours(1, 300));
313
+ export const getTronSuperRepresentatives = async () => {
314
+ return await superRepresentativesCache();
315
+ };
345
316
  export const hydrateSuperRepresentatives = (list) => {
346
317
  log("tron/superRepresentatives", "hydrate " + list.length + " super representatives");
347
318
  superRepresentativesCache.hydrate("", list);
348
319
  };
349
- const fetchSuperRepresentatives = () => __awaiter(void 0, void 0, void 0, function* () {
350
- const result = yield fetch(`/wallet/listwitnesses`);
320
+ const fetchSuperRepresentatives = async () => {
321
+ const result = await fetch(`/wallet/listwitnesses`);
351
322
  const sorted = result.witnesses.sort((a, b) => b.voteCount - a.voteCount);
352
- const superRepresentatives = yield promiseAllBatched(3, sorted, (w) => __awaiter(void 0, void 0, void 0, function* () {
323
+ const superRepresentatives = await promiseAllBatched(3, sorted, async (w) => {
353
324
  const encodedAddress = encode58Check(w.address);
354
- const accountName = yield accountNamesCache(encodedAddress);
355
- const brokerage = yield srBrokeragesCache(encodedAddress);
356
- return Object.assign(Object.assign({}, w), { address: encodedAddress, name: accountName, brokerage, voteCount: w.voteCount || 0, isJobs: w.isJobs || false });
357
- }));
325
+ const accountName = await accountNamesCache(encodedAddress);
326
+ const brokerage = await srBrokeragesCache(encodedAddress);
327
+ return {
328
+ ...w,
329
+ address: encodedAddress,
330
+ name: accountName,
331
+ brokerage,
332
+ voteCount: w.voteCount || 0,
333
+ isJobs: w.isJobs || false,
334
+ };
335
+ });
358
336
  hydrateSuperRepresentatives(superRepresentatives); // put it in cache
359
337
  return superRepresentatives;
360
- });
361
- export const getNextVotingDate = () => __awaiter(void 0, void 0, void 0, function* () {
362
- const { num } = yield fetch(`/wallet/getnextmaintenancetime`);
338
+ };
339
+ export const getNextVotingDate = async () => {
340
+ const { num } = await fetch(`/wallet/getnextmaintenancetime`);
363
341
  return new Date(num);
364
- });
365
- export const getTronSuperRepresentativeData = (max) => __awaiter(void 0, void 0, void 0, function* () {
366
- const list = yield getTronSuperRepresentatives();
367
- const nextVotingDate = yield getNextVotingDate();
342
+ };
343
+ export const getTronSuperRepresentativeData = async (max) => {
344
+ const list = await getTronSuperRepresentatives();
345
+ const nextVotingDate = await getNextVotingDate();
368
346
  return {
369
347
  list: max ? take(list, max) : list,
370
348
  totalVotes: sumBy(list, "voteCount"),
371
349
  nextVotingDate,
372
350
  };
373
- });
374
- export const voteTronSuperRepresentatives = (account, transaction) => __awaiter(void 0, void 0, void 0, function* () {
351
+ };
352
+ export const voteTronSuperRepresentatives = async (account, transaction) => {
375
353
  const payload = {
376
354
  owner_address: decode58Check(account.freshAddress),
377
355
  votes: transaction.votes.map(v => ({
@@ -379,146 +357,143 @@ export const voteTronSuperRepresentatives = (account, transaction) => __awaiter(
379
357
  vote_count: v.voteCount,
380
358
  })),
381
359
  };
382
- return yield post(`/wallet/votewitnessaccount`, payload);
383
- });
384
- export function getTronResources(acc_1, txs_1) {
385
- return __awaiter(this, arguments, void 0, function* (acc, txs, cacheTransactionInfoById = {}) {
386
- if (!acc) {
387
- return defaultTronResources;
360
+ return await post(`/wallet/votewitnessaccount`, payload);
361
+ };
362
+ export async function getTronResources(acc, txs, cacheTransactionInfoById = {}) {
363
+ if (!acc) {
364
+ return defaultTronResources;
365
+ }
366
+ const delegatedFrozenBandwidth = get(acc, "delegated_frozenV2_balance_for_bandwidth", undefined);
367
+ const delegatedFrozenEnergy = get(acc, "account_resource.delegated_frozenV2_balance_for_energy", undefined);
368
+ const frozenBalances = get(acc, "frozenV2", undefined);
369
+ const legacyFrozenBandwidth = get(acc, "frozen[0]", undefined);
370
+ const legacyFrozenEnergy = get(acc, "account_resource.frozen_balance_for_energy", undefined);
371
+ const legacyFrozen = {
372
+ bandwidth: legacyFrozenBandwidth
373
+ ? {
374
+ amount: new BigNumber(legacyFrozenBandwidth.frozen_balance),
375
+ expiredAt: new Date(legacyFrozenBandwidth.expire_time),
376
+ }
377
+ : undefined,
378
+ energy: legacyFrozenEnergy
379
+ ? {
380
+ amount: new BigNumber(legacyFrozenEnergy.frozen_balance),
381
+ expiredAt: new Date(legacyFrozenEnergy.expire_time),
382
+ }
383
+ : undefined,
384
+ };
385
+ const { frozenEnergy, frozenBandwidth } = frozenBalances.reduce((accum, cur) => {
386
+ const amount = new BigNumber(cur?.amount ?? 0);
387
+ if (cur.type === "ENERGY") {
388
+ accum.frozenEnergy = accum.frozenEnergy.plus(amount);
388
389
  }
389
- const delegatedFrozenBandwidth = get(acc, "delegated_frozenV2_balance_for_bandwidth", undefined);
390
- const delegatedFrozenEnergy = get(acc, "account_resource.delegated_frozenV2_balance_for_energy", undefined);
391
- const frozenBalances = get(acc, "frozenV2", undefined);
392
- const legacyFrozenBandwidth = get(acc, "frozen[0]", undefined);
393
- const legacyFrozenEnergy = get(acc, "account_resource.frozen_balance_for_energy", undefined);
394
- const legacyFrozen = {
395
- bandwidth: legacyFrozenBandwidth
396
- ? {
397
- amount: new BigNumber(legacyFrozenBandwidth.frozen_balance),
398
- expiredAt: new Date(legacyFrozenBandwidth.expire_time),
399
- }
400
- : undefined,
401
- energy: legacyFrozenEnergy
402
- ? {
403
- amount: new BigNumber(legacyFrozenEnergy.frozen_balance),
404
- expiredAt: new Date(legacyFrozenEnergy.expire_time),
405
- }
406
- : undefined,
407
- };
408
- const { frozenEnergy, frozenBandwidth } = frozenBalances.reduce((accum, cur) => {
409
- var _a;
410
- const amount = new BigNumber((_a = cur === null || cur === void 0 ? void 0 : cur.amount) !== null && _a !== void 0 ? _a : 0);
411
- if (cur.type === "ENERGY") {
412
- accum.frozenEnergy = accum.frozenEnergy.plus(amount);
390
+ else if (cur.type === undefined) {
391
+ accum.frozenBandwidth = accum.frozenBandwidth.plus(amount);
392
+ }
393
+ return accum;
394
+ }, {
395
+ frozenEnergy: new BigNumber(0),
396
+ frozenBandwidth: new BigNumber(0),
397
+ });
398
+ const unFrozenBalances = get(acc, "unfrozenV2", undefined);
399
+ const unFrozen = unFrozenBalances
400
+ ? unFrozenBalances.reduce((accum, cur) => {
401
+ if (cur && cur.type === "ENERGY") {
402
+ accum.energy.push({
403
+ amount: new BigNumber(cur.unfreeze_amount),
404
+ expireTime: new Date(cur.unfreeze_expire_time),
405
+ });
413
406
  }
414
- else if (cur.type === undefined) {
415
- accum.frozenBandwidth = accum.frozenBandwidth.plus(amount);
407
+ else if (cur) {
408
+ accum.bandwidth.push({
409
+ amount: new BigNumber(cur.unfreeze_amount),
410
+ expireTime: new Date(cur.unfreeze_expire_time),
411
+ });
416
412
  }
417
413
  return accum;
418
- }, {
419
- frozenEnergy: new BigNumber(0),
420
- frozenBandwidth: new BigNumber(0),
421
- });
422
- const unFrozenBalances = get(acc, "unfrozenV2", undefined);
423
- const unFrozen = unFrozenBalances
424
- ? unFrozenBalances.reduce((accum, cur) => {
425
- if (cur && cur.type === "ENERGY") {
426
- accum.energy.push({
427
- amount: new BigNumber(cur.unfreeze_amount),
428
- expireTime: new Date(cur.unfreeze_expire_time),
429
- });
430
- }
431
- else if (cur) {
432
- accum.bandwidth.push({
433
- amount: new BigNumber(cur.unfreeze_amount),
434
- expireTime: new Date(cur.unfreeze_expire_time),
435
- });
436
- }
437
- return accum;
438
- }, { bandwidth: [], energy: [] })
439
- : { bandwidth: [], energy: [] };
440
- const encodedAddress = encode58Check(acc.address);
441
- const tronNetworkInfo = yield getTronAccountNetwork(encodedAddress);
442
- const unwithdrawnReward = yield getUnwithdrawnReward(encodedAddress);
443
- const energy = tronNetworkInfo.energyLimit.minus(tronNetworkInfo.energyUsed);
444
- const bandwidth = extractBandwidthInfo(tronNetworkInfo);
445
- const frozen = {
446
- bandwidth: frozenBandwidth.isGreaterThan(0)
447
- ? {
448
- amount: frozenBandwidth,
449
- }
450
- : undefined,
451
- energy: frozenEnergy.isGreaterThan(0)
452
- ? {
453
- amount: frozenEnergy,
454
- }
455
- : undefined,
456
- };
457
- const delegatedFrozen = {
458
- bandwidth: delegatedFrozenBandwidth
459
- ? {
460
- amount: new BigNumber(delegatedFrozenBandwidth),
461
- }
462
- : undefined,
463
- energy: delegatedFrozenEnergy
464
- ? {
465
- amount: new BigNumber(delegatedFrozenEnergy),
466
- }
467
- : undefined,
468
- };
469
- const tronPower = new BigNumber(get(frozen, "bandwidth.amount", 0))
470
- .plus(get(frozen, "energy.amount", 0))
471
- .plus(get(delegatedFrozen, "bandwidth.amount", 0))
472
- .plus(get(delegatedFrozen, "energy.amount", 0))
473
- .plus(get(legacyFrozen, "energy.amount", 0))
474
- .plus(get(legacyFrozen, "bandwidth.amount", 0))
475
- .dividedBy(1000000)
476
- .integerValue(BigNumber.ROUND_FLOOR)
477
- .toNumber();
478
- const votes = get(acc, "votes", []).map((v) => ({
479
- address: v.vote_address,
480
- voteCount: v.vote_count,
481
- }));
482
- const lastWithdrawnRewardDate = acc.latest_withdraw_time
483
- ? new Date(acc.latest_withdraw_time)
484
- : undefined;
485
- // TODO: rely on the account object when trongrid will provide this info.
486
- const getLastVotedDate = (txs) => {
487
- const lastOp = txs.find(({ type }) => type === "VoteWitnessContract");
488
- return lastOp ? lastOp.date : null;
489
- };
490
- const lastVotedDate = txs ? getLastVotedDate(txs) : undefined;
491
- return {
492
- energy,
493
- bandwidth,
494
- frozen,
495
- unFrozen,
496
- delegatedFrozen,
497
- legacyFrozen,
498
- votes,
499
- tronPower,
500
- unwithdrawnReward,
501
- lastWithdrawnRewardDate,
502
- lastVotedDate,
503
- cacheTransactionInfoById,
504
- };
505
- });
414
+ }, { bandwidth: [], energy: [] })
415
+ : { bandwidth: [], energy: [] };
416
+ const encodedAddress = encode58Check(acc.address);
417
+ const tronNetworkInfo = await getTronAccountNetwork(encodedAddress);
418
+ const unwithdrawnReward = await getUnwithdrawnReward(encodedAddress);
419
+ const energy = tronNetworkInfo.energyLimit.minus(tronNetworkInfo.energyUsed);
420
+ const bandwidth = extractBandwidthInfo(tronNetworkInfo);
421
+ const frozen = {
422
+ bandwidth: frozenBandwidth.isGreaterThan(0)
423
+ ? {
424
+ amount: frozenBandwidth,
425
+ }
426
+ : undefined,
427
+ energy: frozenEnergy.isGreaterThan(0)
428
+ ? {
429
+ amount: frozenEnergy,
430
+ }
431
+ : undefined,
432
+ };
433
+ const delegatedFrozen = {
434
+ bandwidth: delegatedFrozenBandwidth
435
+ ? {
436
+ amount: new BigNumber(delegatedFrozenBandwidth),
437
+ }
438
+ : undefined,
439
+ energy: delegatedFrozenEnergy
440
+ ? {
441
+ amount: new BigNumber(delegatedFrozenEnergy),
442
+ }
443
+ : undefined,
444
+ };
445
+ const tronPower = new BigNumber(get(frozen, "bandwidth.amount", 0))
446
+ .plus(get(frozen, "energy.amount", 0))
447
+ .plus(get(delegatedFrozen, "bandwidth.amount", 0))
448
+ .plus(get(delegatedFrozen, "energy.amount", 0))
449
+ .plus(get(legacyFrozen, "energy.amount", 0))
450
+ .plus(get(legacyFrozen, "bandwidth.amount", 0))
451
+ .dividedBy(1000000)
452
+ .integerValue(BigNumber.ROUND_FLOOR)
453
+ .toNumber();
454
+ const votes = get(acc, "votes", []).map((v) => ({
455
+ address: v.vote_address,
456
+ voteCount: v.vote_count,
457
+ }));
458
+ const lastWithdrawnRewardDate = acc.latest_withdraw_time
459
+ ? new Date(acc.latest_withdraw_time)
460
+ : undefined;
461
+ // TODO: rely on the account object when trongrid will provide this info.
462
+ const getLastVotedDate = (txs) => {
463
+ const lastOp = txs.find(({ type }) => type === "VoteWitnessContract");
464
+ return lastOp ? lastOp.date : null;
465
+ };
466
+ const lastVotedDate = txs ? getLastVotedDate(txs) : undefined;
467
+ return {
468
+ energy,
469
+ bandwidth,
470
+ frozen,
471
+ unFrozen,
472
+ delegatedFrozen,
473
+ legacyFrozen,
474
+ votes,
475
+ tronPower,
476
+ unwithdrawnReward,
477
+ lastWithdrawnRewardDate,
478
+ lastVotedDate,
479
+ cacheTransactionInfoById,
480
+ };
506
481
  }
507
- export const getUnwithdrawnReward = (addr) => __awaiter(void 0, void 0, void 0, function* () {
482
+ export const getUnwithdrawnReward = async (addr) => {
508
483
  try {
509
- const { reward = 0 } = yield fetch(`/wallet/getReward?address=${encodeURIComponent(decode58Check(addr))}`);
484
+ const { reward = 0 } = await fetch(`/wallet/getReward?address=${encodeURIComponent(decode58Check(addr))}`);
510
485
  return new BigNumber(reward);
511
486
  }
512
487
  catch (e) {
513
488
  return Promise.resolve(new BigNumber(0));
514
489
  }
515
- });
516
- export const claimRewardTronTransaction = (account) => __awaiter(void 0, void 0, void 0, function* () {
490
+ };
491
+ export const claimRewardTronTransaction = async (account) => {
517
492
  const url = `/wallet/withdrawbalance`;
518
493
  const data = {
519
494
  owner_address: decode58Check(account.freshAddress),
520
495
  };
521
- const result = yield post(url, data);
496
+ const result = await post(url, data);
522
497
  return result;
523
- });
498
+ };
524
499
  //# sourceMappingURL=index.js.map