Detailed explanation of interaction between php and ethereum client

不言
Release: 2023-03-25 06:18:02
Original
1878 people have browsed it

This article tells you the relevant knowledge points about the interaction between PHP and Ethereum clients. It has certain reference value. Friends in need can follow and learn.

php communicates with ethereum rpc server

1. Json RPC

Json RPC is based on json's remote procedure call, this explanation is relatively abstract. To put it simply, it is to post a json format data and call the method in the rpc server. The json format is fixed. In general, there are the following items:

{ "method": "", "params": [], "id": idNumber }
Copy after login

  • method: method name

  • params: parameter list

  • id: unique identifier for the procedure call No.

##2. Build a Json RPC client

url = $url; // proxy empty($proxy) ? $this->proxy = '' : $this->proxy = $proxy; // debug state empty($debug) ? $this->debug = false : $this->debug = true; // message id $this->id = 1; } /** * Sets the notification state of the object. In this state, notifications are performed, instead of requests. * * @param boolean $notification */ public function setRPCNotification($notification) { empty($notification) ? $this->notification = false : $this->notification = true; } /** * Performs a jsonRCP request and gets the results as an array * * @param string $method * @param array $params * @return array */ public function __call($method,$params) { // check if (!is_scalar($method)) { throw new Exception('Method name has no scalar value'); } // check if (is_array($params)) { // no keys $params = $params[0]; } else { throw new Exception('Params must be given as array'); } // sets notification or request task if ($this->notification) { $currentId = NULL; } else { $currentId = $this->id; } // prepares the request $request = array( 'method' => $method, 'params' => $params, 'id' => $currentId ); $request = json_encode($request); $this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n"; // performs the HTTP POST $opts = array ('http' => array ( 'method' => 'POST', 'header' => 'Content-type: application/json', 'content' => $request )); $context = stream_context_create($opts); if ($fp = fopen($this->url, 'r', false, $context)) { $response = ''; while($row = fgets($fp)) { $response.= trim($row)."\n"; } $this->debug && $this->debug.='***** Server response *****'."\n".$response.'***** End of server response *****'."\n"; $response = json_decode($response,true); } else { throw new Exception('Unable to connect to '.$this->url); } // debug output if ($this->debug) { echo nl2br($debug); } // final checks and return if (!$this->notification) { // check if ($response['id'] != $currentId) { throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')'); } if (!is_null($response['error'])) { throw new Exception('Request error: '. var_export($response['error'], true)); } return $response['result']; } else { return true; } } } ?>
Copy after login

Relatively simple code , if you are lazy, just take it and use it. You can also go to packagist.org to find an rpc client yourself.

3. Two types of methods for calling RPC

There are two types of methods that need to be called. One type It is the RPC server's own method, and the other type is the contract method.

RPC server method calls json format

{ "method": "eth_accounts", "params": [], "id": 1 }
Copy after login

RPC Server's own method The list

It is relatively simple to call the built-in method. Refer to the above link, most of them have examples.

Contract method call json format


Must be used to call the contract method eth_call in the built-in method. The contract method name and contract method parameter list are reflected using params. For example: If we want to call the balanceOf method in the contract, how should the json data be constructed?

Let’s take a look first Function implementation of getBalanace:

function balanceOf(address _owner) public view returns (uint256 balance)
Copy after login

Extract the function prototype:

balanceOf(address)
Copy after login

in geth Run the command under the console:

web3.sha3("balanceOf(address)").substring(0, 10)
Copy after login

Get the function hash "0x70a08231"

Assume that the address to be queried is address _owner = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", then Remove the "0x" in front and add 24 zeros on the left (the general address length is 42 bits, and it is 40 bits after removing the '0x') to form a 64-bit hexadecimal parameter.

Finally obtained The parameter is "0x70a082310000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"

Assume that our contract address is "0xaeab4084194B2a425096fb583Fbcd67385210ac 3".

Then the final json data will be:

{ "method": "eth_call", "params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0x70a0823100000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750"}, "latest"], "id": 1 }
Copy after login

Send the above json data to the server in post mode, then you can call the contract method "balanceOf" to query the token balance in the given address.

You must also be new when calling other methods in the contract Following the above method, let's analyze the transfer method again to deepen our impression:

First, look at the function implementation in the code:

function transfer(address _to, uint256 _value) public returns (bool)
Copy after login

Secondly, extract the function prototype:

transfer(address,uint256) //注意逗号后面不能有空格
Copy after login

Again, run the sha3 function on the console:

web3.sha3("transfer(address,uint256)").substring(0, 10)
Copy after login

Get the function hash "0xa9059cbb"

The first parameter assumes address _to = "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", then go to "0x" and add zeros to 64 bits.


No. Assuming that uint256 _value = 43776, the two parameters are converted into hexadecimal "0xab00", then "0x" is removed, and zeros are added to 64 bits. 27c5ec5750000000000000000000000000000000000000000000000000000000000ab00"

Construct json data:

{ "method": "eth_call", "params": [{"from": "0x38aabef4cd283ccd5091298dedc88d27c5ec5750", "to": "0xaeab4084194B2a425096fb583Fbcd67385210ac3", "data": "0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec5750000000000000000000000000000000000000000000000000000000000000ab00"}, "latest"], "id": 1 }
Copy after login

##from transferor address

    to contract address
  • data The hexadecimal number obtained by the above operation
  • Convert the above steps into code.
  • Build an Ethereum RPC client

getMessage(); } return call_user_func([self::$client, $method], $params); } public static function getBalance($address) { $method_hash = '0x70a08231'; $method_param1_hex = str_pad(substr($address, 2), 64, '0', STR_PAD_LEFT); $data = $method_hash . $method_param1_hex; $params = ['from' => $address, 'to' => self::CONTRACT, 'data' => $data]; $total_balance = self::eth_call([$params, "latest"]); return hexdec($total_balance) / (pow(10, 18)); } public static function transfer($to, $value) { self::personal_unlockAccount([self::COINBASE, "123456", 3600]); $value = bcpow(10, 18) * $value; $method_hash = '0xa9059cbb'; $method_param1_hex =str_pad(substr($to, 2), 64, '0', STR_PAD_LEFT); $method_param2_hex = str_pad(strval(bc_dechex($value)), 64, '0', STR_PAD_LEFT); $data = $method_hash . $method_param1_hex . $method_param2_hex; $params = ['from' => self::COINBASE, 'to' => self::CONTRACT, 'data' => $data]; return self::eth_sendTransaction([$params]); } }
Copy after login

The code is relatively simple, there are a few points to note:

##transfer function The value unit is very small, 10 ^ -18, so if you want to transfer 1,000 times, you actually need to multiply by 10 to the 18th power, where 18 is decimals.

Because Point 1, bcpow should be used instead of the pow function.
  • You cannot use the dechex function that comes with PHP. Because dechex requires that the integer type cannot be larger than PHP_INT_MAX, and this number is 4294967295 on a 32-bit machine. . Due to point 1, all numbers must be multiplied by 10 to the 18th power, so the resulting number is much larger than PHP_INT_MAX. It is recommended to convert decimal to hexadecimal by yourself. If you don't know how to implement it, refer to the above code.
  • When running certain contract methods, such as transfer, the user must be unlocked first.
  • After sending the transaction, it must be started on the server side Mining, so that the transaction will actually be written into the block. For example, after you call transfer, you find that the other party has not received the account. Don't be surprised, start mining and try. If you want to enable automatic code mining, add --mine at the end of geth --rpc...
  • Test:

  • 
              
    Copy after login


    The above is the detailed content of Detailed explanation of interaction between php and ethereum client. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!