web3p / ethereum-tx Goto Github PK
View Code? Open in Web Editor NEWEthereum transaction library in PHP.
Home Page: https://www.web3p.xyz/ethereumtx.html
License: MIT License
Ethereum transaction library in PHP.
Home Page: https://www.web3p.xyz/ethereumtx.html
License: MIT License
hello, I've had this problem
transaction data:
i hope you can help me. if you need more data.
please contrace me
thank you!
There is an issue on this library when sign transaction with chain id.
See issue: https://github.com/sc0Vu/web3.php/issues/56
I think we should reconsider EIP 155 transaction
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
On ethereumjs-tx:
hash function
if (this._chainId > 0) {
const raw = this.raw.slice()
this.v = this._chainId
this.r = 0
this.s = 0
items = this.raw
this.raw = raw
} else {
items = this.raw.slice(0, 6)
}
sign function
const msgHash = this.hash(false)
const sig = ethUtil.ecsign(msgHash, privateKey)
if (this._chainId > 0) {
sig.v += this._chainId * 2 + 8
}
Another ethereum tx library: https://github.com/warren-bank/ethereumjs-tx-sign/blob/14aaa96f8b49e0bdced13d64161fbda3e2300a80/index.js#L91
I have some problem, can you help me?
{
"jsonrpc": "2.0",
"id": "1",
"error": {
"code": -32602,
"message": "transaction could not be decoded: could not recover from address: could not recover secp256k1 key: calculated Rx is larger than curve P"
}
}
Currently, chain id only worked when it's integer.
I think it might be better to support hex string or decimal string.
Need to checkout why we only use integer first.
$ composer require web3p/ethereum-tx
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Can only install one of: simplito/elliptic-php[1.0.4, 1.0.3].
- Can only install one of: simplito/elliptic-php[1.0.3, 1.0.4].
- Can only install one of: simplito/elliptic-php[1.0.3, 1.0.4].
- web3p/ethereum-tx 0.3.4 requires simplito/elliptic-php 1.0.3 -> satisfiable by simplito/elliptic-php[1.0.3].
- Installation request for web3p/ethereum-tx ^0.3.4 -> satisfiable by web3p/ethereum-tx[0.3.4].
- Installation request for simplito/elliptic-php (locked at 1.0.4) -> satisfiable by simplito/elliptic-php[1.0.4].
Installation failed, reverting ./composer.json to its original content.
test address: 0x3db20a82Cf2C02642A8c2E163063640F4Effe59F
when I have capital letters in my address, validation fails
{"from":"0x17b96334442d2eb8bdf4be769f67d38b5e094a90","to":"0xbe45e9ce05a049c6e6bf00e523f2b2d76b11f771","data":"0x","nonce":"0x27","gasPrice":"0x2540be400","value":"0xe8d4a51000","gas":"0x5210","chainId":20180511}
eth_sendRawTransaction get hash:0x8df7c38e9d6c1052c81f79adfb3777f9402f817a69fe6ae0517c356f9516f4a1
Transaction->hash is 0x977faa0fbc7f783c709cd39da8562e9ac7bc142f33afcbde3dd21a17abda797b
I'm currently trying to broadcast a raw ethereum classic transaction. However after the nonce 160, it stopped working and is now returning the following error: rlp: input string too long for uint64, decoding into (types.LegacyTx).Nonce.
.
[
"nonce" => "0xa0"
"from" => "0x3e59426f0aeaf08946f9fa05a4df1d19440b4ec7"
"to" => "0xd2de7e8f69a2493ef2269e78170268a18d9804d6"
"gas" => "0x5208"
"gasPrice" => "0x3b9aca00"
"value" => "0x5af3107a4000"
"chainId" => 61
"data" => ""
]
I used this library to test sendRawTransaction.
But I am getting this error - "transaction could not be decoded: could not recover from address: could not recover secp256k1 key: calculated Rx is larger than curve P" when I send signed transaction
f8ed01850861c46800827d0094d02a1ed82FA5091A5639dc507f2F6130E5Bc61Be80b8886139303539636262303030303030303030303030303030303030303030303030326130383566313530646638333639306165353232653933616136336530363466646166303439303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030343824a0bb8e9387f97cca50d0193bbbc57ebd1071156ed539e89beeeb73e104f8d01df0a07ada6542d9d29dc0c238ce54df923a35995f830f476b2b60167b72a6bbdf793d
This is my signed transaction by using transaction->sign() function
In my view, this result is wrong.
$eth->getTransactionCount($fromAccount, 'pending', function($err, $nonce) use ($eth, $fromAccount, $data) {
$rawTransaction = new Web3Transaction([
"from" => $fromAccount,
"gasPrice" => '0x861c46800',
"gasLimit" => '0x7d00',
"to" => env('CONTRACT_ADDRESS'),
"value" => "0x0",
"data" => $data,
"chainID" => 1,
"nonce" => sprintf('0x%s', dechex(intval($nonce->toString())+1))
]);
$signedTx = $rawTransaction->sign(env('COMPANY_PRIVATE_KEY'));
Log::debug($signedTx);
$eth->sendRawTransaction(sprintf('0x%s', $signedTx), function ($err, $tx) {
if ($err !== null) {
Log::debug("Error: " . $err->getMessage());
}
Log::debug('TX: ' . $tx);
});
});
This is my code to get the result.
Anyone can help me with this issue?
I'm running on Ropsten testnet, a tx returns, but it doesn't appear in explorer, the process doesn't happen. and it returns the same tx id every time.
function sendTransaction() {
$params = [
'nonce' => 546465,
'gas' => '0x' . $this->getEstimateGas()->toHex(),
'gasPrice' => '0x' . dechex(10000000000),
'from' => $this->from,
'to' => $this->to,
'value' => $this->amount,
'chainId' => $this->chainId
];
if (!is_null($this->transactionData)) {
$params['data'] = $this->transactionData;
}
$transaction = new Transaction($params);
$signedTransaction = $transaction->sign($this->privateKey);
$result;
$this->eth->sendRawTransaction('0x'. $signedTransaction, function ($err, $tx) use (&$result) {
if ($err) {
$result = $err;
} else {
$result = $tx;
}
});
return $result;
I think it happened because travis config file name is .travis.yml.
In this repository, this config file name is wrong .travis.yaml.
I have the following code.
require 'vendor/autoload.php';
use Web3\Web3;
use Web3p\EthereumTx\EIP1559Transaction;
$web3 = new Web3('https://eth-rinkeby.alchemyapi.io/v2/--api--');
$fromAddress = '0xB5A2FD09ed2Eb7AA3bBf55C7f8e8D8576B68b0F2';
$toAddress = '0x2928C5Fb489BE1182B3569a3863F1C61Cafde240';
$prvKey = '--private-key--';
$transactionAmount = 145;
$gasLimit = 0;
$baseFeePerGas = 0;
$gasUsed = 0;
$maxFeePerGas = 0;
$estimatedGas = 0;
$web3->eth->getBlockByNumber('pending',false,function($err,$success){
if ($err !== null) {
echo 'Error: ' . $err->getMessage();
exit;
}
global $gasLimit;
global $baseFeePerGas;
global $gasUsed;
$gasLimit = $success->gasLimit;
$baseFeePerGas = $success->baseFeePerGas;
$gasUsed = $success->gasUsed;
});
$estimateGasRequest = [
'from' => $fromAddress,
'to' => $toAddress,
'value' => $transactionAmount
];
$web3->eth->estimateGas($estimateGasRequest,function($err,$success){
if ($err !== null) {
echo 'Error: ' . $err->getMessage();
exit;
}
global $estimatedGas;
$estimatedGas = $success->value;
});
echo $gasLimit; // Outputs 0x1c8debe
echo '<br/>';
echo $baseFeePerGas; // Outputs 0x8
echo '<br/>';
echo $gasUsed; // Outputs 0x1c8bb1d
echo '<br/>';
echo $estimatedGas; // Outputs 21000
echo '<br/>';
I am struggling to understand how I can use the retrieved values in order to fill out the required values for a transaction.
Can someone help me to understand how I can calculate the values marked ?????? in the source code shown?
$gweiFactor = 1 / 1000000000;
$nonce = '113';
// generate transaction instance with transaction parameters
$transactionInfo = [
'gas' => ??????,
'maxPriorityFeePerGas' => ??????,
'maxFeePerGas' => ??????,
'nonce' => '0x' . dechex($nonce),
'from' => $fromAddress,
'to' => $toAddress,
'value' => '0x' . dechex($transactionAmount),
'chainId' => 4, // required
'accessList' => [],
'data' => ''
]);
Even when eth-rinkeby.alchemyapi.io/v2/
accepts values that I send and return a transaction hash, the hash doesn't show up on the test net at all and the transfer doesn't happen.
txFields: Array
(
[nonce] => 0x00
[to] => 0x92a9fea1d70aded8c7de4a8d291a2a0b4cf09b28
[gas] => 0x030d40
[gasPrice] => 0x77359400
[value] => 0x0
[chainId] => 1
[data] => 0x095ea7b30000000000000000000000003091d37ef18cb33af72cf7ca63714733172ce724000000000000000000000000000000000000000000108b2a2c28029094000000
)
06-16-2018 @ 20:12:45 - Failed to sendRawTransaction: RuntimeException: rlp: non-canonical integer (leading zero bytes) for uint64, decoding into (types.Transaction)(types.txdata).AccountNonce in /var/www/html/wp-content/plugins/cryptocurrency-product-for-woocommerce/vendor/olegabr/web3.php/src/RequestManagers/HttpRequestManager.php:114
Stack trace:
#0 /var/www/html/wp-content/plugins/cryptocurrency-product-for-woocommerce/vendor/olegabr/web3.php/src/Providers/HttpProvider.php(62): Web3\RequestManagers\HttpRequestManager->sendPayload('{"id":155983314...', Object(Closure))
#1 /var/www/html/wp-content/plugins/cryptocurrency-product-for-woocommerce/vendor/olegabr/web3.php/src/Eth.php(105): Web3\Providers\HttpProvider->send(Object(Web3\Methods\Eth\SendRawTransaction), Object(Closure))
#2 /var/www/html/wp-content/plugins/cryptocurrency-product-for-woocommerce/cryptocurrency-product-for-woocommerce.php(564): Web3\Eth->__call('sendRawTransact...', Array)
#3 /var/www/html/wp-content/plugins/cryptocurrency-product-for-woocommerce/cryptocurrency-product-for-woocommerce.php(439): CRYPTOCURRENCY_PRODUCT_FOR_WOOCOMMERCE_make_token_deposit(772, '0x92a9fea1d70ad...', '20000000')
#4 /var/www/html/wp-includes/class-wp-hook.php(288): CRYPTOCURRENCY_PRODUCT_FOR_WOOCOMMERCE_save_option_field(772)
#5 /var/www/html/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters('', Array)
#6 /var/www/html/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#7 /var/www/html/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-meta-boxes.php(220): do_action('woocommerce_pro...', 772, Object(WP_Post))
#8 /var/www/html/wp-includes/class-wp-hook.php(288): WC_Admin_Meta_Boxes->save_meta_boxes(772, Object(WP_Post))
#9 /var/www/html/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters('', Array)
#10 /var/www/html/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#11 /var/www/html/wp-includes/post.php(3640): do_action('save_post', 772, Object(WP_Post), true)
#12 /var/www/html/wp-includes/post.php(3713): wp_insert_post(Array, false)
#13 /var/www/html/wp-admin/includes/post.php(377): wp_update_post(Array)
#14 /var/www/html/wp-admin/post.php(194): edit_post()
#15 {main}
The wallet with no out tx ever made (which leads to nonce = 0) is unusable with current code.
When I've made a single out tx for this wallet, the code became work as expected.
When I use sign function you said the private key should be hexed private key with zero prefixed.
But If I input "0x....." private key, then this returns an error
I am using sendRawTransaction on Binance network and it work great. After change network to Cronos, I receive invalid length after send it. (no issue getting gas price or latest nonce)
Here is my code:
$data = $contract->getData('transfer', $to, $value);
$param = [
'nonce' => Utils::toHex($nonce, true),
'from' => $from,
'to' => $contractAddress,
'gas' => Utils::toHex($estimateGas, true),
'gasPrice' => Utils::toHex($gasPrice, true),
'value' => Utils::toHex(0, true),
'chainId' => 338,
'accessList' => [],
'data' => '0x' . $data,
];
$transaction = new ethTransaction($param);
$signedTransaction = '0x' . $transaction->sign($privateKey);
// Send the transaction
$contract->eth->sendRawTransaction($signedTransaction, function ($err, $data) use (&$error, &$receipt, $from,
$to, $amount, $value) {
Not sure what went wrong.
See #11
Suggest that check attribute value before!
in web3j , i got
0xf8ec8202c3830f4240833d09009425721ce611f7c74d0d4163edbca911346ca7b23d80b884d3fc9864000000000000000000000000274049f24e500683f9c3df68840b06cab439e2e8000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000824593a0af0d6593820148d5f852dd5993479978db672142337bc7b5a1c3acb9d99b186ba0534b738be24a6bbf5606d1cb862d79e83e8ad7e8bed2f3b4c7da0e46e54e9aba
in web3p, i got
0xf8ee8430326333830f4240833d09009425721ce611f7c74d0d4163edbca911346ca7b23d80b884d3fc9864000000000000000000000000274049f24e500683f9c3df68840b06cab439e2e8000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000824594a0d9a54f2844abba5ff042a9c3dfb4f204081f3c587fb9e7b3887ccaad578724daa077f500093c5d276513def5765388086d79875e1669127b1d13bc5275ed50355e
length exceeds web3j, when I removed chanId, the length is same, but I got invalid sender
that's my code
public function contractTransaction(string $owner, string $to, int $gasPrice = 1000000, int $gasLimit = 4000000): mixed
{
$data = [
'nonce' => $this->getTransactionCount($owner)->toHex(),
'gasPrice' => '0x' . dechex($gasPrice),
'gasLimit' => '0x' . dechex($gasLimit),
'to' => strtolower(self::ERC_721_ADDRESS),
'value' => '0x' . dechex(0),
'data' => '0x' . $this->getData($to),
];
$transaction = new Transaction($data);
$transaction->offsetSet('chainId', self::CHAIN_ID);
$sign = $transaction->sign(self::PRIVATE_KEY);
return JkService::getInstance()->transaction('0x' . $sign);
}
code in web3j
final Function function = new Function("mint",
Arrays.<Type>asList(new Address(160, recipient),
new Uint256(token_id),
new Utf8String("")),
Collections.<TypeReference<?>>emptyList()
);
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST).send();
BigInteger count = ethGetTransactionCount.getTransactionCount();
String encodedFunction = FunctionEncoder.encode(function);
RawTransaction transaction = RawTransaction.createTransaction(count, gas_price, gas_limit, ERC721ADDRESS, encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(transaction, CHAIN_ID, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get();
String transactionHash = ethSendTransaction.getTransactionHash();
System.out.println("txhash:" + transactionHash);
sorry for my English
Hello and thanks for developing this library.
I noticed that an EIP1559Transaction unlike legacy Transaction objects has the same hash before and after signing the transaction.
For legacy transactions I recreate the transaction object by parsing the signed raw transaction using the "Transaction(string $raw)" constructor and then I call hash() function so I get the final hash of the transaction.
But for EIP1559Transaction there's no way to get final transaction hash. In this case calling signed and unsigned transactions hash() function have the same response and it's of course not the same as what server computes and returns as response of "eth_sendRawTransaction".
With best regards.
I am trying to send BEP-20 tokens from one address to another. I am getting the following error while attempting to sign the transaction with Privatekey. "Uncaught InvalidArgumentException: The input type didn't support" at this line of code $signedTransaction = $ethereumTx->sign($privateKey);
`
require 'web3.php/vendor/autoload.php';
require 'ethereum_tx/autoload.php';
use Web3\Web3;
use Web3\Contract;
use Web3\Utils;
use Web3p\EthereumTx\Transaction;
$web3 = new Web3('https://bsc-dataseed.binance.org/'); // Use the BSC node URL
// Replace with the actual contract address and ABI
$contractAddress = '0x55d398326f99059fF775485246999027B3197955';
$recipientAddress='0x7Affe1A120843E41b271E577900F0B5c43c2C2d9';
$tokenDecimals = 18; // Replace with the actual token's decimal places
$amount = 1; // Replace with the actual amount you want to transfer
$amountInBaseUnits = $amount * (10 ** $tokenDecimals);
$contractABI = "contract ABI";
// Set your wallet's private key
$privateKey = "myprivatekey";
$eth = $web3->eth;
// Create an instance of the contract using the ABI and address
$contract = new Contract($web3->provider, $contractABI, $contractAddress);
$transferFunctionCall = $contract->at($contractAddress)->getData(
'transfer', // Function name
$recipientAddress, // Parameter 1
$amountInBaseUnits // Parameter 2
);
// Fetch the nonce asynchronously
$web3->eth->getTransactionCount('0x02e6deD21C6c46CC4FFF2991988af13069C7c2A3', function ($err, $nonce) use ($web3, $contractAddress, $transferFunctionCall, $privateKey) {
if ($err !== null) {
echo "Error fetching nonce: " . $err->getMessage();
} else {
// Construct the transaction
$transaction = [
'from' => '0x02e6deD21C6c46CC4FFF2991988af13069C7c2A3',
'to' => $contractAddress,
'gas' => '0x' . dechex(100000), // Replace with appropriate gas value
'data' => $transferFunctionCall,
'nonce' => $nonce
];
$ethereumTx = new Transaction($transaction);
$signedTransaction = $ethereumTx->sign($privateKey);
// Send the transaction with a callback function
$web3->eth->sendRawTransaction('0x' . $signedTransaction->getHex(), function ($err, $txHash) {
if ($err !== null) {
echo "Error sending transaction: " . $err->getMessage();
} else {
echo "Transaction Hash: " . $txHash;
}
});
}
});
var_dump($transactionHash);
`
Hello,
so I am pretty new to this kind of coding and wanted to create a function to sent bnb transactions(0.1bnb gasprive 10gwei, gaslimit 21000). For now I am using the testnetwork and I just cant get it to work. Thanks in advance.
use Web3\Web3;
use Web3p\EthereumTx\Transaction;
$web3 = new Web3('https://data-seed-prebsc-1-s1.binance.org:8545');
$eth = $web3->eth;
$transaction = new Transaction([
'nonce' => '0x' . bin2hex(makeRandomString()),
'from' => "0x73AdF374419E4BAaDDC243e2250d6f6661D0Ff46",
'to' => "0x367A32ba87E10e3AdAE8C60546B9383c78a3841A",
'gas' => '0x' . dechex(21000),
'gasPrice' => '0x' . dechex(10000000000),
'value' => '0x' . dechex(100000000),
'chainId' => 97
]);
$signedTransaction = $transaction->sign($privatekey);
$eth->sendRawTransaction('0x'. $signedTransaction, function ($err, $tx) {
if ($err !== null) {
$err->getMessage();
}
echo 'TX: '. $tx . PHP_EOL;
});
function makeRandomString($bits = 256) {
$bytes = ceil($bits / 8);
$return = '';
for ($i = 0; $i < $bytes; $i++) {
$return .= chr(mt_rand(0, 255));
}
return $return;
}`
hi there i have just followed the steps you wrote for sending ethereum transaction but unfortunately in the log the ethereum txdata is always null that is why it is unable to sign transactions ?
Closed
Hello! I created a simple smart contract that I deployed on the bsc testnet. Now, I would like to send XRP tokens from that smart contract to a wallet.
This doesn't work:
// PARAMETERS
$prov = 'https://speedy-nodes-nyc.moralis.io/42d9f6cacd16ccd009e8960a/bsc/testnet';
//$prov = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
$web3 = new Web3(new HttpProvider(new HttpRequestManager($prov)));
$tokenAddress = "0xa83575490d7df4e2f47b7d38ef351a2722ca45b9"; // XRP token
$senderAccount = "0xF2935F3448Ce4e777D514d522Ea32342496eF694"; // Smart Contract
$senderOwner = "0x5f1c07282957E8hsfghsfgha53d2Eb86E6DEE3"; // Account 5 (Owner)
$destAccount = "0xA995b19209sdhfsgh943F332eE044B";
$senderPK = "4193617b3a8bf422965f0sfhsdghfghsfgheb0dc2300102629b75ee";
$abi = file_get_contents(__DIR__ . '/resources/ERC20AbiMarketingPool.json');
$contract = new Contract($prov, $abi);
$eth = $contract->eth;
$secondsToWaitForReceipt = 60;
$factorToMultiplyGasEstimate = 600;
$chainId = 97; // Testnet
$amount = 0.11;
$amountInWholeNumber = intval($amount) * (10 ** 18);
// XRP BALANCE
$contract->at($tokenAddress)->call('balanceOf', $senderAccount, [
'from' => $senderAccount
], function ($err, $results) use ($contract) {
if ($err !== null) {
echo $err->getMessage() . "<br>";
}
if (isset($results)) {
foreach ($results as &$result) {
$bn = Utils::toBn($result);
echo 'XRP Balance: ' . $bn->toString()/1000000000000000000 . "<br><br>";
}
}
});
// TRANSFER XRP TO WALLET
$rawTransactionData = '0x' . $contract->at($tokenAddress)->getData('transfer', $senderAccount, $amountInWholeNumber);
$transactionCount = null;
$eth->getTransactionCount($senderOwner, function ($err, $transactionCountResult) use(&$transactionCount) {
if($err) {
echo 'getTransactionCount error: ' . $err->getMessage() . "<br>";
} else {
$transactionCount = $transactionCountResult;
}
});
echo "\$transactionCount=$transactionCount" . "<br>";
$transactionParams = [
'nonce' => "0x" . dechex($transactionCount->toString()),
'from' => $senderAccount,
'to' => $destAccount,
'gasPrice' => hexdec(dechex(20000000000)),
'value' => '0x0',
'data' => $rawTransactionData
];
$estimatedGas = null;
$eth->estimateGas($transactionParams, function ($err, $gas) use (&$estimatedGas) {
if ($err) {
echo 'estimateGas error: ' . $err->getMessage() . "<br>";
} else {
$estimatedGas = $gas;
}
});
echo "\$estimatedGas=$estimatedGas" . "<br>";
$gasPriceMultiplied = hexdec(dechex($estimatedGas->toString())) * $factorToMultiplyGasEstimate;
echo "\$gasPriceMultiplied=$gasPriceMultiplied" . "<br>";
$transactionParams['gas'] = '0x' . dechex($gasPriceMultiplied);
$transactionParams['chainId'] = $chainId;
$tx = new Transaction($transactionParams);
$signedTx = '0x' . $tx->sign($senderPK);
$txHash = null;
$eth->sendRawTransaction($signedTx, function ($err, $txResult) use (&$txHash) {
if($err) {
echo 'transaction error: ' . $err->getMessage() . "<br>";
} else {
$txHash = $txResult;
}
});
echo "\$txHash=$txHash" . "<br>";
The transaction goes through but it sends 0 BNB (instead of 0.11 XRPs) from the senderOwner (instead of the smart contract) to the destination wallet (that one is good).
Thanks for your help!
Sorry for bringing up the same issue again. I'm trying to send a signed raw transaction to Rinkeby testnet but it always throws me this error. I've checked the signed tx hash with the same data in web3py and it gives me the same hashes. I've also checked them with web3js and I get the same hashes too and I can sign and send the transaction with both libraries without any problems, but I'm facing issues when I'm trying to do the same in web3php.
My private key is hexed and 32 byte-length. I don't know where is the problem right now. This is the transaction code a bit simplified:
$contract = new Contract('http://infura node url/', $contractABI);
$param1 = 40;
$nombreFuncion = 'functionName';
$data = '0x' . $contract->at($contractAddress)->getData($nombreFuncion, $param1, $param2);
$nonce = 0;
$eth->getTransactionCount($acc, function($err, $num) use (&$nonce) {
if ($err != null) {
echo 'Error: ' . $err->getMessage() . PHP_EOL;
return;
}
$nonce = $num;
});
$nonceHex = '0x' . dechex(intval($nonce->toString()+1));
$args_tx = [
'nonce' => $nonceHex,
'from' => $acc1,
'to' => $contractAddress,
'gas' => '0x' . dechex(100000),
'gasPrice' => '0x' . dechex(100),
'data' => $data
];
$tx = new Transaction($args_tx);
$tx_signed = $tx->sign($privateKey);
$eth->sendRawTransaction($tx_signed, function($err, $txHash) {
if($err !== null) {
echo 'Error: ' . $err->getMessage() . PHP_EOL;
return;
}
echo 'txHash: ' . $txHash . PHP_EOL;
});
signed tx hash (which is the same as the serialized one): 0xf8a52b64830186a0949b273326cAE66686945736a2569fFB2d2374EE1880b844f33113450000000000000000000000000000000000000000000000000000000000000028617273757300000000000000000000000000000000000000000000000000000024a059574774ccdca3027ae8c874dd8e196dbeca52c2d82a897357f542ae289235b8a062f88964a245bebae84aa4333c7952bb0b96d1d609e239b4bc2ddf4f3a1c06cf
Thanks in advance!
Since the last release, there have been several updates, including the fix for the transaction hash issue (#41) and the update to web3p/rlp 0.3.5
.
we kindly request a new release to incorporate these updates.
Best regards.
While I try to inspect the internal of a signed tx, and according eip-155[https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md], the signing data should be '0xec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080018080', but in you testcase, it assert to '0xec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080808080' a little differences from eip-155.
The expected outcome on this website https://rawtxdecode.in/?rawTx=f86b0b85250523760082520894eafaf9bb8f35235d0df61275e86fd65d9ef2c3f9870aaa0065c66b8b8026a05fd883bb01a10915ebc06621b925bd6d624cb6768976b73c0d468b31f657d15ba0121d855c539a23aadf6f06ac21165db1ad5efd261842e82a719c9863ca4ac04c.
getFromAddress() does not work with r, s, v:
$transaction['r'] = $r;
$transaction['s'] = $s;
$transaction['v'] = $v;
$fromB = $transaction->getFromAddress();
output error:
Deprecated: Return type of Web3p\EthereumTx\Transaction::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/qindexmedia/xxx/vendor/web3p/ethereum-tx/src/Transaction.php on line 292
Deprecated: Return type of Web3p\EthereumTx\Transaction::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/qindexmedia/xxx/vendor/web3p/ethereum-tx/src/Transaction.php on line 323
Deprecated: Return type of Web3p\EthereumTx\Transaction::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/qindexmedia/xxx/vendor/web3p/ethereum-tx/src/Transaction.php on line 252
Deprecated: Return type of Web3p\EthereumTx\Transaction::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/qindexmedia/xxx/vendor/web3p/ethereum-tx/src/Transaction.php on line 308
Fatal error: Uncaught AssertionError: assert((3 & $j) === $j) in /Users/qindexmedia/xxx/vendor/simplito/elliptic-php/lib/EC.php:224
Stack trace:
#0 /Users/qindexmedia/xxx/vendor/simplito/elliptic-php/lib/EC.php(224): assert(false, 'assert((3 & $j)...')
#1 /Users/qindexmedia/xxx/vendor/web3p/ethereum-tx/src/Transaction.php(474): Elliptic\EC->recoverPubKey('5b6cccfc272b73f...', Array, -12.0)
#2 /Users/qindexmedia/xxx/tes.php(61): Web3p\EthereumTx\Transaction->getFromAddress()
#3 {main}
thrown in /Users/qindexmedia/xxx/vendor/simplito/elliptic-php/lib/EC.php on line 224
I'm using Infura for Kovan network and trying to call "transfer" method of an ERC20 contract. When I send it I get an Invalid RLP error.
My code:
$signedTransaction = '0x' . (new Transaction([
"from" => "0x808AEf27804767A1548b132AA6e883B962A11f5e"
"to" => "0x7d2121dc3b7637af36940bcce0cc95619f972eaa"
"gas" => "0x00cb9d"
"gasPrice" => "0x3b9aca00"
"data" => "0xa9059cbb0000000000000000000000008741f8ce9fb1aad347d08980f44e549cbc1e6d270000000000000000000000000000000000000000000000000000000000989680"
"nonce" => "0x00"
]))->sign($privateKey);
Can it be caused by this package or something in my transaction data is wrong?
Thanks in advance!
$transaction = new Transaction([
'nonce' => Utils::toHex((string) $cb,true),
'from' => $address,
'to' => '0x50ed39a368498dfe43e556ba1c73f3d861e0ad95',
'gas' => Utils::toHex(21000,true),
'gasPrice' => Utils::toHex(26000000000,true),
'value' => '0x00',
'data' => "0xa9059cbb00000000000000000000000000e11189e3229067a668cc9bd08d233e508b260f00000000000000000000000000000000000000000000005c1a5c8a4fecac0000",
'chainId' =>Utils::toHex(80001,true),
]);
$signedTransaction = $transaction->sign("0f9e82ccf75a3729818163482173ab36662ed61a7e0a10fcdbb8c7d694fc986b");
$eth->sendRawTransaction('0x'.$signedTransaction,function ($err,$result){
exit_data($err);
});
result : -3002 invalid sender
You need to add check for nullable $tx in __construct where $this->txData = $tx.
I.e.:
if(!empty($tx))
{
$this->txData = $tx;
}
Do you have any working example of sending custom ERC20 Tokens?
good
.......................
.......................
/**
* @notes 获取data
* @param array $data 数据
* @return $this
/
public function getTransactionData(array $data): self
{
try {
if (in_array($data['symbol'], ['BNB', 'ETH'])) {
return $this;
}
$num = bcmul($data['value'], pow(10, $this->decimals));
$num2hex = Utils::toHex($num, true);
$contractAbi = new Contract($this->provider, $this->abi);
$this->data = '0x'.$contractAbi->at($this->contract)->getData($this->transfer, $data['to'], $num2hex);
return $this;
} catch (\Exception $e) {
throw new Exception($e->getMessage());
}
}
/*
* @notes 离线签名
* @param array $data 数据
* @return $this
*/
public function signed(array $data): self
{
try {
$transaction = new Transaction([
'nonce' => $this->nonce,
'from' => $data['from'],
'to' => $this->contract ?: $data['to'],
'gas' => Utils::toHex($this->contract ? $this->contract_gas : $this->gas, true),
'gasPrice' => $this->gasPrice,
'value' => $this->contract ? '0x' : Utils::toHex(Utils::toWei((string)$data['value'], 'ether'), true),
'chainId' => $this->chainId,
'data' => $data['data'],
]);
$this->sign = $transaction->sign($data['private_key']);
return $this;
} catch (\Exception $e) {
throw new Exception($e->getMessage());
}
}
.......................
.......................
The transaction is signed incorrectly if chainId is passed in the parameters.
$privateKey = '0x4ba88be044ff4ca25acddd0e3ca68fefc8b2ddc9df324cac051a84522184af91';
$transaction = new Transaction([
"to" => "0xffd5b710212fafc1d94cb225de6f94b65e09bfdb",
"from" => "0x1cca1ce0f77060826605aa677fee73e9db3bccec",
"gasPrice" => "0x3b9aca00",
"gas" => "0x9bbd",
"data" => "0x75992d3c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a14a9624abc78d38c13e091dfca1b838673208420000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000002386f26fc10000",
"nonce" => "0x12",
"chainId" => 178,
"value" => "0x00",
]);
$result = '0x' . $transaction->sign($privateKey);
// Result: 0xf9014a12843b9aca00829bbd94ffd5b710212fafc1d94cb225de6f94b65e09bfdb80b8e475992d3c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a14a9624abc78d38c13e091dfca1b838673208420000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000002386f26fc10000820188a099256a16f0af662e62b679e68c8f16006a4cc9375e8ecd3ec9da020e83033d50a036a1ed107c8c9c2f00c3a28b09eadcadbaaab735e503572fcaf9ea203422118
In production we are currently using library ethereumjs-tx to sign such transactions:
var privateKey = '4ba88be044ff4ca25acddd0e3ca68fefc8b2ddc9df324cac051a84522184af91';
var rawTx = {
"to": "0xffd5b710212fafc1d94cb225de6f94b65e09bfdb",
"from": "0x1cca1ce0f77060826605aa677fee73e9db3bccec",
"gasPrice": "0x3b9aca00",
"gas": "0x9bbd",
"data": "0x75992d3c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a14a9624abc78d38c13e091dfca1b838673208420000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000002386f26fc10000",
"nonce": "0x12",
"chainId": 178,
"value": "0x00",
};
var Tx = require('ethereumjs-tx');
var bufferPrivateKey = Buffer.from(privateKey, 'hex');
var tx = new Tx(rawTx);
tx.sign(bufferPrivateKey);
var serializedTx = '0x' + tx.serialize().toString('hex');
console.log(serializedTx);
// Result: 0xf9014912843b9aca00829bbd94ffd5b710212fafc1d94cb225de6f94b65e09bfdb80b8e475992d3c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a14a9624abc78d38c13e091dfca1b838673208420000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000002386f26fc100008201889f95349dff041d67076508a6b041e0b5a0ebd519148b8dd00c365238bd476b42a060978dd6bd98ecbefdaa1dd58e651835c9cdfb1248843b376cf354088d7c39e9
If remove the chainId parameter, then the signatures through php and js converge.
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.