I have tried to compile this code unfortunately i usually get error - solidity

This is the code: function () external payable {
The error when compiling:
ParserError: Expected a state variable declaration. If you intended this as a fallback function or a function to handle plain ether transactions, use the "fallback" keyword or the "receive" keyword instead. --> mytoken.sol:145:32: | 145 | function () external payable { | ^

This error occurs because you're using syntax from Solidity 0.5 or older in version 0.6 or newer.
In Solidity 0.6, the fallback function was changed, and the new syntax is
pragma solidity ^0.6;
contract MyContract {
fallback() external payable {
// TODO implement or leave empty
}
}
You can find more info in the docs section breaking changes.

Related

How to Read Chainlink AggregatorV3Interface in Hardhat Deployment

Total beginner here apologies in advance.
I'm learning Solidity and using Hardhat and trying to figure out how to return the value of the Chainlink price feed in this tutorial contract after deployment. I know how to return the function output in remix but having trouble figuring out how to use console.log or another method in Hardhat. I am able to use console.log for built in functions like token address but can't figure out how to apply to other functions. This is using the Goerli Testnet btw.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract TestChainlink {
AggregatorV3Interface internal priceFeed;
constructor() {
// ETH / USD
priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e);
}
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
// for ETH / USD price is scaled up by 10 ** 8
return price;
}
}
I tried emulating console.log usage that work for built in functions like token address to apply them to the Chainlink getLatestPrice() function.
const Token = await ethers.getContractFactory("TestChainlink");
const token = await Token.deploy();
console.log("Token address:", token.address);
i.e.
I tried a ton of different combinations this was the last one I will spare all the error messages since it probably isn't a complex solve for a non novice.
console.log("ETH Price:", getLatestPrice());
try
let price = await token.getLatestPrice();
console.log(`Eth price is: ${price}`);

“Out of Gas” while transferring ethereum from account to contract

I am using ganache to create 10 ethereum accounts. I want to transfer ethereum from one account to a smart contract. I am doing this by writing two following smart contracts in solidity;
pragma solidity >=0.4.0 <0.6.0;
contract Ether_Transfer_To{
function () external payable { //fallback function
}
function get_balance() public returns(uint){
return address(this).balance;
}
}
contract Ether_Transfer_From{
Ether_Transfer_To private the_instance;
constructor() public{
//the_instance=Ether_Transfer_To(address(this));
the_instance=new Ether_Transfer_To();
}
function get_balance() public returns(uint){
return address(this).balance;
}
function get_balance_of_instance() public returns(uint){
//return address(the_instance).balance;
return the_instance.get_balance();
}
function () external payable {
// msg.sender.send(msg.value)
address(the_instance).send(msg.value);
}
}
When I deploy the contract Ether_Transfer_From smart contract then I get its three-member functions as follows in remix;
But when I sent one 1 Wei from account to smart contract by writing 1 in the text box and clicking on a (fallback) button, then I get the following error;
transact to Ether_Transfer_From. (fallback) errored: VM Exception while
processing transaction: out of gas
I followed the answer of the same question by installing Ganache-cli 7.0.0 beta.0 by using following command;
npm install -g ganache-cli#7.0.0-beta.0
But I still get the same error. I think I am using older Ganache cli instead of Ganache-cli 7.0.0 beta.0 as it goes to C drive and I installed ganache 2.1.1 in D drive previously.
I just want to send ethereum from one account to other but I am really stuck in this out of gas Error. If there is any way to remove this error or transfer ethereum from one account to another then please let me know.
So this is what I did for one of my projects.
This snippet, deploys the compiles the solidity file and then deploys it and gets the address of the deployed contract address
const input = fs.readFileSync('Migrations.sol');
const output = solc.compile(input.toString(), 1);
const bytecode = output.contracts[':Migrations']['bytecode'];
const abi = JSON.parse(output.contracts[':Migrations'].interface);
var contract = new web3.eth.Contract(abi);
contract.deploy({
data: '0x'+bytecode,
})
.send({
from: chairPerson,
gas: 5500000,
gasPrice: '2000000000000'
})
.on('receipt', (receipt) => {
add=receipt.contractAddress;
})
Now using contract's abi, I can call methods of the deployed contract and use the following code to transfer '1.5' ether from one address to another.
contract.methods.registerRequest(fromAddress,toAddress,requestNumber).send({from:fromAddress,value : web3.utils.toWei('1.5', 'ether')}).on('transactionHash', (hashResult) => {-- some code--})
And also make the method in the solidity as payable to allow it to transfer ether, like :
function registerRequest(address requestedBy,address requestedTo,uint requestNumber) payable public{}
Refer : https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#id12
Basically I used web3 api itself to transfer ether from one account
to another by calling my solidity method.
Also, check the following things :
1. While deploying, are you deploying with enough gas ? I faced this error when I was deploying the contract with less gas quantity
2. Your method in solidity should be payable

