diff --git a/CHANGELOG.md b/CHANGELOG.md index dcc49528..bf732e05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,14 @@ Change Log ========= +__6.0.0__ +- Fix [issue543](https://github.com/tronprotocol/tronweb/issues/543), replace type AxiosHeaders with InstanceType. +- Add type for value field in the return of the creation by TransactionBuilder methods. +- Fix known type errors. +- Bump axios from 1.6.8 to 1.7.4 and webpack from 5.78.0 to 5.94.0. +- Add TronWeb.address.toChecksumAddress and TronWeb.address.isChecksumAddress APIs. +- Fix the wrong action of `deocdeInput` API in Contract module. [#557](https://github.com/tronprotocol/tronweb/issues/557) + __6.0.0-beta.4__ - Replace `ethers@v5/abi` with abiCoder of `ethers@v6`. - Bump ethers from v6.11.1 to v6.13.1. diff --git a/README.md b/README.md index 1506cec4..02b6a458 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ [TronWeb](https://tronweb.network) aims to deliver a unified, seamless development experience influenced by Ethereum's [Web3](https://github.com/ethereum/web3.js/) implementation. We have taken the core ideas and expanded upon them to unlock the functionality of TRON's unique feature set along with offering new tools for integrating DApps in the browser, Node.js and IoT devices. -Please note that this version is an experimental beta version. To better support its use in TypeScript projects, we have rewritten the entire library in TypeScript. And to make the TronWeb API more secure and consistent, there are some breaking changes. Please check out [6.x API documentation](https://tronweb.network/docu/docs/intro/) for detailed changes so you can start using the new TypeScript version of TronWeb early. Any questions or feedback are welcome [here](https://github.com/tronprotocol/tronweb/issues/new). +To better support its use in TypeScript projects, we have rewritten the entire library in TypeScript. And to make the TronWeb API more secure and consistent, there are some breaking changes. Please check out [6.x API documentation](https://tronweb.network/docu/docs/intro/) for detailed changes so you can start using the new TypeScript version of TronWeb early. Any questions or feedback are welcome [here](https://github.com/tronprotocol/tronweb/issues/new). **Project scope** @@ -64,11 +64,11 @@ For recent history, see the [CHANGELOG](https://github.com/tronprotocol/tronweb/ ### Node.js ```bash -npm install tronweb@beta +npm install tronweb ``` or ```bash -yarn add tronweb@beta +yarn add tronweb ``` ### Browser @@ -118,7 +118,7 @@ First of all, in your typescript file, define TronWeb: import { TronWeb, utils as TronWebUtils, Trx, TransactionBuilder, Contract, Event, Plugin } from 'tronweb'; ``` -Please note that this is not the same as v5.x. If you want to dive into more differences, check out [migration guide](https://tronweb.network/docu/docs/6.0.0-beta.3/Migrating%20from%20v5) +Please note that this is not the same as v5.x. If you want to dive into more differences, check out [migration guide](https://tronweb.network/docu/docs/6.0.0/Migrating%20from%20v5) When you instantiate TronWeb you can define @@ -170,6 +170,15 @@ const tronWeb = new TronWeb({ ) ``` +## Integrity Check + +The package files will be signed using a GPG key pair, and the correctness of the signature will be verified using the following public key: + +``` +pub: 4371 AB85 E5A5 8FAA 88AD 7FDF 9945 DBCA 8C4B B810 +uid: dev@tronweb.network +``` + ## Contributions In order to contribute you can diff --git a/package-lock.json b/package-lock.json index 0fd1e1b5..ddaa312b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,17 +1,17 @@ { "name": "tronweb", - "version": "6.0.0-beta.4", + "version": "6.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "tronweb", - "version": "6.0.0-beta.4", + "version": "6.0.0", "license": "MIT", "dependencies": { "@babel/runtime": "^7.0.0", "@tronweb3/google-protobuf": "^3.21.2", - "axios": "^1.6.8", + "axios": "^1.7.4", "bignumber.js": "^9.0.1", "ethereum-cryptography": "^2.1.3", "ethers": "^6.13.1", @@ -70,8 +70,8 @@ "rimraf": "^3.0.2", "source-map-support": "^0.5.19", "ts-loader": "^9.4.3", - "typescript": "^5.1.6", - "webpack": "^5.78.0", + "typescript": "^5.5.4", + "webpack": "^5.94.0", "webpack-cli": "^5.0.1", "webpack-node-externals": "^3.0.0" } @@ -2379,26 +2379,6 @@ "@types/node": "*" } }, - "node_modules/@types/eslint": { - "version": "8.56.10", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.10.tgz", - "integrity": "sha512-Shavhk87gCtY2fhXDctcfS3e6FdxWkCx1iUZ9eEUbh7rTqlZT0/IzOkCOVt0fCjcFuZ9FPYfuezTBImfHCDBGQ==", - "dev": true, - "dependencies": { - "@types/estree": "*", - "@types/json-schema": "*" - } - }, - "node_modules/@types/eslint-scope": { - "version": "3.7.7", - "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz", - "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==", - "dev": true, - "dependencies": { - "@types/eslint": "*", - "@types/estree": "*" - } - }, "node_modules/@types/estree": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", @@ -2953,10 +2933,10 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-assertions": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz", - "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==", + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", "dev": true, "peerDependencies": { "acorn": "^8" @@ -3253,9 +3233,9 @@ } }, "node_modules/axios": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.2.tgz", - "integrity": "sha512-2A8QhOMrbomlDuiLeK9XibIBzuHeRcqqNOHp0Cyp5EoJ1IFDh+XZH3A6BkXtv0K4gFGCI0Y4BM7B1wOEi0Rmgw==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", + "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -3480,9 +3460,9 @@ } }, "node_modules/body-parser": { - "version": "1.20.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", - "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", "dev": true, "dependencies": { "bytes": "3.1.2", @@ -3493,7 +3473,7 @@ "http-errors": "2.0.0", "iconv-lite": "0.4.24", "on-finished": "2.4.1", - "qs": "6.11.0", + "qs": "6.13.0", "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" @@ -4416,9 +4396,9 @@ } }, "node_modules/enhanced-resolve": { - "version": "5.17.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.0.tgz", - "integrity": "sha512-dwDPwZL0dmye8Txp2gzFmA6sxALaSvdRDjPH0viLcKrtlOL3tw62nWWweVD1SdILDTJrbrL6tdWVN58Wo6U3eA==", + "version": "5.17.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", + "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", "dev": true, "dependencies": { "graceful-fs": "^4.2.4", @@ -7706,9 +7686,9 @@ } }, "node_modules/micromatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.7.tgz", - "integrity": "sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dev": true, "dependencies": { "braces": "^3.0.3", @@ -8605,12 +8585,12 @@ } }, "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", "dev": true, "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -9911,9 +9891,9 @@ } }, "node_modules/typescript": { - "version": "5.4.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", - "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", + "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -10167,21 +10147,20 @@ } }, "node_modules/webpack": { - "version": "5.91.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.91.0.tgz", - "integrity": "sha512-rzVwlLeBWHJbmgTC/8TvAcu5vpJNII+MelQpylD4jNERPwpBJOE2lEcko1zJX3QJeLjTTAnQxn/OJ8bjDzVQaw==", + "version": "5.94.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz", + "integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==", "dev": true, "dependencies": { - "@types/eslint-scope": "^3.7.3", "@types/estree": "^1.0.5", "@webassemblyjs/ast": "^1.12.1", "@webassemblyjs/wasm-edit": "^1.12.1", "@webassemblyjs/wasm-parser": "^1.12.1", "acorn": "^8.7.1", - "acorn-import-assertions": "^1.9.0", + "acorn-import-attributes": "^1.9.5", "browserslist": "^4.21.10", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.16.0", + "enhanced-resolve": "^5.17.1", "es-module-lexer": "^1.2.1", "eslint-scope": "5.1.1", "events": "^3.2.0", diff --git a/package.json b/package.json index a0b23965..7563f945 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tronweb", - "version": "6.0.0-beta.4", + "version": "6.0.0", "description": "JavaScript SDK that encapsulates the TRON HTTP API", "main": "./lib/commonjs/index.js", "module": "./lib/esm/index.js", @@ -59,7 +59,7 @@ "dependencies": { "@babel/runtime": "^7.0.0", "@tronweb3/google-protobuf": "^3.21.2", - "axios": "^1.6.8", + "axios": "^1.7.4", "bignumber.js": "^9.0.1", "ethereum-cryptography": "^2.1.3", "ethers": "^6.13.1", @@ -118,8 +118,8 @@ "rimraf": "^3.0.2", "source-map-support": "^0.5.19", "ts-loader": "^9.4.3", - "typescript": "^5.1.6", - "webpack": "^5.78.0", + "typescript": "^5.5.4", + "webpack": "^5.94.0", "webpack-cli": "^5.0.1", "webpack-node-externals": "^3.0.0" }, diff --git a/src/lib/TransactionBuilder/TransactionBuilder.ts b/src/lib/TransactionBuilder/TransactionBuilder.ts index eb5f5df1..0f82fcb1 100644 --- a/src/lib/TransactionBuilder/TransactionBuilder.ts +++ b/src/lib/TransactionBuilder/TransactionBuilder.ts @@ -7,19 +7,43 @@ import { Validator } from '../../paramValidator/index.js'; import { GetSignWeightResponse } from '../../types/APIResponse.js'; import { isArray, isInteger, isNotNullOrUndefined, isObject, isString } from '../../utils/validations.js'; import { + AccountCreateContract, AccountPermissionUpdateContract, + AccountUpdateContract, AssetIssueContract, + CancelFreezeBalanceV2Contract, + ClearABIContract, + ContractParamter, ContractType, CreateSmartContract, DelegateResourceContract, DeployConstantContract, + ExchangeCreateContract, + ExchangeInjectContract, + ExchangeTransactionContract, + ExchangeWithdrawContract, FreezeBalanceContract, FreezeBalanceV2Contract, + ParticipateAssetIssueContract, Permission, + ProposalCreateContract, + ProposalDeleteContract, + SetAccountIdContract, + TransferAssetContract, + TransferContract, TriggerSmartContract, UnDelegateResourceContract, + UnfreezeBalanceContract, UnfreezeBalanceV2Contract, UpdateAssetContract, + UpdateBrokerageContract, + UpdateEnergyLimitContract, + UpdateSettingContract, + VoteProposalContract, + VoteWitnessContract, + WithdrawBalanceContract, + WithdrawExpireUnfreezeContract, + WitnessCreateContract, } from '../../types/Contract.js'; import { createTransaction, @@ -47,6 +71,12 @@ import { import { Address } from '../../types/Trx.js'; import { ConstructorFragment, ContractAbiInterface, FunctionFragment } from '../../types/ABI.js'; +interface IArgs extends TriggerSmartContract { + function_selector?: string; + parameter?: string; + fee_limit?: number; + Permission_id?: number; +} export class TransactionBuilder { private tronWeb: TronWeb; private validator: Validator; @@ -63,7 +93,7 @@ export class TransactionBuilder { amount = 0, from: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ): Promise { + ): Promise> { // accept amounts passed as strings amount = parseInt(amount); @@ -91,14 +121,14 @@ export class TransactionBuilder { }, ]); - const data = { + const data: TransferContract = { to_address: toHex(to), owner_address: toHex(from as string), amount: amount, }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.TransferContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.TransferContract, data, options?.permissionId, transactionOptions); } async sendToken( @@ -107,7 +137,7 @@ export class TransactionBuilder { tokenId: string, from: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ): Promise { + ): Promise> { amount = parseInt(amount); this.validator.notValid([ { @@ -138,7 +168,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: TransferAssetContract = { to_address: toHex(to), owner_address: toHex(from as string), asset_name: fromUtf8(tokenId as string), @@ -146,7 +176,7 @@ export class TransactionBuilder { }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.TransferAssetContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.TransferAssetContract, data, options?.permissionId, transactionOptions); } async purchaseToken( @@ -155,7 +185,7 @@ export class TransactionBuilder { amount = 0, buyer: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'buyer', @@ -185,7 +215,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ParticipateAssetIssueContract = { to_address: toHex(issuerAddress), owner_address: toHex(buyer as string), asset_name: fromUtf8(tokenId as string), @@ -193,7 +223,7 @@ export class TransactionBuilder { }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ParticipateAssetIssueContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ParticipateAssetIssueContract, data, options?.permissionId, transactionOptions); } async freezeBalance( @@ -203,7 +233,7 @@ export class TransactionBuilder { ownerAddress: string = this.tronWeb.defaultAddress.hex as string, receiverAddress?: string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -249,7 +279,7 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.FreezeBalanceContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.FreezeBalanceContract, data, options?.permissionId, transactionOptions); } async unfreezeBalance( @@ -257,7 +287,7 @@ export class TransactionBuilder { address: string = this.tronWeb.defaultAddress.hex as string, receiverAddress?: string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -277,7 +307,7 @@ export class TransactionBuilder { msg: 'Invalid resource provided: Expected "BANDWIDTH" or "ENERGY"', }, ]); - const data: { owner_address: string; resource?: Resource; receiver_address?: string } = { + const data: Partial = { owner_address: toHex(address as string), }; if (resource !== 'BANDWIDTH') { @@ -289,7 +319,7 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UnfreezeBalanceContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UnfreezeBalanceContract, data as UnfreezeBalanceContract, options?.permissionId, transactionOptions); } async freezeBalanceV2( @@ -297,7 +327,7 @@ export class TransactionBuilder { resource: Resource = 'BANDWIDTH', address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -326,7 +356,7 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.FreezeBalanceV2Contract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.FreezeBalanceV2Contract, data, options?.permissionId, transactionOptions); } async unfreezeBalanceV2( @@ -334,7 +364,7 @@ export class TransactionBuilder { resource: Resource = 'BANDWIDTH', address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -363,10 +393,13 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UnfreezeBalanceV2Contract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UnfreezeBalanceV2Contract, data, options?.permissionId, transactionOptions); } - async cancelUnfreezeBalanceV2(address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {}) { + async cancelUnfreezeBalanceV2( + address: string = this.tronWeb.defaultAddress.hex as string, + options: TransactionCommonOptions = {} + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -374,12 +407,12 @@ export class TransactionBuilder { value: address as string, }, ]); - const data = { + const data: CancelFreezeBalanceV2Contract = { owner_address: toHex(address as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.CancelAllUnfreezeV2Contract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.CancelAllUnfreezeV2Contract, data, options?.permissionId, transactionOptions); } async delegateResource( @@ -390,7 +423,7 @@ export class TransactionBuilder { lock = false, lockPeriod?: number, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'amount', @@ -447,7 +480,7 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.DelegateResourceContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.DelegateResourceContract, data, options?.permissionId, transactionOptions); } async undelegateResource( @@ -456,7 +489,7 @@ export class TransactionBuilder { resource: Resource = 'BANDWIDTH', address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -496,10 +529,13 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UnDelegateResourceContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UnDelegateResourceContract, data, options?.permissionId, transactionOptions); } - async withdrawExpireUnfreeze(address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {}) { + async withdrawExpireUnfreeze( + address: string = this.tronWeb.defaultAddress.hex as string, + options: TransactionCommonOptions = {} + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -508,15 +544,18 @@ export class TransactionBuilder { }, ]); - const data = { + const data: WithdrawExpireUnfreezeContract = { owner_address: toHex(address), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.WithdrawExpireUnfreezeContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.WithdrawExpireUnfreezeContract, data, options?.permissionId, transactionOptions); } - async withdrawBlockRewards(address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {}) { + async withdrawBlockRewards( + address: string = this.tronWeb.defaultAddress.hex as string, + options: TransactionCommonOptions = {} + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -525,15 +564,19 @@ export class TransactionBuilder { }, ]); - const data = { + const data: WithdrawBalanceContract = { owner_address: toHex(address as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.WithdrawBalanceContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.WithdrawBalanceContract, data, options?.permissionId, transactionOptions); } - async applyForSR(address: string = this.tronWeb.defaultAddress.hex as string, url = '', options: TransactionCommonOptions = {}) { + async applyForSR( + address: string = this.tronWeb.defaultAddress.hex as string, + url = '', + options: TransactionCommonOptions = {} + ): Promise> { this.validator.notValid([ { name: 'origin', @@ -555,20 +598,20 @@ export class TransactionBuilder { }, ]); - const data = { + const data: WitnessCreateContract = { owner_address: toHex(address as string), url: fromUtf8(url as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.WitnessCreateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.WitnessCreateContract, data, options?.permissionId, transactionOptions); } async vote( votes: VoteInfo = {}, voterAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'voter', @@ -606,13 +649,13 @@ export class TransactionBuilder { }; }); - const data = { + const data: VoteWitnessContract = { owner_address: toHex(voterAddress as string), votes: voteList, }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.VoteWitnessContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.VoteWitnessContract, data, options?.permissionId, transactionOptions); } async createSmartContract( @@ -631,7 +674,9 @@ export class TransactionBuilder { // @ts-ignore const tokenId = options.tokenId || options.token_id; - let { abi, parameters = [] } = options; + let { abi } = options; + const { parameters = [] } = options; + let parameter = ''; const { bytecode = false, name = '' } = options; if (abi && isString(abi)) { try { @@ -718,9 +763,9 @@ export class TransactionBuilder { const { rawParameter, funcABIV2, parametersV2 } = options as any; if (rawParameter && isString(rawParameter)) { - parameters = rawParameter.replace(/^(0x)/, ''); + parameter = rawParameter.replace(/^(0x)/, ''); } else if (funcABIV2) { - parameters = encodeParamsV2ByABI(funcABIV2, parametersV2).replace(/^(0x)/, ''); + parameter = encodeParamsV2ByABI(funcABIV2, parametersV2).replace(/^(0x)/, ''); } else { let constructorParams: any = entries.find((it: any) => { return it.type === 'constructor'; @@ -758,12 +803,12 @@ export class TransactionBuilder { } try { - parameters = abiCoder.encode(types, values).replace(/^(0x)/, ''); + parameter = abiCoder.encode(types, values).replace(/^(0x)/, ''); } catch (ex) { throw new Error(ex as string); } } else { - parameters = ''; + parameter = ''; } } @@ -775,7 +820,7 @@ export class TransactionBuilder { origin_energy_limit: originEnergyLimit, abi: JSON.stringify(abi), bytecode, - parameter: parameters, + parameter, name, }; @@ -961,7 +1006,7 @@ export class TransactionBuilder { callValue?: number, feeLimit?: number ) { - const args: TriggerSmartContract = { + const args: IArgs = { contract_address: toHex(contractAddress), owner_address: toHex(issuerAddress), }; @@ -1135,7 +1180,7 @@ export class TransactionBuilder { value.token_id = args.token_id; } const transactionOptions = getTransactionOptions(options); - const transaction = await createTransaction( + const transaction = await createTransaction( this.tronWeb, ContractType.TriggerSmartContract, value, @@ -1243,10 +1288,10 @@ export class TransactionBuilder { contractAddress: string, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { if (!TronWeb.isAddress(contractAddress)) throw new Error('Invalid contract address provided'); if (!TronWeb.isAddress(ownerAddress)) throw new Error('Invalid owner address provided'); - const data = { + const data: ClearABIContract = { contract_address: toHex(contractAddress), owner_address: toHex(ownerAddress as string), }; @@ -1260,13 +1305,13 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ClearABIContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ClearABIContract, data, options?.permissionId, transactionOptions); } async updateBrokerage( brokerage: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { if (!isNotNullOrUndefined(brokerage)) throw new Error('Invalid brokerage provided'); if (!isInteger(brokerage) || brokerage < 0 || brokerage > 100) @@ -1274,19 +1319,19 @@ export class TransactionBuilder { if (!TronWeb.isAddress(ownerAddress)) throw new Error('Invalid owner address provided'); - const data = { + const data: UpdateBrokerageContract = { brokerage: parseInt(brokerage), owner_address: toHex(ownerAddress as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UpdateBrokerageContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UpdateBrokerageContract, data, options?.permissionId, transactionOptions); } async createToken( options: CreateTokenOptions = {} as CreateTokenOptions, issuerAddress: string = this.tronWeb.defaultAddress.hex as string - ) { + ): Promise> { const { name = false, abbreviation = false, @@ -1427,7 +1472,7 @@ export class TransactionBuilder { data.vote_score = parseInt(voteScore); } const transactionOptions = getTransactionOptions(options); - return createTransaction( + return createTransaction( this.tronWeb, ContractType.AssetIssueContract, data as AssetIssueContract, @@ -1440,7 +1485,7 @@ export class TransactionBuilder { accountAddress: string, address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'account', @@ -1453,20 +1498,20 @@ export class TransactionBuilder { value: address as string, }, ]); - const data = { + const data: AccountCreateContract = { owner_address: toHex(address as string), account_address: toHex(accountAddress), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.AccountCreateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.AccountCreateContract, data, options?.permissionId, transactionOptions); } async updateAccount( accountName: string, address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'Name', @@ -1483,20 +1528,20 @@ export class TransactionBuilder { }, ]); - const data = { + const data: AccountUpdateContract = { account_name: fromUtf8(accountName as string), owner_address: toHex(address as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.AccountUpdateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.AccountUpdateContract, data, options?.permissionId, transactionOptions); } async setAccountId( accountId: string, address: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { if (accountId && isString(accountId) && accountId.startsWith('0x')) { accountId = accountId.slice(2); } @@ -1521,19 +1566,19 @@ export class TransactionBuilder { }, ]); - const data = { + const data: SetAccountIdContract = { account_id: accountId, owner_address: toHex(address as string), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.SetAccountIdContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.SetAccountIdContract, data, options?.permissionId, transactionOptions); } async updateToken( options: UpdateTokenOptions = {} as UpdateTokenOptions, issuerAddress: string = this.tronWeb.defaultAddress.hex as string - ) { + ): Promise> { const { description = '', url = false, @@ -1580,7 +1625,7 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UpdateAssetContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UpdateAssetContract, data, options?.permissionId, transactionOptions); } async sendAsset( @@ -1622,7 +1667,7 @@ export class TransactionBuilder { parameters: Record | Record[], issuerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'issuer', @@ -1639,13 +1684,13 @@ export class TransactionBuilder { if (!isObject(parameter)) throw new Error(invalid); } - const data = { + const data: ProposalCreateContract = { owner_address: toHex(issuerAddress as string), parameters: newParams, }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ProposalCreateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ProposalCreateContract, data, options?.permissionId, transactionOptions); } /** @@ -1656,7 +1701,7 @@ export class TransactionBuilder { proposalID: number, issuerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'issuer', @@ -1671,13 +1716,13 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ProposalDeleteContract = { owner_address: toHex(issuerAddress as string), proposal_id: parseInt(proposalID as number), }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ProposalDeleteContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ProposalDeleteContract, data, options?.permissionId, transactionOptions); } /** @@ -1689,7 +1734,7 @@ export class TransactionBuilder { isApproval = false, voterAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'voter', @@ -1709,7 +1754,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: VoteProposalContract = { owner_address: toHex(voterAddress as string), proposal_id: parseInt(proposalID), is_add_approval: isApproval, @@ -1730,7 +1775,7 @@ export class TransactionBuilder { trxBalance: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -1754,7 +1799,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ExchangeCreateContract = { owner_address: toHex(ownerAddress as string), first_token_id: fromUtf8(tokenName), first_token_balance: tokenBalance, @@ -1779,7 +1824,7 @@ export class TransactionBuilder { secondTokenBalance: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -1808,7 +1853,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ExchangeCreateContract = { owner_address: toHex(ownerAddress as string), first_token_id: fromUtf8(firstTokenName), first_token_balance: firstTokenBalance, @@ -1817,7 +1862,7 @@ export class TransactionBuilder { }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ExchangeCreateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ExchangeCreateContract, data, options?.permissionId, transactionOptions); } /** @@ -1831,7 +1876,7 @@ export class TransactionBuilder { tokenAmount: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -1857,7 +1902,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ExchangeInjectContract = { owner_address: toHex(ownerAddress as string), exchange_id: parseInt(exchangeID), token_id: fromUtf8(tokenName), @@ -1879,7 +1924,7 @@ export class TransactionBuilder { tokenAmount: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -1905,7 +1950,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ExchangeWithdrawContract = { owner_address: toHex(ownerAddress as string), exchange_id: parseInt(exchangeID), token_id: fromUtf8(tokenName), @@ -1913,7 +1958,7 @@ export class TransactionBuilder { }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ExchangeWithdrawContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ExchangeWithdrawContract, data, options?.permissionId, transactionOptions); } /** @@ -1928,7 +1973,7 @@ export class TransactionBuilder { tokenAmountExpected: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -1960,7 +2005,7 @@ export class TransactionBuilder { }, ]); - const data = { + const data: ExchangeTransactionContract = { owner_address: toHex(ownerAddress as string), exchange_id: parseInt(exchangeID), token_id: TronWeb.fromAscii(tokenName).replace(/^0x/, ''), @@ -1969,7 +2014,7 @@ export class TransactionBuilder { }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.ExchangeTransactionContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.ExchangeTransactionContract, data, options?.permissionId, transactionOptions); } /** @@ -1980,7 +2025,7 @@ export class TransactionBuilder { userFeePercentage: number, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -2001,14 +2046,14 @@ export class TransactionBuilder { }, ]); - const data = { + const data: UpdateSettingContract = { owner_address: toHex(ownerAddress as string), contract_address: toHex(contractAddress), consume_user_resource_percent: userFeePercentage, }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UpdateSettingContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UpdateSettingContract, data, options?.permissionId, transactionOptions); } /** @@ -2019,7 +2064,7 @@ export class TransactionBuilder { originEnergyLimit = 0, ownerAddress: string = this.tronWeb.defaultAddress.hex as string, options: TransactionCommonOptions = {} - ) { + ): Promise> { this.validator.notValid([ { name: 'owner', @@ -2040,14 +2085,14 @@ export class TransactionBuilder { }, ]); - const data = { + const data: UpdateEnergyLimitContract = { owner_address: toHex(ownerAddress as string), contract_address: toHex(contractAddress), origin_energy_limit: originEnergyLimit, }; const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.UpdateEnergyLimitContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.UpdateEnergyLimitContract, data, options?.permissionId, transactionOptions); } private checkPermissions(permissions: Permission, type: number) { @@ -2083,7 +2128,7 @@ export class TransactionBuilder { witnessPermission?: Permission, activesPermissions?: Permission | Permission[], options: TransactionCommonOptions = {} - ) { + ): Promise> { if (!TronWeb.isAddress(ownerAddress as Address)) throw new Error('Invalid ownerAddress provided'); if (!this.checkPermissions(ownerPermission, 0)) { @@ -2149,14 +2194,14 @@ export class TransactionBuilder { } const transactionOptions = getTransactionOptions(options); - return createTransaction(this.tronWeb, ContractType.AccountPermissionUpdateContract, data, options?.permissionId, transactionOptions); + return createTransaction(this.tronWeb, ContractType.AccountPermissionUpdateContract, data, options?.permissionId, transactionOptions); } - async newTxID(transaction: SignedTransaction, options: { txLocal?: boolean } = {}) { + async newTxID | Transaction)>(transaction: U, options: { txLocal?: boolean } = {}): Promise { if (options?.txLocal) { const contract = transaction.raw_data.contract[0]; try { - const tx = await createTransaction( + const tx = await createTransaction( this.tronWeb, contract.type, contract.parameter.value, @@ -2170,9 +2215,9 @@ export class TransactionBuilder { timestamp: transaction.raw_data.timestamp, } ); - (tx as SignedTransaction).signature = transaction.signature; + (tx as SignedTransaction).signature = (transaction as SignedTransaction).signature; tx.visible = transaction.visible; - return tx; + return tx as U; } catch (e) { throw new Error('Error generating a new transaction id.'); } @@ -2191,7 +2236,7 @@ export class TransactionBuilder { // eslint-disable-next-line @typescript-eslint/ban-ts-comment /* @ts-ignore */ { data: transaction.raw_data.data, fee_limit: transaction.raw_data.fee_limit } - ); + ) as unknown as U; } catch (e) { throw new Error('Error generating a new transaction id.'); } @@ -2214,10 +2259,10 @@ export class TransactionBuilder { transaction.raw_data.expiration += options.extension; } - return await this.newTxID(transaction as SignedTransaction, { txLocal: options.txLocal }); + return await this.newTxID(transaction, { txLocal: options.txLocal }); } - async extendExpiration(transaction: SignedTransaction, extension: number, options: TxLocal = {}) { + async extendExpiration(transaction: Transaction, extension: number, options: TxLocal = {}) { return await this.alterTransaction(transaction, { extension, txLocal: options?.txLocal }); } diff --git a/src/lib/TransactionBuilder/helper.ts b/src/lib/TransactionBuilder/helper.ts index e00599f9..2adc4ba5 100644 --- a/src/lib/TransactionBuilder/helper.ts +++ b/src/lib/TransactionBuilder/helper.ts @@ -93,14 +93,14 @@ function checkBlockHeader(options = {} as Partial): boo return true; } -export async function createTransaction( +export async function createTransaction( tronWeb: TronWeb, type: ContractType, - value: ContractParamter, + value: T, Permission_id?: number, options = {} as Partial> -): Promise { - const tx: Transaction = { +): Promise> { + const tx: Transaction = { visible: false, txID: '', raw_data_hex: '', diff --git a/src/lib/contract/index.ts b/src/lib/contract/index.ts index 42929a52..d4017a97 100644 --- a/src/lib/contract/index.ts +++ b/src/lib/contract/index.ts @@ -105,7 +105,7 @@ export class Contract { }; } - async new(options: CreateSmartContractOptions, privateKey = this.tronWeb.defaultPrivateKey, callback = false) { + async new(options: CreateSmartContractOptions, privateKey = this.tronWeb.defaultPrivateKey) { const address = this.tronWeb.address.fromPrivateKey(privateKey as string); const transaction = await this.tronWeb.transactionBuilder.createSmartContract(options, address as Address); const signedTransaction = await this.tronWeb.trx.sign(transaction, privateKey); diff --git a/src/lib/contract/method.ts b/src/lib/contract/method.ts index 8d4c707a..edecb1cf 100644 --- a/src/lib/contract/method.ts +++ b/src/lib/contract/method.ts @@ -38,7 +38,7 @@ import type { EventFragment, AbiInputsType, AbiOutputsType, -} from '../../types/ABI'; +} from '../../types/ABI.js'; export type AbiFragmentNoErrConstructor = FunctionFragment | EventFragment | FallbackFragment | ReceiveFragment; @@ -107,7 +107,9 @@ export class Method { } decodeInput(data: string) { - return decodeOutput(this.abi, '0x' + data); + const abi = JSON.parse(JSON.stringify(this.abi)); + abi.outputs = abi.inputs; + return decodeOutput(abi, '0x' + data); } onMethod(...args: any[]) { diff --git a/src/lib/providers/HttpProvider.ts b/src/lib/providers/HttpProvider.ts index 25edd3d7..ae22a668 100644 --- a/src/lib/providers/HttpProvider.ts +++ b/src/lib/providers/HttpProvider.ts @@ -55,7 +55,7 @@ export default class HttpProvider { method = method.toLowerCase() as Method; return this.instance - .request<{ data: T }>({ + .request({ data: method == 'post' && Object.keys(payload).length ? payload : null, params: method == 'get' && payload, url, diff --git a/src/lib/trx.ts b/src/lib/trx.ts index b3bb4ab1..e3bee6bb 100644 --- a/src/lib/trx.ts +++ b/src/lib/trx.ts @@ -24,7 +24,7 @@ import { } from '../types/Trx.js'; import { SignedTransaction, Transaction } from '../types/Transaction.js'; import { TypedDataDomain, TypedDataField } from '../utils/typedData.js'; -import { Resource } from '../types/TransactionBuilder'; +import { Resource } from '../types/TransactionBuilder.js'; const TRX_MESSAGE_HEADER = '\x19TRON Signed Message:\n32'; // it should be: '\x15TRON Signed Message:\n32'; @@ -655,7 +655,6 @@ export class Trx { * @param {message to be signed, should be Bytes or string} message * @param {privateKey for signature} privateKey * @param {reserved} options - * @param {callback function} callback */ signMessageV2(message: string | Uint8Array | Array, privateKey = this.tronWeb.defaultPrivateKey) { return Trx.signMessageV2(message, privateKey as string); @@ -872,7 +871,6 @@ export class Trx { * @param duration - is the duration in days to be frozen * @param resource - is the type, must be either "ENERGY" or "BANDWIDTH" * @param options - * @param callback */ async freezeBalance( amount = 0, @@ -924,7 +922,6 @@ export class Trx { * * @param resource - is the type, must be either "ENERGY" or "BANDWIDTH" * @param options - * @param callback */ async unfreezeBalance( resource: Resource = 'BANDWIDTH', @@ -964,7 +961,6 @@ export class Trx { * * @param privateKey - Account private Key * @param accountName - name of the account - * @param callback * * @return modified Transaction Object */ diff --git a/src/tronweb.ts b/src/tronweb.ts index 1f3b7e19..3041d7b2 100644 --- a/src/tronweb.ts +++ b/src/tronweb.ts @@ -1,7 +1,7 @@ import { HttpProvider, providers } from './lib/providers/index.js'; import type { Providers } from './lib/providers/index.js'; import utils from './utils/index.js'; -import BigNumber from 'bignumber.js'; +import { BigNumber } from 'bignumber.js'; import EventEmitter from 'eventemitter3'; import semver from 'semver'; @@ -11,10 +11,10 @@ import { Contract } from './lib/contract/index.js'; import { Plugin } from './lib/plugin.js'; import { Event } from './lib/event.js'; import { keccak256 } from './utils/ethersUtils.js'; -import { fromHex, fromPrivateKey, isAddress, toHex } from './utils/address.js'; +import { fromHex, fromPrivateKey, isAddress, toHex, toChecksumAddress, isChecksumAddress } from './utils/address.js'; import { HeadersType } from './types/Providers.js'; import { isString } from './utils/validations.js'; -import { DefaultAddress, NodeProvider, TronWebOptions } from './types/TronWeb.js'; +import { DefaultAddress, NodeProvider, TronWebOptions, IBigNumber } from './types/TronWeb.js'; import { ContractAbiInterface } from './types/ABI.js'; import { Address } from './types/Trx.js'; @@ -22,7 +22,7 @@ const DEFAULT_VERSION = '4.7.1'; const FEE_LIMIT = 150000000; -const version = '6.0.0-beta.4'; +const version = '6.0.0'; function isValidOptions(options: unknown): options is TronWebOptions { return ( @@ -276,6 +276,12 @@ export class TronWeb extends EventEmitter { toHex(address: string) { return toHex(address); }, + toChecksumAddress(address: string) { + return toChecksumAddress(address); + }, + isChecksumAddress(address: string) { + return isChecksumAddress(address); + }, fromPrivateKey(privateKey: string, strict = false) { return fromPrivateKey(privateKey, strict); }, @@ -288,7 +294,7 @@ export class TronWeb extends EventEmitter { } toHex: typeof TronWeb.toHex; - static toHex(val: string | number | boolean | Record | unknown[] | BigNumber) { + static toHex(val: string | number | boolean | Record | unknown[] | IBigNumber) { if (utils.isBoolean(val)) return TronWeb.fromDecimal(+val); if (utils.isBigNumber(val)) return TronWeb.fromDecimal(val); @@ -357,12 +363,12 @@ export class TronWeb extends EventEmitter { } toDecimal: typeof TronWeb.toDecimal; - static toDecimal(value: string | number | BigNumber) { + static toDecimal(value: string | number | IBigNumber) { return TronWeb.toBigNumber(value).toNumber(); } fromDecimal: typeof TronWeb.fromDecimal; - static fromDecimal(value: number | BigNumber) { + static fromDecimal(value: number | IBigNumber) { const number = TronWeb.toBigNumber(value); const result = number.toString(16); @@ -370,19 +376,19 @@ export class TronWeb extends EventEmitter { } fromSun: typeof TronWeb.fromSun; - static fromSun(sun: number) { + static fromSun(sun: number): string | IBigNumber { const trx = TronWeb.toBigNumber(sun).div(1_000_000); return utils.isBigNumber(sun) ? trx : trx.toString(10); } toSun: typeof TronWeb.toSun; - static toSun(trx: number) { + static toSun(trx: number): string | IBigNumber { const sun = TronWeb.toBigNumber(trx).times(1_000_000); return utils.isBigNumber(trx) ? sun : sun.toString(10); } toBigNumber: typeof TronWeb.toBigNumber; - static toBigNumber(amount: string | number | BigNumber = 0) { + static toBigNumber(amount: string | number | IBigNumber = 0): IBigNumber { if (utils.isBigNumber(amount)) return amount; if (utils.isString(amount) && /^(-|)0x/.test(amount)) return new BigNumber(amount.replace('0x', ''), 16); @@ -420,7 +426,7 @@ export class TronWeb extends EventEmitter { return account; } - async isConnected(callback = false) { + async isConnected() { return { fullNode: await this.fullNode.isConnected(), solidityNode: await this.solidityNode.isConnected(), diff --git a/src/types/APIResponse.ts b/src/types/APIResponse.ts index 95366d6d..a4e6e244 100644 --- a/src/types/APIResponse.ts +++ b/src/types/APIResponse.ts @@ -1,5 +1,5 @@ -import { Permission } from './Contract'; -import { Transaction, TransactionWrapper } from './Transaction'; +import { Permission } from './Contract.js'; +import { Transaction, TransactionWrapper } from './Transaction.js'; export interface BlockHeaderRawData { number: number; diff --git a/src/types/Contract.ts b/src/types/Contract.ts index 311b7be4..1196abf1 100644 --- a/src/types/Contract.ts +++ b/src/types/Contract.ts @@ -1,5 +1,5 @@ -import { Resource } from '../types/TransactionBuilder'; -import { ContractAbiInterface } from './ABI'; +import { Resource } from '../types/TransactionBuilder.js'; +import { ContractAbiInterface } from './ABI.js'; export enum ContractType { AccountCreateContract = 'AccountCreateContract', TransferContract = 'TransferContract', @@ -86,7 +86,7 @@ export interface TransferContract { export interface TransferAssetContract { to_address: string; owner_address: string; - amount: string; + amount: number; asset_name: string; } @@ -100,15 +100,10 @@ export interface ParticipateAssetIssueContract { export interface TriggerSmartContract { owner_address: string; contract_address: string; - parameter?: string; - function_selector?: string; call_value?: number; call_token_value?: number; token_id?: number; data?: string; - - fee_limit?: number; - Permission_id?: number; } export interface FreezeBalanceContract { @@ -245,55 +240,55 @@ export interface ProposalCreateContract { export interface ProposalDeleteContract { owner_address: string; - proposal_id: string; + proposal_id: number; } export interface VoteProposalContract { owner_address: string; - proposal_id: string; - is_add_approval: string; + proposal_id: number; + is_add_approval: boolean; } export interface ExchangeCreateContract { owner_address: string; first_token_id: string; - first_token_balance: string; + first_token_balance: number; second_token_id: string; - second_token_balance: string; + second_token_balance: number; } export interface ExchangeInjectContract { owner_address: string; - exchange_id: string; + exchange_id: number; token_id: string; - quant: string; + quant: number; } export interface ExchangeWithdrawContract { owner_address: string; - exchange_id: string; + exchange_id: number; token_id: string; - quant: string; + quant: number; } export interface ExchangeTransactionContract { owner_address: string; - exchange_id: string; + exchange_id: number; token_id: string; - quant: string; - expected: string; + quant: number; + expected: number; } export interface UpdateSettingContract { owner_address: string; contract_address: string; - consume_user_resource_percent: string; + consume_user_resource_percent: number; } export interface UpdateEnergyLimitContract { owner_address: string; contract_address: string; - origin_energy_limit: string; + origin_energy_limit: number; } export interface AccountPermissionUpdateContract { diff --git a/src/types/Providers.ts b/src/types/Providers.ts index ddc4cc2e..50873aba 100644 --- a/src/types/Providers.ts +++ b/src/types/Providers.ts @@ -1,7 +1,7 @@ import { RawAxiosRequestHeaders, AxiosHeaders, HeadersDefaults } from 'axios'; -export type HeadersType = RawAxiosRequestHeaders | AxiosHeaders | Partial; +export type HeadersType = RawAxiosRequestHeaders | InstanceType | Partial; export type RequestHeaders = RawAxiosRequestHeaders; export interface HttpProviderInstance { - request(config: any): Promise; + request(config: any): Promise<{ data: R }>; } \ No newline at end of file diff --git a/src/types/Transaction.ts b/src/types/Transaction.ts index 4a094f33..56e129a0 100644 --- a/src/types/Transaction.ts +++ b/src/types/Transaction.ts @@ -1,4 +1,4 @@ -import { ContractParamter, ContractType, CreateSmartContract } from './Contract.js'; +import { ContractParamter, ContractType, CreateSmartContract, TriggerSmartContract } from './Contract.js'; export interface ContractParamterWrapper { value: T; @@ -44,7 +44,7 @@ export interface TransactionWrapper { /** * The transaction object created by calling contract function. */ - transaction: Transaction; + transaction: Transaction; /** * Energy required for successfully deploying new contract or trigger contract. * This is returned in `transactionBuilder.estimateEnergy()` and `transactionBuilder.deployConstantContract()` @@ -64,7 +64,7 @@ export interface TransactionWrapper { constant_result?: any; } -export interface SignedTransaction extends Transaction { +export interface SignedTransaction extends Transaction { signature: string[]; contract_address?: string; } diff --git a/src/types/TransactionBuilder.ts b/src/types/TransactionBuilder.ts index 40d298c4..4ffdca5a 100644 --- a/src/types/TransactionBuilder.ts +++ b/src/types/TransactionBuilder.ts @@ -1,5 +1,5 @@ -import { AbiFragment, ContractAbiInterface } from './ABI'; -import { Transaction } from './Transaction'; +import { AbiFragment, ContractAbiInterface } from './ABI.js'; +import { Transaction } from './Transaction.js'; export interface TransactionCommonOptions { /** @@ -57,7 +57,7 @@ export interface CreateSmartContractOptions extends TransactionCommonOptions { * It should be converted hexString after encoded according to ABI encoder. * If constructor has no parameter, this can be optional */ - parameters?: string; + parameters?: unknown[]; /** * Contract name string. */ diff --git a/src/types/TronWeb.ts b/src/types/TronWeb.ts index 45422585..08a35abd 100644 --- a/src/types/TronWeb.ts +++ b/src/types/TronWeb.ts @@ -1,7 +1,10 @@ import { AxiosRequestHeaders } from 'axios'; +import { BigNumber } from 'bignumber.js'; import type { HeadersType } from './Providers.js'; import HttpProvider from '../lib/providers/HttpProvider.js'; +export type IBigNumber = InstanceType; + export interface TronWebOptions { fullNode?: NodeProvider; solidityNode?: NodeProvider; diff --git a/src/types/Trx.ts b/src/types/Trx.ts index d60356ce..15ec05cb 100644 --- a/src/types/Trx.ts +++ b/src/types/Trx.ts @@ -1,5 +1,6 @@ import { AccountType, Permission } from './Contract.js'; import { SignedTransaction, Transaction } from './Transaction.js'; +import { Resource } from './TransactionBuilder.js'; type HTTPMap = Record[]; @@ -62,11 +63,11 @@ export enum ResourceCode { } export interface FreezeV2 { - type: ResourceCode; + type: Resource; amount: number; } export interface UnFreezeV2 { - type: ResourceCode; + type: Resource; unfreeze_amount: number; unfreeze_expire_time: number; } diff --git a/src/types/UtilsTypes.ts b/src/types/UtilsTypes.ts new file mode 100644 index 00000000..d533329f --- /dev/null +++ b/src/types/UtilsTypes.ts @@ -0,0 +1,25 @@ +export type BytesLike = number[] | Uint8Array; + +export type EventQueryDataType = { + block_number: number; + block_timestamp: number; + contract_address: string; + event_name: string; + transaction_id: string; + result: unknown; + resource_Node: string; + _unconfirmed?: boolean; + _fingerprint?: string | undefined; +}; + +export type MapEventQueryDataType = { + block: number; + timestamp: number; + contract: string; + name: string; + transaction: string; + result: unknown; + resourceNode: string; + unconfirmed?: boolean; + fingerprint?: string | undefined; +}; diff --git a/src/types/index.ts b/src/types/index.ts index 1efc3af6..1f03726f 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -6,3 +6,4 @@ export * from './Transaction.js'; export * from './TransactionBuilder.js'; export * from './TronWeb.js'; export * from './Trx.js'; +export * from './UtilsTypes.js'; diff --git a/src/utils/address.ts b/src/utils/address.ts index ad4d1974..e74fdec8 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -1,6 +1,7 @@ import { hexStr2byteArray, byteArray2hexStr } from './code.js'; import { decodeBase58Address, getBase58CheckAddress, isAddressValid, pkToAddress } from './crypto.js'; import { isHex, isString } from './validations.js'; +import { keccak256 } from './ethersUtils.js'; export const ADDRESS_SIZE = 34; export const ADDRESS_PREFIX = '41'; @@ -22,6 +23,44 @@ export function toHex(address: string) { return byteArray2hexStr(decodeBase58Address(address) as number[]).toLowerCase(); } +function getChecksumAddress(address: string): string { + address = address.toLowerCase(); + + const chars = address.substring(2).split(''); + + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); + } + + const hashed = hexStr2byteArray(keccak256(expanded).slice(2)); + + for (let i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + + return ADDRESS_PREFIX + chars.join(''); +} + +export function toChecksumAddress(address: string) { + if (!isAddress(address)) throw new Error(`'${address}' is not a valid address string`); + return getChecksumAddress(toHex(address)); +} + +export function isChecksumAddress(address: string) { + if (!isHex(address) || address.length !== 42) return false; + try { + return toChecksumAddress(address) === address; + } catch { + return false; + } +} + export function fromPrivateKey(privateKey: string, strict = false) { try { return pkToAddress(privateKey, strict); diff --git a/src/utils/base58.ts b/src/utils/base58.ts index b06e8e2e..dd1b6abd 100644 --- a/src/utils/base58.ts +++ b/src/utils/base58.ts @@ -1,4 +1,4 @@ -import type { BytesLike } from './bytes.js'; +import type { BytesLike } from '../types/UtilsTypes.js'; const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; const ALPHABET_MAP = {} as Record; diff --git a/src/utils/base64.ts b/src/utils/base64.ts index d31bc366..37ccbb1b 100644 --- a/src/utils/base64.ts +++ b/src/utils/base64.ts @@ -1,4 +1,4 @@ -import { BytesLike } from './bytes.js'; +import type { BytesLike } from '../types/UtilsTypes.js'; const _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; diff --git a/src/utils/bytes.ts b/src/utils/bytes.ts index f3b3cbcf..45344a0f 100644 --- a/src/utils/bytes.ts +++ b/src/utils/bytes.ts @@ -1,6 +1,5 @@ import { Base64 } from './base64.js'; - -export type BytesLike = number[] | Uint8Array; +import { BytesLike } from '../types/UtilsTypes.js'; export function byte2hexStr(byte: number) { if (byte < 0 || byte > 255) throw new Error('Input must be a byte'); diff --git a/src/utils/code.ts b/src/utils/code.ts index db4542ef..e8815ab6 100644 --- a/src/utils/code.ts +++ b/src/utils/code.ts @@ -6,7 +6,8 @@ import { base64DecodeFromString, base64EncodeToString, } from './bytes.js'; -import type { BytesLike } from './bytes.js'; + +import type { BytesLike } from '../types/UtilsTypes.js'; export function bin2String(array: BytesLike) { return bytesToString(array); diff --git a/src/utils/crypto.ts b/src/utils/crypto.ts index 749b1919..652353eb 100644 --- a/src/utils/crypto.ts +++ b/src/utils/crypto.ts @@ -1,13 +1,15 @@ import { ADDRESS_PREFIX, ADDRESS_PREFIX_BYTE, ADDRESS_SIZE } from './address.js'; import { base64EncodeToString, base64DecodeFromString, hexStr2byteArray } from './code.js'; import { encode58, decode58 } from './base58.js'; -import { BytesLike, byte2hexStr, byteArray2hexStr } from './bytes.js'; +import { byte2hexStr, byteArray2hexStr } from './bytes.js'; import { keccak256, sha256, SigningKey, recoverAddress, arrayify, Signature } from './ethersUtils.js'; import { TypedDataEncoder } from './typedData.js'; import { secp256k1 as secp } from 'ethereum-cryptography/secp256k1'; import type { TypedDataDomain, TypedDataField } from 'ethers'; import { SignedTransaction } from '../types/Transaction.js'; +import type { BytesLike } from '../types/UtilsTypes.js'; + function normalizePrivateKeyBytes(priKeyBytes: BytesLike) { return hexStr2byteArray(byteArray2hexStr(priKeyBytes).padStart(64, '0')); } diff --git a/src/utils/validations.ts b/src/utils/validations.ts index 7b77e1fa..08f58648 100644 --- a/src/utils/validations.ts +++ b/src/utils/validations.ts @@ -1,7 +1,10 @@ -import BigNumber from 'bignumber.js'; +import { BigNumber } from 'bignumber.js'; import validator from 'validator'; import { ADDRESS_PREFIX } from './address.js'; import { AbiParamsCommon } from '../types/ABI.js'; +import { IBigNumber } from '../types/TronWeb.js'; + +import type { EventQueryDataType, MapEventQueryDataType } from '../types/UtilsTypes.js'; export function isValidURL(url: string): boolean { if (typeof url !== 'string') return false; @@ -31,7 +34,7 @@ export function isBoolean(bool: unknown): bool is boolean { return typeof bool === 'boolean'; } -export function isBigNumber(number: unknown): number is BigNumber { +export function isBigNumber(number: unknown): number is IBigNumber { return !!number && (number instanceof BigNumber || (number.constructor && number.constructor.name === 'BigNumber')); } @@ -67,30 +70,6 @@ export function hasProperties(obj: object, ...properties: (string | number | sym ); } -export type EventQueryDataType = { - block_number: number; - block_timestamp: number; - contract_address: string; - event_name: string; - transaction_id: string; - result: unknown; - resource_Node: string; - _unconfirmed?: boolean; - _fingerprint?: string | undefined; -}; - -export type MapEventQueryDataType = { - block: number; - timestamp: number; - contract: string; - name: string; - transaction: string; - result: unknown; - resourceNode: string; - unconfirmed?: boolean; - fingerprint?: string | undefined; -}; - export function mapEvent(event: EventQueryDataType) { const data: MapEventQueryDataType = { block: event.block_number, diff --git a/test/helpers/BlockLib.ts b/test/helpers/BlockLib.ts index aa205667..284d5dcd 100644 --- a/test/helpers/BlockLib.ts +++ b/test/helpers/BlockLib.ts @@ -15,7 +15,7 @@ export default class BlockLib { pluginInterface() { return { - requires: '^6.0.0-beta.0', + requires: '^6.0.0', fullClass: true, }; } diff --git a/test/helpers/GetNowBlock.ts b/test/helpers/GetNowBlock.ts index 800b7a19..1dd5c517 100644 --- a/test/helpers/GetNowBlock.ts +++ b/test/helpers/GetNowBlock.ts @@ -25,7 +25,7 @@ export default class GetNowBlock { someParameter = options.someParameter; } return { - requires: '^6.0.0-beta.0', + requires: '^6.0.0', components: { trx: { // will be overridden diff --git a/test/index.test.ts b/test/index.test.ts index d751954f..e9114d1a 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -2,9 +2,10 @@ import { assert } from 'chai'; import Config from './helpers/config.js'; import { Contract, TronWeb, providers, Types } from './setup/TronWeb.js'; import tronWebBuilder from './helpers/tronWebBuilder.js'; -import BigNumber from 'bignumber.js'; +import { BigNumber } from 'bignumber.js'; import broadcaster from './helpers/broadcaster.js'; import wait from './helpers/wait.js'; +import assertThrow from './helpers/assertThrow.js'; type Address = Types.Address; type RequestHeaders = Types.RequestHeaders; @@ -412,6 +413,28 @@ describe('TronWeb Instance', function () { }); }); + describe('#address.toChecksumAddress', function () { + it('should return the checksum address', function () { + const tronWeb = tronWebBuilder.createInstance(); + assert.equal(tronWeb.address.toChecksumAddress('TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC'), '417E5F4552091A69125d5DfCb7b8C2659029395Bdf') + }); + + it('should throw error', async function () { + const tronWeb = tronWebBuilder.createInstance(); + await assertThrow((async () => { + tronWeb.address.toChecksumAddress('not a valid address'); + })(), "'not a valid address' is not a valid address string"); + }); + }); + + describe('#address.isChecksumAddress', function () { + it('should return the checksum address', function () { + const tronWeb = tronWebBuilder.createInstance(); + assert.isTrue(tronWeb.address.isChecksumAddress('417E5F4552091A69125d5DfCb7b8C2659029395Bdf')); + assert.isFalse(tronWeb.address.isChecksumAddress('417e5f4552091a69125d5dfcb7b8c2659029395bdf')); + }); + }); + describe('#sha3()', function () { it('should match web3 sha function', function () { const input = 'casa'; diff --git a/test/lib/transactionBuilder.test.ts b/test/lib/transactionBuilder.test.ts index aeefcab2..4f2fbfd8 100644 --- a/test/lib/transactionBuilder.test.ts +++ b/test/lib/transactionBuilder.test.ts @@ -2278,6 +2278,7 @@ describe('TronWeb.transactionBuilder', function () { accounts.hex[7] ) ); + await wait(3); transactions.push( await tronWeb.transactionBuilder.createSmartContract( { @@ -2287,6 +2288,7 @@ describe('TronWeb.transactionBuilder', function () { accounts.hex[7] ) ); + await wait(3); transactions.push( await tronWeb.transactionBuilder.createSmartContract( { diff --git a/test/utils/index.test.ts b/test/utils/index.test.ts index 8d4b0bdd..6368c6f7 100644 --- a/test/utils/index.test.ts +++ b/test/utils/index.test.ts @@ -1,6 +1,6 @@ import { assert } from 'chai'; import tronWebBuilder from '../helpers/tronWebBuilder.js'; -import BigNumber from 'bignumber.js'; +import { BigNumber } from 'bignumber.js'; describe('TronWeb.utils', function () { describe('#isValidURL()', function () {