use-tronlink
Version:
A React hook that connects with Tronlink hot wallet
2 lines (1 loc) • 2.79 kB
JavaScript
function ___$insertStyle(e){if(e&&"undefined"!=typeof window){const t=document.createElement("style");return t.setAttribute("type","text/css"),t.innerHTML=e,document.head.appendChild(t),e}}import{useState,useCallback,useEffect}from"react";function __awaiter(e,i,u,c){return new(u=u||Promise)(function(n,t){function r(e){try{o(c.next(e))}catch(e){t(e)}}function a(e){try{o(c.throw(e))}catch(e){t(e)}}function o(e){var t;e.done?n(e.value):((t=e.value)instanceof u?t:new u(function(e){e(t)})).then(r,a)}o((c=c.apply(e,i||[])).next())})}function __generator(r,a){var o,i,u,c={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},e={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(n){return function(e){var t=[n,e];if(o)throw new TypeError("Generator is already executing.");for(;c;)try{if(o=1,i&&(u=2&t[0]?i.return:t[0]?i.throw||((u=i.return)&&u.call(i),0):i.next)&&!(u=u.call(i,t[1])).done)return u;switch(i=0,(t=u?[2&t[0],u.value]:t)[0]){case 0:case 1:u=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,i=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(u=0<(u=c.trys).length&&u[u.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!u||t[1]>u[0]&&t[1]<u[3])){c.label=t[1];break}if(6===t[0]&&c.label<u[1]){c.label=u[1],u=t;break}if(u&&c.label<u[2]){c.label=u[2],c.ops.push(t);break}u[2]&&c.ops.pop(),c.trys.pop();continue}t=a.call(r,c)}catch(e){t=[6,e],i=0}finally{o=u=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}var useTronlink=function(){var e=useState(0),t=e[0],r=e[1],e=useState(!1),n=e[0],a=e[1],e=useState(""),o=e[0],i=e[1],e=useState(""),u=e[0],c=e[1],s=useCallback(function(){return __awaiter(void 0,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:return window.tronLink?[4,window.tronLink.request({method:"tron_requestAccounts"})]:[3,2];case 1:e.sent(),e.label=2;case 2:return window.tronWeb?(t=window.tronWeb.defaultAddress,n=t.name,(t=t.base58)?(i(t),c(n||""),a(!0),[4,window.tronWeb.trx.getBalance(t)]):[3,4]):[2,!1];case 3:return n=e.sent(),r(n),d(),[2,!0];case 4:return a(!1),[2,!1]}})})},[]),l=useCallback(function(){r(0),a(!1),i(""),c("")},[]),d=useCallback(function(){window.addEventListener("load",s),window.addEventListener("message",function(n){return __awaiter(void 0,void 0,void 0,function(){var t;return __generator(this,function(e){return(t=n.data.message)&&("setAccount"!==t.action&&"setNode"!==t.action&&"tabReply"!==t.action&&"accountsChanged"!==t.action||(t.data.address&&s(),"tabReply"===t.action||t.data.address||l())),[2]})})})},[]);return useEffect(function(){s()},[]),{address:o,isConnected:n,trxBalance:t,walletName:u}};export{useTronlink};