Home > Backend Development > PHP Tutorial > Detailed explanation of interaction between php and ethereum client

Detailed explanation of interaction between php and ethereum client

php中世界最好的语言
Release: 2023-03-25 21:48:02
Original
2880 people have browsed it

This time I will bring you a detailed explanation of the interactive use of PHP and the Ethereum client. What are the precautions for the interactive use of PHP and the Ethereum client. The following is a practical case, let's take a look.

php communicates with ethereum rpc server

1. Json RPC

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

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

  • params: parameter list

  • id: unique identification number for the procedure call

2. Build a Json RPC client

<?php
class jsonRPCClient {
  
  /**
   * Debug state
   *
   * @var boolean
   */
  private $debug;
  
  /**
   * The server URL
   *
   * @var string
   */
  private $url;
  /**
   * The request id
   *
   * @var integer
   */
  private $id;
  /**
   * If true, notifications are performed instead of requests
   *
   * @var boolean
   */
  private $notification = false;
  
  /**
   * Takes the connection parameters
   *
   * @param string $url
   * @param boolean $debug
   */
  public function construct($url,$debug = false) {
    // server URL
    $this->url = $url;
    // proxy
    empty($proxy) ? $this->proxy = &#39;&#39; : $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(&#39;Method name has no scalar value&#39;);
    }
    
