Coder Social home page Coder Social logo

web3p / web3.php Goto Github PK

View Code? Open in Web Editor NEW
1.1K 56.0 532.0 1015 KB

A php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.

License: MIT License

PHP 99.74% Shell 0.08% Dockerfile 0.03% Solidity 0.15%
web3 ethereum web3php php smart-contracts hacktoberfest

web3.php's Introduction

web3.php

PHP Build Status codecov Join the chat at https://gitter.im/web3-php/web3.php Licensed under the MIT License

A php interface for interacting with the Ethereum blockchain and ecosystem.

Install

Set minimum stability to dev

"minimum-stability": "dev"

Then

composer require web3p/web3.php dev-master

Or you can add this line in composer.json

"web3p/web3.php": "dev-master"

Usage

New instance

use Web3\Web3;

$web3 = new Web3('http://localhost:8545');

Using provider

use Web3\Web3;
use Web3\Providers\HttpProvider;

$web3 = new Web3(new HttpProvider('http://localhost:8545'));

// timeout
$web3 = new Web3(new HttpProvider('http://localhost:8545', 0.1));

You can use callback to each rpc call:

$web3->clientVersion(function ($err, $version) {
    if ($err !== null) {
        // do something
        return;
    }
    if (isset($version)) {
        echo 'Client version: ' . $version;
    }
});

Async

use Web3\Web3;
use Web3\Providers\HttpAsyncProvider;

$web3 = new Web3(new HttpAsyncProvider('http://localhost:8545'));

// timeout
$web3 = new Web3(new HttpAsyncProvider('http://localhost:8545', 0.1));

// await
$promise = $web3->clientVersion(function ($err, $version) {
    // do somthing
});
Async\await($promise);

Websocket

use Web3\Web3;
use Web3\Providers\WsProvider;

$web3 = new Web3(new WsProvider('ws://localhost:8545'));

// timeout
$web3 = new Web3(new WsProvider('ws://localhost:8545', 0.1));

// await
$promise = $web3->clientVersion(function ($err, $version) {
    // do somthing
});
Async\await($promise);

// close connection
$web3->provider->close();

Eth

use Web3\Web3;

$web3 = new Web3('http://localhost:8545');
$eth = $web3->eth;

Or

use Web3\Eth;

$eth = new Eth('http://localhost:8545');

Net

use Web3\Web3;

$web3 = new Web3('http://localhost:8545');
$net = $web3->net;

Or

use Web3\Net;

$net = new Net('http://localhost:8545');

Batch

web3

$web3->batch(true);
$web3->clientVersion();
$web3->hash('0x1234');
$web3->execute(function ($err, $data) {
    if ($err !== null) {
        // do something
        // it may throw exception or array of exception depends on error type
        // connection error: throw exception
        // json rpc error: array of exception
        return;
    }
    // do something
});

eth

$eth->batch(true);
$eth->protocolVersion();
$eth->syncing();

$eth->provider->execute(function ($err, $data) {
    if ($err !== null) {
        // do something
        return;
    }
    // do something
});

net

$net->batch(true);
$net->version();
$net->listening();

$net->provider->execute(function ($err, $data) {
    if ($err !== null) {
        // do something
        return;
    }
    // do something
});

personal

$personal->batch(true);
$personal->listAccounts();
$personal->newAccount('123456');

$personal->provider->execute(function ($err, $data) {
    if ($err !== null) {
        // do something
        return;
    }
    // do something
});

Contract

use Web3\Contract;

$contract = new Contract('http://localhost:8545', $abi);

// deploy contract
$contract->bytecode($bytecode)->new($params, $callback);

// call contract function
$contract->at($contractAddress)->call($functionName, $params, $callback);

// change function state
$contract->at($contractAddress)->send($functionName, $params, $callback);

// estimate deploy contract gas
$contract->bytecode($bytecode)->estimateGas($params, $callback);

// estimate function gas
$contract->at($contractAddress)->estimateGas($functionName, $params, $callback);

