如何使用?
使用curl、Web3.js、ethers、NodeJS、Java、Go、Python请求以太坊网络
curl
SolarPath 支持 HTTP 访问以太坊网络,以下示例使用 curl
来与以太坊进行交互:
curl https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}'
Web3.js
var Web3 = require('web3');
var url = 'https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY';
var httpProvider = new Web3.providers.HttpProvider(url);
var web3 = new Web3(httpProvider);
web3.eth.getBlockNumber().then((result) => {
console.log("Latest ETH block: " + result);
});
Ethers
var ethers = require('ethers');
var url = 'https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY';
var etherProvider = new ethers.providers.JsonRpcProvider(url);
etherProvider.getBlockNumber().then((result) => {
console.log("Latest ETH block: " + result);
});
Node JS
const https = require('https');
const myKey = 'YOUR-API-KEY';
const data = JSON.stringify({
"jsonrpc":"2.0","method":"eth_blockNumber","params": [],"id":1
});
const options = {
host: 'eth-mainnet.solarpath.io',
port: 443,
path: '/v1/' + myKey,
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
const req = https.request(options, res => {
console.log(`status code: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(data);
req.end();
Java
导入 web3j 依赖项,参阅: https://github.com/web3j/web3j
Web3j web3j =
Web3j.build(new HttpService("https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY"));
EthBlock ethBlock =
web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false)
.send();
System.out.println("Latest ETH block: " + ethBlock.getBlock().getNumber());
通常建议将 Web3j 的实例对象使用static final
进行修饰,在您的服务停止时,调用: web3j.shutdown();
Go
初始化一个新的 go 模块:
go mod init solarpath
安装
go-ethereum
的依赖项,go get github.com/ethereum/go-ethereum/rpc
package main
import (
"fmt"
"log"
"github.com/ethereum/go-ethereum/rpc"
)
type Block struct {
Number string
}
func main() {
client, err := rpc.Dial("https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY")
if err != nil {
log.Fatalf("Could not connect to SolarPath: %v", err)
}
var lastBlock Block
err = client.Call(&lastBlock, "eth_getBlockByNumber", "latest", true)
if err != nil {
fmt.Println("Cannot get the ETH latest block:", err)
return
}
fmt.Printf("Latest ETH block: %v\n", lastBlock.Number)
}
Python
from web3 import Web3, HTTPProvider
web3Provider = Web3(HTTPProvider('https://eth-mainnet.solarpath.io/v1/YOUR-API-KEY'))
print ("Latest ETH block ", web3Provider.eth.blockNumber)
最后更新于