trx.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. import { TronWeb } from '../tronweb.js';
  2. import utils from '../utils/index.js';
  3. import { keccak256, toUtf8Bytes, recoverAddress, SigningKey, Signature } from '../utils/ethersUtils.js';
  4. import { ADDRESS_PREFIX } from '../utils/address.js';
  5. import { Validator } from '../paramValidator/index.js';
  6. import { txCheck } from '../utils/transaction.js';
  7. import { ecRecover } from '../utils/crypto.js';
  8. const TRX_MESSAGE_HEADER = '\x19TRON Signed Message:\n32';
  9. // it should be: '\x15TRON Signed Message:\n32';
  10. const ETH_MESSAGE_HEADER = '\x19Ethereum Signed Message:\n32';
  11. function toHex(value) {
  12. return TronWeb.address.toHex(value);
  13. }
  14. export class Trx {
  15. tronWeb;
  16. cache;
  17. validator;
  18. signMessage;
  19. sendAsset;
  20. send;
  21. sendTrx;
  22. broadcast;
  23. broadcastHex;
  24. signTransaction;
  25. constructor(tronWeb) {
  26. this.tronWeb = tronWeb;
  27. this.cache = {
  28. contracts: {},
  29. };
  30. this.validator = new Validator();
  31. this.signMessage = this.sign;
  32. this.sendAsset = this.sendToken;
  33. this.send = this.sendTransaction;
  34. this.sendTrx = this.sendTransaction;
  35. this.broadcast = this.sendRawTransaction;
  36. this.broadcastHex = this.sendHexTransaction;
  37. this.signTransaction = this.sign;
  38. }
  39. _parseToken(token) {
  40. return {
  41. ...token,
  42. name: this.tronWeb.toUtf8(token.name),
  43. abbr: token.abbr && this.tronWeb.toUtf8(token.abbr),
  44. description: token.description && this.tronWeb.toUtf8(token.description),
  45. url: token.url && this.tronWeb.toUtf8(token.url),
  46. };
  47. }
  48. getCurrentBlock() {
  49. return this.tronWeb.fullNode.request('wallet/getnowblock');
  50. }
  51. getConfirmedCurrentBlock() {
  52. return this.tronWeb.solidityNode.request('walletsolidity/getnowblock');
  53. }
  54. async getBlock(block = this.tronWeb.defaultBlock) {
  55. if (block === false) {
  56. throw new Error('No block identifier provided');
  57. }
  58. if (block == 'earliest')
  59. block = 0;
  60. if (block == 'latest')
  61. return this.getCurrentBlock();
  62. if (isNaN(+block) && utils.isHex(block.toString()))
  63. return this.getBlockByHash(block);
  64. return this.getBlockByNumber(block);
  65. }
  66. async getBlockByHash(blockHash) {
  67. const block = await this.tronWeb.fullNode.request('wallet/getblockbyid', {
  68. value: blockHash,
  69. }, 'post');
  70. if (!Object.keys(block).length) {
  71. throw new Error('Block not found');
  72. }
  73. return block;
  74. }
  75. async getBlockByNumber(blockID) {
  76. if (!utils.isInteger(blockID) || blockID < 0) {
  77. throw new Error('Invalid block number provided');
  78. }
  79. return this.tronWeb.fullNode
  80. .request('wallet/getblockbynum', {
  81. num: parseInt(blockID),
  82. }, 'post')
  83. .then((block) => {
  84. if (!Object.keys(block).length) {
  85. throw new Error('Block not found');
  86. }
  87. return block;
  88. });
  89. }
  90. async getBlockTransactionCount(block = this.tronWeb.defaultBlock) {
  91. const { transactions = [] } = await this.getBlock(block);
  92. return transactions.length;
  93. }
  94. async getTransactionFromBlock(block = this.tronWeb.defaultBlock, index) {
  95. const { transactions } = await this.getBlock(block);
  96. if (!transactions) {
  97. throw new Error('Transaction not found in block');
  98. }
  99. if (index >= 0 && index < transactions.length)
  100. return transactions[index];
  101. else
  102. throw new Error('Invalid transaction index provided');
  103. }
  104. async getTransactionsFromBlock(block = this.tronWeb.defaultBlock) {
  105. const { transactions } = await this.getBlock(block);
  106. if (!transactions) {
  107. throw new Error('Transaction not found in block');
  108. }
  109. return transactions;
  110. }
  111. async getTransaction(transactionID) {
  112. const transaction = await this.tronWeb.fullNode.request('wallet/gettransactionbyid', {
  113. value: transactionID,
  114. }, 'post');
  115. if (!Object.keys(transaction).length) {
  116. throw new Error('Transaction not found');
  117. }
  118. return transaction;
  119. }
  120. async getConfirmedTransaction(transactionID) {
  121. const transaction = await this.tronWeb.solidityNode.request('walletsolidity/gettransactionbyid', {
  122. value: transactionID,
  123. }, 'post');
  124. if (!Object.keys(transaction).length) {
  125. throw new Error('Transaction not found');
  126. }
  127. return transaction;
  128. }
  129. getUnconfirmedTransactionInfo(transactionID) {
  130. return this.tronWeb.fullNode.request('wallet/gettransactioninfobyid', { value: transactionID }, 'post');
  131. }
  132. getTransactionInfo(transactionID) {
  133. return this.tronWeb.solidityNode.request('walletsolidity/gettransactioninfobyid', { value: transactionID }, 'post');
  134. }
  135. getTransactionsToAddress(address = this.tronWeb.defaultAddress.hex, limit = 30, offset = 0) {
  136. return this.getTransactionsRelated(this.tronWeb.address.toHex(address), 'to', limit, offset);
  137. }
  138. getTransactionsFromAddress(address = this.tronWeb.defaultAddress.hex, limit = 30, offset = 0) {
  139. return this.getTransactionsRelated(this.tronWeb.address.toHex(address), 'from', limit, offset);
  140. }
  141. async getTransactionsRelated(address = this.tronWeb.defaultAddress.hex, direction = 'all', limit = 30, offset = 0) {
  142. if (this.tronWeb.fullnodeSatisfies('>=4.1.1')) {
  143. throw new Error('This api is not supported any more');
  144. }
  145. if (!['to', 'from', 'all'].includes(direction)) {
  146. throw new Error('Invalid direction provided: Expected "to", "from" or "all"');
  147. }
  148. if (direction == 'all') {
  149. const [from, to] = await Promise.all([
  150. this.getTransactionsRelated(address, 'from', limit, offset),
  151. this.getTransactionsRelated(address, 'to', limit, offset),
  152. ]);
  153. return [
  154. ...from.map((tx) => ((tx.direction = 'from'), tx)),
  155. ...to.map((tx) => ((tx.direction = 'to'), tx)),
  156. ].sort((a, b) => {
  157. return b.raw_data.timestamp - a.raw_data.timestamp;
  158. });
  159. }
  160. if (!this.tronWeb.isAddress(address)) {
  161. throw new Error('Invalid address provided');
  162. }
  163. if (!utils.isInteger(limit) || limit < 0 || (offset && limit < 1)) {
  164. throw new Error('Invalid limit provided');
  165. }
  166. if (!utils.isInteger(offset) || offset < 0) {
  167. throw new Error('Invalid offset provided');
  168. }
  169. address = this.tronWeb.address.toHex(address);
  170. return this.tronWeb.solidityNode
  171. .request(`walletextension/gettransactions${direction}this`, {
  172. account: {
  173. address,
  174. },
  175. offset,
  176. limit,
  177. }, 'post')
  178. .then(({ transaction }) => {
  179. return transaction;
  180. });
  181. }
  182. async getAccount(address = this.tronWeb.defaultAddress.hex) {
  183. if (!this.tronWeb.isAddress(address)) {
  184. throw new Error('Invalid address provided');
  185. }
  186. address = this.tronWeb.address.toHex(address);
  187. return this.tronWeb.solidityNode.request('walletsolidity/getaccount', {
  188. address,
  189. }, 'post');
  190. }
  191. getAccountById(id) {
  192. return this.getAccountInfoById(id, { confirmed: true });
  193. }
  194. async getAccountInfoById(id, options) {
  195. this.validator.notValid([
  196. {
  197. name: 'accountId',
  198. type: 'hex',
  199. value: id,
  200. },
  201. {
  202. name: 'accountId',
  203. type: 'string',
  204. lte: 32,
  205. gte: 8,
  206. value: id,
  207. },
  208. ]);
  209. if (id.startsWith('0x')) {
  210. id = id.slice(2);
  211. }
  212. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getaccountbyid`, {
  213. account_id: id,
  214. }, 'post');
  215. }
  216. async getBalance(address = this.tronWeb.defaultAddress.hex) {
  217. const { balance = 0 } = await this.getAccount(address);
  218. return balance;
  219. }
  220. async getUnconfirmedAccount(address = this.tronWeb.defaultAddress.hex) {
  221. if (!this.tronWeb.isAddress(address)) {
  222. throw new Error('Invalid address provided');
  223. }
  224. address = this.tronWeb.address.toHex(address);
  225. return this.tronWeb.fullNode.request('wallet/getaccount', {
  226. address,
  227. }, 'post');
  228. }
  229. getUnconfirmedAccountById(id) {
  230. return this.getAccountInfoById(id, { confirmed: false });
  231. }
  232. async getUnconfirmedBalance(address = this.tronWeb.defaultAddress.hex) {
  233. const { balance = 0 } = await this.getUnconfirmedAccount(address);
  234. return balance;
  235. }
  236. async getBandwidth(address = this.tronWeb.defaultAddress.hex) {
  237. if (!this.tronWeb.isAddress(address)) {
  238. throw new Error('Invalid address provided');
  239. }
  240. address = this.tronWeb.address.toHex(address);
  241. return this.tronWeb.fullNode
  242. .request('wallet/getaccountnet', {
  243. address,
  244. }, 'post')
  245. .then(({ freeNetUsed = 0, freeNetLimit = 0, NetUsed = 0, NetLimit = 0 }) => {
  246. return freeNetLimit - freeNetUsed + (NetLimit - NetUsed);
  247. });
  248. }
  249. async getTokensIssuedByAddress(address = this.tronWeb.defaultAddress.hex) {
  250. if (!this.tronWeb.isAddress(address)) {
  251. throw new Error('Invalid address provided');
  252. }
  253. address = this.tronWeb.address.toHex(address);
  254. return this.tronWeb.fullNode
  255. .request('wallet/getassetissuebyaccount', {
  256. address,
  257. }, 'post')
  258. .then(({ assetIssue }) => {
  259. if (!assetIssue)
  260. return {};
  261. const tokens = assetIssue
  262. .map((token) => {
  263. return this._parseToken(token);
  264. })
  265. .reduce((tokens, token) => {
  266. return (tokens[token.name] = token), tokens;
  267. }, {});
  268. return tokens;
  269. });
  270. }
  271. async getTokenFromID(tokenID) {
  272. if (utils.isInteger(tokenID))
  273. tokenID = tokenID.toString();
  274. if (!utils.isString(tokenID) || !tokenID.length) {
  275. throw new Error('Invalid token ID provided');
  276. }
  277. return this.tronWeb.fullNode
  278. .request('wallet/getassetissuebyname', {
  279. value: this.tronWeb.fromUtf8(tokenID),
  280. }, 'post')
  281. .then((token) => {
  282. if (!token.name) {
  283. throw new Error('Token does not exist');
  284. }
  285. return this._parseToken(token);
  286. });
  287. }
  288. async listNodes() {
  289. const { nodes = [] } = await this.tronWeb.fullNode.request('wallet/listnodes');
  290. return nodes.map(({ address: { host, port } }) => `${this.tronWeb.toUtf8(host)}:${port}`);
  291. }
  292. async getBlockRange(start = 0, end = 30) {
  293. if (!utils.isInteger(start) || start < 0) {
  294. throw new Error('Invalid start of range provided');
  295. }
  296. if (!utils.isInteger(end) || end < start) {
  297. throw new Error('Invalid end of range provided');
  298. }
  299. if (end + 1 - start > 100) {
  300. throw new Error('Invalid range size, which should be no more than 100.');
  301. }
  302. return this.tronWeb.fullNode
  303. .request('wallet/getblockbylimitnext', {
  304. startNum: parseInt(start),
  305. endNum: parseInt(end) + 1,
  306. }, 'post')
  307. .then(({ block = [] }) => block);
  308. }
  309. async listSuperRepresentatives() {
  310. const { witnesses = [] } = await this.tronWeb.fullNode.request('wallet/listwitnesses');
  311. return witnesses;
  312. }
  313. async listTokens(limit = 0, offset = 0) {
  314. if (!utils.isInteger(limit) || limit < 0 || (offset && limit < 1)) {
  315. throw new Error('Invalid limit provided');
  316. }
  317. if (!utils.isInteger(offset) || offset < 0) {
  318. throw new Error('Invalid offset provided');
  319. }
  320. if (!limit) {
  321. return this.tronWeb.fullNode
  322. .request('wallet/getassetissuelist')
  323. .then(({ assetIssue = [] }) => assetIssue.map((token) => this._parseToken(token)));
  324. }
  325. return this.tronWeb.fullNode
  326. .request('wallet/getpaginatedassetissuelist', {
  327. offset: parseInt(offset),
  328. limit: parseInt(limit),
  329. }, 'post')
  330. .then(({ assetIssue = [] }) => assetIssue.map((token) => this._parseToken(token)));
  331. }
  332. async timeUntilNextVoteCycle() {
  333. const { num = -1 } = await this.tronWeb.fullNode.request('wallet/getnextmaintenancetime');
  334. if (num == -1) {
  335. throw new Error('Failed to get time until next vote cycle');
  336. }
  337. return Math.floor(num / 1000);
  338. }
  339. async getContract(contractAddress) {
  340. if (!this.tronWeb.isAddress(contractAddress)) {
  341. throw new Error('Invalid contract address provided');
  342. }
  343. if (this.cache.contracts[contractAddress]) {
  344. return this.cache.contracts[contractAddress];
  345. }
  346. contractAddress = this.tronWeb.address.toHex(contractAddress);
  347. const contract = await this.tronWeb.fullNode.request('wallet/getcontract', {
  348. value: contractAddress,
  349. });
  350. if (contract.Error) {
  351. throw new Error('Contract does not exist');
  352. }
  353. this.cache.contracts[contractAddress] = contract;
  354. return contract;
  355. }
  356. ecRecover(transaction) {
  357. return Trx.ecRecover(transaction);
  358. }
  359. static ecRecover(transaction) {
  360. if (!txCheck(transaction)) {
  361. throw new Error('Invalid transaction');
  362. }
  363. if (!transaction.signature?.length) {
  364. throw new Error('Transaction is not signed');
  365. }
  366. if (transaction.signature.length === 1) {
  367. const tronAddress = ecRecover(transaction.txID, transaction.signature[0]);
  368. return TronWeb.address.fromHex(tronAddress);
  369. }
  370. return transaction.signature.map((sig) => {
  371. const tronAddress = ecRecover(transaction.txID, sig);
  372. return TronWeb.address.fromHex(tronAddress);
  373. });
  374. }
  375. async verifyMessage(message, signature, address = this.tronWeb.defaultAddress.base58, useTronHeader = true) {
  376. if (!utils.isHex(message)) {
  377. throw new Error('Expected hex message input');
  378. }
  379. if (Trx.verifySignature(message, address, signature, useTronHeader)) {
  380. return true;
  381. }
  382. throw new Error('Signature does not match');
  383. }
  384. static verifySignature(message, address, signature, useTronHeader = true) {
  385. message = message.replace(/^0x/, '');
  386. const messageBytes = [
  387. ...toUtf8Bytes(useTronHeader ? TRX_MESSAGE_HEADER : ETH_MESSAGE_HEADER),
  388. ...utils.code.hexStr2byteArray(message),
  389. ];
  390. const messageDigest = keccak256(new Uint8Array(messageBytes));
  391. const recovered = recoverAddress(messageDigest, Signature.from(`0x${signature.replace(/^0x/, '')}`));
  392. const tronAddress = ADDRESS_PREFIX + recovered.substr(2);
  393. const base58Address = TronWeb.address.fromHex(tronAddress);
  394. return base58Address == TronWeb.address.fromHex(address);
  395. }
  396. async verifyMessageV2(message, signature) {
  397. return Trx.verifyMessageV2(message, signature);
  398. }
  399. static verifyMessageV2(message, signature) {
  400. return utils.message.verifyMessage(message, signature);
  401. }
  402. verifyTypedData(domain, types, value, signature, address = this.tronWeb.defaultAddress.base58) {
  403. if (Trx.verifyTypedData(domain, types, value, signature, address))
  404. return true;
  405. throw new Error('Signature does not match');
  406. }
  407. static verifyTypedData(domain, types, value, signature, address) {
  408. const messageDigest = utils._TypedDataEncoder.hash(domain, types, value);
  409. const recovered = recoverAddress(messageDigest, Signature.from(`0x${signature.replace(/^0x/, '')}`));
  410. const tronAddress = ADDRESS_PREFIX + recovered.substr(2);
  411. const base58Address = TronWeb.address.fromHex(tronAddress);
  412. return base58Address == TronWeb.address.fromHex(address);
  413. }
  414. async sign(transaction, privateKey = this.tronWeb.defaultPrivateKey, useTronHeader = true, multisig = false) {
  415. // Message signing
  416. if (utils.isString(transaction)) {
  417. if (!utils.isHex(transaction)) {
  418. throw new Error('Expected hex message input');
  419. }
  420. return Trx.signString(transaction, privateKey, useTronHeader);
  421. }
  422. if (!utils.isObject(transaction)) {
  423. throw new Error('Invalid transaction provided');
  424. }
  425. if (!multisig && transaction.signature) {
  426. throw new Error('Transaction is already signed');
  427. }
  428. if (!multisig) {
  429. const address = this.tronWeb.address
  430. .toHex(this.tronWeb.address.fromPrivateKey(privateKey))
  431. .toLowerCase();
  432. if (address !== this.tronWeb.address.toHex(transaction.raw_data.contract[0].parameter.value.owner_address)) {
  433. throw new Error('Private key does not match address in transaction');
  434. }
  435. if (!txCheck(transaction)) {
  436. throw new Error('Invalid transaction');
  437. }
  438. }
  439. return utils.crypto.signTransaction(privateKey, transaction);
  440. }
  441. static signString(message, privateKey, useTronHeader = true) {
  442. message = message.replace(/^0x/, '');
  443. const value = `0x${privateKey.replace(/^0x/, '')}`;
  444. const signingKey = new SigningKey(value);
  445. const messageBytes = [
  446. ...toUtf8Bytes(useTronHeader ? TRX_MESSAGE_HEADER : ETH_MESSAGE_HEADER),
  447. ...utils.code.hexStr2byteArray(message),
  448. ];
  449. const messageDigest = keccak256(new Uint8Array(messageBytes));
  450. const signature = signingKey.sign(messageDigest);
  451. const signatureHex = ['0x', signature.r.substring(2), signature.s.substring(2), Number(signature.v).toString(16)].join('');
  452. return signatureHex;
  453. }
  454. /**
  455. * sign message v2 for verified header length
  456. *
  457. * @param {message to be signed, should be Bytes or string} message
  458. * @param {privateKey for signature} privateKey
  459. * @param {reserved} options
  460. */
  461. signMessageV2(message, privateKey = this.tronWeb.defaultPrivateKey) {
  462. return Trx.signMessageV2(message, privateKey);
  463. }
  464. static signMessageV2(message, privateKey) {
  465. return utils.message.signMessage(message, privateKey);
  466. }
  467. _signTypedData(domain, types, value, privateKey = this.tronWeb.defaultPrivateKey) {
  468. return Trx._signTypedData(domain, types, value, privateKey);
  469. }
  470. static _signTypedData(domain, types, value, privateKey) {
  471. return utils.crypto._signTypedData(domain, types, value, privateKey);
  472. }
  473. async multiSign(transaction, privateKey = this.tronWeb.defaultPrivateKey, permissionId = 0) {
  474. if (!utils.isObject(transaction) || !transaction.raw_data || !transaction.raw_data.contract) {
  475. throw new Error('Invalid transaction provided');
  476. }
  477. // If owner permission or permission id exists in transaction, do sign directly
  478. // If no permission id inside transaction or user passes permission id, use old way to reset permission id
  479. if (!transaction.raw_data.contract[0].Permission_id && permissionId > 0) {
  480. // set permission id
  481. transaction.raw_data.contract[0].Permission_id = permissionId;
  482. // check if private key insides permission list
  483. const address = this.tronWeb.address
  484. .toHex(this.tronWeb.address.fromPrivateKey(privateKey))
  485. .toLowerCase();
  486. const signWeight = await this.getSignWeight(transaction, permissionId);
  487. if (signWeight.result.code === 'PERMISSION_ERROR') {
  488. throw new Error(signWeight.result.message);
  489. }
  490. let foundKey = false;
  491. signWeight.permission.keys.map((key) => {
  492. if (key.address === address)
  493. foundKey = true;
  494. });
  495. if (!foundKey) {
  496. throw new Error(privateKey + ' has no permission to sign');
  497. }
  498. if (signWeight.approved_list && signWeight.approved_list.indexOf(address) != -1) {
  499. throw new Error(privateKey + ' already sign transaction');
  500. }
  501. // reset transaction
  502. if (signWeight.transaction && signWeight.transaction.transaction) {
  503. transaction = signWeight.transaction.transaction;
  504. if (permissionId > 0) {
  505. transaction.raw_data.contract[0].Permission_id = permissionId;
  506. }
  507. }
  508. else {
  509. throw new Error('Invalid transaction provided');
  510. }
  511. }
  512. // sign
  513. if (!txCheck(transaction)) {
  514. throw new Error('Invalid transaction');
  515. }
  516. return utils.crypto.signTransaction(privateKey, transaction);
  517. }
  518. async getApprovedList(transaction) {
  519. if (!utils.isObject(transaction)) {
  520. throw new Error('Invalid transaction provided');
  521. }
  522. return this.tronWeb.fullNode.request('wallet/getapprovedlist', transaction, 'post');
  523. }
  524. async getSignWeight(transaction, permissionId) {
  525. if (!utils.isObject(transaction) || !transaction.raw_data || !transaction.raw_data.contract)
  526. throw new Error('Invalid transaction provided');
  527. if (utils.isInteger(permissionId)) {
  528. transaction.raw_data.contract[0].Permission_id = parseInt(permissionId);
  529. }
  530. else if (typeof transaction.raw_data.contract[0].Permission_id !== 'number') {
  531. transaction.raw_data.contract[0].Permission_id = 0;
  532. }
  533. return this.tronWeb.fullNode.request('wallet/getsignweight', transaction, 'post');
  534. }
  535. async sendRawTransaction(signedTransaction) {
  536. if (!utils.isObject(signedTransaction)) {
  537. throw new Error('Invalid transaction provided');
  538. }
  539. if (!signedTransaction.signature || !utils.isArray(signedTransaction.signature)) {
  540. throw new Error('Transaction is not signed');
  541. }
  542. const result = await this.tronWeb.fullNode.request('wallet/broadcasttransaction', signedTransaction, 'post');
  543. return {
  544. ...result,
  545. transaction: signedTransaction,
  546. };
  547. }
  548. async sendHexTransaction(signedHexTransaction) {
  549. if (!utils.isHex(signedHexTransaction)) {
  550. throw new Error('Invalid hex transaction provided');
  551. }
  552. const params = {
  553. transaction: signedHexTransaction,
  554. };
  555. const result = await this.tronWeb.fullNode.request('wallet/broadcasthex', params, 'post');
  556. if (result.result) {
  557. return {
  558. ...result,
  559. transaction: JSON.parse(result.transaction),
  560. hexTransaction: signedHexTransaction,
  561. };
  562. }
  563. return result;
  564. }
  565. async sendTransaction(to, amount, options = {}) {
  566. if (typeof options === 'string')
  567. options = { privateKey: options };
  568. if (!this.tronWeb.isAddress(to)) {
  569. throw new Error('Invalid recipient provided');
  570. }
  571. if (!utils.isInteger(amount) || amount <= 0) {
  572. throw new Error('Invalid amount provided');
  573. }
  574. options = {
  575. privateKey: this.tronWeb.defaultPrivateKey,
  576. address: this.tronWeb.defaultAddress.hex,
  577. ...options,
  578. };
  579. if (!options.privateKey && !options.address) {
  580. throw new Error('Function requires either a private key or address to be set');
  581. }
  582. const address = options.privateKey ? this.tronWeb.address.fromPrivateKey(options.privateKey) : options.address;
  583. const transaction = await this.tronWeb.transactionBuilder.sendTrx(to, amount, address);
  584. const signedTransaction = await this.sign(transaction, options.privateKey);
  585. const result = await this.sendRawTransaction(signedTransaction);
  586. return result;
  587. }
  588. async sendToken(to, amount, tokenID, options = {}) {
  589. if (typeof options === 'string')
  590. options = { privateKey: options };
  591. if (!this.tronWeb.isAddress(to)) {
  592. throw new Error('Invalid recipient provided');
  593. }
  594. if (!utils.isInteger(amount) || amount <= 0) {
  595. throw new Error('Invalid amount provided');
  596. }
  597. if (utils.isInteger(tokenID))
  598. tokenID = tokenID.toString();
  599. if (!utils.isString(tokenID)) {
  600. throw new Error('Invalid token ID provided');
  601. }
  602. options = {
  603. privateKey: this.tronWeb.defaultPrivateKey,
  604. address: this.tronWeb.defaultAddress.hex,
  605. ...options,
  606. };
  607. if (!options.privateKey && !options.address) {
  608. throw new Error('Function requires either a private key or address to be set');
  609. }
  610. const address = options.privateKey ? this.tronWeb.address.fromPrivateKey(options.privateKey) : options.address;
  611. const transaction = await this.tronWeb.transactionBuilder.sendToken(to, amount, tokenID, address);
  612. const signedTransaction = await this.sign(transaction, options.privateKey);
  613. const result = await this.sendRawTransaction(signedTransaction);
  614. return result;
  615. }
  616. /**
  617. * Freezes an amount of TRX.
  618. * Will give bandwidth OR Energy and TRON Power(voting rights)
  619. * to the owner of the frozen tokens.
  620. *
  621. * @param amount - is the number of frozen trx
  622. * @param duration - is the duration in days to be frozen
  623. * @param resource - is the type, must be either "ENERGY" or "BANDWIDTH"
  624. * @param options
  625. */
  626. async freezeBalance(amount = 0, duration = 3, resource = 'BANDWIDTH', options = {}, receiverAddress) {
  627. if (typeof options === 'string')
  628. options = { privateKey: options };
  629. if (!['BANDWIDTH', 'ENERGY'].includes(resource)) {
  630. throw new Error('Invalid resource provided: Expected "BANDWIDTH" or "ENERGY"');
  631. }
  632. if (!utils.isInteger(amount) || amount <= 0) {
  633. throw new Error('Invalid amount provided');
  634. }
  635. if (!utils.isInteger(duration) || duration < 3) {
  636. throw new Error('Invalid duration provided, minimum of 3 days');
  637. }
  638. options = {
  639. privateKey: this.tronWeb.defaultPrivateKey,
  640. address: this.tronWeb.defaultAddress.hex,
  641. ...options,
  642. };
  643. if (!options.privateKey && !options.address) {
  644. throw new Error('Function requires either a private key or address to be set');
  645. }
  646. const address = options.privateKey ? this.tronWeb.address.fromPrivateKey(options.privateKey) : options.address;
  647. const freezeBalance = await this.tronWeb.transactionBuilder.freezeBalance(amount, duration, resource, address, receiverAddress);
  648. const signedTransaction = await this.sign(freezeBalance, options.privateKey);
  649. const result = await this.sendRawTransaction(signedTransaction);
  650. return result;
  651. }
  652. /**
  653. * Unfreeze TRX that has passed the minimum freeze duration.
  654. * Unfreezing will remove bandwidth and TRON Power.
  655. *
  656. * @param resource - is the type, must be either "ENERGY" or "BANDWIDTH"
  657. * @param options
  658. */
  659. async unfreezeBalance(resource = 'BANDWIDTH', options = {}, receiverAddress) {
  660. if (typeof options === 'string')
  661. options = { privateKey: options };
  662. if (!['BANDWIDTH', 'ENERGY'].includes(resource)) {
  663. throw new Error('Invalid resource provided: Expected "BANDWIDTH" or "ENERGY"');
  664. }
  665. options = {
  666. privateKey: this.tronWeb.defaultPrivateKey,
  667. address: this.tronWeb.defaultAddress.hex,
  668. ...options,
  669. };
  670. if (!options.privateKey && !options.address) {
  671. throw new Error('Function requires either a private key or address to be set');
  672. }
  673. const address = options.privateKey ? this.tronWeb.address.fromPrivateKey(options.privateKey) : options.address;
  674. const unfreezeBalance = await this.tronWeb.transactionBuilder.unfreezeBalance(resource, address, receiverAddress);
  675. const signedTransaction = await this.sign(unfreezeBalance, options.privateKey);
  676. const result = await this.sendRawTransaction(signedTransaction);
  677. return result;
  678. }
  679. /**
  680. * Modify account name
  681. * Note: Username is allowed to edit only once.
  682. *
  683. * @param privateKey - Account private Key
  684. * @param accountName - name of the account
  685. *
  686. * @return modified Transaction Object
  687. */
  688. async updateAccount(accountName, options = {}) {
  689. if (typeof options === 'string')
  690. options = { privateKey: options };
  691. if (!utils.isString(accountName) || !accountName.length) {
  692. throw new Error('Name must be a string');
  693. }
  694. options = {
  695. privateKey: this.tronWeb.defaultPrivateKey,
  696. address: this.tronWeb.defaultAddress.hex,
  697. ...options,
  698. };
  699. if (!options.privateKey && !options.address)
  700. throw Error('Function requires either a private key or address to be set');
  701. const address = options.privateKey ? this.tronWeb.address.fromPrivateKey(options.privateKey) : options.address;
  702. const updateAccount = await this.tronWeb.transactionBuilder.updateAccount(accountName, address);
  703. const signedTransaction = await this.sign(updateAccount, options.privateKey);
  704. const result = await this.sendRawTransaction(signedTransaction);
  705. return result;
  706. }
  707. /**
  708. * Gets a network modification proposal by ID.
  709. */
  710. async getProposal(proposalID) {
  711. if (!utils.isInteger(proposalID) || proposalID < 0) {
  712. throw new Error('Invalid proposalID provided');
  713. }
  714. return this.tronWeb.fullNode.request('wallet/getproposalbyid', {
  715. id: parseInt(proposalID),
  716. }, 'post');
  717. }
  718. /**
  719. * Lists all network modification proposals.
  720. */
  721. async listProposals() {
  722. const { proposals = [] } = await this.tronWeb.fullNode.request('wallet/listproposals', {}, 'post');
  723. return proposals;
  724. }
  725. /**
  726. * Lists all parameters available for network modification proposals.
  727. */
  728. async getChainParameters() {
  729. const { chainParameter = [] } = await this.tronWeb.fullNode.request('wallet/getchainparameters', {}, 'post');
  730. return chainParameter;
  731. }
  732. /**
  733. * Get the account resources
  734. */
  735. async getAccountResources(address = this.tronWeb.defaultAddress.hex) {
  736. if (!this.tronWeb.isAddress(address)) {
  737. throw new Error('Invalid address provided');
  738. }
  739. return this.tronWeb.fullNode.request('wallet/getaccountresource', {
  740. address: this.tronWeb.address.toHex(address),
  741. }, 'post');
  742. }
  743. /**
  744. * Query the amount of resources of a specific resourceType delegated by fromAddress to toAddress
  745. */
  746. async getDelegatedResourceV2(fromAddress = this.tronWeb.defaultAddress.hex, toAddress = this.tronWeb.defaultAddress.hex, options = { confirmed: true }) {
  747. if (!this.tronWeb.isAddress(fromAddress)) {
  748. throw new Error('Invalid address provided');
  749. }
  750. if (!this.tronWeb.isAddress(toAddress)) {
  751. throw new Error('Invalid address provided');
  752. }
  753. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getdelegatedresourcev2`, {
  754. fromAddress: toHex(fromAddress),
  755. toAddress: toHex(toAddress),
  756. }, 'post');
  757. }
  758. /**
  759. * Query the resource delegation index by an account
  760. */
  761. async getDelegatedResourceAccountIndexV2(address = this.tronWeb.defaultAddress.hex, options = { confirmed: true }) {
  762. if (!this.tronWeb.isAddress(address)) {
  763. throw new Error('Invalid address provided');
  764. }
  765. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getdelegatedresourceaccountindexv2`, {
  766. value: toHex(address),
  767. }, 'post');
  768. }
  769. /**
  770. * Query the amount of delegatable resources of the specified resource Type for target address, unit is sun.
  771. */
  772. async getCanDelegatedMaxSize(address = this.tronWeb.defaultAddress.hex, resource = 'BANDWIDTH', options = { confirmed: true }) {
  773. if (!this.tronWeb.isAddress(address)) {
  774. throw new Error('Invalid address provided');
  775. }
  776. this.validator.notValid([
  777. {
  778. name: 'resource',
  779. type: 'resource',
  780. value: resource,
  781. msg: 'Invalid resource provided: Expected "BANDWIDTH" or "ENERGY"',
  782. },
  783. ]);
  784. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getcandelegatedmaxsize`, {
  785. owner_address: toHex(address),
  786. type: resource === 'ENERGY' ? 1 : 0,
  787. }, 'post');
  788. }
  789. /**
  790. * Remaining times of available unstaking API
  791. */
  792. async getAvailableUnfreezeCount(address = this.tronWeb.defaultAddress.hex, options = { confirmed: true }) {
  793. if (!this.tronWeb.isAddress(address)) {
  794. throw new Error('Invalid address provided');
  795. }
  796. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getavailableunfreezecount`, {
  797. owner_address: toHex(address),
  798. }, 'post');
  799. }
  800. /**
  801. * Query the withdrawable balance at the specified timestamp
  802. */
  803. async getCanWithdrawUnfreezeAmount(address = this.tronWeb.defaultAddress.hex, timestamp = Date.now(), options = { confirmed: true }) {
  804. if (!this.tronWeb.isAddress(address)) {
  805. throw new Error('Invalid address provided');
  806. }
  807. if (!utils.isInteger(timestamp) || timestamp < 0) {
  808. throw new Error('Invalid timestamp provided');
  809. }
  810. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode'].request(`wallet${options.confirmed ? 'solidity' : ''}/getcanwithdrawunfreezeamount`, {
  811. owner_address: toHex(address),
  812. timestamp: timestamp,
  813. }, 'post');
  814. }
  815. /**
  816. * Get the exchange ID.
  817. */
  818. async getExchangeByID(exchangeID) {
  819. if (!utils.isInteger(exchangeID) || exchangeID < 0) {
  820. throw new Error('Invalid exchangeID provided');
  821. }
  822. return this.tronWeb.fullNode.request('wallet/getexchangebyid', {
  823. id: exchangeID,
  824. }, 'post');
  825. }
  826. /**
  827. * Lists the exchanges
  828. */
  829. async listExchanges() {
  830. return this.tronWeb.fullNode
  831. .request('wallet/listexchanges', {}, 'post')
  832. .then(({ exchanges = [] }) => exchanges);
  833. }
  834. /**
  835. * Lists all network modification proposals.
  836. */
  837. async listExchangesPaginated(limit = 10, offset = 0) {
  838. return this.tronWeb.fullNode
  839. .request('wallet/getpaginatedexchangelist', {
  840. limit,
  841. offset,
  842. }, 'post')
  843. .then(({ exchanges = [] }) => exchanges);
  844. }
  845. /**
  846. * Get info about thre node
  847. */
  848. async getNodeInfo() {
  849. return this.tronWeb.fullNode.request('wallet/getnodeinfo', {}, 'post');
  850. }
  851. async getTokenListByName(tokenID) {
  852. if (utils.isInteger(tokenID))
  853. tokenID = tokenID.toString();
  854. if (!utils.isString(tokenID) || !tokenID.length) {
  855. throw new Error('Invalid token ID provided');
  856. }
  857. return this.tronWeb.fullNode
  858. .request('wallet/getassetissuelistbyname', {
  859. value: this.tronWeb.fromUtf8(tokenID),
  860. }, 'post')
  861. .then((token) => {
  862. if (Array.isArray(token.assetIssue)) {
  863. return token.assetIssue.map((t) => this._parseToken(t));
  864. }
  865. else if (!token.name) {
  866. throw new Error('Token does not exist');
  867. }
  868. return this._parseToken(token);
  869. });
  870. }
  871. getTokenByID(tokenID) {
  872. if (utils.isInteger(tokenID))
  873. tokenID = tokenID.toString();
  874. if (!utils.isString(tokenID) || !tokenID.length) {
  875. throw new Error('Invalid token ID provided');
  876. }
  877. return this.tronWeb.fullNode
  878. .request('wallet/getassetissuebyid', {
  879. value: tokenID,
  880. }, 'post')
  881. .then((token) => {
  882. if (!token.name) {
  883. throw new Error('Token does not exist');
  884. }
  885. return this._parseToken(token);
  886. });
  887. }
  888. async getReward(address, options = {}) {
  889. options.confirmed = true;
  890. return this._getReward(address, options);
  891. }
  892. async getUnconfirmedReward(address, options = {}) {
  893. options.confirmed = false;
  894. return this._getReward(address, options);
  895. }
  896. async getBrokerage(address, options = {}) {
  897. options.confirmed = true;
  898. return this._getBrokerage(address, options);
  899. }
  900. async getUnconfirmedBrokerage(address, options = {}) {
  901. options.confirmed = false;
  902. return this._getBrokerage(address, options);
  903. }
  904. async _getReward(address = this.tronWeb.defaultAddress.hex, options) {
  905. this.validator.notValid([
  906. {
  907. name: 'origin',
  908. type: 'address',
  909. value: address,
  910. },
  911. ]);
  912. const data = {
  913. address: toHex(address),
  914. };
  915. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode']
  916. .request(`wallet${options.confirmed ? 'solidity' : ''}/getReward`, data, 'post')
  917. .then((result = { reward: undefined }) => {
  918. if (typeof result.reward === 'undefined') {
  919. throw new Error('Not found.');
  920. }
  921. return result.reward;
  922. });
  923. }
  924. async _getBrokerage(address = this.tronWeb.defaultAddress.hex, options) {
  925. this.validator.notValid([
  926. {
  927. name: 'origin',
  928. type: 'address',
  929. value: address,
  930. },
  931. ]);
  932. const data = {
  933. address: toHex(address),
  934. };
  935. return this.tronWeb[options.confirmed ? 'solidityNode' : 'fullNode']
  936. .request(`wallet${options.confirmed ? 'solidity' : ''}/getBrokerage`, data, 'post')
  937. .then((result = {}) => {
  938. if (typeof result.brokerage === 'undefined') {
  939. throw new Error('Not found.');
  940. }
  941. return result.brokerage;
  942. });
  943. }
  944. async getBandwidthPrices() {
  945. return this.tronWeb.fullNode.request('wallet/getbandwidthprices', {}, 'post')
  946. .then((result = {}) => {
  947. if (typeof result.prices === 'undefined') {
  948. throw new Error('Not found.');
  949. }
  950. return result.prices;
  951. });
  952. }
  953. async getEnergyPrices() {
  954. return this.tronWeb.fullNode.request('wallet/getenergyprices', {}, 'post')
  955. .then((result = {}) => {
  956. if (typeof result.prices === 'undefined') {
  957. throw new Error('Not found.');
  958. }
  959. return result.prices;
  960. });
  961. }
  962. }
  963. //# sourceMappingURL=trx.js.map