Infura的基本用途和具体实例


Infura 是一个由 ConsenSys 开发的以太坊基础设施服务提供商,它可以让开发人员轻松地与以太坊网络进行交互,而无需自己运行和维护一个以太坊节点。

Infura 可以做什么?

1. 向以太坊网络发送交易并获取交易的结果

const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;

const RPC_ENDPOINT = 'https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID';
const PRIVATE_KEY = 'YOUR_PRIVATE_KEY';

const web3 = new Web3(new Web3.providers.HttpProvider(RPC_ENDPOINT));

// 构建交易对象
const txObj = {
    
    
  nonce: web3.utils.toHex(await web3.eth.getTransactionCount(MY_ADDR)),
  to: TO_ADDR,
  value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
  gasLimit: web3.utils.toHex(21000),
  gasPrice: web3.utils.toHex(await web3.eth.getGasPrice())
};

// 签名交易
const privateKey = Buffer.from(PRIVATE_KEY, 'hex');
const tx = new Tx(txObj, {
    
     'chain': 'ropsten' });
tx.sign(privateKey);
const serializedTx = tx.serialize().toString('hex');

// 发送交易
const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx);
console.log('Transaction hash:', receipt.transactionHash);
console.log('Transaction receipt:', receipt);

上述代码首先使用Web3和ethereumjs-tx库进行交易构建和签名,然后使用Infura发送已签名的交易并等待交易收据。交易收据包含有关交易状态和相关信息的重要信息,例如交易哈希值、交易费用和交易状态等。可以使用这些信息对自己的应用程序进行处理和存储。

2. 获取以太坊地址的余额、交易历史记录等信息

获取余额

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/<YOUR PROJECT ID>');

const address = '0x123456...'; // 替换为您要查询的地址
web3.eth.getBalance(address, (err, balance) => {
    
    
  if (err) {
    
    
    console.error(err);
  } else {
    
    
    console.log(`Address ${
      
      address} has a balance of ${
      
      web3.utils.fromWei(balance, 'ether')} ETH`);
  }
});

获取交易历史记录

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/<YOUR PROJECT ID>');

const address = '0x123456...'; // 替换为您要查询的地址
web3.eth.getTransactionsByAddress(address, (err, txs) => {
    
    
  if (err) {
    
    
    console.error(err);
  } else {
    
    
    console.log(`Address ${
      
      address} has ${
      
      txs.length} transactions:`);
    txs.forEach((tx) => console.log(`Transaction hash: ${
      
      tx.hash}`));
  }
});

注意:Infura需要您注册并获得项目ID才能使用。将代码中的替换为您自己的项目ID。

3. 通过 Web3.js 等以太坊库与智能合约进行交互

  1. 创建web3.js实例
   const Web3 = require('web3');
   const infuraKey = '<Infura API Key>';
   const infuraEndpoint = 'https://mainnet.infura.io/v3/' + infuraKey;
   const provider = new Web3.providers.HttpProvider(infuraEndpoint);
   const web3 = new Web3(provider);
  1. 获取智能合约实例
   const abi = <智能合约ABI>;
   const contractAddress = '<智能合约地址>';
   const contract = new web3.eth.Contract(abi, contractAddress);
  1. 调用智能合约方法
   const methodName = '<智能合约方法名>';
   const methodArgs = [<参数1>, <参数2>, ...];
   const txOptions = {
    
    
     from: '<发送方地址>',
     gas: '<Gas上限>',
     gasPrice: '<Gas价格>',
   };
   const result = await contract.methods[methodName](...methodArgs).send(txOptions);

完整代码

const Web3 = require('web3');
const infuraKey = '<Infura API Key>';
const infuraEndpoint = 'https://mainnet.infura.io/v3/' + infuraKey;
const provider = new Web3.providers.HttpProvider(infuraEndpoint);
const web3 = new Web3(provider);

const abi = <智能合约ABI>;
const contractAddress = '<智能合约地址>';
const contract = new web3.eth.Contract(abi, contractAddress);

const methodName = '<智能合约方法名>';
const methodArgs = [<参数1>, <参数2>, ...];
const txOptions = {
    
    
  from: '<发送方地址>',
  gas: '<Gas上限>',
  gasPrice: '<Gas价格>',
};
const result = await contract.methods[methodName](...methodArgs).send(txOptions);

3. 使用 Infura 发送以太币

首先,您需要在 Infura 上注册一个账号并获取一个 API 密钥。然后使用 Web3.js 库与 Infura 进行交互。

const Web3 = require('web3');

// 连接到以太坊网络
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/your-project-id'));

// 发送以太币
const sendTransaction = async () => {
    
    
  const account = '0xYourAccountAddress';
  const privateKey = '0xYourPrivateKey';
  const toAddress = '0xRecipientAddress';
  const value = '1000000000000000000'; // 1 ETH

  const gasPrice = await web3.eth.getGasPrice();
  const gasLimit = '21000';

  const nonce = await web3.eth.getTransactionCount(account);
  const transaction = {
    
    
    from: account,
    to: toAddress,
    value: value,
    gasPrice: gasPrice,
    gas: gasLimit,
    nonce: nonce
  };

  const signedTransaction = await web3.eth.accounts.signTransaction(transaction, privateKey);
  const transactionReceipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
  console.log(transactionReceipt);
};

sendTransaction();

4. 其他服务

  1. 提供以太坊节点服务。
    Infura提供了可靠和高性能的以太坊节点服务,可以让应用程序开发者在不部署自己的节点的情况下,访问以太坊网络。

  2. 支持多个以太坊网络。
    Infura支持多个以太坊网络,包括主网、测试网络和私有网络等,可满足不同开发者的需求。

  3. 提供Web3.js API。
    Infura提供了Web3.js API,使得应用程序可以通过API与以太坊网络进行交互。

  4. 提供IPFS节点服务。
    Infura提供了IPFS节点服务,以便应用程序可以访问分布式存储网络IPFS。

  5. 提供其他区块链协议支持。
    Infura支持其他区块链协议,例如IPFS和Filecoin等,以满足不同开发者的需求。

猜你喜欢

转载自blog.csdn.net/m0_70127749/article/details/130262290