eth解析交易事件 go代码实例

package main

import (
	"context"
	"fmt"
	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/accounts/abi"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethclient"
	"log"
	"math/big"
	"strings"
)



const ABI = `[
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": false,
				"internalType": "address",
				"name": "addr",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint64",
				"name": "ocId",
				"type": "uint64"
			}
		],
		"name": "buyEvent",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": false,
				"internalType": "uint64",
				"name": "ocId",
				"type": "uint64"
			},
			{
				"indexed": false,
				"internalType": "uint8",
				"name": "isprofit",
				"type": "uint8"
			},
			{
				"indexed": false,
				"internalType": "uint40",
				"name": "exerciseTime",
				"type": "uint40"
			},
			{
				"indexed": false,
				"internalType": "uint32",
				"name": "amount",
				"type": "uint32"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "profit",
				"type": "uint256"
			}
		],
		"name": "exerciseEvent",
		"type": "event"
	},
	{
		"inputs": [],
		"name": "buyOptionById",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	}
]`


func main() {
	EventOption()
}



func EventOption() {
	abi:=GetABI(ABI)
	cli, err := ethclient.Dial("ws://192.168.19.66:7545")
	if err != nil {
		fmt.Println("连接私链失败:", err)
		return
	}
	//函数结束自动关闭连接
	defer cli.Close()
	contractAddress := common.HexToAddress("0xf3ed85874fbb39681e8b076554ac69f2255c1028")
	query := ethereum.FilterQuery{
		Addresses: []common.Address{contractAddress},
	}
	logs := make(chan types.Log)
	sub, err := cli.SubscribeFilterLogs(context.Background(), query, logs)
	if err != nil {
		log.Fatal(err)
	}

	for {
		select {
		case err := <-sub.Err():
			log.Fatal(err)
		case vLog := <-logs:
			switch vLog.Topics[0].String() {
				//buyEvent事件 这里的hash为事件名buyEvent(address,uint64)进行keccack256计算得出的
			case "0xbf5ed60d1b60f93841065247988234acab61d25f0cdb23dae3507eb01809e42f":
                   //这步是对监听到的DATA数据进行解析
				intr, err := abi.Events["buyEvent"].Inputs.UnpackValues(vLog.Data)
				if err != nil {
					panic(err)
				}
                //打印监听到的参数
				fmt.Println(intr[0].(common.Address).String(),intr[1].(*big.Int).Uint64())
				fmt.Println("交易hash",vLog.TxHash.String())
				//exerciseEvent事件 exerciseEvent(uint64,uint8,uint40,uint32,uint256)
			case "0xc32df39ae9f5cc595be756fd57aa0a8976bf1c8a5aad5199dc2001efa4a384b5":
            //这步是对监听到的DATA数据进行解析
				intr, err := abi.Events["exerciseEvent"].Inputs.UnpackValues(vLog.Data)
				if err != nil {
					panic(err)
				}
				list:=[]interface{}{}
				for _,v:=range intr{
					list=append(list,v)
				}
                //打印监听到的参数
				fmt.Println(list)
				fmt.Println("交易hash",vLog.TxHash.String())
			}
		}
	}
}

//获取ABI对象
func GetABI(abiJSON string)abi.ABI {
	wrapABI,err:=abi.JSON(strings.NewReader(abiJSON))
	if err!=nil {
		panic(err)
	}
	return wrapABI
}

附上测试用的合约代码

pragma solidity ^0.6.8;
 

contract Attacker{
    event buyEvent(address addr,uint64 ocId);
    event exerciseEvent(uint64 ocId,uint8 isprofit,uint40 exerciseTime,uint32 amount,uint256 profit);
    function buyOptionById() external {
       address addr=msg.sender;
        emit buyEvent(addr,666666);
        emit exerciseEvent(111,222,333,444,555);
    } 
}

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个基于Python的Eth代币转账实现代码示例,需要使用web3.py库: ```python from web3 import Web3 import json # 1. 连接到以太坊节点 web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/{your-infura-project-id}')) # 2. 加载代币合约ABI with open('abi.json', 'r') as abi_definition: abi = json.load(abi_definition) # 3. 获取代币合约 contract_address = '0x1234567890123456789012345678901234567890' contract = web3.eth.contract(address=contract_address, abi=abi) # 4. 发送代币转账交易 token_sender_address = '0x1234567890123456789012345678901234567890' token_sender_private_key = '{your-private-key}' token_receiver_address = '0x0987654321098765432109876543210987654321' token_amount = 1000 gas_limit = 100000 gas_price = web3.toWei('20', 'gwei') # 获取nonce值 nonce = web3.eth.getTransactionCount(token_sender_address) # 构造交易数据 transaction = { 'nonce': nonce, 'to': contract_address, 'value': 0, 'gas': gas_limit, 'gasPrice': gas_price, 'data': contract.functions.transfer(token_receiver_address, token_amount).buildTransaction({'from': token_sender_address}).hex(), } # 对交易进行签名 signed_txn = web3.eth.account.signTransaction(transaction, private_key=token_sender_private_key) # 发送交易 tx_hash = web3.eth.sendRawTransaction(signed_txn.rawTransaction) # 等待交易被打包 tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash) # 打印交易信息 print(f'Transaction sent: {tx_hash.hex()}') print(f'Transaction receipt: {tx_receipt}') ``` 其中,需要将代码中的以下参数替换为实际的值: - `{your-infura-project-id}`:Infura项目ID - `abi.json`:代币合约ABI文件路径 - `contract_address`:代币合约地址 - `token_sender_address`:代币发送者地址 - `token_sender_private_key`:代币发送者私钥 - `token_receiver_address`:代币接收者地址 - `token_amount`:代币数量 - `gas_limit`:交易的gas限制 - `gas_price`:交易的gas价格 需要注意的是,这只是一个简单的示例代码,实际使用中需要根据具体情况进行调整和完善。同时,在使用时需要非常小心,以免出现错误导致代币丢失。建议在测试环境中进行充分的测试,确保代码的正确性和安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值