编译Solidity文件

  1. npm install -g solc@0.4.26
  2. solcjs test.sol --bin --abi --optimize -o output/

错误: RangeError: Maximum call stack size exceeded, 可能是solc版本问题,可更换版本解决。

部署合约

  1. // 获取 .abi 文件内容
  2. // 将Compute_sol_Compute.abi文件的内容复制出来,放到 web3.eth.contract() 中去
  3. 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"}]);
  4. // 获取 .bin 文件内容
  5. // 将Compute_sol_Compute.bin文件的内容复制出来,注意在内容前面需要加上 '0x'
  6. var contractBin = '0x608060405234801561001057600080fd5b5060c48061001f6000396000f30060806040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416636567817181146057578063df541bdb14607b578063eb67eaa714607b575b600080fd5b348015606257600080fd5b506069608d565b60408051918252519081900360200190f35b348015608657600080fd5b5060696093565b60001990565b6000905600a165627a7a7230582097a996970a2bc74a5559e5ff8f77e5cf0c282836bb0d512a7aea12c4383c7d3b0029'
  7. // 计算需要的 gas
  8. var gasValue = eth.estimateGas({data:contractBin})
  9. // 部署合约
  10. 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,原因是账户余额不足,需要挖矿。

调用合约

  1. contract.add_overflow()
  2. //如果该函数会改变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连接私链

  1. # start_chain.sh
  2. 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

  1. // 新建用户
  2. > personal.newAccount("123")
  3. // 解锁用户
  4. > personal.unlockAccount(eth.accounts[1])
  5. Unlock account 0x8d75df41d0e5eb75fbef2b9e39705bccd24676b6
  6. Passphrase:
  7. true

Metamask导入私钥,chain/keystore/
1.png