// get constructor data
$constructorData = $contract->bytecode($bytecode)->getData($params);

// get function data
$functionData = $contract->at($contractAddress)->getData($functionName, $params);

Assign value to outside scope(from callback scope to outside scope)

Due to callback is not like javascript callback, if we need to assign value to outside scope, we need to assign reference to callback.

$newAccount = '';

$web3->personal->newAccount('123456', function ($err, $account) use (&$newAccount) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    $newAccount = $account;
    echo 'New account: ' . $account . PHP_EOL;
});

Examples

To run examples, you need to run ethereum blockchain local (testrpc).

If you are using docker as development machain, you can try ethdock to run local ethereum blockchain, just simply run docker-compose up -d testrpc and expose the 8545 port.

Develop

Local php cli installed

  1. Clone the repo and install packages.
git clone https://github.com/web3p/web3.php.git && cd web3.php && composer install
  1. Run test script.
vendor/bin/phpunit

Docker container

  1. Clone the repo and run docker container.
git clone https://github.com/web3p/web3.php.git
  1. Copy web3.php to web3.php/docker/app directory and start container.
cp files docker/app && docker-compose up -d php ganache
  1. Enter php container and install packages.
docker-compose exec php ash
  1. Change testHost in TestCase.php
/**
 * testHost
 * 
 * @var string
 */
protected $testHost = 'http://ganache:8545';
  1. Run test script
vendor/bin/phpunit
Install packages

Enter container first

docker-compose exec php ash
  1. gmp
apk add gmp-dev
docker-php-ext-install gmp
  1. bcmath
docker-php-ext-install bcmath
Remove extension

Move the extension config from /usr/local/etc/php/conf.d/

mv /usr/local/etc/php/conf.d/extension-config-name to/directory

API

Todo.

Contribution

Thank you to all the people who already contributed to web3.php!

License

MIT

web3.php's People

Contributors

1099511627776 avatar a10000005588 avatar amateescu avatar arul- avatar brokenpieworld avatar lsmelan avatar miguilimzero avatar pash7ka avatar refear99 avatar sc0vu avatar sciku1 avatar serderovsh avatar sinabs avatar sunshuzhou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web3.php's Issues

Unlock account

$web3 = new Web3('MY_ETHEREUM_HOST_NAME');
$web3->personal->unlockAccount('MY_WALLET_ADDRESS', 'MY_WALLET_PASSWORD', function ($err, $result) {
    if ($err !== null) {
        throw $err;
    }
});

RuntimeException (-32602)
invalid argument 2: json: cannot unmarshal string into Go value of type uint64

I assume that the error in the Web3\Formatters\QuantityFormatter::format() method:

public static function format($value)
{
    $value = Utils::toString($value);
    $bn = Utils::toBn($value);
    return '0x' . $bn->toHex(true);
}

unclockAccount duration param must be integer (?), but QuantityFormatter formats it to string (hex).
If replace (just for testing) this method to

public static function format($value)
{
    if (is_int($value)) {
        return $value;
    }
    $value = Utils::toString($value);
    $bn = Utils::toBn($value);
    return '0x' . $bn->toHex(true);
}

the error disappears and the "unlockAccount" starts to work.

Transaction never finishes no error

when I execute my transaction using ->send it just hangs and then eventually says killed. any way to debug what might be happening? I know the address is correct and rpc is working as I can execute a "call" on the same contract and return a value from a different function.

Web3\Contracts\Ethabi

Web3\Contracts\Ethabi

  • types
uint
int
bytes
string
address
bool
  • static types
<type>
<type>[M]
<type>[M][N]
  • dynamic types
bytes
string
<type>[]
  • encode signature

  • encode params

Parse result

Right now we just json decode result.

I think it better to parse result.

Maybe make each method as a single object, eg src/Methods/Eth/GetTransactionCountMethod.

  • Let methods be objects. #22 #23

  • Let methods test separately. #11

  • InputFormatters outputFormatters

contract->call problem when returning multiple parameters

