I am building an ERC20 Token. I have used the decimals properly. So, I am transfering 10^21 tokens to a function to transfer my token.
Minted tokens : 1000000 * (10**decimals) # decimals = 18
So I should be able to transfer this amount?
I made a UI and used web3.js where I got this error.
Unhandled Rejection (Error):
invalid number value (arg="_price", coderType="uint256", value="1e+21")
Then I also tried in Remix for the same values. there also the transaction failed. Execution is failing for numbers like if I want to transfer 10*20 token. then also the transaction fails.
Solved it using this:
https://github.com/ethereum/web3.js/issues/2077#issuecomment-468530879
const dec = window.web3.utils.toBN(this.props.decimals)
const price_ = window.web3.utils.toBN(this.Object.value*(100))
const price ="0x"+ price_.mul(window.web3.utils.toBN(10).pow(dec)).toString("hex")
Related
According to the docs for web3.eth.sendTransaction and the docs for eth_sendTransaction:
The transaction object can contain an optional data parameter which should be a String that consists of:
either an ABI byte string containing the data of the function call on a contract, or in the case of a contract-creation transaction the initialisation code.
I want to assign a string to data and have the string be stored along with the record of the transaction on the blockchain, so that I can retrieve that string when I retrieve the record of that transaction later.
const [testAccount] = await window.ethereum.request({ method: "eth_requestAccounts" })
const web3 = new Web3(window.ethereum)
if (!testAccount) {
return
}
let transactionHash = await web3.eth.sendTransaction({
from: testAccount,
to: testAccount,
value: web3.utils.toWei('0.0003'),
data: web3.utils.utf8ToHex(JSON.stringify({ a: 1, b: 2 }))
})
let transaction = await web3.eth.getTransaction(transactionHash)
let data = JSON.parse(web3.utils.hexToUtf8(transaction.data))
console.log(data.a) // should log 1
When I execute sendTransaction (using Metamask, while connected to the Ropsten network), I get the following error:
Error: Error: TxGasUtil - Trying to call a function on a non-contract address
{
"originalError": {
"errorKey": "transactionErrorNoContract",
"getCodeResponse": "0x"
}
}
Apparently, you cannot assign any string to data and expect the string to be incorporated in the record of the transaction on the blockchain, out-of-the-box, simply by assigning a value to it. Is this correct?
Question: Do I need to write a custom smart-contract in order to achieve this ?
This is a feature/limitation specific to MetaMask. Possibly to protect their users who want to interact with a smart contract but are connected to a different network where the contract is not deployed.
However, it is technically possible to send a valid transaction with non-empty data field to a non-contract address. You just need to use a different node provider to broadcast the transaction. Unfortunately the node provider in MetaMask is hardcoded so it's not possible using this wallet.
Example: This transaction on the Ropsten testnet to the 0xdac1... address that has the USDT token contract deployed on the mainnet, but is a non-contract address on the testnet. It is a valid transaction, successfully bought gas from the sender address to cover the transaction fees, mined in a block, just didn't execute any smart contract code (as there is no smart contract on the recipient address).
Do I need to write a custom smart-contract in order to achieve this ?
You can also write a smart contract function in Solidity that receives data as a function argument, but does nothing on this. Thus, GoEthereum node stores this data as calldata of the transaction and it can be later retrieved.
I am pretty sure some cross-chain bridges operate in this manner. Transactions only write data as the part of calldata (cheaper than Solidity storage) and then other clients read it from there.
I'm trying to create a "real" transaction from inside a smart contract to an EOA. This is so that I can attach data/input_data to send to it.
I've read several resources on this but I've come to contradictory information: some say it's impossible, some say that call() can achieve this. I've been testing multiple methods and have not come to see that it is possible.
Here's a simple example of what I'm trying to achieve:
pragma solidity 0.8.6;
contract Simple {
uint32 value;
constructor() payable {
// Contract is initialized with 0.5 ether
value = 22;
}
function foo() public {
require(address(this).balance >= 0.1 ether);
// Along with transfering ether, I want to send some data to the EOA,
// for example, whichever value is in the variable "value"
payable(msg.sender).transfer(0.1 ether);
}
}
On a "normal" transaction, it is possible to set the field "input data" (normally used to make function calls when sending a transaction to a smart contract), which allows us to send data on a transaction from an EOA to another EOA. I was able to achieve this already.
But, from my understanding, contracts "can't" create transactions; they only create "internal transactions" (informal name) that are associated with the "parent transaction" (transaction that called the contract in the first place) and therefore don't have the data field. But they're able to call another contract on the network, so I assume they're able to send some data along the network, right?
Furthermore, this question seems to imply that the low level call() method is able to achieve this. I've tried multiple approaches but have not been able to reproduce the wanted behaviour.
msg.sender.call{value: 0.1 ether}("data", value); // Doesn't work
msg.sender.call{value: 0.1 ether}(value); // Doesn't work
msg.sender.call{value: 0.1 ether}(abi.encodeWithSignature(value)) // Doesn't work
At some point, I did find my message on a block's "extra data", but from my understanding, this was written there by the miner for some reason.
So, to sum it up, is it possible to, from a contract, send ether + message to an EOA account? How would I achieve this?
Edit: Fixed the function name, which was a reserved keyword.
function msg() public {
This function name is a bit problematic, because you're overriding the global msg variable, and can't use the msg.sender.
So I changed the function name to generic foo().
function foo() public {
msg.sender.call{value: 0.1 ether}
Since Solidity 0.8, an address is not payable by default (source: docs). So if you want to send them the native currency (in case of Ethereum, that's ETH), you need to cast the address to payable first.
payable(msg.sender).call{value: 0.1 ether}
Finally to the data sending part.
At some point, I did find my message on a block's "extra data", but from my understanding, this was written there by the miner for some reason.
I'm not exactly sure, but it seems like you stumbled upon the correct field, which is simply the data field of the raw transaction, and the blockchain explorer probably named it "extra data". The data field is not filled by the miner, but by the transaction creator.
Since you're sending an integer, and the data field is bytes (array of bytes), you need to encode it to bytes. In your case:
abi.encode(value)
To you put it all together:
pragma solidity 0.8.6;
contract Simple {
uint value;
constructor() payable {
value = 22;
}
function foo() public {
require(address(this).balance >= 0.1 ether);
payable(msg.sender).call{value: 0.1 ether}(abi.encode(value));
}
}
When you execute the foo() function (and the contract has enough funds), it will create an internal transaction (some blockchain explorers might use a different name) to the msg.sender with value 0.1 ether and the decimal 22 encoded as hex 16 in the data field.
I have ERC-20 token smart-contract which methods I call using sendSignedTransaction from web3.js. After I know transaction is succesfully mined I need to check contract method execution result. How do I do it if all I have is transaction hash?
Example: method transferFrom(from, to, tokens) returns true or false depending on whether transferring was successful. So if I try to transfer 100 tokens from empty wallet, contract method will return false.
Upd: Okay, as I understood there is no way of determining method outcome using txHash after transaction is mined and confirmed. Then which ways exists to handle this case? How can I make sure that tokens were transferred?
You can emit an event inside your contract code ( actually in ERC20 standard there is always a transfer event present ) and then inside web3js, read all the events till latest block using this line of code:
Events = Contract.eventName({}, {fromBlock: 0, toBlock: 'latest'});
Newbie.
There is a go-ethereum method:
eth.estimateGas({from:'firstAccount', to:'secondAccount'})
that works well,
but same method with contract address like:
eth.estimateGas({from:'firstAccount', to:'contractAddr'})
fails with error
gas required exceeds allowance or always failing transaction
I have looked into go-ethereum source code and it has the line, that contains proposal to use contract address as second parameter:
https://github.com/ethereum/go-ethereum/blob/master/accounts/abi/bind/base.go#L221
The question is: is there any possibily to use eth.estimateGas with contract address as second parameter and how to avoid above error?
Thank you.
You're not specifying what you're executing in the contract, so there's nothing to estimate. When you estimateGas for a transfer to an EOA account, there is no contract code to execute, so there is no message data to be sent as part of the transaction object. If you're estimating gas on a contract call, you need to include the data for the contract.
For example, if you want to estimate gas to setValue(2) method in this contract
pragma solidity ^0.4.19;
contract SimpleContract {
uint256 _value;
function setValue(uint256 value) public {
_value = value;
}
}
your call would be
var data = '552410770000000000000000000000000000000000000000000000000000000000000002';
eth.estimateGas({from: fromAccount, to: contractAddress, data});
The value for data comes from encoding the function signature and the parameter value(s). You can use a simple tool (like https://abi.hashex.org) to generate this. You just enter the function name along with the parameter argument types and their values, and it will generate the message data for you. You can also do this using web3js.
EDIT - I neglected to consider contracts with fallback functions. Executing estimateGas on a contract without passing in message data provide the estimate for contracts that have a fallback function. If the contract does not have a fallback function, the call will fail.
I want to send a message on a transaction. Here is my codes:
_data = web3.toHex('xxxx');
instance.function_name(param1, param2, param3, param4, {value: web3.toWei(_price, 'ether'), from: web3.eth.accounts[0], data:_data}).then(...);
The transaction is processed successfully, But the input data message is not the _data value in the etherscan.io
can anybody help me? Thank you.
The data field in the transaction object is used when deploying a contract or when using the general sendTransaction or sendRawTransaction methods. If you are using a contract instance, the data field is ignored.
From the Solidity docs:
Object - (optional) The (previous) last parameter can be a transaction object, see web3.eth.sendTransaction parameter 1 for more. Note: data and to properties will not be taken into account.
If you want to send the data manually, use sendTransaction.
The information shown in Etherscan is the decoded data from the signed transaction describing the function call made. It is not free form user data (if that's what you're trying to insert). The first 32 bits of the data are the function signature and each 256 bit block afterwards are the parameters.
See this source for more in-depth information.