web3.eth.contract

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

web3.eth.contract(abiArray)

创建一个Solidity的合约对象,用来在某个地址上初始化合约。

参数:

  • Array - 一到多个描述合约的函数,事件的ABI对象。

返回值:

Object - 一个合约对象。

示例:

var MyContract = web3.eth.contract(abiArray);

// instantiate by address
var contractInstance = MyContract.at([address]);

// deploy new contract
var contractInstance = MyContract.new([contructorParam1] [, contructorParam2], {data: '0x12345...', from: myAccount, gas: 1000000});

// Get the data to deploy the contract manually
var contractData = MyContract.new.getData([contructorParam1] [, contructorParam2], {data: '0x12345...'});
// contractData = '0x12345643213456000000000023434234'

你可以或者使用一个在某个地址上已经存在的合约,或者使用编译后的字节码部署一个全新的的合约。

// Instantiate from an existing address:
var myContractInstance = MyContract.at(myContractAddress);


// Or deploy a new contract:

// Deploy the contract asyncronous from Solidity file:
...
const fs = require("fs");
const solc = require('solc')

let source = fs.readFileSync('nameContract.sol', 'utf8');
let compiledContract = solc.compile(source, 1);
let abi = compiledContract.contracts['nameContract'].interface;
let bytecode = compiledContract.contracts['nameContract'].bytecode;
let gasEstimate = web3.eth.estimateGas({data: bytecode});
let MyContract = web3.eth.contract(JSON.parse(abi));

var myContractReturned = MyContract.new(param1, param2, {
   from:mySenderAddress,
   data:bytecode,
   gas:gasEstimate}, function(err, myContract){
    if(!err) {
       // NOTE: The callback will fire twice!
       // Once the contract has the transactionHash property set and once its deployed on an address.

       // e.g. check tx hash on the first call (transaction send)
       if(!myContract.address) {
           console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract
       
       // check address on the second call (contract deployed)
       } else {
           console.log(myContract.address) // the contract address
       }

       // Note that the returned "myContractReturned" === "myContract",
       // so the returned "myContractReturned" object will also get the address set.
    }
  });

// Deploy contract syncronous: The address will be added as soon as the contract is mined.
// Additionally you can watch the transaction by using the "transactionHash" property
var myContractInstance = MyContract.new(param1, param2, {data: myContractCode, gas: 300000, from: mySenderAddress});
myContractInstance.transactionHash // The hash of the transaction, which created the contract
myContractInstance.address // undefined at start, but will be auto-filled later

示例:

// contract abi
var abi = [{
     name: 'myConstantMethod',
     type: 'function',
     constant: true,
     inputs: [{ name: 'a', type: 'string' }],
     outputs: [{name: 'd', type: 'string' }]
}, {
     name: 'myStateChangingMethod',
     type: 'function',
     constant: false,
     inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }],
     outputs: []
}, {
     name: 'myEvent',
     type: 'event',
     inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]
}];

// creation of contract object
var MyContract = web3.eth.contract(abi);

// initiate contract for an address
var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');

// call constant function
var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'

// send a transaction to a function
myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000});

// short hand style
web3.eth.contract(abi).at(address).myAwesomeMethod(...);

// create filter
var filter = myContractInstance.myEvent({a: 5}, function (error, result) {
  if (!error)
    console.log(result);
    /*
    {
        address: '0x8718986382264244252fc4abd0339eb8d5708727',
        topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005",
        data: "0x0000000000000000000000000000000000000000000000000000000000000001",
        ...
    }
    */
});

合约对象的方法

// Automatically determines the use of call or sendTransaction based on the method type
myContractInstance.myMethod(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);

// Explicitly calling this method
myContractInstance.myMethod.call(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);

// Explicitly sending a transaction to this method
myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback]);

// Get the call data, so you can call the contract through some other means
var myCallData = myContractInstance.myMethod.getData(param1 [, param2, ...]);
// myCallData = '0x45ff3ff6000000000004545345345345..'

