- 第 1 章 区块链
- 第 2 章 以太坊
- 第 3 章 以太坊私链入门
- 第 4 章 以太坊网络
- 第 5 章 geth v1.8.16 命令详解
- 第 6 章 Wallet
- 第 7 章 Token
- 第 8 章 智能合约语言 Solidity v0.5.0
- 第 9 章 Truffle v4.1.8 开发框架
- 第 10 章 web3.js - 1.0.0
- 第 11 章 web3j v3.4.0 - Jave Client
- 11.2. 启动以太坊
- 11.3. Maven pom.xml 文件
- 11.4. Java 与 Solidity 数据类型映射关系
- 11.5. 常量
- 11.6. 连接到服务器获取版本号
- 11.7. 获得以太坊状态信息
- 11.8. 单位转换
- 11.9. 账号管理
- 11.10. Credentials
- 11.11. 交易
- 11.12. 钱包
- 11.13. 智能合约
- 11.14. ERC20合约
- 11.15. Infura
- 11.16. 助记词
- 11.17. 过滤器 (Filter)
- 11.18. Subscription
- 11.19. 解锁账号
- 11.20. IBAN (International Bank Account Number)
- 11.21. Springboot with Ethereum (web3j)
- 第 12 章 web3.py - A python interface for interacting with the Ethereum blockchain and ecosystem.
- 第 14 章 Ethereum Developer APIs
- 第 15 章 infura
- 第 16 章 以太坊案例
- 第 17 章 FAQ
- 17.3. Error: authentication needed: password or unlock
- 17.4. 新增节点后不生效
- 17.5. Unhandled rejection Error: Returned error: The method personal_unlockAccount does not exist/is not available
- 17.6. Error: exceeds block gas limit
- 17.7. Migrations.sol:11:3: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(…) { … }" instead.
- 17.8. Exception in thread "main" rx.exceptions.OnErrorNotImplementedException: Invalid response received: okhttp3.internal.http.RealResponseBody@6c25e6c4
- 17.9. 旧版本 Remix(browser-solidity) 本地安装
- 第 18 章 Hyperledger Fabric v2.0.0
- 第 19 章 Hyperledger Fabric 运维
- 第 20 章 Chaincode 链码(智能合约)
- 第 21 章 Hyperledger Fabric Client SDK for Node.js
- 第 22 章 fabric-sdk-java
- 第 24 章 已知 Hyperledger 落地案例
- 第 25 章 Fabric Command
- 第 26 章 Fabric FAQ
- 第 27 章 IPFS(InterPlanetary File System,星际文件系统)
- 第 28 章 IPFS 命令
- 第 29 章 IPFS WebUI
- 第 30 章 IPFS 集群配置
- 第 31 章 IPFS API
- 第 32 章 IPFS Faq
- 第 33 章 EOS
- 第 34 章 EOS 安装
- 第 35 章 CLEOS
- 第 36 章 智能合约开发
- 第 37 章 EOS Dapp 开发
- 第 38 章 FAQ
- 第 39 章 BaaS (Blockchain as a Service) 平台
- 第 40 章 BitCoin
- 第 41 章 其他区块链相关
- 附录 1. 附录
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
10.5. web3.eth
10.5. web3.eth
10.5.1. 查看账号列表
var Web3 = require('web3'); var web3 = new Web3('http://localhost:8545'); web3.eth.getAccounts().then(console.log);
10.5.2. 查询矿工账号
var Web3 = require('web3'); var web3 = new Web3('http://localhost:8545'); web3.eth.getCoinbase().then(console.log);
Callback 方式
web3.eth.getCoinbase( function(error, result){ if (error) { console.error(error); } else { console.log(result); } })
10.5.3. 获得余额
web3.eth.getBalance(req.query.address).then(function(balance){ res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": web3.utils.fromWei(balance)}}); });
Callback 方式
web3.eth.getBalance(req.query.address, function (error, wei) { if (!error) { var balance = web3.utils.fromWei(wei, 'ether'); res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": balance}}); }else{ console.log(error); res.json({"status": false, "code":1, "data":{"error":error.message}}); } });
捕捉错误
router.get('/balance.json', function(req, res) { try { web3.eth.getBalance(req.query.address, function (error, wei) { if (!error) { var balance = web3.utils.fromWei(wei, 'ether'); res.json({"status": true, "code":0, "data":{"account":req.query.address, "balance": balance}}); }else{ console.log(error); res.json({"status": false, "code":1, "data":{"error":error.message}}) } }); } catch(error){ res.json({"status": false, "code":1, "data":{"error":error.message}}); }; });
10.5.4. web3.eth.sendTransaction()
web3.eth.sendTransaction({ from: coinbase, to: '0x2C687bfF93677D69bd20808a36E4BC2999B4767C', value: web3.utils.toWei('2','ether') }, function(error, result){ if(!error) { console.log("#" + result + "#") } else { console.error(error); } }); var code = "0x603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3"; web3.eth.sendTransaction({from: coinbase, data: code}, function(err, transactionHash) { if (!err) console.log(transactionHash); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385" }); web3.eth.sendTransaction({from: coinbase, data: code}).then(function(receipt){ console.log(receipt); });
10.5.5. web3.eth.sendSignedTransaction() 私钥签名转账
10.5.5.1. 例子1
var account = web3.eth.accounts.privateKeyToAccount(privateKey); web3.eth.accounts.signTransaction({ from: account.address, to: "0x0013a861865d74b13ba94713d4e84d97c57e7081", gas: "3000000", value: '100000000000000000', gasPrice: '0x09184e72a000', data: "0x00" }, account.privateKey) .then(function(result) { console.log("Results: ", result) web3.eth.sendSignedTransaction(result.rawTransaction) .on('receipt', console.log); })
10.5.5.2. 例子2
获取 pending 状态的区块
[ethereum@netkiller web3.example]$ vim test.js [ethereum@netkiller web3.example]$ export PRIVATE_KEY=585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e [ethereum@netkiller web3.example]$ echo $PRIVATE_KEY 585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e [ethereum@netkiller web3.example]$ node > process.env["PRIVATE_KEY"] '585a219fd6a5583b325e96770a88e69660f404efc06e56be71d82beedb7a989e'
[ethereum@netkiller web3.example]$ cat transfer.js fs = require('fs'); const Web3 = require('web3'); var Tx = require('ethereumjs-tx'); const web3 = new Web3('http://localhost:8545'); console.log(web3.version) coinbase = "0xaa96686a050e4916afbe9f6d8c5107062fa646dd"; address = "0x372fda02e8a1eca513f2ee5901dc55b8b5dd7411" contractAddress = "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A" const main = async () => { var balance = await web3.eth.getBalance(coinbase); console.log(`Balance ETH: ${balance} \n`); const abi = fs.readFileSync('output/NetkillerToken.abi', 'utf-8'); const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: address}); var balance = await contract.methods.balanceOf(address).call(); console.log(`Balance before send: ${balance} \n`); var count = await web3.eth.getTransactionCount(coinbase); const gasPrice = await web3.eth.getGasPrice(); console.log(`gasPrice: ${gasPrice}\n`) var gasLimit = 1000000; var transferAmount = 1000; // Chain ID of Ropsten Test Net is 3, replace it to 1 for Main Net var chainId = 1; var rawTransaction = { "from": coinbase, /* "nonce": "0x" + count.toString(16),*/ "nonce": web3.utils.toHex(count), "gasPrice": web3.utils.toHex(gasPrice), "gasLimit": web3.utils.toHex(gasLimit), "to": contractAddress, "value": "0x0", "data": contract.methods.transfer(address, transferAmount).encodeABI(), "chainId": web3.utils.toHex(chainId) }; console.log(`Raw of Transaction: \n${JSON.stringify(rawTransaction, null, '\t')}\n`); // The private key for myAddress in .env var privateKey = new Buffer(process.env["PRIVATE_KEY"], 'hex'); var tx = new Tx(rawTransaction); tx.sign(privateKey); var serializedTx = tx.serialize(); // Comment out these four lines if you don't really want to send the TX right now console.log(`Attempting to send signed tx: ${serializedTx.toString('hex')}\n`); var receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')); // The receipt info of transaction, Uncomment for debug console.log(`Receipt info: \n${JSON.stringify(receipt, null, '\t')}\n`); // The balance may not be updated yet, but let's check var balance = await contract.methods.balanceOf(address).call(); console.log(`Balance after send: ${balance}`); } main();
[ethereum@netkiller web3.example]$ node test.js 1.0.0-beta.34 Balance ETH: 8695480352861952 Balance before send: 100 gasPrice: 3000000000 Raw of Transaction: { "from": "0xaa96686a050e4916afbe9f6d8c5107062fa646dd", "nonce": "0x20", "gasPrice": "0xb2d05e00", "gasLimit": "0xf4240", "to": "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A", "value": "0x0", "data": "0xa9059cbb000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd741100000000000000000000000000000000000000000000000000000000000003e8", "chainId": "0x1" } Attempting to send signed tx: f8a92084b2d05e00830f4240949abcf16f6685fe1f79168534b1d30056c90b8a8a80b844a9059cbb000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd741100000000000000000000000000000000000000000000000000000000000003e825a05017058348d8f751cc40e71c13a63b8d8e21683841bd002c9f6bf691d34b6a4ba07df3fa8792aa66cc272ff89373509f6335272a4298e98177536a79c8ab7c947c Receipt info: { "blockHash": "0x32f45f27040b1df616ff4efd25557416793782541b995a6d4ecbd66f8441783f", "blockNumber": 5518045, "contractAddress": null, "cumulativeGasUsed": 5054117, "from": "0xaa96686a050e4916afbe9f6d8c5107062fa646dd", "gasUsed": 36184, "logs": [ { "address": "0x9ABcF16f6685fE1F79168534b1D30056c90B8A8A", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000aa96686a050e4916afbe9f6d8c5107062fa646dd", "0x000000000000000000000000372fda02e8a1eca513f2ee5901dc55b8b5dd7411" ], "data": "0x00000000000000000000000000000000000000000000000000000000000003e8", "blockNumber": 5518045, "transactionHash": "0x203ebcbe1cc8340c4b5a13f4e6c36a4f63142754437e0f43b0ff5e5c0bf512cc", "transactionIndex": 104, "blockHash": "0x32f45f27040b1df616ff4efd25557416793782541b995a6d4ecbd66f8441783f", "logIndex": 94, "removed": false, "id": "log_7ef3f104" } ], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000100000000040000000000000000000000000000000008000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000002000000000000000000000000000000001200000000000000000000200000000000000000000000000000100000000000000000000000000000000000", "status": true, "to": "0x9abcf16f6685fe1f79168534b1d30056c90b8a8a", "transactionHash": "0x203ebcbe1cc8340c4b5a13f4e6c36a4f63142754437e0f43b0ff5e5c0bf512cc", "transactionIndex": 104 } Balance after send: 1100
10.5.6. web3.eth.getBlock() 获取区块
获取 pending 状态的区块
web3.eth.getBlock( "pending", function (error, block) { if (error) { console.error(error); } else { console.log(block.transactions.length); } })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论