web3p / web3.php Goto Github PK
View Code? Open in Web Editor NEWA php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.
License: MIT License
A php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.
License: MIT License
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.
Methods and params validator
Methods
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\Utils
Fatal error: Uncaught RuntimeException: invalid argument 1: json: cannot unmarshal number into Go value of type bool
array(2) {
[0]=>
string(6) "latest"
[1]=>
bool(false)
}
->>>>>
array(2) {
[0]=>
string(6) "latest"
[1]=>
int(0) <<<<<-- ISSUE!!!
}
BooleanFormatter.php
->
line 31
return (int) $value;
->>>>
return (bool) $value;
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"
无法获取依赖
提示
What this new
function is used for and is there a way to work it around for the PHP 5.6 version?
The error: https://travis-ci.org/olegabr/web3.php/jobs/364199138#L561
Maybe don't use this class.
Db functions are deprecated and will be removed in the future. see https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring
Web3\Provider*
v0.1
v0.2
WebSocketProvider
IPCProvider
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?
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal
https://github.com/paritytech/parity/wiki/JSONRPC-personal-module
Due to parity only have these four methods in personal module, so just implement these:
Geth personal api:
Methods
The eth_getBalance second param has default value.
See https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getbalance
Web3\Web3
Web3\Eth
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.
echo Utils::toWei("1.6", 'ether')->toString();
will print 1000000000000000000
echo Utils::toWei("0.1", 'ether')->toString();
will print 0
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:
Or this https://travis-ci.org/sc0Vu/web3.php/builds/328051275:
Usage examples.
Fake a ethereum chain when test
I saw web3js always format output as number string.
Right now we just return bignumber instance.
Should we return number string or bignumber instance?
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!
I do not know why errors occur.
PHP 7.1.8
/* /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 );
?>
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
--
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)" } }
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?
https://github.com/ethereum/wiki/wiki/JSON-RPC#json-rpc-methods
$provider->sendPayload($jsonRpcObject->toPayload()); ?!
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 ?
Right now we use infura service as ethereum blockchain service.
Maybe use ethereumjs-testrpc or ganache-cli to test.
The problem might be using php and nodejs on travis-ci.
https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/scripts/test.sh
before_install:
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\Utils::toBn(48) // print 0x00
phpseclib\Math\BigInteger {#550
+value: "0x00"
+"engine": "bcmath (OpenSSL)"
}
`
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?
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?
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
vs
web3js use eth_getLogs
$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
Others
Is this supported watching solidity events from a contracts sendTransaction?
Web3\Contracts\Ethabi
uint
int
bytes
string
address
bool
<type>
<type>[M]
<type>[M][N]
bytes
string
<type>[]
encode signature
encode params
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
https://github.com/ethereum/wiki/wiki/Whisper
$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.
I've been working on trying to retrieve a contracts info how can I do this?
This is the contract https://etherscan.io/address/0x2Fa0ac498D01632f959D3C18E38f4390B005e200
And I want to get this info from the Read Contract https://etherscan.io/address/0x2Fa0ac498D01632f959D3C18E38f4390B005e200#readContract
Throw exception when transaction data is not valid.
Right now it return false.
Spec https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber
{"id":1,"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",false]}
return block result, it should return hash
{"id":1,"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",true]}
also return block result
0x vs 0X
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
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) {
});
web3js use Method object to append methods to object like eth.
We can use __call to make this function.
Web3\Web3('uri')
Web3\Web3(\Web3\Providers\Provider)
JSON RPC
clientVersion
sha3
Document
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.