English
 找回密码
 立即注册

[Ethereum Smart Contract Development Notes] Using Infura and web3.js to call the contract

Vitalik 2025-11-3 22:44 53029人围观 ETH

unitimes.media Global perspective, unique insights "Go to the Infura official website to apply, just enter some basic information and email, and you will receive the API-key. ”-Infura Logo from Consensys-Infura provides public Ethereum mainnet and test ne
unitimes.media



Global perspective, unique insights

“Go to the Infura official website to apply, just enter some basic information and email, and you will receive the API-key. ”



-Infura Logo from Consensys-

Infura provides public Ethereum mainnet and testnet nodes. Go to the Infura official website to apply, just enter some basic information and email, and you will receive the API-key.



-Infura API keys-

Use RPC to query the status stored in the contract

The most frequently requested status is the balance of Token. I will use the EOS Token contract as an example to give it a try.

Get contract information

Through Etherscan, most well-known contracts can be directly searched.



To call a contract, at least:

•Contract address, for example:

0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0

•The function signature to be called, for example, taking the ERC 20 Token contract, the function to be called to query the balance is balanceOf(address), and its corresponding function signature is 70a08231.

How to obtain function signature?

Take balanceOf(address) as an example:

i. Pass balanceOf(address) through sha3



ii. Remove the first 8 bits except 0x

70a08231

The above process can be completed with any tool, taking web3.js as an example:

var functionSig = we3.sha3("balanceOf(address)").substr(2,8)

In addition, you can also paste the contract code into Remix (Editor's note: see the link at the end of the article). The complete contract interface and corresponding function signature can be seen in the details of the contract.



Use RPC

An RPC can be called via a simple POST using the nodes provided by Infura. See the Ethereum RPC doc for what RPC methods there are.

If the function you want to call is just to query and not update the status of the contract, then use the eth_call RPC. POST Data is as follows:



The value of params contains:

•"to": contract address

•"data": Parameters thrown to the contract. It consists of three parts: 0x, 70a08231 and a 32 bytes parameter 00000000000000000000000033b8287511ac7F003902e83D642Be46 (that is, the account I want to query)

"latest", which means using the latest blockchain data

example



0x0000000000000000000000000000000000000000000000b1d16ec625a59d3e is hexadecimal, converted to decimal is 12813144212159962430. The decimal of EOS token is 18, which means that my account only has a few 12.8x EOS tokens.

web3.js(Ethereum JavaScript API)

If you want to update the status of the contract, you need to send a transaction. To send the transaction, you need a wallet or private key to sign the transaction and provide Ether for the handling fee. Because there is a handling fee for sending transactions, in order to save some money, I set up a contract to conduct this experiment on the Ropsten test chain. The above steps are quite troublesome. I used web3.js to write two simple programs, one to query the contract status and the other to update the contract status. The function of web3.js is similar to RPC, but it is a JavaScript suite. Please see the JavaScript API doc for what APIs are available.

Install

npm install web3 ethereumjs-tx --save

Officially recommended initialization method



Deploy test contract

This time we deploy a very simple contract. The contract only stores one state data and can update the state through set(). For details on how to deploy a contract, please refer to my other article (Editor's note: also see the link at the end of the article).

Contract program code:

pragma solidity ^0.4.19;

contract SimpleStorage {
   uint public data;

   function set(uint x) public {
       data = x;
   }
}

Contract address:

0x5fb30123b9efedcd15094266948fb7c862279ee1

Contract function signatures:

{
   "73d4a13a": "data()",
   "60fe47b1": "set(uint256)"}

Query contract status

Use web3.eth.call .

// Request
var result = web3.eth.call({
  to: "0x5fb30123b9efedcd15094266948fb7c862279ee1",
   data: "0x" + "73d4a13a"
});

// Print Result
console.log(parseInt(result, 16));

The result of Print will be 0 because the status has not been updated.

Update contract status

Use web3.eth.sendRawTransaction.

The SendTransaction provided by RPC and web3.js is connected to a node and uses the account in the node to send the transaction. If you want to use your own account, you have to use sendRawTransaction, which means you have to create the transaction yourself, sign it yourself, and then send it through sendRawTransaction.

Define raw transaction



rawTx contains:

• nonce: records the number of transactions sent by the current account, used to avoid replay attacks, and adds 1 for each transaction. You can use RPC eth_getTransactionCount to query the nonce of the current account. You can also use Etherscan to check, but the No Of Transactions displayed by Etherscan will include transactions that were sent but failed, so it will not be accurate.

•gasPrice: Generally use 1 Gwei (= 1000000000 = 0x3B9ACA00)

•gasLimit: Gaslimit estimation can refer to using ethereum browser to calculate gas cost.

•to: contract address

•value: The amount of Ether to be sent, because it is just to call the contract, so set it to 0

•data: Parameters thrown to the contract. 由三个部分组成: 0x 、 60fe47b1 和一个32 bytes 的参数000000000000000000000000000000000000000000000000000000000000000a (*也就是我要更新的值,这边设 10 *)

Create and Sign raw transaction

To introduce another package ethereumjs-tx. Remember to install it with npm first.

var Tx = require('ethereumjs-tx');

Create a raw transaction.

var tx = new Tx(rawTx);

Sign with your own private key.



Send raw transaction



Result

If successful, a transaction hash will be returned, such as:



After the transaction is successfully sent and included in the block, query the contract status again, and the *Print result will be 10*.

You can use Etherscan to confirm whether the transaction has been included in the block and the result of the contract execution (the execution may fail due to parameter errors).



References

• Establishing an updateable smart contract on the blockchain (1)

• Ethereum JSON RPC Document

• We3.js API Document

Originally published at gist.github.com.

原文链接: https://medium.com/taipei-ethereum-meetup/ethereum-%E6%99%BA%E8%83%BD%E5%90%88%E7%B4%84%E9%96%8B%E7%99%BC%E7%AD%86%E8%A8%98-%E4%B8%8D%E7%94%A8%E8%87%AA%E5%B7%B1%E8%B7%91%E7%AF%80%E9%BB%9E-%E4%BD%BF%E7%94%A8-infura-%E5%92%8C-web3-js-%E5%91%BC%E5%8F%AB%E5%90%88%E7%B4%84-2b8c852ed3d2

Original author: Anderson



International financial technology new media and community platform



UNITIMES

Website: unitimes.media

Sina Weibo: @Unitimes

精彩评论0
我有话说......
TA还没有介绍自己。