github.com/trezor/blockbook@v0.4.1-0.20240328132726-e9a08582ee2c/bchain/coins/polygon/polygonrpc.go (about) 1 package polygon 2 3 import ( 4 "context" 5 "encoding/json" 6 7 "github.com/ethereum/go-ethereum/ethclient" 8 "github.com/ethereum/go-ethereum/rpc" 9 "github.com/golang/glog" 10 "github.com/juju/errors" 11 "github.com/trezor/blockbook/bchain" 12 "github.com/trezor/blockbook/bchain/coins/eth" 13 ) 14 15 const ( 16 // MainNet is production network 17 MainNet eth.Network = 137 18 ) 19 20 // PolygonRPC is an interface to JSON-RPC polygon service. 21 type PolygonRPC struct { 22 *eth.EthereumRPC 23 } 24 25 // NewPolygonRPC returns new PolygonRPC instance. 26 func NewPolygonRPC(config json.RawMessage, pushHandler func(bchain.NotificationType)) (bchain.BlockChain, error) { 27 c, err := eth.NewEthereumRPC(config, pushHandler) 28 if err != nil { 29 return nil, err 30 } 31 32 s := &PolygonRPC{ 33 EthereumRPC: c.(*eth.EthereumRPC), 34 } 35 36 return s, nil 37 } 38 39 // Initialize polygon rpc interface 40 func (b *PolygonRPC) Initialize() error { 41 b.OpenRPC = func(url string) (bchain.EVMRPCClient, bchain.EVMClient, error) { 42 r, err := rpc.Dial(url) 43 if err != nil { 44 return nil, nil, err 45 } 46 rc := ð.EthereumRPCClient{Client: r} 47 ec := ð.EthereumClient{Client: ethclient.NewClient(r)} 48 return rc, ec, nil 49 } 50 51 rc, ec, err := b.OpenRPC(b.ChainConfig.RPCURL) 52 if err != nil { 53 return err 54 } 55 56 // set chain specific 57 b.Client = ec 58 b.RPC = rc 59 b.MainNetChainID = MainNet 60 b.NewBlock = eth.NewEthereumNewBlock() 61 b.NewTx = eth.NewEthereumNewTx() 62 63 ctx, cancel := context.WithTimeout(context.Background(), b.Timeout) 64 defer cancel() 65 66 id, err := b.Client.NetworkID(ctx) 67 if err != nil { 68 return err 69 } 70 71 // parameters for getInfo request 72 switch eth.Network(id.Uint64()) { 73 case MainNet: 74 b.Testnet = false 75 b.Network = "livenet" 76 default: 77 return errors.Errorf("Unknown network id %v", id) 78 } 79 80 glog.Info("rpc: block chain ", b.Network) 81 82 return nil 83 }