@layerzerolabs/tron-utilities 3.0.15 → 3.0.17

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.
package/dist/index.d.ts CHANGED
@@ -1,90 +1,289 @@
1
1
  import TronWeb, { TransactionResult, TransactionInfo } from 'tronweb';
2
2
  export { BlockTransaction, ChainParameter, ContractExecutionParams, Transaction, default as TronWeb } from 'tronweb';
3
3
 
4
+ /**
5
+ * Enum representing the types of transactions that can be performed on the Tron network.
6
+ */
4
7
  declare enum TronTransactionType {
5
8
  TRIGGER_SMART_CONTRACT = "TriggerSmartContract"
6
9
  }
10
+ /**
11
+ * Interface representing the overrides for a transaction.
12
+ */
7
13
  interface TransactionOverrides {
14
+ /**
15
+ * The gas limit for the transaction.
16
+ */
8
17
  gasLimit?: number;
18
+ /**
19
+ * The gas price for the transaction.
20
+ */
9
21
  gasPrice?: number;
22
+ /**
23
+ * The energy factor for the transaction.
24
+ */
10
25
  energyFactor?: number;
26
+ /**
27
+ * The value to be sent with the transaction.
28
+ */
11
29
  value?: number;
12
30
  }
31
+ /**
32
+ * Interface representing a partial Tron transaction.
33
+ */
13
34
  interface PartialTronTransaction {
35
+ /**
36
+ * Indicates whether the transaction is visible.
37
+ */
14
38
  visible: boolean;
39
+ /**
40
+ * The transaction ID.
41
+ */
15
42
  txID: string;
43
+ /**
44
+ * The raw data in hexadecimal format.
45
+ */
16
46
  raw_data_hex: string;
47
+ /**
48
+ * The raw data of the transaction.
49
+ * @see {@link PartialTronTransactionContract}
50
+ */
17
51
  raw_data: {
18
52
  contract: [PartialTronTransactionContract];
19
53
  };
20
54
  }
55
+ /**
56
+ * Interface representing a full Tron transaction.
57
+ */
21
58
  interface TronTransaction extends PartialTronTransaction {
59
+ /**
60
+ * The raw data of the transaction.
61
+ */
22
62
  raw_data: {
63
+ /**
64
+ * The contract details of the transaction.
65
+ * @see {@link FullTronTransactionContract}
66
+ */
23
67
  contract: [FullTronTransactionContract];
68
+ /**
69
+ * The reference block bytes.
70
+ */
24
71
  ref_block_bytes: string;
72
+ /**
73
+ * The reference block hash.
74
+ */
25
75
  ref_block_hash: string;
76
+ /**
77
+ * The expiration time of the transaction.
78
+ */
26
79
  expiration: number;
80
+ /**
81
+ * The fee limit for the transaction.
82
+ */
27
83
  fee_limit: number;
84
+ /**
85
+ * The timestamp of the transaction.
86
+ */
28
87
  timestamp: number;
29
88
  };
30
89
  }
90
+ /**
91
+ * Interface representing a signed Tron transaction.
92
+ */
31
93
  interface SignedTronTransaction extends TronTransaction {
94
+ /**
95
+ * The signatures of the transaction.
96
+ */
32
97
  signature: string[];
33
98
  }
99
+ /**
100
+ * Interface representing the parameter value of a partial Tron transaction.
101
+ */
34
102
  interface PartialTronTransactionParameterValue {
103
+ /**
104
+ * The data of the transaction.
105
+ */
35
106
  data: string;
107
+ /**
108
+ * The contract address.
109
+ */
36
110
  contract_address: string;
111
+ /**
112
+ * The owner address.
113
+ */
37
114
  owner_address: string;
38
115
  }
116
+ /**
117
+ * Interface representing the parameter value of a full Tron transaction.
118
+ */
39
119
  interface TronTransactionParameterValue extends PartialTronTransactionParameterValue {
120
+ /**
121
+ * The token ID.
122
+ */
40
123
  token_id?: number;
124
+ /**
125
+ * The call token value.
126
+ */
41
127
  call_token_value?: number;
128
+ /**
129
+ * The call value.
130
+ */
42
131
  call_value?: number;
43
132
  }
133
+ /**
134
+ * Interface representing the parameter of a Tron transaction.
135
+ * @template T - The type of the parameter value.
136
+ */
44
137
  interface TronTransactionParameter<T> {
138
+ /**
139
+ * The value of the parameter.
140
+ */
45
141
  value: T;
142
+ /**
143
+ * The type URL of the parameter.
144
+ */
46
145
  type_url: `type.googleapis.com/protocol.${TronTransactionType}`;
47
146
  }
147
+ /**
148
+ * Interface representing a Tron transaction contract.
149
+ * @template T - The type of the parameter value.
150
+ */
48
151
  interface TronTransactionContract<T> {
152
+ /**
153
+ * The parameter of the transaction contract.
154
+ */
49
155
  parameter: TronTransactionParameter<T>;
156
+ /**
157
+ * The type of the transaction contract.
158
+ */
50
159
  type: TronTransactionType;
160
+ /**
161
+ * The permission ID for the transaction contract.
162
+ */
51
163
  Permission_id?: number;
52
164
  }
165
+ /**
166
+ * Type representing a partial Tron transaction contract.
167
+ */
53
168
  type PartialTronTransactionContract = TronTransactionContract<PartialTronTransactionParameterValue>;
169
+ /**
170
+ * Type representing a full Tron transaction contract.
171
+ */
54
172
  type FullTronTransactionContract = TronTransactionContract<TronTransactionParameterValue>;
173
+ /**
174
+ * Interface representing the raw data of a Tron block header.
175
+ */
55
176
  interface TronBlockHeaderRawData {
177
+ /**
178
+ * The block number.
179
+ */
56
180
  number: number;
181
+ /**
182
+ * The transaction trie root.
183
+ */
57
184
  txTrieRoot: string;
185
+ /**
186
+ * The witness address.
187
+ */
58
188
  witness_address: string;
189
+ /**
190
+ * The parent hash.
191
+ */
59
192
  parentHash: string;
193
+ /**
194
+ * The timestamp of the block.
195
+ */
60
196
  timestamp: number;
61
197
  }
198
+ /**
199
+ * Interface representing a Tron block header.
200
+ */
62
201
  interface TronBlockHeader {
202
+ /**
203
+ * The raw data of the block header.
204
+ */
63
205
  raw_data: TronBlockHeaderRawData;
206
+ /**
207
+ * The witness signature.
208
+ */
64
209
  witness_signature: string;
65
210
  }
211
+ /**
212
+ * Interface representing Tron block data.
213
+ */
66
214
  interface TronBlockData {
215
+ /**
216
+ * The block ID.
217
+ */
67
218
  blockID: string;
219
+ /**
220
+ * The block header.
221
+ */
68
222
  block_header: TronBlockHeader;
69
223
  }
224
+ /**
225
+ * Interface representing a TronWeb error response (type 1).
226
+ */
70
227
  interface TronWebError1 {
228
+ /**
229
+ * The error code.
230
+ */
71
231
  code: string;
232
+ /**
233
+ * The error message.
234
+ */
72
235
  message: string;
236
+ /**
237
+ * The transaction ID.
238
+ */
73
239
  txid: string;
74
240
  }
241
+ /**
242
+ * Interface representing a TronWeb error response (type 2).
243
+ */
75
244
  interface TronWebError2 {
245
+ /**
246
+ * The error message.
247
+ */
76
248
  Error: string;
77
249
  }
250
+ /**
251
+ * Type representing a TronWeb error response.
252
+ */
78
253
  type TronWebErrorResponse = TronWebError1 | TronWebError2;
79
254
 
255
+ /**
256
+ * Type representing provider settings.
257
+ * It can be either a string representing the URL or an object containing the URL and an optional API key.
258
+ */
80
259
  type ProviderSetting = {
260
+ /**
261
+ * The URL of the provider.
262
+ */
81
263
  url: string;
264
+ /**
265
+ * The API key for the provider (optional).
266
+ */
82
267
  apiKey?: string;
83
268
  } | string;
