编译Solidity文件
npm install -g solc@0.4.26
solcjs test.sol --bin --abi --optimize -o output/
错误: RangeError: Maximum call stack size exceeded
, 可能是solc版本问题,可更换版本解决。
部署合约
// 获取 .abi 文件内容
// 将Compute_sol_Compute.abi文件的内容复制出来,放到 web3.eth.contract() 中去
var contractAbi = web3.eth.contract([{"constant":true,"inputs":[],"name":"sub_underflow","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"add_overflow","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"mul_overflow","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]);
// 获取 .bin 文件内容
// 将Compute_sol_Compute.bin文件的内容复制出来,注意在内容前面需要加上 '0x'
var contractBin = '0x608060405234801561001057600080fd5b5060c48061001f6000396000f30060806040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416636567817181146057578063df541bdb14607b578063eb67eaa714607b575b600080fd5b348015606257600080fd5b506069608d565b60408051918252519081900360200190f35b348015608657600080fd5b5060696093565b60001990565b6000905600a165627a7a7230582097a996970a2bc74a5559e5ff8f77e5cf0c282836bb0d512a7aea12c4383c7d3b0029'
// 计算需要的 gas
var gasValue = eth.estimateGas({data:contractBin})
// 部署合约
var contract = contractAbi.new({from: web3.eth.accounts[0],data: contractBin,gas: gasValue}, function (e, contract){console.log(e, contract);if (typeof contract.address !== 'undefined') {console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);}})
错误1:Error: insufficient funds for gas * price + value undefined
,原因是账户余额不足,需要挖矿。
调用合约
contract.add_overflow()
//如果该函数会改变storage,需要添加参数{from:eth.coinbase, gas:200000}
交易参数详解:
参数名 | 类型 | 详情 |
---|---|---|
from | DATA,20字节 | 发起交易的地址 |
to | DATA,20字节 | 可选项,交易转账地址 |
gas | 数字,默认为 90000 | 提供给交易的 gas 数量,未使用的 gas 会返回到账户中 |
gasPrice | 数字 | 可选项,gas 的单价 |
value | 数字 | 可选项,交易转账金额 |
data | DATA,20字节 | 方法的参数 |
nonce | 数字 | 可选项,允许覆盖使用相同 nonce 的交易数据 |
MetaMask连接私链
# start_chain.sh
geth --datadir "chain" --nodiscover --http --http.addr 127.0.0.1 --http.port 14712 --allow-insecure-unlock console 2>>output.log
Metamask配置:
RPC URL: http://127.0.0.1:14712
链ID: 602
// 新建用户
> personal.newAccount("123")
// 解锁用户
> personal.unlockAccount(eth.accounts[1])
Unlock account 0x8d75df41d0e5eb75fbef2b9e39705bccd24676b6
Passphrase:
true
Metamask导入私钥,chain/keystore/