创建虚拟学习环境:
打开cmd,全局安装ganache-cli :npm install -g ganache-cli
安装完成之后输入ganache-cli,出现下面的界面,表示安装成功:
新建 web3.js 文件
安装web3.js库 npm install web3 --save
引入web3库, 连接ganache
web3.eth.getAccounts().then((accounts) => { console.log(accounts); //返回节点所控制的账户列表 var account = accounts[0]; web3.eth.getBalance(account).then((balance) => { console.log(balance); //返回地址在指定区块的余额 var balanceWei = web3.utils.fromWei(balance, "ether"); console.log(balanceWei); //返回地址在指定区块的余额 }); });
可以看到连接到了ganache, 并打印出来10个账号
创建合约 打开这个地址,写上简单的合约
remix.ethereum.org/
写完了发布合约
发布合约完成的话就部署合约
上面这个代码可以在编译详情复制
可以看倒合约地址
那部署完了合约了,就需要连接合约,调用合约里面的方法
第一个参数是 remix里面的ABI, 第二个参数是刚刚部署完成的合约地址
var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
var myContract = new web3.eth.Contract(
inputs: [],
stateMutability: "nonpayable",
type: "constructor",
inputs: [],
name: "getcount",
outputs: [
internalType: "uint256",
name: "",
type: "uint256",
stateMutability: "view",
type: "function",
inputs: [
internalType: "uint256",
name: "step",
type: "uint256",
name: "kipcount",
outputs: [],
stateMutability: "nonpayable",
type: "function",
"0x0557ea49D50457c0a2dA38CF77c3ed57EAf8edaE"
// {
// from: "0x1234567890123456789012345678901234567891", // 默认交易发送地址
// gasPrice: "20000000000", // 以 wei 为单位的默认 gas 价格,当前价格为 20 gwei
// }
调用只能合约上的方法,send调用方式改变智能合约状态,会消耗gas,call 方式则不会消耗gas,仅用于查看等
myContract.methods
.kipcount(12)
.send({ from: "0x9c2494C461e923050847439b1F709723659d6a3c" })
.then(function () {
myContract.methods
.getcount()
.call()
.then(function (result) {
console.log("counter:" + result);
复制代码