合约对象内封装了使用合约的相关方法。可以通过传入参数,和交易对象来使用方法。

参数:

  • String|Number - (可选)零或多个函数参数。如果传入一个字符串,需要使用十六进制编码,如,0xdedbeef
  • Object - (可选)最后一个参数(如果传了callback,则是倒数第二个参数),可以是一个交易对象。查看web3.eth.sendTransaction的第一个参数说明来了解更多。注意,这里不需要填datato属性。
  • Number|String -(可选)如果不设置此值使用web3.eth.defaultBlock设定的块,否则使用指定的块。
  • Function -(可选)回调函数,用于支持异步的方式执行[async]。

返回值:

String - 如果发起的是一个call,对应的是返回结果。如果是transaction,则要么是一个创建的合约地址,或者是一个transaction的哈希值。查看web3.eth.sendTransaction了解更多。

示例:

// creation of contract object
var MyContract = web3.eth.contract(abi);

// initiate contract for an address
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'

myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000}, function(err, result){ ... });

合约对象的事件

你可以像web3.eth.filter这样使用事件,他们有相同的方法,但需要传递不同的对象来创建事件过滤器。

参数:

  • Object - 你想返回的索引值(过滤哪些日志)。如,{'valueA': 1, 'valueB': [myFirstAddress, mySecondAddress]}。默认情况下,所以有过滤项被设置为null。意味着默认匹配的是合约所有的日志。
  • Object - 附加的过滤选项。参见web3.eth.filter的第一个参数。默认情况下,这个对象会设置address为当前合约地址,同时第一个主题为事件的签名。
  • Function -(可选)传入一个回调函数,将立即开始监听,这样就不用主动调用myEvent.watch(function(){})[async]。

回调返回值:

Object - 事件对象,如下:

  • address: String,32字节 - 日志产生的合约地址。
  • args: Object - 事件的参数。
  • blockHash: String,32字节 - 日志所在块的哈希。如果是pending的日志,则为null
  • blockNumber: Number - 日志所在块的块号。如果是pending的日志,则为null
  • logIndex: Number - 日志在区块中的序号。如果是pending的日志,则为null
  • event: String - 事件名称。
  • removed: bool - 标识产生事件的这个交易是否被移除(因为孤块),或从未生效(被拒绝的交易)。
  • transactionIndex: Number - 产生日志的交易在区块中的序号。如果是pending的日志,则为null
  • transactionHash: String,32字节 - 产生日志的交易哈希值。

示例:

var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

// watch for an event with {some: 'args'}
var myEvent = myContractInstance.MyEvent({some: 'args'}, {fromBlock: 0, toBlock: 'latest'});
myEvent.watch(function(error, result){
   ...
});

// would get all past logs again.
var myResults = myEvent.get(function(error, logs){ ... });

...

// would stop and uninstall the filter
myEvent.stopWatching();

合约 allEvents

var events = myContractInstance.allEvents([additionalFilterObject]);

// watch for changes
events.watch(function(error, event){
  if (!error)
    console.log(event);
});

// Or pass a callback to start watching immediately
var events = myContractInstance.allEvents([additionalFilterObject,] function(error, log){
  if (!error)
    console.log(log);
});

调用合约创建的所有事件的回调。

参数:

  • Object - 附加的过滤选项。参见web3.eth.filter的第一个参数。默认情况下,这个对象会设置address为当前合约地址,同时第一个主题为事件的签名。
  • Function -(可选)传入一个回调函数,将立即开始监听,这样就不用主动调用myEvent.watch(function(){})[async]。

回调返回值:

Object - 详见合约对象的事件了解更多。

示例:

var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

// watch for an event with {some: 'args'}
var events = myContractInstance.allEvents({fromBlock: 0, toBlock: 'latest'});
events.watch(function(error, result){
   ...
});

// would get all past logs again.
events.get(function(error, logs){ ... });

...

// would stop and uninstall the filter
myEvent.stopWatching();