記事ディレクトリ
Infura は、ConsenSys によって開発された Ethereum インフラストラクチャ サービス プロバイダーであり、開発者は Ethereum ノードを自分で実行および維持する必要なく、Ethereum ネットワークと簡単に対話できます。
インフラにできること
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 などの Ethereum ライブラリを介してスマート コントラクトとやり取りする
- 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);
- スマート コントラクト インスタンスを取得する
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);
完全なコード
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. その他のサービス
-
イーサリアム ノード サービスを提供します。
Infura は、アプリケーション開発者が独自のノードを展開することなく Ethereum ネットワークにアクセスできるようにする、信頼性が高く高性能な Ethereum ノード サービスを提供します。 -
複数の Ethereum ネットワークのサポート。
Infura は、さまざまな開発者のニーズを満たすために、メイン ネットワーク、テスト ネットワーク、プライベート ネットワークなどを含む複数の Ethereum ネットワークをサポートしています。 -
Web3.js API を提供します。
Infura は、アプリケーションが API を介して Ethereum ネットワークとやり取りできるようにする Web3.js API を提供します。 -
IPFS ノード サービスを提供します。
Infura は、アプリケーションが分散ストレージ ネットワーク IPFS にアクセスできるように、IPFS ノード サービスを提供します。 -
他のブロックチェーン プロトコルのサポートを提供します。
Infura は、さまざまな開発者のニーズを満たすために、IPFS や Filecoin などの他のブロックチェーン プロトコルをサポートしています。