以太坊智能合约代币应用开发(5)-web3调用智能代币合约
2018-03-05 14:28
701 查看
一、概述
在上面的文章中已经说明了web3与geth的交互,下面将使用web3访问我们已经部署好的代币合约二、应用实践
1、新建文件
在nodejs项目下新建一个contract.js 文件2、创建合约实例
Web3 = require("web3") var web3 = new Web3(Web3.givenProvider||'http://127.0.0.1:8545'); web3.setProvider('http://127.0.0.1:8545'); var myContract = new web3.eth.Contract([ { "constant": true, "inputs": [ { "name": "", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "addr", "type": "address" } ], "name": "getBalance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "name": "initialSupply", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ], '0x7b05b7bca697f821e94de75f62005c13b66f4575', { from: '0xa5d4725d9dc3f7e73818936abe151602ad6d26fa', // default from address gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case });上面的代码使用abi与合约地址构建了只能合约实例
其中0x7b05b7bca697f821e94de75f62005c13b66f4575是合约的地址,在部署合约中可以看到
3、调用合约的balanceof方法查看账户余额
myContract.methods.balanceOf('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa').call().then(function(r){ console.log('show the custom account balance:'); console.log(r) })
4、使用智能合约发起交易
myContract.methods.transfer('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa',100).send().then(function(r){ console.log('use the contract to send coin:'); console.log(r) })
5、再次查询双方的合约余额
代码略相关文章推荐
- 以太坊智能合约代币应用开发(4)-web3客户端与geth节点交互
- 基于mcat开发智能合约应用(二)调用合约
- 自主研发具有知识产权的智能合约平台:相对以太坊来说我们更适合行业应用的开发
- 『孔壹学院』以太坊(Ethereum)代币系统、智能合约开发实战课程
- 以太坊智能合约代币应用开发(3)-部署智能合约
- 以太坊智能合约开发DApp应用示例
- 手把手教你搭建智能合约测试环境、开发、编译、部署以及如何通过JS调用合约方法
- 区块链开发(三)编写调试第一个以太坊智能合约
- 【白皮书】以太坊 (Ethereum ):下一代智能合约和去中心化应用平台
- 开发部署一个智能合约(以太坊-Ethereum)
- 区块链开发(三)编写调试第一个以太坊智能合约
- 【白皮书】以太坊 (Ethereum ):下一代智能合约和去中心化应用平台
- 以太坊私链上开发一个ICO智能合约
- 基于mcat开发以太坊智能合约
- vDice是一款应用以太坊智能合约技术的骰子游戏应用
- 区块链开发(三)编写调试第一个以太坊智能合约
- 基于mcat开发智能合约应用(三)编码自动化与合约交互