when using:
$contract->call("getRecord", 12345, function($err, $data) {
print_r($data);
}

the getRecord method in the contract returns 4 elements (address, string, string, uint256)

the $data returned is ONLY the uint256 (as an array). It looks like the decodeParameters function in Ethabi called from Contract.php is only returning the last element instead of returning an array of all elements. Any idea on how to get to all 4 returned elements? It works as expected in javascript web3 class. Thanks!
-jack

Missing web3.eth.accounts.recover method?

Would like to add a feature request. I see the corresponding sign method in src/Methods/Eth/Sign.php and would like to see a recover method ie: src/Methods/Eth/Recover.php.

Great work btw!

Decoding JSON RPC Response.

I have made my own curl request to etherscan and infura via php to get my contract data into php.

how would I use this project just to decode the json-rpc response returned data?

I dont see any php libraries to decode the response.

Your requirements could not be resolved to an installable set of packages

I did install by manual, but on command "composer require sc0vu/web3.php dev-master", I got this error

Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package sc0vu/web3.php No version set (parsed as 1.0.0) is satisfiable by sc0vu/web3.php[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

What can be wrong? And how can I install web3.php lib?

Web3

Web3\Web3('uri')
Web3\Web3(\Web3\Providers\Provider)

JSON RPC

  • clientVersion

  • sha3

Enhance QuantityValidator

As spec write, Quantity is integer of a block number.

Right now it validate pattern is 0x[a-fA-F0-9]+, I think it could be better to test upper bound or lower bound.

web3.php/src/Contracts/Ethabi.php decodeParameters

I do not know why errors occur.

environment

PHP 7.1.8

code

/* /path/to/project/Web3Test.php */
<?php
require_once /path/to/project/vendor/autoload.php" ;
require_once /path/to/project/vendor/fguillot/json-rpc/src/JsonRPC/Client.php" ;
require_once /path/to/project/vendor/sc0vu/web3.php/src/Contracts/Ethabi.php" ;

use Web3\Contracts\Ethabi;
use JsonRPC\Client;

unset( $ethabi );
$ethabi = new Ethabi(["address" => "Web3\Contracts\Types\Address", "uint" => "Web3\Contracts\Types\Uinteger" ]);

$result = $ethabi->decodeParameters( [ "address", "address", "uint256" ], "0x0000000000000000000000000000000000000000000000000000000000001489000000000000000000000000000000000000000000000000000000000000050b" );
var_dump( $result );

?>

output

Fatal error: Uncaught Error: Call to a member function staticPartLength() on string in /path/to/project/vendor/sc0vu/web3.php/src/Contracts/Ethabi.php:240 Stack trace: #0 /path/to/project/Web3Test.php(11): Web3\Contracts\Ethabi->decodeParameters(Array, '0x0000000000000...') #1 {main} thrown in /path/to/project/vendor/sc0vu/web3.php/src/Contracts/Ethabi.php on line 240
-- 

want

array(3) { [0]=> string(42) "0x0000000000000000000000000000000000001489" [1]=> string(42) "0x000000000000000000000000000000000000050b" [2]=> object(phpseclib\Math\BigInteger)#4 (2) { ["value"]=> string(2) "0x" ["engine"]=> string(26) "internal (64-bit, OpenSSL)" } } 

Sending ETH address as parameter

Several functions that do not need parameters run correctly as expected

EG:
$contract->at("0xd0a6E6C54DbC68Db5db3A091B171A77447Ff7ccf");
$contract->call("time", $params, "test");
with $params not actually used is fine.

however example
$params = ['0x2660614ca342b2bf58d2a07c4fd0cb85cdb95f10'];
$contract->call("keys", $params, "test");
does not work

Do you know how ethereum address parameter can be sent to a contract?

Personal Example shows me error

Creating account good, but on unlock it shows this error
Error: Invalid params: invalid type: integer 300, expected a 0x-prefixed, hex-encoded number of length 32

ๆ— ๆณ•่Žทๅ–ไพ่ต–

Install
Set minimum stability to dev

"minimum-stability": "dev"
Then

composer require sc0vu/web3.php dev-master
Or you can add this line in composer.json

"sc0vu/web3.php": "dev-master"

ๆ— ๆณ•่Žทๅ–ไพ่ต–

ๆ็คบ

  • The requested package sc0vu/web3.php No version set (parsed as 1.0.0) is satisfiable by sc0vu/web3.php[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

QuantityFormatter::format() problem

This method converts to hex wrong. I don't know why, but it adds some '0' after '0x'.

For example:
QuantityFormatter::format('600000')
convert 600000 to 0x0927c0. Valid hex must be: 0x927C0.

Because of this, I get the following error:

invalid argument 0: json: cannot unmarshal hex number with leading zero digits into Go struct field SendTxArgs.gas of type *hexutil.Big

Also, i don't understand why in examples values passed in hex (gas for example), but in Web3\Methods\Eth\SendTransaction::$inputFormatters param used TransactionFormatter::class in which again the values are converted into hex. Hex to hex?

Web3\Eth

web3js use Method object to append methods to object like eth.

We can use __call to make this function.

  • eth_protocolVersion
  • eth_syncing
  • eth_coinbase
  • eth_mining
  • eth_hashrate
  • eth_gasPrice
  • eth_accounts
  • eth_blockNumber
  • eth_getBalance
  • eth_getStorageAt
  • eth_getTransactionCount
  • eth_getBlockTransactionCountByHash
  • eth_getBlockTransactionCountByNumber
  • eth_getUncleCountByBlockHash
  • eth_getUncleCountByBlockNumber
  • eth_getCode
  • eth_sign
  • eth_sendTransaction
  • eth_sendRawTransaction
  • eth_call
  • eth_estimateGas
  • eth_getBlockByHash
  • eth_getBlockByNumber
  • eth_getTransactionByHash
  • eth_getTransactionByBlockHashAndIndex
  • eth_getTransactionByBlockNumberAndIndex
  • eth_getTransactionReceipt
  • eth_getUncleByBlockHashAndIndex
  • eth_getUncleByBlockNumberAndIndex
  • eth_getCompilers
  • eth_compileLLL
  • eth_compileSolidity
  • eth_compileSerpent
  • eth_newFilter
  • eth_newBlockFilter
  • eth_newPendingTransactionFilter
  • eth_uninstallFilter
  • eth_getFilterChanges
  • eth_getFilterLogs
  • eth_getLogs
  • eth_getWork
  • eth_submitWork
  • eth_submitHashrate

Formatter

Methods

  • InputFormatter
  • OutputFormatter

Signed Raw Transaction

Hey

Is it possible to get some example of how to sign raw transaction with private key which is calling contract function.

What i'm trying to do is like

$contract  = new Contract($nodeAddress, $abi)->at($contractAddress);
$transactionData = $contract->getData('functionName', 'address', 'bool', [
             'from' => $fromAddress,
             'to'    => $toAddress,
             'gas' => $gas,
            'gasPrice' => $gasPrice
]);
$web3= new Web3(new HttpProvider(new HttpRequestManager($nodeAddress, $timeOut)));
$eth = $web3->getEth();
$eth->sign($privateKey, $transactionData, function($err, $result) {
});

Contract Transaction never hits chain

Im trying to do token transfer, the code gives back me tx, parity dose not show any errors but transactions never gets mined any advice how to fix this ?

How to sign Ethereum transactions with this library?

Is it possible to sendRawTransaction with this library by using private keys - without accounts creating. And is it possible to sign transactions with this lib or maybe you can recommend some ethereumjs-tx analog for PHP?

Web3\Net

  • net_version
  • net_peerCount
  • net_listening

Tests

  • HttpProvider
  • HttpRequestManager
  • Validators
  • Methods
  • Formatters
  • utils
  • Provider
  • RequestManager
  • web3
  • eth
  • net
  • Split test functions

Test will throw this error sometimes

Test will throw this error sometimes:

Test\Unit\PersonalApiTest::testSendTransaction

sender doesn't have enough funds to send tx. The upfront cost is: 90001 and the sender's account only has: 65535

On travis, sometimes get this error, I can't figure out why this happen https://travis-ci.org/sc0Vu/web3.php/builds/328039019:

  1. Test\Unit\AddressFormatterTest::testFormat
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/AddressFormatterTest.php:24
  2. Test\Unit\AddressTypeTest::testIsType
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/AddressTypeTest.php:52
  3. Test\Unit\BooleanFormatterTest::testFormat
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/BooleanFormatterTest.php:24
  4. Test\Unit\BooleanTypeTest::testIsType
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/BooleanTypeTest.php:52
  5. Test\Unit\BytesTypeTest::testIsType
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/BytesTypeTest.php:58
  6. Test\Unit\ContractTest::testDeploy
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/ContractTest.php:305
  7. Test\Unit\ContractTest::testSend
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/ContractTest.php:305

Or this https://travis-ci.org/sc0Vu/web3.php/builds/328051275:

  1. Test\Unit\AddressFormatterTest::testFormat
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/AddressFormatterTest.php:24
  2. Test\Unit\AddressTypeTest::testIsType
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/AddressTypeTest.php:52
  3. Test\Unit\BooleanFormatterTest::testFormat
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/BooleanFormatterTest.php:24
  4. Test\Unit\BooleanTypeTest::testIsType
    cURL error 7: Failed to connect to localhost port 8545: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:50
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:52
    /home/travis/build/sc0Vu/web3.php/src/RequestManagers/HttpRequestManager.php:117
    /home/travis/build/sc0Vu/web3.php/src/Providers/HttpProvider.php:62
    /home/travis/build/sc0Vu/web3.php/src/Eth.php:105
    /home/travis/build/sc0Vu/web3.php/test/TestCase.php:53
    /home/travis/build/sc0Vu/web3.php/test/unit/BooleanTypeTest.php:5

Insufficient funds when sending a transaction

First of all, great work on this @sc0Vu! I know this is still bleeding edge at the moment but I encountered an issue that I hope you can help me out with. Below is a snippet from my proof of concept code to send transactions on the rinkeby testnet.

$web3 = new Web3(new HttpProvider(new HttpRequestManager(env('INFURA_URL'), 5.0)));
$eth = $web3->eth;

$eth->getBalance(env('WALLET_ADDRESS'), function ($err, $balance) {
    if ($err !== null) {
        $this->error($err->getMessage());
    }
    $this->comment(sprintf('Current balance: %s ETH', wei_to_ether($balance)));
});

$eth->gasPrice(function ($err, $gasPrice) {
    if ($err !== null) {
        $this->error($err->getMessage());
    }
    $this->gasPrice = $gasPrice;
    $this->comment(sprintf('Gas price: %s gwei', wei_to_gwei($gasPrice->toString())));
});

$eth->estimateGas(['from' => env('WALLET_ADDRESS')], function ($err, $gas) {
    if ($err !== null) {
        $this->error($err->getMessage());
    }
    $this->gasEstimate = $gas;
    $this->comment(sprintf('Gas limit: %s units', $gas->toString()));
});

$eth->getTransactionCount(env('WALLET_ADDRESS'), 'pending', function ($err, $nonce) use ($eth) {
    if ($err !== null) {
        $this->error($err->getMessage());
    }
    $this->comment(sprintf('Nonce: %s', $nonce));

    for ($i = 0; $i < count($this->recipients); $i++) {
        $this->info(
            sprintf(
                'Sending %s ETH to %s',
                $this->recipients[$i]['amount'],
                $this->recipients[$i]['address']
            )
        );

        // @todo: should use TransactionFormatter to do all hex conversion (when it works)
        $txParams = [
            'from' => env('WALLET_ADDRESS'),
            'to' => $this->recipients[$i]['address'],
            'value' => sprintf(decimal_to_hex(ether_to_wei($this->recipients[$i]['amount']))),
            'nonce' => sprintf(decimal_to_hex($nonce->toString() + $i)),
            'gasLimit' => decimal_to_hex($this->gasEstimate->toString()),
            'gasPrice' => decimal_to_hex($this->gasPrice->toString()),
            'chainId' => 4,
        ];

        $transaction = new Transaction($txParams);

        $signedTransaction = $transaction->sign(env('WALLET_PRIVATE_KEY'));

        // Send the transaction
        $eth->sendRawTransaction(sprintf('0x%s', $signedTransaction), function ($err, $tx) {
            if ($err !== null) {
                $this->error($err->getMessage());
            }
            $this->comment(sprintf('TX: %s', $tx));
        });
    }
});

Everything works flawlessly until sending the transaction, it comes back with the following error insufficient funds for gas * price + value. I'm sure that I have sufficient funds, as I have a very similar proof of concept using web3js that works fine. Below are the transaction parameters right before signing for both versions:

PHP

array:7 [
  "from" => "0x83ca28679f477Cd4710B72D11e47905A66dd6Dd4"
  "to" => "0xEFd7b1e4F28Dcd8000abb62974A77DB6a35618A6"
  "value" => "0x5af3107a4000"
  "nonce" => "0x89"
  "gasLimit" => "0xcf08"
  "gasPrice" => "0x3b9aca00"
  "chainId" => 4
]

Javascript

{ from: '0x83ca28679f477Cd4710B72D11e47905A66dd6Dd4',
  to: '0xEFd7b1e4F28Dcd8000abb62974A77DB6a35618A6',
  value: '0x5af3107a4000',
  nonce: '0x89',
  gasLimit: '0xcf08',
  gasPrice: '0x3b9aca00',
  chainId: 4 }

As you can see the parameters are identical so I'm a bit lost as to why the transaction doesn't get through. Any thoughts?

Web3\Contracts\SolidityTypes

  • Web3\Contracts\SolidityType
  • Web3\Contracts\Types\IType
  • Web3\Contracts\Types\Address
  • Web3\Contracts\Types\Boolean
  • Web3\Contracts\Types\Bytes
  • Web3\Contracts\Types\Dynamicbytes
  • Web3\Contracts\Types\Intger
  • Web3\Contracts\Types\Str
  • Web3\Contracts\Types\Uinteger

Separate transaction validator and call validator.

There are different between eth transaction and eth call object.

We using the same validator now, could use another call validator instead of transaction validator to validate eth call.

Object - The transaction call object
from: DATA, 20 Bytes - (optional) The address the transaction is sent from.
to: DATA, 20 Bytes - The address the transaction is directed to.
gas: QUANTITY - (optional) Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions.
gasPrice: QUANTITY - (optional) Integer of the gasPrice used for each paid gas
value: QUANTITY - (optional) Integer of the value send with this transaction
data: DATA - (optional) Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI

Web3\Contract

Web3\Contract

Method

https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction

Event

https://github.com/ethereum/wiki/blob/78990aca283f67ceb26ed70c8eb82008424aaf64/JSON-RPC.md#eth_getlogs

vs

https://github.com/ethereum/wiki/blob/78990aca283f67ceb26ed70c8eb82008424aaf64/JSON-RPC.md#eth_newfilter

web3js use eth_getLogs

How to long poll to get log?

  1. multithread or multiprocess (multiprocess doesn't work on Windows)
  2. block loop script
  3. libuv?
$contract = new Contract($provider, $abi)
$contract->at($address)

$txParams = [
    'from' => '',
    'value' => ''
];
$contract->send($method, $params, $txParams, $callback) // create contract if no address
$contract->call($method, $params, $txParams, $callback) // throw if no address
$contract->estimateGas($method, $params, $txParams, $callback) // throw if no address

Method

  • estimateGas
  • getData
  • send
  • call
  • new

Others

  • methods
  • event

Providers

Web3\Provider*

v0.1

  • HttpProvider

v0.2

  • WebSocketProvider

  • IPCProvider

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.