blockchain - 使用web3进行contract相关的开发和调用

访问量: 870

refer to: https://web3js.readthedocs.io/en/v1.7.3/web3-eth-contract.html

安装

npm install web3

调用web3

创建一个文件: (当前目录下) run.js  (前提是本地运行了 npx hardhat node)

var Web3 = require('web3')
var web3 = new Web3('ws://localhost:8545')
web3.eth.getAccounts()
    .then(console.log);

查看本地的account: web3.eth.getAccounts()

调用contract:

需要的前提是: 我们知道contract的源代码,然后根据源代码生成 contract abi 。(或者该源代码已经被verify了。)

refer to: https://ethereum.stackexchange.com/questions/3149/how-do-you-get-a-json-file-abi-from-a-known-contract-address

solcjs contracts/SayHi.sol --abi 

然后会生成一个 新的文件: contracts_SayHi_sol_SayHi.abi

[{"inputs":[],"name":"get","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}]

然后在当前目录创建文件: run_contract.js  ,内容如下:

(参考:https://stackoverflow.com/questions/59441099/web3js-contract-deploy-never-resolved-the-promise-or-never-exits)

var Contract = require('web3-eth-contract')

run()

async function run(){

  Contract.setProvider('ws://localhost:8545')

  let contractAbi = [{"inputs":[],"name":"getNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}]

  let contractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3'

  var contract = new Contract(contractAbi, contractAddress)

  let from = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'

  await contract.methods.getNumber().send({from: from})
    .then(console.log)
 
await contract.methods.store(333).send({from: from}) .on('receipt', function(data){ console.info("receipt, data is: ", data) }).on('error', function(error) { console.log('error', error); }).on('transactionHash', function(transactionHash) { console.log('transactionHash', transactionHash); }).on('confirmation', function(confirmationNumber, receipt) { console.log('confirmation', confirmationNumber); }); }
process.exit() // 如果是node的话
}

contract.call() 与 contract.send()的区别

call() 的话只是调用。 不改变EVM的状态(就是适合对于getter方法)

send()的话,会发起一个转账, 会改变EVM的状态。(会产生tx )

调用contract的方式

1. 本地节点的调用:  ( json-rpc 调用, web3 console调用, 自动签名,需要send_transaction)

2. infura的调用:(json-rpc调用, 程序进行的签名  send_rawTransaction)

3. web 页面的调用(H5, web3的调用, 手动进行签名)

订阅/RSS Feed

Subscribe