web3とpromiseの組み合わせやっとしっくり来た
このタイミングでpromise使えば、EVMと通信後に処理を進められる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Solidity1</title> </head> <body> <p id="p1"></p> <script src="./const.js"></script> <script> // blockchain start window.addEventListener("load",function() { // スマートコントラクト /* var promise = new Promise((resolve) => { window.web3.eth.getAccounts((err, accounts) => { web3 = new Web3(web3.currentProvider) web3.eth.defaultAccount = accounts[0]; contract = web3.eth.contract(JSON.parse(abi)).at(addr); contract.setText(text, (err,success)=>{resolve(success)}); }); }).then((value)=>{}); */ var promise = new Promise((resolve) => { if (typeof web3 !== 'undefined') { window.web3 = new Web3(web3.currentProvider); // web3.eth.defaultAccount = OWNER_ADDR; console.log("window.web3.eth.defaultAccount(設定前) : " + window.web3.eth.defaultAccount); console.log("window.web3.eth.accounts[0] : " + window.web3.eth.accounts[0]); console.log("OWNER_ADDR : " + OWNER_ADDR); web3.eth.getAccounts((err, accounts)=>{ resolve(accounts); }); } else { document.write("Please install metamask"); } }); promise.then((accounts)=>{ var eth = window.web3.eth; var abiObj = JSON.parse(ABI); var contract = eth.contract(abiObj).at(CONTRACT_ADDR); console.log("window.web3.eth.defaultAccount(設定前) : " + window.web3.eth.defaultAccount); console.log("window.web3.eth.accounts[0] : " + window.web3.eth.accounts[0]); console.log("OWNER_ADDR : " + OWNER_ADDR); }); // こいつは送金成功する // contract.deposit(1, {value: 1000000000000000000, from: OWNER_ADDR}, function(err){ }); // 引き出し。owener設定したら成功した // contract.withdraw(7, function(err){ }); var p = document.getElementById("p1"); var str = "output : " + abiObj; p.innerHTML = str; }); // blockchain end </script> </body> </html> |