diff --git a/.npmignore b/.npmignore index 05524a6..c62904d 100644 --- a/.npmignore +++ b/.npmignore @@ -1,3 +1,6 @@ .env *.log .idea +src +tests +node_modules diff --git a/README.md b/README.md index f058c78..45f895d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ https://developers.tron.network/reference/tronweb-object ### Installation -Required: node v14/16 LTS +Required: node v14+ LTS ```shell npm install --save-dev @daochild/tronweb-typescript @@ -16,12 +16,7 @@ npm install --save-dev @daochild/tronweb-typescript ### Using -Watch example in ``./src/tests/test.ts`` - -Import should be looks like this: -```typescript -import * as tronwebTypes from "@types/tronweb"; -``` +No special requirements. Just import and use. ### Would be nice to do diff --git a/package.json b/package.json index 9f006b9..e55c036 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,9 @@ { "name": "@daochild/tronweb-typescript", - "version": "1.0.103", + "version": "1.1.0", "description": "Typescript support package for tronweb library ^4.x", - "main": "", - "types": "./src/index.d.ts", + "types": "./dist/index", + "type": "module", "keywords": ["tron", "tronweb", "typescript", "tronweb-typescript", "tronweb-ts"], "scripts": { "start": "npm run build && node build/index.js", diff --git a/src/index.ts b/src/index.ts index b99ed96..0910eea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,190 @@ -'use strict'; +declare module 'tronweb' { + import {BigNumber} from "bignumber.js" + import { + Account, + AccountMnemonic, + AssetTRC10, + AssetUpdate, + BlockInfo, + BlockInput, + BlockTransaction, + BytesLike, + ChainParameter, + ContractExecutionParams, + CreateRandomOptions, + DelegatedResourceAccount, + DelegatedResourceList, + EnergyEstimate, + EventResult, + Exchange, + Header, + HexString, + JsonFragment, + KeyValue, + Miner, + NodeInfo, + Proposal, + Resource, + SideOptions, + TokenInfo, + Transaction, + TransactionResult, + TriggerConstantContractResult, + TronAccountResource, + TronContract, + TronContractResult, + TronWebConstructor, + TrxAccount + } from "tronweb/interfaces"; -/// + export class TronWeb { + address: any; + transactionBuilder: any; + trx: any; + utils: any; + constructor(fullNode: string, solidityNode: string, eventServer: string|boolean, privateKey?: string|boolean); + constructor(fullNode: string, solidityNode: string, eventServer: string|boolean, sideOptions: SideOptions, privateKey?: string|boolean); + constructor(obj: TronWebConstructor); + contract(data: JsonFragment[], address: string): TronContract; + setHeader(header: Header): void|Error; + currentProvider(): any; + currentProviders(): any; + getEventByTransactionID(transactionID: string): Promise; + getEventResult(contractAddress: string, options?: Object): Promise; // check this return + isConnected(): Object; + isValidProvider(provider: any): any; + setAddress(address: string): void|Error; + setDefaultBlock(blockID?: BlockInput): void|string|boolean; + setEventServer(eventServer: any): void|Error; + setFullNode(fullNode: any): void|Error; + setPrivateKey(privateKey: string): void|Error; + setSolidityNode(solidityNode: any): void|Error; + createAccount(): Promise; + createRandom(options?: CreateRandomOptions): Promise; + fromAscii(string: any, padding: any): any; + fromDecimal(value: number|string): string; + fromSun(sun: string|number): string; + fromUtf8(string: string): string; + fromMnemonic(mnemonic: string, path?: string, wordlist?: string): AccountMnemonic|Error; + isAddress(address: string): boolean; + sha3(string: string, prefix?: boolean): HexString; + toAscii(hex: HexString): string; + toBigNumber(amount: number|string|HexString): BigNumber|Object; + toDecimal(value: string|HexString): number|string; + toHex(val: string|number|object|[]|BigNumber): HexString; + toSun(trx: number): string; + toUtf8(hex: string): string; + BigNumber(val: number|string|HexString): BigNumber + } + + export namespace TronWeb { + export namespace transactionBuilder { + function addUpdateData(unsignedTransaction: JSON|Object, memo: string): Promise; + function applyForSR(address: string, url: string, options?: number): Promise; + function createAccount(address: string, options?: JSON|Object): Promise; + function createAsset(options: AssetTRC10, issuerAddress: string): Promise; + function createProposal(parameters: KeyValue[], issuerAddress: string, options?: number): Promise; + function createSmartContract(options: ContractExecutionParams, issuerAddress: string): Promise; + function createToken(options: AssetTRC10, issuerAddress: string): Promise; + function delegateResource(amount: number, receiverAddress: string, resource: string, address: string, lock: boolean, options?: Object): Promise; + function deleteProposal(proposalID: number, issuerAddress: string, options?: number): Promise; + function estimateEnergy(contractAddress: string|HexString, functionSelector: string, options: Object, parameter: any[], issuerAddress: string|HexString): Promise; + function extendExpiration(transaction: Transaction|JSON|Object, extension: number): Promise; + function freezeBalance(amount: number, duration: number, resource: Resource, ownerAddress: string, receiverAddress: string, options?: number): Promise; + function freezeBalanceV2(amount: number, resource: Resource, ownerAddress: string, options?: Object): Promise; + function injectExchangeTokens(exchangeID: number, tokenID: string, tokenAmount: number, ownerAddress: string, options?: number): Promise; + function purchaseAsset(issuerAddress: string, tokenID: string, amount: number, buyer?: string, options?: number): Promise; + function purchaseToken(issuerAddress: string, tokenID: string, amount: number, buyer?: string, options?: number): Promise; + function sendAsset(to: string, amount: number, tokenID: string, from: string, options: number): Promise; + function sendToken(to: string, amount: number|string, tokenID: string, pk?: string): Promise; + function sendTrx(to: string, amount: number, from: string, options: number): Promise; + function tradeExchangeTokens(exchangeID: number, tokenID: string, tokenAmountSold: number, tokenAmountExpected: number, ownerAddress: string, options: number): Promise; + function triggerConfirmedConstantContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; + function triggerConstantContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; + function triggerSmartContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; + function undelegateResource(amount: number, receiverAddress: string, resource: string, address: string, options?: Object): Promise; + function unfreezeBalance(resource: Resource, address: string, receiver: string, options: number): Promise; + function unfreezeBalanceV2(amount: number, resource: Resource, address: string, options: Object): Promise; + function updateSetting(contract_address: string, consume_user_resource_percent: number, owner_address: string, options: number): Promise; + function updateAccountPermissions(owner_address: string, ownerPermissions: Object, witnessPermissions: Object|null, activesPermissions: Object[]): Promise; + function updateAsset(options: AssetUpdate, issuerAddress: string): Promise; + function updateBrokerage(brokerage: number, ownerAddress: string): Promise; + function updateEnergyLimit(contract_address: string, origin_energy_limit: number, owner_address: string, options: number): Promise; + function updateToken(options: AssetUpdate, issuerAddress: string): Promise; + function vote(votes: Object, voterAddress: string, option: number): Promise; + function voteProposal(proposalID: number, hasApproval: string, voterAddress: string, options: number): Promise; + function withdrawBlockRewards(address: string, options: number): Promise; + function withdrawExchangeTokens(exchangeID: number, tokenID: string, tokenAmount: number, ownerAddress: string, options: number): Promise; + function withdrawExpireUnfreeze(address: string): Promise; + } + export namespace trx { + function getAccount(address: HexString|string): Promise; + function getAccountResources(address: HexString|string): Promise; + function getApprovedList(r: Transaction): Promise; + function getAvailableUnfreezeCount(address: string|HexString, options?: Object): Promise; + function getBalance(address: string|HexString): Promise; + function getBandwidth(address: string|HexString): Promise; + function getBlock(block?: number|string): Promise; + function getBlockByHash(blockHash: string): Promise; + function getBlockByNumber(blockID: number): Promise; + function getBlockRange(start: number, end: number): Promise; + function getBlockTransactionCount(block: number|string): Promise; + function getBrokerage(address: string|HexString): Promise; + function getCanDelegatedMaxSize(address: string|HexString, resource?: Resource, options?: Object): Promise; + function getCanWithdrawUnfreezeAmount(address: string|HexString, timestamp?: number, options?: Object): Promise; + function getChainParameters(): Promise; + function getConfirmedTransaction(transactionID: string): Promise; + function getContract(contractAddress: string|HexString): Promise; + function getCurrentBlock(): Promise; + function getDelegatedResourceV2(fromAddress: string|HexString, toAddress: string|HexString, options?: Object): Promise; + function getDelegatedResourceAccountIndexV2(address: string|HexString, options?: Object): Promise; + function getExchangeByID(exchangeID: number): Promise; + function getNodeInfo(): Promise; + function getReward(address: string|HexString): Promise; + function getSignWeight(tx: Transaction): Promise; + function getTokenByID(tknID: string|number): Promise; + function getTokenFromID(tokenID: string|number): Promise; + function getTokenListByName(name: string): Promise; + function getTokensIssuedByAddress(address: string|HexString): Promise; + function getTransaction(transactionID: string): Promise; + function getTransactionFromBlock(block: number|string, index: number): Promise; + function getTransactionInfo(transactionID: string): Promise; + function getUnconfirmedBalance(address: string): Promise; + function getUnconfirmedBrokerage(address: string): Promise; + function getUnconfirmedReward(address: string): Promise; + function getUnconfirmedTransactionInfo(txid: string): Promise; + function listExchanges(): Promise; + function listExchangesPaginated(limit: number, offset: number): Promise; + function listNodes(): Promise; + function listProposals(): Promise; + function listSuperRepresentatives(): Promise; + function listTokens(limit?: number, offset?: number): Promise; + function sendRawTransaction(signedTransaction: JSON|Object, options?: any): Promise; + function sendHexTransaction(signedHexTransaction: string|HexString): Promise; + function sendToken(to: string, amount: number, tokenID: string, from: string, options: number): Promise; + function sendTransaction(to: string, amount: number, pk?: string): Promise; + function sign(transaction: Object, privateKey: string): Promise; + function sign(str: string, privateKey: string): Promise; + function signMessageV2(msg: string|BytesLike, privateKey: string): Promise; + function timeUntilNextVoteCycle(): Promise; + function multiSign(tx: JSON|Object, pk: string, permissionId: number): Promise; + function verifyMessage(message: string|HexString, signature: string, address: string): Promise; + function verifyMessageV2(message: string|HexString, signature: string): Promise; + function _signTypedData(domain: JSON|Object, types: JSON|Object, value: JSON|Object, privateKey: string): Promise; + function verifyTypedData(domain: JSON|Object, types: JSON|Object, value: JSON|Object, signature: string, address: string): Promise; + } + export namespace address { + function fromHex(hex: string): string; + function fromPrivateKey(pk: string): string; + function toHex(base58: string): string; + } + export namespace utils { + export namespace transaction { + function txJsonToPb(tx: JSON|Object): Object; + function txPbToTxID(tx: JSON|Object): string; + } + } + } + + export default TronWeb; +} diff --git a/src/interfaces.ts b/src/interfaces.ts new file mode 100644 index 0000000..d695ffc --- /dev/null +++ b/src/interfaces.ts @@ -0,0 +1,574 @@ +declare module 'tronweb/interfaces' { + + /** + * A string which is prefixed with ``0x`` and followed by any number + * of case-agnostic hexadecimal characters. + * + * It must match the regular expression ``/0x[0-9A-Fa-f]*\/``. + */ + export type HexString = string; + + /** + * A [[HexString]] whose length is even, which ensures it is a valid + * representation of binary data. + */ + export type DataHexString = string; + + /** + * An object that can be used to represent binary data. + */ + export type BytesLike = DataHexString | Uint8Array; + + /** + * About frgaments... + * + * @_subsection api/abi/abi-coder:Fragments [about-fragments] + */ + /** + * A type description in a JSON API. + */ + export interface JsonFragmentType { + /** + * The parameter name. + */ + readonly name?: string; + /** + * If the parameter is indexed. + */ + readonly indexed?: boolean; + /** + * The type of the parameter. + */ + readonly type?: string; + /** + * The internal Solidity type. + */ + readonly internalType?: string; + /** + * The components for a tuple. + */ + readonly components?: ReadonlyArray; + } + + /** + * A fragment for a method, event or error in a JSON API. + */ + export interface JsonFragment { + /** + * The name of the error, event, function, etc. + */ + readonly name?: string; + + /** + * The type of the fragment (e.g. ``event``, ``"function"``, etc.) + */ + readonly type?: string; + + /** + * If the event is anonymous. + */ + readonly anonymous?: boolean; + + /** + * If the function is payable. + */ + readonly payable?: boolean; + + /** + * If the function is constant. + */ + readonly constant?: boolean; + + /** + * The mutability state of the function. + */ + readonly stateMutability?: string; + + /** + * The input parameters. + */ + readonly inputs?: ReadonlyArray; + + /** + * The output parameters. + */ + readonly outputs?: ReadonlyArray; + + /** + * The gas limit to use when sending a transaction for this function. + */ + readonly gas?: string; + } + + export type Resource = "BANDWIDTH"|"ENERGY" + + export type BlockInput = 'latest'|'earliest'|number + + export interface Account { + address: { + base58: string, + hex: string + }, + privateKey: string, + publicKey: string + __proto__: Object + } + + export interface AccountMnemonic { + mnemonic: { + phrase: string, + path: string + locale: string + }, + privateKey: string, + publicKey: string, + address: string + } + + export interface CreateRandomOptions { + path: string, + extraEntropy: string, + locale: string + } + + export interface Transaction { + block: number, + timestamp: number, + contract: string, + name: string, + transaction: string, + result: { + r: string, + afterSeed: string, + s: string, + index: string, + previousSeed: string, + updater: string, + timestamp: string + }, + resourceNode: string + } + + export interface EventResult { + block: number, + timestamp: number, + contract: string, + name: string, + transaction: string, + result: { + index: string, + rng: string, + timestamp: string + }, + resourceNode: string + } + + export interface TrxAccount { + address: string; + balance: number; + frozen: { frozen_balance: number, expire_time: number }[]; + create_time: number; + latest_opration_time: number; + latest_consume_free_time: number; + account_resource: { + frozen_balance_for_energy: { frozen_balance: number, expire_time: number }, + latest_consume_time_for_energy: number + }; + owner_permission: { permission_name: string, threshold: number, keys: [[Object]|Object] }; + active_permission: { + type: string, + id: number, + permission_name: string, + threshold: number, + operations: string, + keys: [Array] + }[]; + assetV2: { key: string, value: number }[]; + free_asset_net_usageV2: { key: string, value: number }[]; + } + + export interface ParameterValueOnTriggerSC { + data: string, + token_id: number, + owner_address: string, + call_token_value: number, + contract_address: string + } + + export interface RawDataContract { + parameter: { + value: { + amount: number; + owner_address: string; + to_address: string; + }|ParameterValueOnTriggerSC|Object, + type_url: string; + }, + type: string; + } + + export interface Transaction { + visible: boolean; + signature?: string[]; + txID: string; + raw_data: { + contract: RawDataContract[]|Object[], + ref_block_bytes: string; + ref_block_hash: string; + expiration: number; + timestamp: number; + fee_limit?: number; + }, + raw_data_hex: string; + } + + export interface TransactionResult { + result: { [key: string]: any }|boolean; + approved_list?: string[]; + transaction: { + result: { result: boolean }; + txid: string; + transaction: { + signature: any[]; + txID: string; + raw_data: object[]; + raw_data_hex: string; + }; + }|Transaction; + } + + export interface TronAccountResource { + freeNetLimit: number; + netLimit: number; + assetNetUsed: { key: string; value: number }[]; + assetNetLimit: { key: string; value: number }[]; + totalNetLimit: number; + totalNetWeight: number; + energyLimit: number; + totalEnergyLimit: number; + totalEnergyWeight: number; + } + + export interface BlockTransaction { + txID: string, + raw_data: Object[], + raw_data_hex: string, + ret?: any[], + signature?: any[], + } + + export interface BlockInfo { + blockID: string; + block_header: { + raw_data: { + number?: number; + txTrieRoot: string; + witness_address: string; + parentHash: string; + timestamp?: number; + version?: number; + }; + witness_signature: string; + }, + transactions?: BlockTransaction[], + } + + export interface KeyValue { + key: string, + value?: number + } + + export interface ChainParameter extends KeyValue {} + + export interface DelegatedResource { + from: string; + to: string; + frozen_balance_for_bandwidth: number; + } + + export interface DelegatedResourceList { + delegatedResource: DelegatedResource[]; + } + + export interface DelegatedResourceAccount { + account: string|HexString, + toAccounts: string[]|HexString[] + } + + export interface Exchange { + exchange_id: number; + creator_address: string|HexString; + create_time: number; + first_token_id: string; + first_token_balance: number; + second_token_id: string; + second_token_balance: number; + } + + export interface ConfigNodeInfo { + activeNodeSize: number; + allowAdaptiveEnergy: number; + allowCreationOfContracts: number; + backupListenPort: number; + backupMemberSize: number; + backupPriority: number; + codeVersion: string; + dbVersion: number; + discoverEnable: boolean; + listenPort: number; + maxConnectCount: number; + maxTimeRatio: number; + minParticipationRate: number; + minTimeRatio: number; + p2pVersion: string; + passiveNodeSize: number; + sameIpMaxConnectCount: number; + sendNodeSize: number; + supportConstant: boolean; + versionName: string; + versionNum: string; + } + + export interface MachineInfo { + cpuCount: number; + cpuRate: number; + deadLockThreadCount: number; + deadLockThreadInfoList: any[]; // this can be improved by defining a specific type + freeMemory: number; + javaVersion: string; + jvmFreeMemory: number; + jvmTotalMemoery: number; + memoryDescInfoList: any[]; // this can be improved by defining a specific type + osName: string; + processCpuRate: number; + threadCount: number; + totalMemory: number; + } + + export interface PeerInfo { + active: boolean; + avgLatency: number; + blockInPorcSize: number; + connectTime: number; + disconnectTimes: number; + headBlockTimeWeBothHave: number; + headBlockWeBothHave: string; + host: string; + inFlow: number; + lastBlockUpdateTime: number; + lastSyncBlock: string; + localDisconnectReason: string; + needSyncFromPeer: boolean; + needSyncFromUs: boolean; + nodeCount: number; + nodeId: string; + port: number; + remainNum: number; + remoteDisconnectReason: string; + score: number; + syncBlockRequestedSize: number; + syncFlag: boolean; + syncToFetchSize: number; + syncToFetchSizePeekNum: number; + unFetchSynNum: number; + } + + export interface NodeInfo { + activeConnectCount: number; + beginSyncNum: number; + block: string; + cheatWitnessInfoMap: any; // this can be improved by defining a specific type + configNodeInfo: ConfigNodeInfo; + currentConnectCount: number; + machineInfo: MachineInfo; + passiveConnectCount: number; + peerList: PeerInfo[]; + solidityBlock: string; + totalFlow: number; + } + + export interface TokenInfo { + owner_address: string; + name: string; + abbr: string; + total_supply: number; + trx_num: number; + precision: number; + num: number; + start_time: number; + end_time: number; + description: string; + url: string; + id: string; + } + + export interface Transaction { + id: string; + fee: number; + blockNumber: number; + blockTimeStamp: number; + contractResult: string[]; + contract_address: string; + receipt: { + origin_energy_usage: number; + energy_usage_total: number; + net_fee: number; + result: string; + }; + log: { + address: string; + topics: string[]; + data: string; + }[]; + internal_transactions?: { + hash: string; + caller_address: string; + transferTo_address: string; + callValueInfo: string[]; + note: string; + }[]; + } + + export interface Proposal { + proposal_id: number; + proposer_address: string; + parameters: { [key: string]: any }[]; // Assuming the parameters can be of any type + expiration_time: number; + create_time: number; + approvals: string[]; + state: 'APPROVED' | 'DISAPPROVED' | 'IN_VOTING'; + } + + export interface Miner { + address: string; + voteCount: number; + url: string; + totalProduced: number; + totalMissed: number; + latestBlockNum: number; + latestSlotNum: number; + isJobs: boolean; + } + + export interface AssetTRC10 { + name: string; + abbreviation: string; + description: string; + url: string; + totalSupply: number; + trxRatio: number; + tokenRatio: number; + saleStart: number; + saleEnd: number; + freeBandwidth: number; + freeBandwidthLimit: number; + frozenAmount: number; + frozenDuration: number; + precision: number; + permission_id?: number; + } + + export interface ContractExecutionParams { + feeLimit: number; + callValue: number; + tokenId?: string; + tokenValue?: number; + userFeePercentage: number; + originEnergyLimit: number; + abi: string; + bytecode: string; + parameters?: string; + name: string; + permissionId?: number; + } + + export interface EnergyEstimate { + result: Object, + energy_required: number + } + + export interface TriggerConstantContractResult { + result: { + result: boolean; + }; + energy_used: number; + constant_result: string[]; + logs: { + address: string; + data: string; + topics: string[]; + }[]; + transaction: { + ret: {}[]; + visible: boolean; + txID: string; + raw_data: { + contract: { + parameter: { + value: { + data: string; + owner_address: string; + contract_address: string; + }; + type_url: string; + }; + type: string; + }[]; + ref_block_bytes: string; + ref_block_hash: string; + expiration: number; + timestamp: number; + }; + raw_data_hex: string; + }; + } + + export interface Header { + ["string"]: string + } + + export interface TronWebConstructor { + fullHost: string, + headers?: Header, + privateKey?: string + } + + export interface SideOptions { + fullNode: string, + solidityNode: string, + eventServer: string, + mainGatewayAddress: string, + sideGatewayAddress: string, + sideChainId: string + } + + export interface AssetUpdate { + description?: string; + url?: string; + freeBandwidth: number; + freeBandwidthLimit: number; + permissionId?: number; + } + + export interface TronContract { + tronWeb: Object, + injectPromise: Function, + address: string + abi: JsonFragment[] | [] + eventListener: boolean, + bytecode: boolean|string, + deployed: boolean|string, + lastBlock: boolean|string|number, + methods: Object + methodInstances: Object + props: [], + } + + export interface TronContractResult { + contract_address: string + origin_address: string + abi: JsonFragment[]|[]|Object + bytecode: boolean|string, + name: string + } +} diff --git a/src/tests/test.ts b/src/tests/test.ts deleted file mode 100644 index d262623..0000000 --- a/src/tests/test.ts +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -/// - - -import * as tronweb from "@types/tronweb"; -const TronWeb = require('tronweb') - -const tronWeb: tronweb.TronWeb = new TronWeb({ - fullHost: 'https://api.trongrid.io', - // eventServer: 'https://api.someotherevent.io', - // privateKey: 'your private key' - } -) - -/// check typing - -// const checkAccount = tronWeb.address.fromHex('ff') -// const checkUtils = tronWeb.utils.transaction.txPbToTxID({}) diff --git a/src/typings/interfaces.d.ts b/src/typings/interfaces.d.ts deleted file mode 100644 index a90f151..0000000 --- a/src/typings/interfaces.d.ts +++ /dev/null @@ -1,571 +0,0 @@ -/** - * A string which is prefixed with ``0x`` and followed by any number - * of case-agnostic hexadecimal characters. - * - * It must match the regular expression ``/0x[0-9A-Fa-f]*\/``. - */ -export type HexString = string; - -/** - * A [[HexString]] whose length is even, which ensures it is a valid - * representation of binary data. - */ -export type DataHexString = string; - -/** - * An object that can be used to represent binary data. - */ -export type BytesLike = DataHexString | Uint8Array; - -/** - * About frgaments... - * - * @_subsection api/abi/abi-coder:Fragments [about-fragments] - */ -/** - * A type description in a JSON API. - */ -export interface JsonFragmentType { - /** - * The parameter name. - */ - readonly name?: string; - /** - * If the parameter is indexed. - */ - readonly indexed?: boolean; - /** - * The type of the parameter. - */ - readonly type?: string; - /** - * The internal Solidity type. - */ - readonly internalType?: string; - /** - * The components for a tuple. - */ - readonly components?: ReadonlyArray; -} - -/** - * A fragment for a method, event or error in a JSON API. - */ -export interface JsonFragment { - /** - * The name of the error, event, function, etc. - */ - readonly name?: string; - - /** - * The type of the fragment (e.g. ``event``, ``"function"``, etc.) - */ - readonly type?: string; - - /** - * If the event is anonymous. - */ - readonly anonymous?: boolean; - - /** - * If the function is payable. - */ - readonly payable?: boolean; - - /** - * If the function is constant. - */ - readonly constant?: boolean; - - /** - * The mutability state of the function. - */ - readonly stateMutability?: string; - - /** - * The input parameters. - */ - readonly inputs?: ReadonlyArray; - - /** - * The output parameters. - */ - readonly outputs?: ReadonlyArray; - - /** - * The gas limit to use when sending a transaction for this function. - */ - readonly gas?: string; -} - -export type Resource = "BANDWIDTH"|"ENERGY" - -export type BlockInput = 'latest'|'earliest'|number - -export interface Account { - address: { - base58: string, - hex: string - }, - privateKey: string, - publicKey: string - __proto__: Object -} - -export interface AccountMnemonic { - mnemonic: { - phrase: string, - path: string - locale: string - }, - privateKey: string, - publicKey: string, - address: string -} - -export interface CreateRandomOptions { - path: string, - extraEntropy: string, - locale: string -} - -export interface Transaction { - block: number, - timestamp: number, - contract: string, - name: string, - transaction: string, - result: { - r: string, - afterSeed: string, - s: string, - index: string, - previousSeed: string, - updater: string, - timestamp: string - }, - resourceNode: string -} - -export interface EventResult { - block: number, - timestamp: number, - contract: string, - name: string, - transaction: string, - result: { - index: string, - rng: string, - timestamp: string - }, - resourceNode: string -} - -export interface TrxAccount { - address: string; - balance: number; - frozen: { frozen_balance: number, expire_time: number }[]; - create_time: number; - latest_opration_time: number; - latest_consume_free_time: number; - account_resource: { - frozen_balance_for_energy: { frozen_balance: number, expire_time: number }, - latest_consume_time_for_energy: number - }; - owner_permission: { permission_name: string, threshold: number, keys: [[Object]|Object] }; - active_permission: { - type: string, - id: number, - permission_name: string, - threshold: number, - operations: string, - keys: [Array] - }[]; - assetV2: { key: string, value: number }[]; - free_asset_net_usageV2: { key: string, value: number }[]; -} - -export interface ParameterValueOnTriggerSC { - data: string, - token_id: number, - owner_address: string, - call_token_value: number, - contract_address: string -} - -export interface RawDataContract { - parameter: { - value: { - amount: number; - owner_address: string; - to_address: string; - }|ParameterValueOnTriggerSC|Object, - type_url: string; - }, - type: string; -} - -export interface Transaction { - visible: boolean; - signature?: string[]; - txID: string; - raw_data: { - contract: RawDataContract[]|Object[], - ref_block_bytes: string; - ref_block_hash: string; - expiration: number; - timestamp: number; - fee_limit?: number; - }, - raw_data_hex: string; -} - -export interface TransactionResult { - result: { [key: string]: any }|boolean; - approved_list?: string[]; - transaction: { - result: { result: boolean }; - txid: string; - transaction: { - signature: any[]; - txID: string; - raw_data: object[]; - raw_data_hex: string; - }; - }|Transaction; -} - -export interface TronAccountResource { - freeNetLimit: number; - netLimit: number; - assetNetUsed: { key: string; value: number }[]; - assetNetLimit: { key: string; value: number }[]; - totalNetLimit: number; - totalNetWeight: number; - energyLimit: number; - totalEnergyLimit: number; - totalEnergyWeight: number; -} - -export interface BlockTransaction { - txID: string, - raw_data: Object[], - raw_data_hex: string, - ret?: any[], - signature?: any[], -} - -export interface BlockInfo { - blockID: string; - block_header: { - raw_data: { - number?: number; - txTrieRoot: string; - witness_address: string; - parentHash: string; - timestamp?: number; - version?: number; - }; - witness_signature: string; - }, - transactions?: BlockTransaction[], -} - -export interface KeyValue { - key: string, - value?: number -} - -export interface ChainParameter extends KeyValue {} - -export interface DelegatedResource { - from: string; - to: string; - frozen_balance_for_bandwidth: number; -} - -export interface DelegatedResourceList { - delegatedResource: DelegatedResource[]; -} - -export interface DelegatedResourceAccount { - account: string|HexString, - toAccounts: string[]|HexString[] -} - -export interface Exchange { - exchange_id: number; - creator_address: string|HexString; - create_time: number; - first_token_id: string; - first_token_balance: number; - second_token_id: string; - second_token_balance: number; -} - -export interface ConfigNodeInfo { - activeNodeSize: number; - allowAdaptiveEnergy: number; - allowCreationOfContracts: number; - backupListenPort: number; - backupMemberSize: number; - backupPriority: number; - codeVersion: string; - dbVersion: number; - discoverEnable: boolean; - listenPort: number; - maxConnectCount: number; - maxTimeRatio: number; - minParticipationRate: number; - minTimeRatio: number; - p2pVersion: string; - passiveNodeSize: number; - sameIpMaxConnectCount: number; - sendNodeSize: number; - supportConstant: boolean; - versionName: string; - versionNum: string; -} - -export interface MachineInfo { - cpuCount: number; - cpuRate: number; - deadLockThreadCount: number; - deadLockThreadInfoList: any[]; // this can be improved by defining a specific type - freeMemory: number; - javaVersion: string; - jvmFreeMemory: number; - jvmTotalMemoery: number; - memoryDescInfoList: any[]; // this can be improved by defining a specific type - osName: string; - processCpuRate: number; - threadCount: number; - totalMemory: number; -} - -export interface PeerInfo { - active: boolean; - avgLatency: number; - blockInPorcSize: number; - connectTime: number; - disconnectTimes: number; - headBlockTimeWeBothHave: number; - headBlockWeBothHave: string; - host: string; - inFlow: number; - lastBlockUpdateTime: number; - lastSyncBlock: string; - localDisconnectReason: string; - needSyncFromPeer: boolean; - needSyncFromUs: boolean; - nodeCount: number; - nodeId: string; - port: number; - remainNum: number; - remoteDisconnectReason: string; - score: number; - syncBlockRequestedSize: number; - syncFlag: boolean; - syncToFetchSize: number; - syncToFetchSizePeekNum: number; - unFetchSynNum: number; -} - -export interface NodeInfo { - activeConnectCount: number; - beginSyncNum: number; - block: string; - cheatWitnessInfoMap: any; // this can be improved by defining a specific type - configNodeInfo: ConfigNodeInfo; - currentConnectCount: number; - machineInfo: MachineInfo; - passiveConnectCount: number; - peerList: PeerInfo[]; - solidityBlock: string; - totalFlow: number; -} - -export interface TokenInfo { - owner_address: string; - name: string; - abbr: string; - total_supply: number; - trx_num: number; - precision: number; - num: number; - start_time: number; - end_time: number; - description: string; - url: string; - id: string; -} - -export interface Transaction { - id: string; - fee: number; - blockNumber: number; - blockTimeStamp: number; - contractResult: string[]; - contract_address: string; - receipt: { - origin_energy_usage: number; - energy_usage_total: number; - net_fee: number; - result: string; - }; - log: { - address: string; - topics: string[]; - data: string; - }[]; - internal_transactions?: { - hash: string; - caller_address: string; - transferTo_address: string; - callValueInfo: string[]; - note: string; - }[]; -} - -export interface Proposal { - proposal_id: number; - proposer_address: string; - parameters: { [key: string]: any }[]; // Assuming the parameters can be of any type - expiration_time: number; - create_time: number; - approvals: string[]; - state: 'APPROVED' | 'DISAPPROVED' | 'IN_VOTING'; -} - -export interface Miner { - address: string; - voteCount: number; - url: string; - totalProduced: number; - totalMissed: number; - latestBlockNum: number; - latestSlotNum: number; - isJobs: boolean; -} - -export interface AssetTRC10 { - name: string; - abbreviation: string; - description: string; - url: string; - totalSupply: number; - trxRatio: number; - tokenRatio: number; - saleStart: number; - saleEnd: number; - freeBandwidth: number; - freeBandwidthLimit: number; - frozenAmount: number; - frozenDuration: number; - precision: number; - permission_id?: number; -} - -export interface ContractExecutionParams { - feeLimit: number; - callValue: number; - tokenId?: string; - tokenValue?: number; - userFeePercentage: number; - originEnergyLimit: number; - abi: string; - bytecode: string; - parameters?: string; - name: string; - permissionId?: number; -} - -export interface EnergyEstimate { - result: Object, - energy_required: number -} - -export interface TriggerConstantContractResult { - result: { - result: boolean; - }; - energy_used: number; - constant_result: string[]; - logs: { - address: string; - data: string; - topics: string[]; - }[]; - transaction: { - ret: {}[]; - visible: boolean; - txID: string; - raw_data: { - contract: { - parameter: { - value: { - data: string; - owner_address: string; - contract_address: string; - }; - type_url: string; - }; - type: string; - }[]; - ref_block_bytes: string; - ref_block_hash: string; - expiration: number; - timestamp: number; - }; - raw_data_hex: string; - }; -} - -export interface Header { - ["string"]: string -} - -export interface TronWebConstructor { - fullHost: string, - headers?: Header, - privateKey?: string -} - -export interface SideOptions { - fullNode: string, - solidityNode: string, - eventServer: string, - mainGatewayAddress: string, - sideGatewayAddress: string, - sideChainId: string -} - -interface AssetUpdate { - description?: string; - url?: string; - freeBandwidth: number; - freeBandwidthLimit: number; - permissionId?: number; -} - -export interface TronContract { - tronWeb: Object, - injectPromise: Function, - address: string - abi: JsonFragment[] | [] - eventListener: boolean, - bytecode: boolean|string, - deployed: boolean|string, - lastBlock: boolean|string|number, - methods: Object - methodInstances: Object - props: [], -} - -export interface TronContractResult { - contract_address: string - origin_address: string - abi: JsonFragment[]|[]|Object - bytecode: boolean|string, - name: string -} diff --git a/src/typings/tronweb.d.ts b/src/typings/tronweb.d.ts deleted file mode 100644 index e44bc3b..0000000 --- a/src/typings/tronweb.d.ts +++ /dev/null @@ -1,192 +0,0 @@ -/// - -declare module '@types/tronweb' { - import {BigNumber} from "bignumber.js" - import { - Account, - AccountMnemonic, - AssetTRC10, - AssetUpdate, - BlockInfo, - BlockInput, - BlockTransaction, - BytesLike, - ChainParameter, - ContractExecutionParams, - CreateRandomOptions, - DelegatedResourceAccount, - DelegatedResourceList, - EnergyEstimate, - EventResult, - Exchange, - Header, - HexString, - JsonFragment, - KeyValue, - Miner, - NodeInfo, - Proposal, - Resource, - SideOptions, - TokenInfo, - Transaction, - TransactionResult, - TriggerConstantContractResult, - TronAccountResource, - TronContract, - TronContractResult, - TronWebConstructor, - TrxAccount - } from "tronweb/typings/interfaces"; - - export class TronWeb { - address: any; - transactionBuilder: any; - trx: any; - utils: any; - constructor(fullNode: string, solidityNode: string, eventServer: string|boolean, privateKey?: string|boolean); - constructor(fullNode: string, solidityNode: string, eventServer: string|boolean, sideOptions: SideOptions, privateKey?: string|boolean); - constructor(obj: TronWebConstructor); - contract(data: JsonFragment[], address: string): TronContract; - setHeader(header: Header): void|Error; - currentProvider(): any; - currentProviders(): any; - getEventByTransactionID(transactionID: string): Promise; - getEventResult(contractAddress: string, options?: Object): Promise; // check this return - isConnected(): Object; - isValidProvider(provider: any): any; - setAddress(address: string): void|Error; - setDefaultBlock(blockID?: BlockInput): void|string|boolean; - setEventServer(eventServer: any): void|Error; - setFullNode(fullNode: any): void|Error; - setPrivateKey(privateKey: string): void|Error; - setSolidityNode(solidityNode: any): void|Error; - createAccount(): Promise; - createRandom(options?: CreateRandomOptions): Promise; - fromAscii(string: any, padding: any): any; - fromDecimal(value: number|string): string; - fromSun(sun: string|number): string; - fromUtf8(string: string): string; - fromMnemonic(mnemonic: string, path?: string, wordlist?: string): AccountMnemonic|Error; - isAddress(address: string): boolean; - sha3(string: string, prefix?: boolean): HexString; - toAscii(hex: HexString): string; - toBigNumber(amount: number|string|HexString): BigNumber|Object; - toDecimal(value: string|HexString): number|string; - toHex(val: string|number|object|[]|BigNumber): HexString; - toSun(trx: number): string; - toUtf8(hex: string): string; - BigNumber(val: number|string|HexString): BigNumber - } - - export namespace TronWeb { - export namespace transactionBuilder { - function addUpdateData(unsignedTransaction: JSON|Object, memo: string): Promise; - function applyForSR(address: string, url: string, options?: number): Promise; - function createAccount(address: string, options?: JSON|Object): Promise; - function createAsset(options: AssetTRC10, issuerAddress: string): Promise; - function createProposal(parameters: KeyValue[], issuerAddress: string, options?: number): Promise; - function createSmartContract(options: ContractExecutionParams, issuerAddress: string): Promise; - function createToken(options: AssetTRC10, issuerAddress: string): Promise; - function delegateResource(amount: number, receiverAddress: string, resource: string, address: string, lock: boolean, options?: Object): Promise; - function deleteProposal(proposalID: number, issuerAddress: string, options?: number): Promise; - function estimateEnergy(contractAddress: string|HexString, functionSelector: string, options: Object, parameter: any[], issuerAddress: string|HexString): Promise; - function extendExpiration(transaction: Transaction|JSON|Object, extension: number): Promise; - function freezeBalance(amount: number, duration: number, resource: Resource, ownerAddress: string, receiverAddress: string, options?: number): Promise; - function freezeBalanceV2(amount: number, resource: Resource, ownerAddress: string, options?: Object): Promise; - function injectExchangeTokens(exchangeID: number, tokenID: string, tokenAmount: number, ownerAddress: string, options?: number): Promise; - function purchaseAsset(issuerAddress: string, tokenID: string, amount: number, buyer?: string, options?: number): Promise; - function purchaseToken(issuerAddress: string, tokenID: string, amount: number, buyer?: string, options?: number): Promise; - function sendAsset(to: string, amount: number, tokenID: string, from: string, options: number): Promise; - function sendToken(to: string, amount: number|string, tokenID: string, pk?: string): Promise; - function sendTrx(to: string, amount: number, from: string, options: number): Promise; - function tradeExchangeTokens(exchangeID: number, tokenID: string, tokenAmountSold: number, tokenAmountExpected: number, ownerAddress: string, options: number): Promise; - function triggerConfirmedConstantContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; - function triggerConstantContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; - function triggerSmartContract(contractAddress: string, functions: string, options: Object, parameter: any[], issuerAddress: string): Promise; - function undelegateResource(amount: number, receiverAddress: string, resource: string, address: string, options?: Object): Promise; - function unfreezeBalance(resource: Resource, address: string, receiver: string, options: number): Promise; - function unfreezeBalanceV2(amount: number, resource: Resource, address: string, options: Object): Promise; - function updateSetting(contract_address: string, consume_user_resource_percent: number, owner_address: string, options: number): Promise; - function updateAccountPermissions(owner_address: string, ownerPermissions: Object, witnessPermissions: Object|null, activesPermissions: Object[]): Promise; - function updateAsset(options: AssetUpdate, issuerAddress: string): Promise; - function updateBrokerage(brokerage: number, ownerAddress: string): Promise; - function updateEnergyLimit(contract_address: string, origin_energy_limit: number, owner_address: string, options: number): Promise; - function updateToken(options: AssetUpdate, issuerAddress: string): Promise; - function vote(votes: Object, voterAddress: string, option: number): Promise; - function voteProposal(proposalID: number, hasApproval: string, voterAddress: string, options: number): Promise; - function withdrawBlockRewards(address: string, options: number): Promise; - function withdrawExchangeTokens(exchangeID: number, tokenID: string, tokenAmount: number, ownerAddress: string, options: number): Promise; - function withdrawExpireUnfreeze(address: string): Promise; - } - export namespace trx { - function getAccount(address: HexString|string): Promise; - function getAccountResources(address: HexString|string): Promise; - function getApprovedList(r: Transaction): Promise; - function getAvailableUnfreezeCount(address: string|HexString, options?: Object): Promise; - function getBalance(address: string|HexString): Promise; - function getBandwidth(address: string|HexString): Promise; - function getBlock(block?: number|string): Promise; - function getBlockByHash(blockHash: string): Promise; - function getBlockByNumber(blockID: number): Promise; - function getBlockRange(start: number, end: number): Promise; - function getBlockTransactionCount(block: number|string): Promise; - function getBrokerage(address: string|HexString): Promise; - function getCanDelegatedMaxSize(address: string|HexString, resource?: Resource, options?: Object): Promise; - function getCanWithdrawUnfreezeAmount(address: string|HexString, timestamp?: number, options?: Object): Promise; - function getChainParameters(): Promise; - function getConfirmedTransaction(transactionID: string): Promise; - function getContract(contractAddress: string|HexString): Promise; - function getCurrentBlock(): Promise; - function getDelegatedResourceV2(fromAddress: string|HexString, toAddress: string|HexString, options?: Object): Promise; - function getDelegatedResourceAccountIndexV2(address: string|HexString, options?: Object): Promise; - function getExchangeByID(exchangeID: number): Promise; - function getNodeInfo(): Promise; - function getReward(address: string|HexString): Promise; - function getSignWeight(tx: Transaction): Promise; - function getTokenByID(tknID: string|number): Promise; - function getTokenFromID(tokenID: string|number): Promise; - function getTokenListByName(name: string): Promise; - function getTokensIssuedByAddress(address: string|HexString): Promise; - function getTransaction(transactionID: string): Promise; - function getTransactionFromBlock(block: number|string, index: number): Promise; - function getTransactionInfo(transactionID: string): Promise; - function getUnconfirmedBalance(address: string): Promise; - function getUnconfirmedBrokerage(address: string): Promise; - function getUnconfirmedReward(address: string): Promise; - function getUnconfirmedTransactionInfo(txid: string): Promise; - function listExchanges(): Promise; - function listExchangesPaginated(limit: number, offset: number): Promise; - function listNodes(): Promise; - function listProposals(): Promise; - function listSuperRepresentatives(): Promise; - function listTokens(limit?: number, offset?: number): Promise; - function sendRawTransaction(signedTransaction: JSON|Object, options?: any): Promise; - function sendHexTransaction(signedHexTransaction: string|HexString): Promise; - function sendToken(to: string, amount: number, tokenID: string, from: string, options: number): Promise; - function sendTransaction(to: string, amount: number, pk?: string): Promise; - function sign(transaction: Object, privateKey: string): Promise; - function sign(str: string, privateKey: string): Promise; - function signMessageV2(msg: string|BytesLike, privateKey: string): Promise; - function timeUntilNextVoteCycle(): Promise; - function multiSign(tx: JSON|Object, pk: string, permissionId: number): Promise; - function verifyMessage(message: string|HexString, signature: string, address: string): Promise; - function verifyMessageV2(message: string|HexString, signature: string): Promise; - function _signTypedData(domain: JSON|Object, types: JSON|Object, value: JSON|Object, privateKey: string): Promise; - function verifyTypedData(domain: JSON|Object, types: JSON|Object, value: JSON|Object, signature: string, address: string): Promise; - } - export namespace address { - function fromHex(hex: string): string; - function fromPrivateKey(pk: string): string; - function toHex(base58: string): string; - } - export namespace utils { - export namespace transaction { - function txJsonToPb(tx: JSON|Object): Object; - function txPbToTxID(tx: JSON|Object): string; - } - } - } - - export default TronWeb; -} diff --git a/tests/test.ts b/tests/test.ts new file mode 100644 index 0000000..2c24599 --- /dev/null +++ b/tests/test.ts @@ -0,0 +1,19 @@ +'use strict'; + +import TronWeb from "tronweb" +import "../dist/index"; + +const tronWeb = new TronWeb({ + fullHost: 'https://api.trongrid.io', + // eventServer: 'https://api.someotherevent.io', + // privateKey: 'your private key' + } +) + +async function main() { + await tronWeb.getEventByTransactionID() + await tronWeb.transactionBuilder.applyForSR() + await tronWeb.trx.getAccount() + await tronWeb.address.fromHex() + await tronWeb.utils.transaction.txJsonToPb() +} diff --git a/tsconfig.json b/tsconfig.json index c6a6796..b22a777 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,24 +1,26 @@ { "compilerOptions": { - "baseUrl": ".", - "paths": { - "tronweb/*": ["./src/*"] - }, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, "module": "commonjs", - "lib": [ - "es6" - ], + "esModuleInterop": true, + "target": "es5", "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "types": [ "node" ], - "typeRoots": [ "../node_modules/@types", "./src/typings/tronweb.d.ts" ], - "noEmit": true, - "forceConsistentCasingInFileNames": true + "allowJs": true, + "emitDeclarationOnly": true, + "skipLibCheck": true, + "sourceMap": true, + "outDir": "dist", + "declaration": true, + "baseUrl": ".", + "types": ["node"], + "lib": ["esnext", "dom", "es6", "es5", "es2020", "es2022"] }, - "files": [ - "./src/index.ts", - "./src/typings/tronweb.d.ts", + "include": [ + "src/**/*", + "test/**/*" + ], + "exclude": [ + "node_modules" ] }