web3.eth.call

优质
小牛编辑
128浏览
2023-12-01

web3.eth.call(callObject [, defaultBlock] [, callback])

在节点的VM中,直接执行消息调用交易。但不会将数据合并区块链中(这样的调用不会修改状态)。

参数:

  • Object - 返回一个交易对象,同web3.eth.sendTransaction。与sendTransaction的区别在于,from属性是可选的。
  • Number|String -(可选)如果不设置此值使用web3.eth.defaultBlock设定的块,否则使用指定的块。
  • Function -(可选)回调函数,用于支持异步的方式执行[async]。

返回值:

String - 函数调用返回的值。

示例:

var Web3 = require('web3');

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

var from = web3.eth.accounts[0];
//部署合约的发布地址
/*合约内容如下
pragma solidity ^0.4.0;

contract Calc{
  function add(uint a, uint b) returns (uint){
    return a + b;
  }
}
*/
var to = "0xa4b813d788218df688d167102e5daff9b524a8bc";

//要发送的数据
//格式说明见: http://me.tryblockchain.org/Solidity-call-callcode-delegatecall.html
var data = "0x771602f700000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002";

var result = web3.eth.call({
  from : from,
  to : to,
  data : data
});

//返回结果32字长的结果3
console.log(result);