Basic usage and specific examples of Infura


Infura is an Ethereum infrastructure service provider developed by ConsenSys that allows developers to easily interact with the Ethereum network without having to run and maintain an Ethereum node themselves.

What can Infura do?

1. Send a transaction to the Ethereum network and get the result of the transaction

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);

The above code first uses Web3 and ethereumjs-tx library for transaction construction and signing, then uses Infura to send the signed transaction and wait for the transaction receipt. The transaction receipt contains important information about the state of the transaction and related information, such as the transaction hash, transaction fee, and transaction status. You can use this information for processing and storage by your own applications.

2. Obtain the balance, transaction history and other information of the Ethereum address

get balance

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`);
  }
});

Get transaction history

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}`));
  }
});

Notice:Infura requires you to register and obtain a project ID before you can use it. Replace in the code with your own project ID.

3. Interact with smart contracts through Ethereum libraries such as Web3.js

  1. Create a web3.js instance
   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. Get smart contract instance
   const abi = <智能合约ABI>;
   const contractAddress = '<智能合约地址>';
   const contract = new web3.eth.Contract(abi, contractAddress);
  1. Call the smart contract method
   const methodName = '<智能合约方法名>';
   const methodArgs = [<参数1>, <参数2>, ...];
   const txOptions = {
    
    
     from: '<发送方地址>',
     gas: '<Gas上限>',
     gasPrice: '<Gas价格>',
   };
   const result = await contract.methods[methodName](...methodArgs).send(txOptions);

full code

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. Send Ether with Infura

First, you need to register an account on Infura and obtain an API key. Then use the Web3.js library to interact with 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. Other services

  1. Provide Ethereum node service.
    Infura provides a reliable and high-performance Ethereum node service that allows application developers to access the Ethereum network without deploying their own nodes.

  2. Support for multiple Ethereum networks.
    Infura supports multiple Ethereum networks, including the main network, test network and private network, etc., to meet the needs of different developers.

  3. Provide Web3.js API.
    Infura provides a Web3.js API that enables applications to interact with the Ethereum network through the API.

  4. Provide IPFS node service.
    Infura provides the IPFS node service so that applications can access the distributed storage network IPFS.

  5. Provide support for other blockchain protocols.
    Infura supports other blockchain protocols, such as IPFS and Filecoin, to meet the needs of different developers.

Guess you like

Origin blog.csdn.net/m0_70127749/article/details/130262290