合约地址示例
https://hecoinfo.com/address/0x910651F81a605a6Ef35d05527d24A72fecef8bF0#code
在取abi的时候,要先看当前合约是否为代理合约,如果是代理合约的话需要去取源合约的api,因为我们是调用源合约的方法,不能直接通过代理合约去调用源合约的方法(个人理解,有误指正)
以下是代理合约
点击跳转到源合约:https://hecoinfo.com/address/0x543a2ae552d993342a92e87aefc966b69534a798#code
拿到他的abi
getPastEvents调用合约
web3文档
https://web3js.readthedocs.io/en/v1.3.4/web3-eth-contract.html#getpastevents
初始化Contract
import Web3 from 'web3'
import contractABI from '../ABI/contractABI.json'//contractABI为上面源合约地址的abi
const web3 = new Web3(window.ethereum)
var myContractInstance = new web3.eth.Contract(contractABI, adderss, {
from: '0x23FCB0E1DDbC821Bd26D5429BA13B7D5c96C0DE0',
gasPrice: '100',
...
});
adderss取值为代理合约,也就是我们自己合约地址的address,并非源合约地址的address
调用合约
获取所有合约事件
扫描二维码关注公众号,回复:
14233744 查看本文章

myContractInstance.getPastEvents('allEvents', {
filter: {
}, fromBlock: 0, toBlock: 'latest'}).then((res) => {
console.log(res)
})
获取指定合约事件
myContractInstance.getPastEvents('ChargeFee', {
filter: {
}, fromBlock: 0, toBlock: 'latest'}).then((res) => {
console.log(res)
})
demo
import React from 'react'
import Web3 from 'web3'
import contractABI from '../ABI/contractABI.json'
const web3 = new Web3(window.ethereum)
var myContractInstance = new web3.eth.Contract(contractABI, '0x910651F81a605a6Ef35d05527d24A72fecef8bF0', {
from: '0x23FCB0E1DDbC821Bd26D5429BA13B7D5c96C0DE0',
gasPrice: '100'
});
export default function Demo() {
const getAllEvens = () => {
myContractInstance.getPastEvents('allEvents', {
filter: {
}, fromBlock: 0, toBlock: 'latest'}).then((res) => {
console.log(res)
})
}
const getEven = (event) => {
myContractInstance.getPastEvents(event, {
filter: {
}, fromBlock: 0, toBlock: 'latest'}).then((res) => {
console.log(res)
})
}
return (
<div>
<button onClick={
getAllEvens}>获取所有事件allEvents</button>
<button onClick={
() => getEven('Transfer')}>获取单个事件Transfer</button>
<button onClick={
() => getEven('ChargeFee')}>获取单个事件ChargeFee</button>
</div>
)
}
合约是在以太坊主链上的,需要连接以太坊主链才能获取到数据,否则为空数组
获取全部和获取某一个事件的区别貌似就是,获取单个事件是从全部事件里面筛选出来的,相当于一个query参数(个人理解),不过这样请求速度肯定会更快