UNPKG

tronbox

Version:

TronBox - Simple development framework for Tron

1 lines 15.4 kB
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}var _require=require("web3"),Web3=_require.Web3,Web3Contract=_require.Contract;var TronWrap=require("../TronWrap");var _require2=require("../TronWrap"),constants=_require2.constants;var BigNumber=require("bignumber.js");var contract=function(module){function Provider(provider){this.provider=provider}var tronWrap;Provider.prototype.send=function(){return this.provider.send.apply(this.provider,arguments)};Provider.prototype.sendAsync=function(){return this.provider.sendAsync.apply(this.provider,arguments)};var Utils={is_object:function is_object(val){return(0,_typeof2["default"])(val)==="object"&&!Array.isArray(val)},is_big_number:function is_big_number(val){if((0,_typeof2["default"])(val)!=="object")return false;try{new BigNumber(val);return true}catch(e){return false}},merge:function merge(){var merged={};var args=Array.prototype.slice.call(arguments);for(var i=0;i<args.length;i++){var object=args[i];var keys=Object.keys(object);for(var j=0;j<keys.length;j++){var key=keys[j];var value=object[key];merged[key]=value}}return merged},bootstrap:function bootstrap(fn){Object.keys(fn._static_methods).forEach(function(key){fn[key]=fn._static_methods[key].bind(fn)});Object.keys(fn._properties).forEach(function(key){fn.addProp(key,fn._properties[key])});return fn},linkBytecode:function linkBytecode(bytecode,links){Object.keys(links).forEach(function(library_name){var library_address=links[library_name];var regex=new RegExp("__"+library_name+"_+","g");bytecode=bytecode.replace(regex,library_address.replace("0x","").replace("41",""))});return bytecode}};function Contract(contract){var constructor=this.constructor;this.abi=constructor.abi;if(typeof contract==="string"){this.address=contract;this.contract=new Web3Contract(this.abi,"")}else{this.allEvents=contract.allEvents;this.contract=contract;this.address=contract.address}}function toCamelCase(str){return str.replace(/_([a-z])/g,function(g){return g[1].toUpperCase()})}function filterEnergyParameter(args){var deployParameters=Object.keys(constants.deployParameters);var lastArg=args[args.length-1];if((0,_typeof2["default"])(lastArg)!=="object"||Array.isArray(lastArg))return[args,{}];args.pop();var res={};for(var property in lastArg){var camelCased=toCamelCase(property);if(~deployParameters.indexOf(camelCased)){res[camelCased]=lastArg[property]}}return[args,res]}Contract._static_methods={initTronWeb:function initTronWeb(options){if(!tronWrap){tronWrap=TronWrap(options)}},setProvider:function setProvider(provider){if(!provider){throw new Error("Invalid provider passed to setProvider(); provider is "+provider)}this.currentProvider=provider},"new":function _new(){var self=this;if(!this.currentProvider){throw new Error(this.contractName+" error: Please call setProvider() first before calling new().")}var _filterEnergyParamete=filterEnergyParameter(Array.prototype.slice.call(arguments)),_filterEnergyParamete2=(0,_slicedToArray2["default"])(_filterEnergyParamete,2),args=_filterEnergyParamete2[0],params=_filterEnergyParamete2[1];if(!this.bytecode){throw new Error(this._json.contractName+" error: contract binary not set. Can't deploy new instance.")}var regex=/__[^_]+_+/g;var unlinked_libraries=self.binary.match(regex);if(unlinked_libraries!=null){unlinked_libraries=unlinked_libraries.map(function(name){return name.replace(/_/g,"")}).sort().filter(function(name,index,arr){if(index+1>=arr.length){return true}return name!==arr[index+1]}).join(", ");throw new Error(self.contractName+" contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of "+self._json.contractName+": "+unlinked_libraries)}return new Promise(function(accept,reject){var tx_params={parameters:args};var last_arg=args[args.length-1];if(Utils.is_object(last_arg)&&!Utils.is_big_number(last_arg)){tx_params=args.pop()}var constructor=self.abi.filter(function(item){return item.type==="constructor"});if(constructor.length&&constructor[0].inputs.length!==args.length){throw new Error(self.contractName+" contract constructor expected "+constructor[0].inputs.length+" arguments, received "+args.length)}tx_params=Utils.merge(self.class_defaults,tx_params);if(!tx_params.data){tx_params.data=self.binary}tx_params.contractName=self.contractName;for(var param in params){tx_params[param]=params[param]}tx_params.abi=self.abi;tronWrap._deployContract(tx_params,_callback);function _callback(err,res){if(err){reject(err);return}self.at(res.address).then(function(newContract){newContract.transactionHash=res.transactionHash;accept(newContract)})}})},at:function at(address){var newContract=this.clone(JSON.parse(JSON.stringify(this._json)));if(this.provider){newContract.setProvider(this.provider)}if(this.network_id){newContract.setNetwork(this.network_id)}newContract.defaults(this.class_defaults);newContract.address=tronWrap.address.toHex(address);return newContract.deployed()},call:function call(methodName){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key]}var self=this;var methodArgs={};var lastArg=args[args.length-1];if(!Array.isArray(lastArg)&&(0,_typeof2["default"])(lastArg)==="object"){methodArgs=args.pop()}if(!methodArgs.call_value){methodArgs.call_value=0}if(args.length===1&&Array.isArray(args[0])){try{var funAbi={};var _iterator=_createForOfIteratorHelper(self.abi),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var item=_step.value;if(item.name===methodName){funAbi=item}}}catch(err){_iterator.e(err)}finally{_iterator.f()}tronWrap.utils.abi.encodeParamsV2ByABI(funAbi,args[0]);args=args[0]}catch(_unused){}}var option={};return new Promise(function(accept,reject){function _callback(err,res){if(err){reject(err);return}accept(res)}option=Utils.merge({address:self.address,methodName:methodName,args:args,abi:self.abi,methodArgs:methodArgs},self.defaults());tronWrap.triggerContract(option,_callback)})},deployed:function deployed(){var self=this;return new Promise(function(accept,reject){if(!self.isDeployed()){throw new Error(self.contractName+" has not been deployed to detected network")}var getContract;if(tronWrap._web3){self.address=self.address.toLowerCase().replace(/^41/,"0x");getContract=tronWrap._web3.eth.getCode(self.address)}else{self.address=self.address.toLowerCase().replace(/^0x/,"41");getContract=tronWrap.trx.getContract(self.address)}getContract.then(function(res){var noCodeMsg="".concat(self.contractName," has not been deployed to detected network; no code at address ").concat(self.address);if(tronWrap._web3){if(res==="0x"){throw new Error(noCodeMsg)}}else{if(!res.contract_address){throw new Error(noCodeMsg)}}var abi=self.abi||[];var _loop=function _loop(){var item=abi[i];if(self.hasOwnProperty(item.name))return 1;if(/(function|event)/i.test(item.type)&&item.name){var f=function f(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}return self.call.apply(null,[item.name].concat(args))};self[item.name]=f;self[item.name].call=f}};for(var i=0;i<abi.length;i++){if(_loop())continue}accept(self)})["catch"](function(err){reject(err)})})},defaults:function defaults(class_defaults){if(!this.class_defaults){this.class_defaults={}}if(!class_defaults){class_defaults={}}var self=this;Object.keys(class_defaults).forEach(function(key){var value=class_defaults[key];self.class_defaults[key]=value});return this.class_defaults},hasNetwork:function hasNetwork(network_id){return this._json.networks[network_id+""]!=null},isDeployed:function isDeployed(){if(!this.network_id){return false}if(!this._json.networks[this.network_id]){return false}return!!this.network.address},setNetwork:function setNetwork(network_id){if(!network_id)return;this.network_id=network_id+""},resetAddress:function resetAddress(){delete this.network.address},link:function link(name,address){var self=this;if(typeof name==="function"){var _contract=name;if(!_contract.isDeployed()){throw new Error("Cannot link contract without an address.")}this.link(_contract.contractName,_contract.address);Object.keys(_contract.events).forEach(function(topic){self.network.events[topic]=_contract.events[topic]});return}if((0,_typeof2["default"])(name)==="object"){var obj=name;Object.keys(obj).forEach(function(name){var a=obj[name];self.link(name,a)});return}if(!this._json.networks[this.network_id]){this._json.networks[this.network_id]={events:{},links:{}}}this.network.links[name]=address},clone:function clone(json){var self=this;json=json||{};var temp=function TruffleContract(){this.constructor=temp;return Contract.apply(this,arguments)};temp.prototype=Object.create(self.prototype);var network_id;if((0,_typeof2["default"])(json)!=="object"){network_id=json;json=self._json}json=Utils.merge({},self._json||{},json);temp._static_methods=this._static_methods;temp._properties=this._properties;temp._property_values={};temp._json=json;Utils.bootstrap(temp);temp.class_defaults=temp.prototype.defaults||{};if(network_id){temp.setNetwork(network_id)}Object.keys(json).forEach(function(key){if(key.indexOf("x-")!==0)return;temp[key]=json[key]});return temp},addProp:function addProp(key,fn){var self=this;var getter=function getter(){if(fn.get!=null){return fn.get.call(self)}return self._property_values[key]||fn.call(self)};var setter=function setter(val){if(fn.set!=null){fn.set.call(self,val);return}throw new Error(key+" property is immutable")};var definition={};definition.enumerable=false;definition.configurable=false;definition.get=getter;definition.set=setter;Object.defineProperty(this,key,definition)},toJSON:function toJSON(){return this._json}};Contract._properties={contract_name:{get:function get(){return this.contractName},set:function set(val){this.contractName=val}},contractName:{get:function get(){return this._json.contractName||"Contract"},set:function set(val){this._json.contractName=val}},abi:{get:function get(){return this._json.abi},set:function set(val){this._json.abi=val}},network:function network(){var network_id=this.network_id;if(!network_id){throw new Error(this.contractName+" has no network id set, cannot lookup artifact data. Either set the network manually using "+this.contractName+".setNetwork(), run "+this.contractName+".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically.")}if(!this._json.networks[network_id]){throw new Error(this.contractName+" has no network configuration for its current network id ("+network_id+").")}var returnVal=this._json.networks[network_id];if(!returnVal.links){returnVal.links={}}if(!returnVal.events){returnVal.events={}}return returnVal},networks:function networks(){return this._json.networks},address:{get:function get(){var address=this.network.address;if(!address){throw new Error("Cannot find deployed address: "+this.contractName+" not deployed or address not set.")}return address},set:function set(val){if(!val){throw new Error("Cannot set deployed address; malformed value: "+val)}var network_id=this.network_id;if(!network_id){throw new Error(this.contractName+" has no network id set, cannot lookup artifact data. Either set the network manually using "+this.contractName+".setNetwork(), run "+this.contractName+".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically.")}if(!this._json.networks[network_id]){this._json.networks[network_id]={events:{},links:{}}}this.network.address=val}},transactionHash:{get:function get(){var transactionHash=this.network.transactionHash;if(transactionHash===null){throw new Error("Could not find transaction hash for "+this.contractName)}return transactionHash},set:function set(val){this.network.transactionHash=val}},links:function links(){if(!this.network_id){throw new Error(this.contractName+" has no network id set, cannot lookup artifact data. Either set the network manually using "+this.contractName+".setNetwork(), run "+this.contractName+".detectNetwork(), or use new(), at() or deployed() as a thenable which will detect the network automatically.")}if(!this._json.networks[this.network_id]){return{}}return this.network.links||{}},events:function events(){return[]},binary:function binary(){return Utils.linkBytecode(this.bytecode,this.links)},deployedBinary:function deployedBinary(){return Utils.linkBytecode(this.deployedBytecode,this.links)},unlinked_binary:{get:function get(){return this.bytecode},set:function set(val){this.bytecode=val}},bytecode:{get:function get(){return this._json.bytecode},set:function set(val){this._json.bytecode=val}},deployedBytecode:{get:function get(){var code=this._json.deployedBytecode;if(code.indexOf("0x")!==0){code="0x"+code}return code},set:function set(val){var code=val;if(val.indexOf("0x")!==0){code="0x"+code}this._json.deployedBytecode=code}},sourceMap:{get:function get(){return this._json.sourceMap},set:function set(val){this._json.sourceMap=val}},deployedSourceMap:{get:function get(){return this._json.deployedSourceMap},set:function set(val){this._json.deployedSourceMap=val}},source:{get:function get(){return this._json.source},set:function set(val){this._json.source=val}},sourcePath:{get:function get(){return this._json.sourcePath},set:function set(val){this._json.sourcePath=val}},legacyAST:{get:function get(){return this._json.legacyAST},set:function set(val){this._json.legacyAST=val}},ast:{get:function get(){return this._json.ast},set:function set(val){this._json.ast=val}},compiler:{get:function get(){return this._json.compiler},set:function set(val){this._json.compiler=val}},schema_version:function schema_version(){return this.schemaVersion},schemaVersion:function schemaVersion(){return this._json.schemaVersion},updated_at:function updated_at(){return this.updatedAt},updatedAt:function updatedAt(){try{return this.network.updatedAt||this._json.updatedAt}catch(e){return this._json.updatedAt}},web3:function web3(){return new Web3}};Utils.bootstrap(Contract);module.exports=Contract;return Contract}(module||{});