269
+ /**
270
+ * Creates a TronWeb instance.
271
+ *
272
+ * @param {{ rpcSetting: ProviderSetting; privateKey: string } | TronWeb} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.
273
+ * @returns {TronWeb} The created TronWeb instance.
274
+ */
84
275
  declare function createTronWeb(signer: {
85
276
  rpcSetting: ProviderSetting;
86
277
  privateKey: string;
87
278
  } | TronWeb): TronWeb;
279
+ /**
280
+ * Signs and sends a Tron transaction.
281
+ *
282
+ * @param {object} txn - The transaction object containing data, to, and transaction overrides.
283
+ * @param {object} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.
284
+ * @param {number} [permissionId] - The permission ID for multi-sig.
285
+ * @returns {Promise<object>} A promise that resolves to an object containing txId, result, and wait function.
286
+ */
88
287
  declare function signAndSendTronTransaction(txn: {
89
288
  data: string;
90
289
  to: string;
@@ -96,11 +295,28 @@ declare function signAndSendTronTransaction(txn: {
96
295
  result: TransactionResult;
97
296
  wait: () => Promise<TransactionInfo>;
98
297
  }>;
298
+ /**
299
+ * Sends a signed Tron transaction.
300
+ *
301
+ * @param {SignedTronTransaction} signedTxn - The signed Tron transaction.
302
+ * @param {TronWeb} client - The TronWeb client.
303
+ * @returns {Promise<object>} A promise that resolves to an object containing txId, result, and wait function.
304
+ * @throws {Error} If the transaction broadcast fails.
305
+ */
99
306
  declare function sendTronTransaction(singedTxn: SignedTronTransaction, client: TronWeb): Promise<{
100
307
  txId: string;
101
308
  result: TransactionResult;
102
309
  wait: () => Promise<TransactionInfo>;
103
310
  }>;
311
+ /**
312
+ * Signs a Tron transaction.
313
+ *
314
+ * @param {object} txn - The transaction object containing data, to, and transaction overrides.
315
+ * @param {object} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.
316
+ * @param {number} [permissionId] - The permission ID for multi-sig.
317
+ * @returns {Promise<SignedTronTransaction>} A promise that resolves to the signed Tron transaction.
318
+ * @throws {Error} If the private key is invalid.
319
+ */
104
320
  declare function signTronTx(txn: {
105
321
  data: string;
106
322
  to: string;
@@ -108,15 +324,58 @@ declare function signTronTx(txn: {
108
324
  rpcSetting: ProviderSetting;
109
325
  privateKey: string;
110
326
  } | TronWeb, permissionId?: number): Promise<SignedTronTransaction>;
327
+ /**
328
+ * Fills in the missing fields of a Tron transaction.
329
+ *
330
+ * @param {TronWeb} signer - The TronWeb client.
331
+ * @param {PartialTronTransaction} txn - The partial Tron transaction.
332
+ * @param {TransactionOverrides} [overrides={}] - The transaction overrides.
333
+ * @returns {Promise<TronTransaction>} A promise that resolves to the full Tron transaction.
334
+ */
111
335
  declare function fullFillTxn(signer: TronWeb, txn: PartialTronTransaction, overrides?: TransactionOverrides): Promise<TronTransaction>;
336
+ /**
337
+ * Checks the result of a Tron transaction.
338
+ *
339
+ * @param {TronWeb} tronWeb - The TronWeb client.
340
+ * @param {string} txId - The transaction ID.
341
+ * @returns {Promise<TransactionInfo>} A promise that resolves to the transaction info.
342
+ * @throws {Error} If the transaction fails or times out.
343
+ */
112
344
  declare function checkResult(tronWeb: TronWeb, txId: string): Promise<TransactionInfo>;
113
345
 
346
+ /**
347
+ * Interface representing a provider conversion strategy.
348
+ */
114
349
  interface ProviderConversionStrategy {
350
+ /**
351
+ * Converts a URL to its REST endpoint equivalent.
352
+ *
353
+ * @param {string} url - The URL to convert.
354
+ * @returns {string} The converted REST endpoint URL.
355
+ */
115
356
  asREST(url: string): string;
357
+ /**
358
+ * Converts a URL to its JSON-RPC endpoint equivalent.
359
+ *
360
+ * @param {string} url - The URL to convert.
361
+ * @returns {string} The converted JSON-RPC endpoint URL.
362
+ */
116
363
  asJSONRPC(url: string): string;
117
364
  }
365
+ /**
366
+ * Class representing a factory for creating provider conversion strategies.
367
+ */
118
368
  declare class StrategyFactory {
369
+ /**
370
+ * A map of URL patterns to provider conversion strategies.
371
+ */
119
372
  static strategies: Map<RegExp, ProviderConversionStrategy>;
373
+ /**
374
+ * Gets the appropriate provider conversion strategy for a given URL.
375
+ *
376
+ * @param {string} url - The URL to get the conversion strategy for.
377
+ * @returns {ProviderConversionStrategy} The provider conversion strategy.
378
+ */
120
379
  static get(url: string): ProviderConversionStrategy;
121
380
  }
122
381
 
package/dist/index.mjs CHANGED
@@ -12,11 +12,30 @@ var MINUTE = 60 * SECOND;
12
12
  var HOUR = 60 * MINUTE;
13
13
  var DAY = 24 * HOUR;
14
14
  var Time = {
15
+ /**
16
+ * Millisecond unit.
17
+ */
15
18
  MILLISECOND,
19
+ /**
20
+ * Second unit.
21
+ */
16
22
  SECOND,
23
+ /**
24
+ * Minute unit.
25
+ */
17
26
  MINUTE,
27
+ /**
28
+ * Hour unit.
29
+ */
18
30
  HOUR,
31
+ /**
32
+ * Day unit.
33
+ */
19
34
  DAY,
35
+ /**
36
+ * Gets the current time in milliseconds since the Unix epoch.
37
+ * @returns {number} The current time in milliseconds.
38
+ */
20
39
  get NOW() {
21
40
  return Date.now();
22
41
  }
@@ -24,33 +43,75 @@ var Time = {
24
43
 
25
44
  // src/url.ts
26
45
  var DefaultProviderConversionStrategy = class {
46
+ /**
47
+ * Converts a URL to its REST endpoint equivalent.
48
+ *
49
+ * @param {string} url - The URL to convert.
50
+ * @returns {string} The converted REST endpoint URL.
51
+ */
27
52
  asREST(url) {
28
53
  return url.replace(/\/jsonrpc$/, "");
29
54
  }
55
+ /**
56
+ * Converts a URL to its JSON-RPC endpoint equivalent.
57
+ *
58
+ * @param {string} url - The URL to convert.
59
+ * @returns {string} The converted JSON-RPC endpoint URL.
60
+ */
30
61
  asJSONRPC(url) {
31
62
  return url.trim().replace(/\/?$/, "/jsonrpc");
32
63
  }
33
64
  };
34
65
  var AnkrProviderConversionStrategy = class {
66
+ /**
67
+ * Converts a URL to its REST endpoint equivalent.
68
+ *
69
+ * @param {string} url - The URL to convert.
70
+ * @returns {string} The converted REST endpoint URL.
71
+ */
35
72
  asREST(url) {
36
73
  if (/tron\/[0-9a-fA-F]{10,}/.test(url)) {
37
74
  return url.replace(/\/tron_jsonrpc$/, "/premium-http/tron");
38
75
  }
39
76
  return url.replace(/\/tron_jsonrpc$/, "/http/tron");
40
77
  }
78
+ /**
79
+ * Converts a URL to its JSON-RPC endpoint equivalent.
80
+ *
81
+ * @param {string} url - The URL to convert.
82
+ * @returns {string} The converted JSON-RPC endpoint URL.
83
+ */
41
84
  asJSONRPC(url) {
42
85
  return url.trim().replace(/\/(premium-http|http)\/tron/, "/tron_jsonrpc");
43
86
  }
44
87
  };
45
88
  var QuiknodeProviderConversionStrategy = class {
89
+ /**
90
+ * Converts a URL to its REST endpoint equivalent.
91
+ *
92
+ * @param {string} url - The URL to convert.
93
+ * @returns {string} The converted REST endpoint URL.
94
+ */
46
95
  asREST(url) {
47
96
  return url.replace(/\/jsonrpc$/, "");
48
97
  }
98
+ /**
99
+ * Converts a URL to its JSON-RPC endpoint equivalent.
100
+ *
101
+ * @param {string} url - The URL to convert.
102
+ * @returns {string} The converted JSON-RPC endpoint URL.
103
+ */
49
104
  asJSONRPC(url) {
50
105
  return url.trim().replace(/\/?$/, "/jsonrpc");
51
106
  }
52
107
  };
53
108
  var _StrategyFactory = class _StrategyFactory {
109
+ /**
110
+ * Gets the appropriate provider conversion strategy for a given URL.
111
+ *
112
+ * @param {string} url - The URL to get the conversion strategy for.
113
+ * @returns {ProviderConversionStrategy} The provider conversion strategy.
114
+ */
54
115
  static get(url) {
55
116
  for (const [pattern, strategy] of this.strategies) {
56
117
  if (pattern.test(url)) {
@@ -60,6 +121,9 @@ var _StrategyFactory = class _StrategyFactory {
60
121
  return new DefaultProviderConversionStrategy();
61
122
  }
62
123
  };
124
+ /**
125
+ * A map of URL patterns to provider conversion strategies.
126
+ */
63
127
  _StrategyFactory.strategies = /* @__PURE__ */ new Map();
64
128
  _StrategyFactory.strategies.set(/api.trongrid.io/, new DefaultProviderConversionStrategy());
65
129
  _StrategyFactory.strategies.set(/ankr.com/, new AnkrProviderConversionStrategy());
@@ -158,8 +222,7 @@ async function fullFillTxn(signer, txn, overrides = {}) {
158
222
  });
159
223
  async function getGasPrice() {
160
224
  const { time, value } = gasPriceCache;
161
- if (time > Time.NOW - 15 * Time.SECOND && value != "")
162
- return value;
225
+ if (time > Time.NOW - 15 * Time.SECOND && value != "") return value;
163
226
  const newGaspPrice = await etherProvider.getGasPrice().then((x) => x.toString());
164
227
  gasPriceCache = { time: Time.NOW, value: newGaspPrice };
165
228
  return newGaspPrice;
@@ -177,8 +240,7 @@ async function fullFillTxn(signer, txn, overrides = {}) {
177
240
  async function getEnergyFactor(raw) {
178
241
  const addr = raw.raw_data.contract[0].parameter.value.contract_address;
179
242
  const cached = energyFactorsCache.get(addr);
180
- if (cached && cached.time > Time.NOW - 10 * Time.MINUTE)
181
- return cached.value;
243
+ if (cached && cached.time > Time.NOW - 10 * Time.MINUTE) return cached.value;
182
244
  const MAX_ENERGY_FACTOR = 1.2;
183
245
  const response = await signer.fullNode.request(
184
246
  "wallet/getcontractinfo",
@@ -260,5 +322,5 @@ async function checkResult(tronWeb, txId) {
260
322
  }
261
323
 
262
324
  export { StrategyFactory, TronTransactionType, checkResult, createTronWeb, fullFillTxn, sendTronTransaction, signAndSendTronTransaction, signTronTx };
263
- //# sourceMappingURL=out.js.map
325
+ //# sourceMappingURL=index.mjs.map
264
326
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tron.ts","../src/time.ts","../src/url.ts"],"names":["TronTransactionType","overrides","txId","output"],"mappings":";AAAA,SAAS,cAAc;AACvB,OAAO,aAAa;AAEpB,SAAS,WAAW,aAAa;;;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C;AAAA,IACJ;AAAA,EACJ;AACA,QAAM,KAAK,OAAO,MAAM,YAAY,WAAW,EAAE;AACjD,KAAG,OAAO,OAAO,MAAM,YAAY,WAAW,EAAE,EAAE,QAAQ,OAAO,EAAE;AACnE,KAAG,eAAe,OAAO,MAAM,YAAY,iBAAiB,EAAE,EAAE,YAAY;AAE5E,SAAO;AACX;AAEA,eAAsB,YAAY,SAAkB,MAAwC;AACxF,QAAM,YAAY,KAAK,IAAI;AAC3B,QAAM,cAAc,MAAO,KAAK;AAEhC,QAAM,OAAO,eAAgBC,OAAwC;AACjE,QAAI,QAAQ;AACZ,WAAO,UAAU,IAAI;AACjB,YAAMC,UAAS,MAAM,QAAQ,IAAI,mBAAmBD,KAAI;AACxD,UAAI,OAAO,KAAKC,OAAM,EAAE,SAAS,GAAG;AAChC,eAAOA;AAAA,MACX;AAGA,UAAI,KAAK,IAAI,IAAI,YAAY,aAAa;AACtC,cAAM,IAAI,MAAM,iDAAiD;AAAA,MACrE;AAGA,YAAM,MAAM,IAAI;AAAA,IACpB;AACA,UAAM,IAAI,MAAM,2CAA2CD,KAAI,EAAE;AAAA,EACrE;AAEA,QAAM,SAAS,MAAM,KAAK,IAAI;AAE9B,MAAI,OAAO,WAAW,UAAa,OAAO,WAAW,UAAU;AAC3D,UAAM,IAAI,MAAM,QAAQ,OAAO,OAAO,cAAc,EAAE,CAAC;AAAA,EAC3D;AAEA,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,gBAAgB,GAAG;AACjE,UAAM,IAAI,MAAM,wBAAwB,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,EAC3E;AAEA,SAAO;AACX","sourcesContent":["import { ethers } from 'ethers'\nimport TronWeb from 'tronweb'\n\nimport { getLogger, sleep } from '@layerzerolabs/lz-utilities'\n\nimport { Time } from './time'\nimport { StrategyFactory } from './url'\n\nimport type {\n BlockTransaction,\n ChainParameter,\n ContractExecutionParams,\n ContractInfo,\n Transaction,\n TransactionInfo,\n TransactionResult,\n} from 'tronweb'\n\nexport enum TronTransactionType {\n TRIGGER_SMART_CONTRACT = 'TriggerSmartContract',\n}\n\nexport interface TransactionOverrides {\n gasLimit?: number\n gasPrice?: number\n energyFactor?: number\n value?: number\n}\n\nexport interface PartialTronTransaction {\n visible: boolean\n txID: string\n raw_data_hex: string\n raw_data: {\n contract: [PartialTronTransactionContract]\n }\n}\n\nexport interface TronTransaction extends PartialTronTransaction {\n raw_data: {\n contract: [FullTronTransactionContract]\n ref_block_bytes: string\n ref_block_hash: string\n expiration: number\n fee_limit: number\n timestamp: number\n }\n}\n\nexport interface SignedTronTransaction extends TronTransaction {\n signature: string[]\n}\n\ninterface PartialTronTransactionParameterValue {\n data: string\n contract_address: string\n owner_address: string\n}\n\ninterface TronTransactionParameterValue extends PartialTronTransactionParameterValue {\n token_id?: number\n call_token_value?: number\n call_value?: number\n}\n\ninterface TronTransactionParameter<T> {\n value: T\n type_url: `type.googleapis.com/protocol.${TronTransactionType}`\n}\n\ninterface TronTransactionContract<T> {\n parameter: TronTransactionParameter<T>\n type: TronTransactionType\n Permission_id?: number\n}\n\ntype PartialTronTransactionContract = TronTransactionContract<PartialTronTransactionParameterValue>\ntype FullTronTransactionContract = TronTransactionContract<TronTransactionParameterValue>\n\ninterface TronBlockHeaderRawData {\n number: number\n txTrieRoot: string\n witness_address: string\n parentHash: string\n timestamp: number\n}\n\ninterface TronBlockHeader {\n raw_data: TronBlockHeaderRawData\n witness_signature: string\n}\n\nexport interface TronBlockData {\n blockID: string\n block_header: TronBlockHeader\n}\n\ninterface TronWebError1 {\n code: string\n message: string\n txid: string\n}\n\ninterface TronWebError2 {\n Error: string\n}\ntype TronWebErrorResponse = TronWebError1 | TronWebError2\n\nexport {\n TronWeb,\n BlockTransaction,\n ContractExecutionParams,\n ChainParameter,\n Transaction,\n TronWebError1,\n TronWebError2,\n TronWebErrorResponse,\n}\n\nconst logger = getLogger()\n\nexport type ProviderSetting =\n | {\n url: string\n apiKey?: string\n }\n | string\n\nexport function createTronWeb(signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb): TronWeb {\n if (!(signer instanceof TronWeb)) {\n const fullHostUrl = typeof signer.rpcSetting === 'string' ? signer.rpcSetting : signer.rpcSetting.url\n const client = new TronWeb({\n fullHost: StrategyFactory.get(fullHostUrl).asREST(fullHostUrl),\n headers: {\n 'TRON-PRO-API-KEY': typeof signer.rpcSetting === 'string' ? '' : signer.rpcSetting.apiKey ?? '',\n },\n privateKey: signer.privateKey.replace(/^0x/, ''),\n })\n return client\n }\n return signer\n}\n\nexport async function signAndSendTronTransaction(\n txn: {\n data: string\n to: string\n } & TransactionOverrides,\n signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb,\n permissionId?: number // for multi-sig\n): Promise<{ txId: string; result: TransactionResult; wait: () => Promise<TransactionInfo> }> {\n const signedTxn = await signTronTx(txn, signer, permissionId)\n const client = createTronWeb(signer)\n return sendTronTransaction(signedTxn, client)\n}\n\nexport async function sendTronTransaction(\n singedTxn: SignedTronTransaction,\n client: TronWeb\n): Promise<{ txId: string; result: TransactionResult; wait: () => Promise<TransactionInfo> }> {\n // reference: https://developers.tron.network/reference/json-rpc-api-overview\n // JSON-RPC interface is not fully supported by the TRON network.\n // Furthermore, The JSON-RPC service needs to be enabled and set the port in the node configuration\n // file. If not configured, the service is disable by default.\n // broadcast signedTransaction\n const broadcastResponse = await client.trx.sendRawTransaction(singedTxn)\n if (broadcastResponse.code !== undefined) {\n const err = {\n error: broadcastResponse.code,\n message: TronWeb.toUtf8(broadcastResponse.message ?? ''),\n }\n throw new Error(JSON.stringify(err, null, 2))\n }\n\n return {\n txId: singedTxn.txID,\n result: broadcastResponse,\n wait: async (): Promise<TransactionInfo> => {\n return checkResult(client, singedTxn.txID)\n },\n }\n}\n\nexport async function signTronTx(\n txn: {\n data: string\n to: string\n } & TransactionOverrides,\n _signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb,\n permissionId?: number // for multi-sig\n): Promise<SignedTronTransaction> {\n const signer: TronWeb = createTronWeb(_signer)\n\n // privateKey = privateKey.replace(/^0x/, '') // remove the 0x prefix\n // private key to address\n // const from = TronWeb.address.fromPrivateKey(privateKey)\n if (typeof signer.defaultAddress.hex !== 'string') {\n throw new Error(`signer.defaultAddress.hex is not a valid hex string`)\n }\n\n const partialTxn: PartialTronTransaction = {\n visible: false,\n txID: '',\n raw_data_hex: '',\n raw_data: {\n contract: [\n {\n parameter: {\n value: {\n data: txn.data.replace(/^0x/, ''),\n contract_address: TronWeb.address.toHex(txn.to),\n owner_address: signer.defaultAddress.hex,\n },\n type_url: `type.googleapis.com/protocol.${TronTransactionType.TRIGGER_SMART_CONTRACT}`,\n },\n type: TronTransactionType.TRIGGER_SMART_CONTRACT,\n Permission_id: permissionId,\n },\n ],\n },\n }\n\n const fullTxn = await fullFillTxn(signer, partialTxn, {\n gasLimit: txn.gasLimit,\n gasPrice: txn.gasPrice,\n energyFactor: txn.energyFactor,\n value: txn.value,\n })\n\n // sign transaction\n const signedTransaction = await signer.trx.sign(fullTxn)\n if (signedTransaction.signature === undefined) {\n throw new Error('Invalid private key provided')\n }\n return signedTransaction as SignedTronTransaction\n}\n\nlet gasPriceCache: { time: number; value: string } = { time: 0, value: '' }\nconst energyFactorsCache = new Map<string, { time: number; value: number }>()\n\nexport async function fullFillTxn(\n signer: TronWeb,\n txn: PartialTronTransaction,\n overrides: TransactionOverrides = {}\n): Promise<TronTransaction> {\n const apiKey = signer.fullNode.headers['TRON-PRO-API-KEY']\n const etherProvider = new ethers.providers.StaticJsonRpcProvider({\n url: StrategyFactory.get(signer.fullNode.host).asJSONRPC(signer.fullNode.host),\n headers: {\n ...(typeof apiKey !== 'undefined' ? { 'TRON-PRO-API-KEY': apiKey } : {}),\n },\n })\n\n // cache the gasPrice with a 15sec TTL\n async function getGasPrice(): Promise<string> {\n const { time, value } = gasPriceCache\n if (time > Time.NOW - 15 * Time.SECOND && value != '') return value\n const newGaspPrice = await etherProvider.getGasPrice().then((x) => x.toString())\n gasPriceCache = { time: Time.NOW, value: newGaspPrice }\n return newGaspPrice\n }\n\n async function getGasLimit(raw: PartialTronTransaction): Promise<number> {\n const gasLimit = await etherProvider.estimateGas({\n to: raw.raw_data.contract[0].parameter.value.contract_address.replace(/^41/, '0x'), // need to slice off the \"41\" prefix that Tron appends to addresses\n data: '0x' + raw.raw_data.contract[0].parameter.value.data,\n from: raw.raw_data.contract[0].parameter.value.owner_address.replace(/^41/, '0x'),\n value: overrides.value ?? 0,\n })\n return gasLimit.toNumber()\n }\n\n // cache the energy_factor with a 10min TTL, energy factors should be updated by Tron every 6h\n async function getEnergyFactor(raw: PartialTronTransaction): Promise<number> {\n /* eslint-disable @typescript-eslint/no-unsafe-assignment */\n const addr = raw.raw_data.contract[0].parameter.value.contract_address\n const cached = energyFactorsCache.get(addr)\n if (cached && cached.time > Time.NOW - 10 * Time.MINUTE) return cached.value\n const MAX_ENERGY_FACTOR = 1.2\n // refers: https://developers.tron.network/reference/getcontractinfo\n const response = await signer.fullNode.request(\n 'wallet/getcontractinfo',\n { value: addr, visible: false },\n 'post'\n )\n const contractInfo: ContractInfo = response as ContractInfo\n const energy_factor = contractInfo.contract_state.energy_factor ?? MAX_ENERGY_FACTOR\n energyFactorsCache.set(addr, { time: Time.NOW, value: energy_factor })\n return energy_factor\n /* eslint-enable @typescript-eslint/no-unsafe-assignment */\n }\n\n async function getFeeLimit(raw: PartialTronTransaction, overrides: TransactionOverrides = {}): Promise<number> {\n // https://developers.tron.network/docs/set-feelimit#how-to-determine-the-feelimit-parameter\n // https://developers.tron.network/reference/getcontractinfo, get energy_factor\n // https://developers.tron.network/docs/resource-model#dynamic-energy-model, max factor\n // Tight FeeLimit of contract transaction = estimated basic energy consumption * (1 + energy_factor) * EnergyPrice\n // Loose FeeLimit of contract transaction = estimated basic energy consumption * (1 + max_energy_factor) * EnergyPrice\n const MAX_FEE_LIMIT = 15000000000\n const energy_factor = overrides.energyFactor ?? (await getEnergyFactor(raw))\n const gasLimit = overrides.gasLimit ?? (await getGasLimit(raw))\n const energyPrice = overrides.gasPrice ?? Number(await getGasPrice())\n const factor = 1 + energy_factor\n const feeLimit = gasLimit * factor * energyPrice\n const feeLimit_adjusted = Math.ceil(feeLimit) * 1.2 // based on reading other parts of the code, we add a 20% cushion on fee limits\n return Math.floor(Math.min(feeLimit_adjusted, MAX_FEE_LIMIT))\n }\n\n const metadata = (await signer.fullNode.request('wallet/getblock', { detail: false }, 'post')) as TronBlockData\n const ref_block_bytes = metadata.block_header.raw_data.number.toString(16).slice(-4).padStart(4, '0')\n const ref_block_hash = metadata.blockID.slice(16, 32)\n const expiration = metadata.block_header.raw_data.timestamp + 60 * 1000\n const { timestamp } = metadata.block_header.raw_data\n\n const tx: TronTransaction = {\n ...txn,\n raw_data: {\n contract: [\n {\n parameter: {\n value: {\n ...txn.raw_data.contract[0].parameter.value,\n call_value: overrides.value ?? 0,\n },\n type_url: txn.raw_data.contract[0].parameter.type_url,\n },\n type: txn.raw_data.contract[0].type,\n },\n ],\n ref_block_bytes,\n ref_block_hash,\n expiration,\n fee_limit: await getFeeLimit(txn, overrides),\n timestamp,\n },\n }\n const pb = signer.utils.transaction.txJsonToPb(tx)\n tx.txID = signer.utils.transaction.txPbToTxID(pb).replace(/^0x/, '')\n tx.raw_data_hex = signer.utils.transaction.txPbToRawDataHex(pb).toLowerCase()\n\n return tx\n}\n\nexport async function checkResult(tronWeb: TronWeb, txId: string): Promise<TransactionInfo> {\n const startTime = Date.now()\n const waitTimeout = 1000 * 60 * 5 // 5 minutes\n // TODO: get the block producer interval from the chain and sleep for that time\n const wait = async function (txId: string): Promise<TransactionInfo> {\n let tries = 0\n while (tries++ < 20) {\n const output = await tronWeb.trx.getTransactionInfo(txId)\n if (Object.keys(output).length > 0) {\n return output\n }\n\n // check if timeout\n if (Date.now() - startTime > waitTimeout) {\n throw new Error('Timeout waiting for transaction to be processed')\n }\n // wait 1 seconds for next check, mainnet block producer interval is 3 seconds,\n // but we need a small interval for the local network to speed up the test\n await sleep(1200)\n }\n throw new Error(`Failed to get transactionInfo for txId: ${txId}`)\n }\n\n const output = await wait(txId)\n\n if (output.result !== undefined && output.result === 'FAILED') {\n throw new Error(TronWeb.toUtf8(output.resMessage ?? ''))\n }\n\n if (!Object.prototype.hasOwnProperty.call(output, 'contractResult')) {\n throw new Error('Failed to execute: ' + JSON.stringify(output, null, 2))\n }\n\n return output\n}\n","// Base unit in milliseconds\nconst MILLISECOND = 1\nconst SECOND = 1000 * MILLISECOND\nconst MINUTE = 60 * SECOND\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\n\nexport const Time = {\n MILLISECOND,\n SECOND,\n MINUTE,\n HOUR,\n DAY,\n get NOW() {\n return Date.now()\n },\n} as const\n","export interface ProviderConversionStrategy {\n asREST(url: string): string\n asJSONRPC(url: string): string\n}\n\nclass DefaultProviderConversionStrategy implements ProviderConversionStrategy {\n asREST(url: string): string {\n return url.replace(/\\/jsonrpc$/, '')\n }\n\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/?$/, '/jsonrpc')\n }\n}\n\nclass AnkrProviderConversionStrategy implements ProviderConversionStrategy {\n asREST(url: string): string {\n if (/tron\\/[0-9a-fA-F]{10,}/.test(url)) {\n return url.replace(/\\/tron_jsonrpc$/, '/premium-http/tron')\n }\n\n return url.replace(/\\/tron_jsonrpc$/, '/http/tron')\n }\n\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/(premium-http|http)\\/tron/, '/tron_jsonrpc')\n }\n}\n\nclass QuiknodeProviderConversionStrategy implements ProviderConversionStrategy {\n asREST(url: string): string {\n return url.replace(/\\/jsonrpc$/, '')\n }\n\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/?$/, '/jsonrpc')\n }\n}\n\nexport class StrategyFactory {\n public static strategies = new Map<RegExp, ProviderConversionStrategy>()\n\n static {\n StrategyFactory.strategies.set(/api.trongrid.io/, new DefaultProviderConversionStrategy())\n StrategyFactory.strategies.set(/ankr.com/, new AnkrProviderConversionStrategy())\n StrategyFactory.strategies.set(/quiknode.pro/, new QuiknodeProviderConversionStrategy())\n }\n\n static get(url: string): ProviderConversionStrategy {\n for (const [pattern, strategy] of this.strategies) {\n if (pattern.test(url)) {\n return strategy\n }\n }\n return new DefaultProviderConversionStrategy()\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/time.ts","../src/url.ts","../src/tron.ts"],"names":["TronTransactionType","overrides","txId","output"],"mappings":";;;;;;;;AACA,IAAM,WAAc,GAAA,CAAA;AACpB,IAAM,SAAS,GAAO,GAAA,WAAA;AACtB,IAAM,SAAS,EAAK,GAAA,MAAA;AACpB,IAAM,OAAO,EAAK,GAAA,MAAA;AAClB,IAAM,MAAM,EAAK,GAAA,IAAA;AAKV,IAAM,IAAO,GAAA;AAAA;AAAA;AAAA;AAAA,EAIhB,WAAA;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA;AAAA;AAAA;AAAA;AAAA,EAKA,IAAA;AAAA;AAAA;AAAA;AAAA,EAKA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,GAAM,GAAA;AACN,IAAA,OAAO,KAAK,GAAI,EAAA;AAAA;AAExB,CAAA;;;ACnBA,IAAM,oCAAN,MAA8E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO1E,OAAO,GAAqB,EAAA;AACxB,IAAO,OAAA,GAAA,CAAI,OAAQ,CAAA,YAAA,EAAc,EAAE,CAAA;AAAA;AACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,UAAU,GAAqB,EAAA;AAC3B,IAAA,OAAO,GAAI,CAAA,IAAA,EAAO,CAAA,OAAA,CAAQ,QAAQ,UAAU,CAAA;AAAA;AAEpD,CAAA;AAKA,IAAM,iCAAN,MAA2E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOvE,OAAO,GAAqB,EAAA;AACxB,IAAI,IAAA,wBAAA,C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A;AAC3D,IAAA,MAAM,IAAI,KAAM,CAAA,OAAA,CAAQ,OAAO,MAAO,CAAA,UAAA,IAAc,EAAE,CAAC,CAAA;AAAA;AAG3D,EAAA,IAAI,CAAC,MAAO,CAAA,SAAA,CAAU,eAAe,IAAK,CAAA,MAAA,EAAQ,gBAAgB,CAAG,EAAA;AACjE,IAAM,MAAA,IAAI,MAAM,qBAAwB,GAAA,IAAA,CAAK,UAAU,MAAQ,EAAA,IAAA,EAAM,CAAC,CAAC,CAAA;AAAA;AAG3E,EAAO,OAAA,MAAA;AACX","file":"index.mjs","sourcesContent":["// Base unit in milliseconds\nconst MILLISECOND = 1\nconst SECOND = 1000 * MILLISECOND\nconst MINUTE = 60 * SECOND\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\n\n/**\n * Object representing various time units and the current time.\n */\nexport const Time = {\n /**\n * Millisecond unit.\n */\n MILLISECOND,\n\n /**\n * Second unit.\n */\n SECOND,\n\n /**\n * Minute unit.\n */\n MINUTE,\n\n /**\n * Hour unit.\n */\n HOUR,\n\n /**\n * Day unit.\n */\n DAY,\n\n /**\n * Gets the current time in milliseconds since the Unix epoch.\n * @returns {number} The current time in milliseconds.\n */\n get NOW() {\n return Date.now()\n },\n} as const\n","/**\n * Interface representing a provider conversion strategy.\n */\nexport interface ProviderConversionStrategy {\n /**\n * Converts a URL to its REST endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted REST endpoint URL.\n */\n asREST(url: string): string\n\n /**\n * Converts a URL to its JSON-RPC endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted JSON-RPC endpoint URL.\n */\n asJSONRPC(url: string): string\n}\n\n/**\n * Class representing the default provider conversion strategy.\n */\nclass DefaultProviderConversionStrategy implements ProviderConversionStrategy {\n /**\n * Converts a URL to its REST endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted REST endpoint URL.\n */\n asREST(url: string): string {\n return url.replace(/\\/jsonrpc$/, '')\n }\n\n /**\n * Converts a URL to its JSON-RPC endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted JSON-RPC endpoint URL.\n */\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/?$/, '/jsonrpc')\n }\n}\n\n/**\n * Class representing the Ankr provider conversion strategy.\n */\nclass AnkrProviderConversionStrategy implements ProviderConversionStrategy {\n /**\n * Converts a URL to its REST endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted REST endpoint URL.\n */\n asREST(url: string): string {\n if (/tron\\/[0-9a-fA-F]{10,}/.test(url)) {\n return url.replace(/\\/tron_jsonrpc$/, '/premium-http/tron')\n }\n\n return url.replace(/\\/tron_jsonrpc$/, '/http/tron')\n }\n\n /**\n * Converts a URL to its JSON-RPC endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted JSON-RPC endpoint URL.\n */\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/(premium-http|http)\\/tron/, '/tron_jsonrpc')\n }\n}\n\n/**\n * Class representing the Quiknode provider conversion strategy.\n */\nclass QuiknodeProviderConversionStrategy implements ProviderConversionStrategy {\n /**\n * Converts a URL to its REST endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted REST endpoint URL.\n */\n asREST(url: string): string {\n return url.replace(/\\/jsonrpc$/, '')\n }\n\n /**\n * Converts a URL to its JSON-RPC endpoint equivalent.\n *\n * @param {string} url - The URL to convert.\n * @returns {string} The converted JSON-RPC endpoint URL.\n */\n asJSONRPC(url: string): string {\n return url.trim().replace(/\\/?$/, '/jsonrpc')\n }\n}\n\n/**\n * Class representing a factory for creating provider conversion strategies.\n */\nexport class StrategyFactory {\n /**\n * A map of URL patterns to provider conversion strategies.\n */\n public static strategies = new Map<RegExp, ProviderConversionStrategy>()\n\n static {\n StrategyFactory.strategies.set(/api.trongrid.io/, new DefaultProviderConversionStrategy())\n StrategyFactory.strategies.set(/ankr.com/, new AnkrProviderConversionStrategy())\n StrategyFactory.strategies.set(/quiknode.pro/, new QuiknodeProviderConversionStrategy())\n }\n\n /**\n * Gets the appropriate provider conversion strategy for a given URL.\n *\n * @param {string} url - The URL to get the conversion strategy for.\n * @returns {ProviderConversionStrategy} The provider conversion strategy.\n */\n static get(url: string): ProviderConversionStrategy {\n for (const [pattern, strategy] of this.strategies) {\n if (pattern.test(url)) {\n return strategy\n }\n }\n return new DefaultProviderConversionStrategy()\n }\n}\n","import { ethers } from 'ethers'\nimport TronWeb from 'tronweb'\n\nimport { getLogger, sleep } from '@layerzerolabs/lz-utilities'\n\nimport { Time } from './time'\nimport { StrategyFactory } from './url'\n\nimport type {\n BlockTransaction,\n ChainParameter,\n ContractExecutionParams,\n ContractInfo,\n Transaction,\n TransactionInfo,\n TransactionResult,\n} from 'tronweb'\n\n/**\n * Enum representing the types of transactions that can be performed on the Tron network.\n */\nexport enum TronTransactionType {\n TRIGGER_SMART_CONTRACT = 'TriggerSmartContract',\n}\n\n/**\n * Interface representing the overrides for a transaction.\n */\nexport interface TransactionOverrides {\n /**\n * The gas limit for the transaction.\n */\n gasLimit?: number\n\n /**\n * The gas price for the transaction.\n */\n gasPrice?: number\n\n /**\n * The energy factor for the transaction.\n */\n energyFactor?: number\n\n /**\n * The value to be sent with the transaction.\n */\n value?: number\n}\n\n/**\n * Interface representing a partial Tron transaction.\n */\nexport interface PartialTronTransaction {\n /**\n * Indicates whether the transaction is visible.\n */\n visible: boolean\n\n /**\n * The transaction ID.\n */\n txID: string\n\n /**\n * The raw data in hexadecimal format.\n */\n raw_data_hex: string\n\n /**\n * The raw data of the transaction.\n * @see {@link PartialTronTransactionContract}\n */\n raw_data: {\n contract: [PartialTronTransactionContract]\n }\n}\n\n/**\n * Interface representing a full Tron transaction.\n */\nexport interface TronTransaction extends PartialTronTransaction {\n /**\n * The raw data of the transaction.\n */\n raw_data: {\n /**\n * The contract details of the transaction.\n * @see {@link FullTronTransactionContract}\n */\n contract: [FullTronTransactionContract]\n\n /**\n * The reference block bytes.\n */\n ref_block_bytes: string\n\n /**\n * The reference block hash.\n */\n ref_block_hash: string\n\n /**\n * The expiration time of the transaction.\n */\n expiration: number\n\n /**\n * The fee limit for the transaction.\n */\n fee_limit: number\n\n /**\n * The timestamp of the transaction.\n */\n timestamp: number\n }\n}\n\n/**\n * Interface representing a signed Tron transaction.\n */\nexport interface SignedTronTransaction extends TronTransaction {\n /**\n * The signatures of the transaction.\n */\n signature: string[]\n}\n\n/**\n * Interface representing the parameter value of a partial Tron transaction.\n */\ninterface PartialTronTransactionParameterValue {\n /**\n * The data of the transaction.\n */\n data: string\n\n /**\n * The contract address.\n */\n contract_address: string\n\n /**\n * The owner address.\n */\n owner_address: string\n}\n\n/**\n * Interface representing the parameter value of a full Tron transaction.\n */\ninterface TronTransactionParameterValue extends PartialTronTransactionParameterValue {\n /**\n * The token ID.\n */\n token_id?: number\n\n /**\n * The call token value.\n */\n call_token_value?: number\n\n /**\n * The call value.\n */\n call_value?: number\n}\n\n/**\n * Interface representing the parameter of a Tron transaction.\n * @template T - The type of the parameter value.\n */\ninterface TronTransactionParameter<T> {\n /**\n * The value of the parameter.\n */\n value: T\n\n /**\n * The type URL of the parameter.\n */\n type_url: `type.googleapis.com/protocol.${TronTransactionType}`\n}\n\n/**\n * Interface representing a Tron transaction contract.\n * @template T - The type of the parameter value.\n */\ninterface TronTransactionContract<T> {\n /**\n * The parameter of the transaction contract.\n */\n parameter: TronTransactionParameter<T>\n\n /**\n * The type of the transaction contract.\n */\n type: TronTransactionType\n\n /**\n * The permission ID for the transaction contract.\n */\n Permission_id?: number\n}\n\n/**\n * Type representing a partial Tron transaction contract.\n */\ntype PartialTronTransactionContract = TronTransactionContract<PartialTronTransactionParameterValue>\n\n/**\n * Type representing a full Tron transaction contract.\n */\ntype FullTronTransactionContract = TronTransactionContract<TronTransactionParameterValue>\n\n/**\n * Interface representing the raw data of a Tron block header.\n */\ninterface TronBlockHeaderRawData {\n /**\n * The block number.\n */\n number: number\n\n /**\n * The transaction trie root.\n */\n txTrieRoot: string\n\n /**\n * The witness address.\n */\n witness_address: string\n\n /**\n * The parent hash.\n */\n parentHash: string\n\n /**\n * The timestamp of the block.\n */\n timestamp: number\n}\n\n/**\n * Interface representing a Tron block header.\n */\ninterface TronBlockHeader {\n /**\n * The raw data of the block header.\n */\n raw_data: TronBlockHeaderRawData\n\n /**\n * The witness signature.\n */\n witness_signature: string\n}\n\n/**\n * Interface representing Tron block data.\n */\nexport interface TronBlockData {\n /**\n * The block ID.\n */\n blockID: string\n\n /**\n * The block header.\n */\n block_header: TronBlockHeader\n}\n\n/**\n * Interface representing a TronWeb error response (type 1).\n */\ninterface TronWebError1 {\n /**\n * The error code.\n */\n code: string\n\n /**\n * The error message.\n */\n message: string\n\n /**\n * The transaction ID.\n */\n txid: string\n}\n\n/**\n * Interface representing a TronWeb error response (type 2).\n */\ninterface TronWebError2 {\n /**\n * The error message.\n */\n Error: string\n}\n\n/**\n * Type representing a TronWeb error response.\n */\ntype TronWebErrorResponse = TronWebError1 | TronWebError2\n\nexport {\n TronWeb,\n BlockTransaction,\n ContractExecutionParams,\n ChainParameter,\n Transaction,\n TronWebError1,\n TronWebError2,\n TronWebErrorResponse,\n}\n\nconst logger = getLogger()\n\n/**\n * Type representing provider settings.\n * It can be either a string representing the URL or an object containing the URL and an optional API key.\n */\nexport type ProviderSetting =\n | {\n /**\n * The URL of the provider.\n */\n url: string\n\n /**\n * The API key for the provider (optional).\n */\n apiKey?: string\n }\n | string\n\n/**\n * Creates a TronWeb instance.\n *\n * @param {{ rpcSetting: ProviderSetting; privateKey: string } | TronWeb} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.\n * @returns {TronWeb} The created TronWeb instance.\n */\nexport function createTronWeb(signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb): TronWeb {\n if (!(signer instanceof TronWeb)) {\n const fullHostUrl = typeof signer.rpcSetting === 'string' ? signer.rpcSetting : signer.rpcSetting.url\n const client = new TronWeb({\n fullHost: StrategyFactory.get(fullHostUrl).asREST(fullHostUrl),\n headers: {\n 'TRON-PRO-API-KEY': typeof signer.rpcSetting === 'string' ? '' : signer.rpcSetting.apiKey ?? '',\n },\n privateKey: signer.privateKey.replace(/^0x/, ''),\n })\n return client\n }\n return signer\n}\n\n/**\n * Signs and sends a Tron transaction.\n *\n * @param {object} txn - The transaction object containing data, to, and transaction overrides.\n * @param {object} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.\n * @param {number} [permissionId] - The permission ID for multi-sig.\n * @returns {Promise<object>} A promise that resolves to an object containing txId, result, and wait function.\n */\nexport async function signAndSendTronTransaction(\n txn: {\n data: string\n to: string\n } & TransactionOverrides,\n signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb,\n permissionId?: number // for multi-sig\n): Promise<{ txId: string; result: TransactionResult; wait: () => Promise<TransactionInfo> }> {\n const signedTxn = await signTronTx(txn, signer, permissionId)\n const client = createTronWeb(signer)\n return sendTronTransaction(signedTxn, client)\n}\n\n/**\n * Sends a signed Tron transaction.\n *\n * @param {SignedTronTransaction} signedTxn - The signed Tron transaction.\n * @param {TronWeb} client - The TronWeb client.\n * @returns {Promise<object>} A promise that resolves to an object containing txId, result, and wait function.\n * @throws {Error} If the transaction broadcast fails.\n */\nexport async function sendTronTransaction(\n singedTxn: SignedTronTransaction,\n client: TronWeb\n): Promise<{ txId: string; result: TransactionResult; wait: () => Promise<TransactionInfo> }> {\n // reference: https://developers.tron.network/reference/json-rpc-api-overview\n // JSON-RPC interface is not fully supported by the TRON network.\n // Furthermore, The JSON-RPC service needs to be enabled and set the port in the node configuration\n // file. If not configured, the service is disable by default.\n // broadcast signedTransaction\n const broadcastResponse = await client.trx.sendRawTransaction(singedTxn)\n if (broadcastResponse.code !== undefined) {\n const err = {\n error: broadcastResponse.code,\n message: TronWeb.toUtf8(broadcastResponse.message ?? ''),\n }\n throw new Error(JSON.stringify(err, null, 2))\n }\n\n return {\n txId: singedTxn.txID,\n result: broadcastResponse,\n wait: async (): Promise<TransactionInfo> => {\n return checkResult(client, singedTxn.txID)\n },\n }\n}\n\n/**\n * Signs a Tron transaction.\n *\n * @param {object} txn - The transaction object containing data, to, and transaction overrides.\n * @param {object} signer - The signer object containing rpcSetting and privateKey, or an existing TronWeb instance.\n * @param {number} [permissionId] - The permission ID for multi-sig.\n * @returns {Promise<SignedTronTransaction>} A promise that resolves to the signed Tron transaction.\n * @throws {Error} If the private key is invalid.\n */\nexport async function signTronTx(\n txn: {\n data: string\n to: string\n } & TransactionOverrides,\n _signer: { rpcSetting: ProviderSetting; privateKey: string } | TronWeb,\n permissionId?: number // for multi-sig\n): Promise<SignedTronTransaction> {\n const signer: TronWeb = createTronWeb(_signer)\n\n // privateKey = privateKey.replace(/^0x/, '') // remove the 0x prefix\n // private key to address\n // const from = TronWeb.address.fromPrivateKey(privateKey)\n if (typeof signer.defaultAddress.hex !== 'string') {\n throw new Error(`signer.defaultAddress.hex is not a valid hex string`)\n }\n\n const partialTxn: PartialTronTransaction = {\n visible: false,\n txID: '',\n raw_data_hex: '',\n raw_data: {\n contract: [\n {\n parameter: {\n value: {\n data: txn.data.replace(/^0x/, ''),\n contract_address: TronWeb.address.toHex(txn.to),\n owner_address: signer.defaultAddress.hex,\n },\n type_url: `type.googleapis.com/protocol.${TronTransactionType.TRIGGER_SMART_CONTRACT}`,\n },\n type: TronTransactionType.TRIGGER_SMART_CONTRACT,\n Permission_id: permissionId,\n },\n ],\n },\n }\n\n const fullTxn = await fullFillTxn(signer, partialTxn, {\n gasLimit: txn.gasLimit,\n gasPrice: txn.gasPrice,\n energyFactor: txn.energyFactor,\n value: txn.value,\n })\n\n // sign transaction\n const signedTransaction = await signer.trx.sign(fullTxn)\n if (signedTransaction.signature === undefined) {\n throw new Error('Invalid private key provided')\n }\n return signedTransaction as SignedTronTransaction\n}\n\nlet gasPriceCache: { time: number; value: string } = { time: 0, value: '' }\nconst energyFactorsCache = new Map<string, { time: number; value: number }>()\n\n/**\n * Fills in the missing fields of a Tron transaction.\n *\n * @param {TronWeb} signer - The TronWeb client.\n * @param {PartialTronTransaction} txn - The partial Tron transaction.\n * @param {TransactionOverrides} [overrides={}] - The transaction overrides.\n * @returns {Promise<TronTransaction>} A promise that resolves to the full Tron transaction.\n */\nexport async function fullFillTxn(\n signer: TronWeb,\n txn: PartialTronTransaction,\n overrides: TransactionOverrides = {}\n): Promise<TronTransaction> {\n const apiKey = signer.fullNode.headers['TRON-PRO-API-KEY']\n const etherProvider = new ethers.providers.StaticJsonRpcProvider({\n url: StrategyFactory.get(signer.fullNode.host).asJSONRPC(signer.fullNode.host),\n headers: {\n ...(typeof apiKey !== 'undefined' ? { 'TRON-PRO-API-KEY': apiKey } : {}),\n },\n })\n\n /**\n * Gets the current gas price.\n * cache the gasPrice with a 15sec TTL\n *\n * @returns {Promise<string>} A promise that resolves to the current gas price as a string.\n */\n async function getGasPrice(): Promise<string> {\n const { time, value } = gasPriceCache\n if (time > Time.NOW - 15 * Time.SECOND && value != '') return value\n const newGaspPrice = await etherProvider.getGasPrice().then((x) => x.toString())\n gasPriceCache = { time: Time.NOW, value: newGaspPrice }\n return newGaspPrice\n }\n\n /**\n * Estimates the gas limit for a given transaction.\n *\n * @param {PartialTronTransaction} raw - The partial Tron transaction.\n * @returns {Promise<number>} A promise that resolves to the estimated gas limit.\n */\n async function getGasLimit(raw: PartialTronTransaction): Promise<number> {\n const gasLimit = await etherProvider.estimateGas({\n to: raw.raw_data.contract[0].parameter.value.contract_address.replace(/^41/, '0x'), // need to slice off the \"41\" prefix that Tron appends to addresses\n data: '0x' + raw.raw_data.contract[0].parameter.value.data,\n from: raw.raw_data.contract[0].parameter.value.owner_address.replace(/^41/, '0x'),\n value: overrides.value ?? 0,\n })\n return gasLimit.toNumber()\n }\n\n /**\n * Gets the energy factor for a given transaction.\n * Caches the energy factor with a 10-minute TTL. Energy factors should be updated by Tron every 6 hours.\n *\n * @param {PartialTronTransaction} raw - The partial Tron transaction.\n * @returns {Promise<number>} A promise that resolves to the energy factor.\n */\n async function getEnergyFactor(raw: PartialTronTransaction): Promise<number> {\n /* eslint-disable @typescript-eslint/no-unsafe-assignment */\n const addr = raw.raw_data.contract[0].parameter.value.contract_address\n const cached = energyFactorsCache.get(addr)\n if (cached && cached.time > Time.NOW - 10 * Time.MINUTE) return cached.value\n const MAX_ENERGY_FACTOR = 1.2\n // refers: https://developers.tron.network/reference/getcontractinfo\n const response = await signer.fullNode.request(\n 'wallet/getcontractinfo',\n { value: addr, visible: false },\n 'post'\n )\n const contractInfo: ContractInfo = response as ContractInfo\n const energy_factor = contractInfo.contract_state.energy_factor ?? MAX_ENERGY_FACTOR\n energyFactorsCache.set(addr, { time: Time.NOW, value: energy_factor })\n return energy_factor\n /* eslint-enable @typescript-eslint/no-unsafe-assignment */\n }\n\n /**\n * Calculates the fee limit for a given transaction.\n *\n * @param {PartialTronTransaction} raw - The partial Tron transaction.\n * @param {TransactionOverrides} [overrides={}] - The transaction overrides.\n * @returns {Promise<number>} A promise that resolves to the calculated fee limit.\n */\n async function getFeeLimit(raw: PartialTronTransaction, overrides: TransactionOverrides = {}): Promise<number> {\n // https://developers.tron.network/docs/set-feelimit#how-to-determine-the-feelimit-parameter\n // https://developers.tron.network/reference/getcontractinfo, get energy_factor\n // https://developers.tron.network/docs/resource-model#dynamic-energy-model, max factor\n // Tight FeeLimit of contract transaction = estimated basic energy consumption * (1 + energy_factor) * EnergyPrice\n // Loose FeeLimit of contract transaction = estimated basic energy consumption * (1 + max_energy_factor) * EnergyPrice\n const MAX_FEE_LIMIT = 15000000000\n const energy_factor = overrides.energyFactor ?? (await getEnergyFactor(raw))\n const gasLimit = overrides.gasLimit ?? (await getGasLimit(raw))\n const energyPrice = overrides.gasPrice ?? Number(await getGasPrice())\n const factor = 1 + energy_factor\n const feeLimit = gasLimit * factor * energyPrice\n const feeLimit_adjusted = Math.ceil(feeLimit) * 1.2 // based on reading other parts of the code, we add a 20% cushion on fee limits\n return Math.floor(Math.min(feeLimit_adjusted, MAX_FEE_LIMIT))\n }\n\n const metadata = (await signer.fullNode.request('wallet/getblock', { detail: false }, 'post')) as TronBlockData\n const ref_block_bytes = metadata.block_header.raw_data.number.toString(16).slice(-4).padStart(4, '0')\n const ref_block_hash = metadata.blockID.slice(16, 32)\n const expiration = metadata.block_header.raw_data.timestamp + 60 * 1000\n const { timestamp } = metadata.block_header.raw_data\n\n const tx: TronTransaction = {\n ...txn,\n raw_data: {\n contract: [\n {\n parameter: {\n value: {\n ...txn.raw_data.contract[0].parameter.value,\n call_value: overrides.value ?? 0,\n },\n type_url: txn.raw_data.contract[0].parameter.type_url,\n },\n type: txn.raw_data.contract[0].type,\n },\n ],\n ref_block_bytes,\n ref_block_hash,\n expiration,\n fee_limit: await getFeeLimit(txn, overrides),\n timestamp,\n },\n }\n const pb = signer.utils.transaction.txJsonToPb(tx)\n tx.txID = signer.utils.transaction.txPbToTxID(pb).replace(/^0x/, '')\n tx.raw_data_hex = signer.utils.transaction.txPbToRawDataHex(pb).toLowerCase()\n\n return tx\n}\n\n/**\n * Checks the result of a Tron transaction.\n *\n * @param {TronWeb} tronWeb - The TronWeb client.\n * @param {string} txId - The transaction ID.\n * @returns {Promise<TransactionInfo>} A promise that resolves to the transaction info.\n * @throws {Error} If the transaction fails or times out.\n */\nexport async function checkResult(tronWeb: TronWeb, txId: string): Promise<TransactionInfo> {\n const startTime = Date.now()\n const waitTimeout = 1000 * 60 * 5 // 5 minutes\n // TODO: get the block producer interval from the chain and sleep for that time\n const wait = async function (txId: string): Promise<TransactionInfo> {\n let tries = 0\n while (tries++ < 20) {\n const output = await tronWeb.trx.getTransactionInfo(txId)\n if (Object.keys(output).length > 0) {\n return output\n }\n\n // check if timeout\n if (Date.now() - startTime > waitTimeout) {\n throw new Error('Timeout waiting for transaction to be processed')\n }\n // wait 1 seconds for next check, mainnet block producer interval is 3 seconds,\n // but we need a small interval for the local network to speed up the test\n await sleep(1200)\n }\n throw new Error(`Failed to get transactionInfo for txId: ${txId}`)\n }\n\n const output = await wait(txId)\n\n if (output.result !== undefined && output.result === 'FAILED') {\n throw new Error(TronWeb.toUtf8(output.resMessage ?? ''))\n }\n\n if (!Object.prototype.hasOwnProperty.call(output, 'contractResult')) {\n throw new Error('Failed to execute: ' + JSON.stringify(output, null, 2))\n }\n\n return output\n}\n"]}