utils.js
1 let Utils = { 2 fromAscii: function(str) { 3 var _web3 = new Web3(); 4 return _web3.utils ? _web3.utils.fromAscii(str) : _web3.fromAscii(str); 5 }, 6 toAscii: function(str) { 7 var _web3 = new Web3(); 8 return _web3.utils.toAscii(str); 9 }, 10 secureSend: function(web3, toSend, params, isContractDeploy, cb, hashCb) { 11 cb = cb || function() {}; 12 hashCb = hashCb || function () {}; 13 return new Promise((resolve, reject) => { 14 let hash; 15 let calledBacked = false; 16 17 function callback(err, receipt) { 18 if (calledBacked) { 19 return; 20 } 21 if (!err && (isContractDeploy && !receipt.contractAddress)) { 22 return; // Not deployed yet. Need to wait 23 } 24 if (interval) { 25 clearInterval(interval); 26 } 27 calledBacked = true; 28 cb(err, receipt); 29 if (err) { 30 return reject(err); 31 } 32 resolve(receipt); 33 } 34 35 // This interval is there to compensate for the event that sometimes doesn't get triggered when using WebSocket 36 // FIXME The issue somehow only happens when the blockchain node is started in the same terminal 37 // Only poll with a Websocket provider 38 if (web3.currentProvider.constructor.name === 'WebsocketProvider') { 39 var interval = setInterval(function () { 40 if (!hash) { 41 return; 42 } 43 44 web3.eth.getTransactionReceipt(hash, function (err, receipt) { 45 if (!err && !receipt) { 46 return; 47 } 48 49 callback(err, receipt); 50 }); 51 }, 100); 52 } 53 54 //toSend.estimateGas() 55 // .then(gasEstimated => { 56 //params.gas = gasEstimated + 1000; 57 return toSend.send(params, function(err, transactionHash) { 58 if (err) { 59 return callback(err); 60 } 61 hash = transactionHash; 62 hashCb(hash); 63 }) 64 .on('receipt', function(receipt) { 65 if (!isContractDeploy || receipt.contractAddress) { 66 callback(null, receipt); 67 } 68 }).then(function(_contract) { 69 if (!hash) { 70 return; // Somehow we didn't get the receipt yet... Interval will catch it 71 } 72 web3.eth.getTransactionReceipt(hash, callback); 73 }).catch(callback); 74 //}); 75 }); 76 } 77 }; 78 79 export default Utils;