Is this a remix,compiler or an openzeplin bug?

I just wrote a simple code to test openzeplin Safemath library. I am using the latest version of remix ide and compiling for ^0.5.0.
Remix is using 0.5.0_commit.1d4f565a compiler
The environment is JavaScript VM
EVM Version is the compiler default
The add function does not seem to be working in the code given below
I have tried x.sub(1) it throws an exception as expected, i have also tried initializing x to different values but still does not work.
pragma solidity ^0.5.0;
import "./SafeMath.sol";
contract SimpleStorage {
using SafeMath for uint;
uint x;
event incremented(uint x);
constructor() public{
x=0;
}
function increment() public {
x.add(1);
emit incremented(x);
}
function get() external view returns (uint) {
return x;
}
}
Expected output is an increment by one on every call to the function but getting the same value every time. Emit also shows the same value.
Well, it's your bug :)
Instead of x.add(1) try x = x.add(1). Add function is not inplace, new value is returned and you need to assign the new value to x.

Solidity 'out of gas' exception when trying to transfer Ether

I try to transfer Ether from the contract to an address but it gives the error that the transaction is out of gas. I think it's a small problem but I can't find it. I have to specifically use solidity version 0.4.24.
The warning from Remix
The error from MetaMask
I have tried different methods, like:
address.transfer(amount);
address.send(amount);
address.call.value(amount)( );
All methods will give the same out of gas exception. and the send and call method will also give a warning that it's outdated and that I should use the transfer method.
I also tried to adjust the gas and it didn't work, I also tried the needed 2,300 for the transfer listed on the docs.
The code:
pragma solidity ^0.4.24;
contract TestContract {
function payAddress(address _address) external payable {
_address.transfer(msg.value);
}
}
If the problem is that the contract doesn't have any Ether to transfer, can it use the Ether I send with the function call? Or is the problem something else?
Thank you for reading.
edit:
I have tried to send Ether to my Contract and that works, I do have Ether on my contract now, but the function still gives the same error as before. So the problem is something else.
Current code:
pragma solidity ^0.4.24;
contract TestContract {
function() external payable { }
function payContract() public payable {}
function paySomeone(address _address, uint256 _amount) external {
_address.transfer(_amount);
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
}
The balance of the contract
The parameters I use
Same MetaMask error as before
As you can see here the balance of the contract is 10 wei, but when i try to send 9 wei it still gives the same out of gas error. I also still get the same error from Remix as before.
I also post the issue on the Stack exchange and got an answer there. The issue was my
Ganache version. I switched to the Robsten test network and it worked. I'll link the post here.
Yes. In order to send ether from contract to another address, first you must send some ether to the contract address. Take a look at this and this.

Truffle console send ETH to smartContract

I want to send some ETH to smart contract address
Test.deployed().then(function(instance) {return instance.contribute("0x1e0c326f4f24b5e9f5d42d695f48983d0a72b240", {from:web3.eth.accounts[0],value:10});})
but I always get
truffle(development)> Test.deployed().then(function(instance) {return instance.contribute("0x1e0c326f4f24b5e9f5d42d695f48983d0a72b240", {from:web3.eth.accounts[0],value:10});})
TypeError: instance.contribute is not a function
at evalmachine.<anonymous>:1:61
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
truffle(development)> truffle(development)>
I am using last version of truffle, so version 4.x
Same problem with
Test.deployed().then(function(instance) {return instance.getElements.call();})
Updated
contract MyContract Common {
function setMultisigWallet(address newMultisigWallet) public onlyOwner {
multisigWallet = newMultisigWallet;
}
function() external payable {
executeSale();
}
}
Send a transaction directly to a contract via instance.sendTransaction(). This is promisified like all available contract instance functions, and has the same API as web3.eth.sendTransaction but without the callback. The to value will be automatically filled in for you if not specified.