如何订阅事件"传入事务成功";。也就是说,我想知道以太币已经到了我的钱包里。如何使用订阅。我什么都不懂。
package main
import (
"context"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"log"
)
func main() {
client, err := ethclient.Dial("wss://mainnet.infura.io/ws/v3/XXXXXXXXXXXXXXXX")
if err != nil {
log.Fatal(err)
}
accs := map[string]string{
"0x92321477416e93Ea452f16015e2F2a13B3BDe8B7":"12e2cc06fb999fa29306f10db6b366e61a4946b9527286a0c56640c94cebd950",
}
keys := make([]common.Address, 0, len(accs))
for k := range accs {
keys = append(keys, common.HexToAddress(k))
}
var ch = make(chan types.Log)
sub, err := client.SubscribeFilterLogs(context.Background(), ethereum.FilterQuery{
BlockHash: nil,
FromBlock: nil,
ToBlock: nil,
Addresses: keys,
Topics: nil,
}, ch)
if err != nil {
log.Fatal(err)
}
defer sub.Unsubscribe()
for l := range ch {
// ???
}
}
请帮帮我。我在哪里可以找到例子?
在此处输入图像描述
我正在查看infura.io的API文档,但没有发现它们有支付的终点。您上面链接的图像是他们用于电子邮件通知的UI选项,与API无关。为了订阅一个操作,必须在他们端启动该操作。您必须为它们提供一个回调,以便在该操作发生时执行。你的回调会发出警报,但当触发(支出(发生时,他们会调用它。他们有进入webhook的地方吗?如果是,这将是您的订阅。
虽然此选项可能不是订阅,但一个可能的解决方法是轮询getBalance端点,并将结果与以前的结果进行比较,如果增加,则提醒您。
我的解决方案
sub, err := client.SubscribeNewHead(context.Background(), ch)
获取块
b, err := client.BlockByNumber(context.Background(), l.Number)
检查所有交易
for _, tx := range b.Transactions() {
msg, err := tx.AsMessage(types.NewEIP155Signer(tx.ChainId()))
}
在消息中。To(地址((
实际上go ethereum已经在他们的测试脚本中提供了一个演示:
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/ethclient/gethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const (
url = "https://mainnet.infura.io/v3/xxxxxxxx"
wss = "wss://eth-mainnet.alchemyapi.io/v2/xxxxxxxxxxx"
// wss = "wss://mainnet.infura.io/ws/v3/xxxxxxxx"
)
func watch() {
backend, err := ethclient.Dial(url)
if err != nil {
log.Printf("failed to dial: %v", err)
return
}
rpcCli, err := rpc.Dial(wss)
if err != nil {
log.Printf("failed to dial: %v", err)
return
}
gcli := gethclient.New(rpcCli)
txch := make(chan common.Hash, 100)
_, err = gcli.SubscribePendingTransactions(context.Background(), txch)
if err != nil {
log.Printf("failed to SubscribePendingTransactions: %v", err)
return
}
for {
select {
case txhash := <-txch:
tx, _, err := backend.TransactionByHash(context.Background(), txhash)
if err != nil {
continue
}
data, _ := tx.MarshalJSON()
log.Printf("tx: %v", string(data))
}
}
}
func DoTest() {
go watch()
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
<-signalChan
}