    // check
    if (is_array($params)) {
      // no keys
      $params = $params[0];
    } else {
      throw new Exception(&#39;Params must be given as array&#39;);
    }
    
    // sets notification or request task
    if ($this->notification) {
      $currentId = NULL;
    } else {
      $currentId = $this->id;
    }
    
    // prepares the request
    $request = array(
            &#39;method&#39; => $method,
            &#39;params&#39; => $params,
            &#39;id&#39; => $currentId
            );
    $request = json_encode($request);
    $this->debug && $this->debug.=&#39;***** Request *****&#39;."\n".$request."\n".&#39;***** End Of request *****&#39;."\n\n";
    // performs the HTTP POST
    $opts = array (&#39;http&#39; => array (
              &#39;method&#39; => &#39;POST&#39;,
              &#39;header&#39; => &#39;Content-type: application/json&#39;,
              &#39;content&#39; => $request
              ));
    $context = stream_context_create($opts);
    if ($fp = fopen($this->url, &#39;r&#39;, false, $context)) {
      $response = &#39;&#39;;
      while($row = fgets($fp)) {
        $response.= trim($row)."\n";
      }
      $this->debug && $this->debug.=&#39;***** Server response *****&#39;."\n".$response.&#39;***** End of server response *****&#39;."\n";
      $response = json_decode($response,true);
    } else {
      throw new Exception(&#39;Unable to connect to &#39;.$this->url);
    }
    
    // debug output
    if ($this->debug) {
      echo nl2br($debug);
    }
    
    // final checks and return
    if (!$this->notification) {
      // check
      if ($response[&#39;id&#39;] != $currentId) {
        throw new Exception(&#39;Incorrect response id (request id: &#39;.$currentId.&#39;, response id: &#39;.$response[&#39;id&#39;].&#39;)&#39;);
      }
      if (!is_null($response[&#39;error&#39;])) {
        throw new Exception(&#39;Request error: &#39;. var_export($response[&#39;error&#39;], true));
      }
      
      return $response[&#39;result&#39;];
      
    } else {
      return true;
    }
  }
}
?>
Copy after login

Relatively simple code, if you are lazy, just 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 is RPC server Built-in methods, the other type is contract methods.

RPC server method calls json format

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

List of RPC Server’s built-in methods

Calling built-in methods is relatively simple. Refer to the above link, most of them have examples.

Contract method call json format

To call the contract method, you must use the eth_call in the built-in method. The contract method name and contract method parameter list use params to reflect, for example: if we want to call the balanceOf method in the contract, how should the json data be constructed?

First look at the 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

Run the command under geth 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 previous " 0x", and add 24 zeros on the left (general address length is 42 bits, 40 bits after removing '0x'), forming a 64-bit hexadecimal parameter.

The final parameter is "0x70a082310000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec57 50 "

Suppose our contract address is "0xaeab4084194B2a425096fb583Fbcd67385210ac3".

Then the final json data obtained is:

{
  "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 a given address.

Calling other methods in the contract must also follow 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

Thirdly, run the sha3 function on the console:

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

Get function hash "0xa9059cbb"

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

The second parameter assumes uint256 _value = 43776, then convert it into hexadecimal "0xab00", remove "0x", and add zeros to 64 bits.

Connect them

"0xa9059cbb00000000000000000000000038aabef4cd283ccd5091298dedc88d27c5ec57500 000000000000000000000000000000000000000000000000000000000ab00"

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

<?php 
require &#39;./jsonRPCClient.php&#39;;
//php自带的dechex无法把大整型转换为十六进制
function bc_dechex($decimal)
{
  $result = [];
  while ($decimal != 0) {
    $mod = $decimal % 16;
    $decimal = floor($decimal / 16);
    array_push($result, dechex($mod));    
  }
  return join(array_reverse($result));
}
class EthereumRPCClient
{
  public static $client = null;
  
  //布署合约的账户地址
  const COINBASE = &#39;0x38aabef4cd283ccd5091298dedc88d27c5ec5750&#39;;
  
  //合约地址
  const CONTRACT = &#39;0xaeab4084194B2a425096fb583Fbcd67385210ac3&#39;;
  public static function callStatic($method, $params)
  {
    $params = count($params) < 1 ? [] : $params[0];
    try {
      if (is_null(self::$client)) {
        self::$client = new jsonRPCClient(&#39;http://127.0.0.1:8545&#39;, true);  
      }
    } catch (\Exception $e) {
      echo $e->getMessage();
    }
    return call_user_func([self::$client, $method], $params);
  }
  public static function getBalance($address)
  {
    $method_hash = &#39;0x70a08231&#39;;
    $method_param1_hex = str_pad(substr($address, 2), 64, &#39;0&#39;, STR_PAD_LEFT);
    $data = $method_hash . $method_param1_hex;
    $params = [&#39;from&#39; => $address, &#39;to&#39; => self::CONTRACT, &#39;data&#39; => $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 = &#39;0xa9059cbb&#39;;
    $method_param1_hex =str_pad(substr($to, 2), 64, &#39;0&#39;, STR_PAD_LEFT);  
    $method_param2_hex = str_pad(strval(bc_dechex($value)), 64, &#39;0&#39;, STR_PAD_LEFT);
    $data = $method_hash . $method_param1_hex . $method_param2_hex;
    $params = [&#39;from&#39; => self::COINBASE, &#39;to&#39; => self::CONTRACT, &#39;data&#39; => $data];
    return self::eth_sendTransaction([$params]);
  }
}
Copy after login

Code comparison Simple, there are a few points to note:

  • The value unit of the transfer function is very small, 10 ^ -18, so if you want to transfer 1,000 times, you actually have to multiply 10 times 18 times Square, the 18 here are decimals.

  • Due to point 1, bcpow should be used instead of the pow function.

  • 不能使用php自带的dechex函数. 因为dechex要求整型不能大于 PHP_INT_MAX, 而这个数在32位机上为4294967295。由于第1 点, 所有的数都要乘于10的18次方, 所以得到的数要远远大于PHP_INT_MAX. 建议自己实现10进制转16进制,如果你不知道如何实现,参考上述代码。

  • 在运行某些合约方法, 比如transfer时, 要先unlock用户.

  • 发送交易之后, 一定要在服务器端启动挖矿, 这样交易才会真的写入到区块, 比如你调用transfer之后,却发现对方没有到账,先别吃惊,启动挖矿试试。如果想启用自动挖码, 在geth --rpc ...最后加上 --mine.

测试:

<?php 
var_dump(EthereumRPCClient::personal_newAccount([&#39;password&#39;]));
var_dump(EthereumRPCClient::personal_unlockAccount([EthereumRPCClient::COINBASE, "password", 3600]);
var_dump(EthereumRPCClient::getBalance("0x...."));
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

PHP使用file_get_contents发送http请求步骤详解

PHP实现随机剔除算法

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template