How to use Truffle with Solidity 6.0? - ethereum

Reading official Truffle docs, I noticed Truffle not support Solidity 6.0
pragma solidity >=0.4.21 <0.6.0;
Are there any ways to use Truffle with Solidity 6.0?

Yes this works with this migration
pragma solidity >=0.4.21 <0.7.0;
contract Migrations {
address public owner;
uint public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}
And this compiler settings
compilers: {
solc: {
version: "^0.6.0",
And also need re-install Truffle to latest version

You can set the solidity version in the truffle config file.
module.exports = {
networks: {
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 7545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
},
compilers: {
solc: {
version: "0.6.0",
settings: {
optimizer: {
enabled: true, // Default: false
runs: 1000, // Default: 200
},
},
},
},
};

Related

How to correctly pass --network parameter to Hardhat scripts?

I'm trying to deploy to Goerli, but my deploy script seems to ignore the --network parameter.
Here is my hardhat.config.ts:
import { HardhatUserConfig } from "hardhat/config";
import "#nomicfoundation/hardhat-toolbox";
import "hardhat-gas-reporter"
import "#nomiclabs/hardhat-ethers";
import * as dotenv from 'dotenv'
dotenv.config();
const env:any = process.env;
const config: HardhatUserConfig = {
solidity: {
[...]
},
networks: {
hardhat: {
[...]
},
goerli: {
url: 'https://goerli.infura.io/v3/',
accounts: [env['DEPLOYER_PRIVATE_KEY']]
},
},
[...]
};
export default config;
Then I run:
npx hardhat run scripts/deploy.ts --network goerli
And in my deploy.ts:
async function main() {
const [deployer] = await ethers.getSigners();
console.log('Using RPC ', ethers.provider.connection.url);
console.log('Deploying from address', deployer.address);
[...] // contract deployment code
}
However it fails with error "could not detect network". It makes sense because it also logs (from my code):
Using RPC http://localhost:8545
Deploying from address 0x3a5Bd3fBc2a17f2eECf2Cff44aef38bd7dc4fd7c
My address is correct, the address logged indeed corresponds to the account that I provided with the private key from dotenv, so it's being read from the config correctly. However, the RPC URL is incorrect: it seems that it's trying to connect to my local RPC and failing.
Why isn't Hardhat respecting the url property in the config, and still trying to connect to my local instance?
Change
const config: HardhatUserConfig = {
solidity: {
[...]
},
to
module.exports = {
solidity: "0.8.4",
networks: {
goerli: {
url: 'https://goerli.infura.io/v3/',
accounts: [env['DEPLOYER_PRIVATE_KEY']]
}
}
};
If you want to deploy on Hardhat you can run npx hardhat node and remove goerli and const env:any = process.env;.

BSC Testnet addLiquiditiyETH TRANSFER_FROM_FAILED

I'm coding an bep20 token and if I want to add Liquidity with pancakeswap I get the following error:
ProviderError: Error: VM Exception while processing transaction: reverted with reason string 'TransferHelper: TRANSFER_FROM_FAILED'
Does anyone know why this is not working?
PancakeRouter address: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1
PancakeFactory address: 0x6725F303b657a9451d8BA641348b6761A6CC7a17
My addLiquidity function:
function addLiquidity() public payable {
_approve(address(this), _pancakeRouterAddress, totalSupply());
_pancakeRouter.addLiquidityETH(
address(this),
totalSupply(),
0,
0,
address(this),
block.timestamp
);
}
Hardhat fork: npx hardhat node --fork https://data-seed-prebsc-1-s1.binance.org:8545
Hardhat networks config:
networks: {
localhost: {
url: 'http://localhost:8545',
chainId: 31337,
forking: {
url: " https://data-seed-prebsc-1-s1.binance.org:8545",
}
},
},
Ensure two things when you add liquidity which uses transferFrom() function internally:
You have approved the spendor (here router)
you have at least the amount you have approved the spendor to spend

HardHat and Rinkeby ProviderError: Must be authenticated Error

When I run
npx hardhat console --network rinkeby
accounts = await ethers.provider.listAccounts();
I get
Uncaught ProviderError: Must be authenticated!
with below rinkeby network config in hardhat.config.js
rinkeby: {
url: "ALCHEMY_URL",
accounts:["YOUR_PRIVATE_KEY"],
}
Solution: update config file with below lines:
rinkeby: {
url: "ALCHEMY_URL",
accounts: ["YOUR_PRIVATE_KEY"],
gas: 2100000,
gasPrice: 8000000000,
saveDeployments: true,
}
This works like a charm. Hope this helped in saving some of your time.
Finally, your hardhat.config.js should look like this
require('#nomiclabs/hardhat-waffle');
module.exports = {
solidity: '0.8.0',
networks: {
ropsten: {
url: `${ARCHEM_APP_URL}`,
accounts: [`${ACCOUNT_KEY}`],
gas: 2100000,
gasPrice: 8000000000,
saveDeployments: true,
}
}
}

Go-ethereum private network in Proof-of-Authority problem: call contract method but nothing response

When I created a 2 nodes private network with POA consensus and it works fine when I sent a simple transaction.
But when I deploy a simple contract SimpleStorage.sol with Truffle, I want to call the get() method by using the myetherwallet, but it returns 0 , not 100.
The detailed of SimpleStorage is as shown below:
pragma solidity >=0.4.17;
contract SimpleStorage {
uint storedData = 100;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
System information
Geth Version: 1.8.23-stable
Git Commit: c942700427557e3ff6de3aaf6b916e2f056c1ec2
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.11.5
Operating System: darwin (MacOs)
GOPATH=
GOROOT=/Users/travis/.gimme/versions/go1.11.5.darwin.amd64
Truffle v5.0.7 (core: 5.0.7)
Solidity v0.5.0 (solc-js)
Node v9.10.0
Behavior to reproduce
Genesis.json
{
"config": {
"chainId": 1515,
"homesteadBlock": 1,
"eip150Block": 2,
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"eip155Block": 3,
"eip158Block": 3,
"byzantiumBlock": 4,
"clique": {
"period": 2,
"epoch": 30000
}
},
"nonce": "0x0",
"timestamp": "0x5d5769ad",
"extraData": "0x00000000000000000000000000000000000000000000000000000000000000003b50d35ed4032c984992ad0d757ba65338523919fc0f1c754a2dfa18640ce2a0950aea20d1d206940000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x7FFFFFFFFFFFF",
"difficulty": "0x1",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {
"3b50d35ed4032c984992ad0d757ba65338523919": {
"balance": "0x200000000000000000000000000000000000000000000000000000000000000"
},
"fc0f1c754a2dfa18640ce2a0950aea20d1d20694": {
"balance": "0x200000000000000000000000000000000000000000000000000000000000000"
}
},
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
Geth start command
geth --datadir node1/ --syncmode 'full' --port 30312 --rpc --rpcaddr 0.0.0.0 --rpcport 8502 --rpccorsdomain "*" --ws --wsaddr 0.0.0.0 --wsport 8602 --wsorigins "*" --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3 --wsapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3 --bootnodes 'enode://4765bd12afddce5bb5a2ea55e58ffcdbade132a593bddd9f2723e18460b407039bf07e3fa851b12b0b20c8e0b4c2d3518c9578f201b4efe6ab4d9243e28cccaa#127.0.0.1:30310' --networkid 1515 --gasprice '1' -unlock '0x3b50d35ed4032c984992ad0d757ba65338523919' --password node1/password.txt --mine --targetgaslimit 2251799813685247
Truffle set up
truffle-config.js
module.exports = {
networks: {
geth: {
host: "127.0.0.1",
port: 8501,
from: "0xfc0f1c754a2dfa18640ce2a0950aea20d1d20694",
network_id: "*",
gasPrice: "0x47B7600",
gas: "0x47B7600"
}
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
// version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
// settings: { // See the solidity docs for advice about optimization and evmVersion
// optimizer: {
// enabled: false,
// runs: 200
// },
// evmVersion: "byzantium"
// }
}
}
}
migration script
truffle migrate --network geth --reset
Expected behavior
When called get() method, it should return 100.
Actual behaviour
It returned 0
I found that there's another one ran into a similar issue as me:
One of ethereum solidity methods is not working properly got error Returned values aren't valid, did it run Out of Gas
Can anyone help me to address this issue?
I have figured out why I cannot retrieve the value from variable storedData...
When I set storedData to be public, then it works fined.
(But to be noticed that if using ganache-cli, I can get the storedData even if it is not public variable...)
pragma solidity >=0.4.17;
contract SimpleStorage {
// uint storedData = 100;
uint public storedData = 100; // set it to be public
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}

Solidity v^0.5.0 compiler error [invalid callback specified]

I'm trying to compile my contract but get this error:
AssertionError [ERR_ASSERTION]: Invalid callback specified.
One answer was to change the version of the compiler but my version is up to date (0.5.0).
I'm actually trying to take an old code (0.4.17) and upgrade it. Tried for 2 days and just kept failing.
Here is my contract:
pragma solidity ^0.5.0;
contract Lottery{
address public manager;
address payable [] public players;
modifier restricted {
require(msg.sender == manager);
_;
}
constructor() public {
manager = msg.sender;
}
function participate() public payable {
require(msg.value > .01 ether);
players.push(msg.sender);
}
function pseudoRandom() private view returns(uint){
return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
}
function pickWinner() public restricted {
require(msg.sender == manager);
uint index = pseudoRandom() % players.length;
address(players[index]).transfer(address(this).balance);
(players) = new address payable[](0);
}
function getPlayers() public view returns(address payable[] memory){
return players;
}
}
here is my package.json:
{
"name": "lottery",
"version": "1.0.0",
"description": "lottery contract with Solidity",
"main": "compile.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "mocha"
},
"author": "Torof",
"license": "ISC",
"dependencies": {
"ganache-cli": "^6.2.1",
"mocha": "^5.2.0",
"save": "^2.3.2",
"solc": "^0.5.0",
"tar": "^4.4.8",
"truffle": "^4.1.14",
"truffle-hdwallet-provider": "0.0.6",
"web3": "^1.0.0-beta.36"
}
}
and here is the compiler:
const path = require('path');
const fs = require('fs');
const solc = require('solc'); //Could the error be here ?
const lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');
const source = fs.readFileSync( lotteryPath, 'utf8');
module.exports = solc.compile(source, 1).contracts[':Lottery'];
console.log(solc.compile(source, 1));
And lastly I found this err message but don't get it:
[ts]
Could not find a declaration file for module 'solc'.
'/home/torof/desk/coding/Udemy/ETH-stephenGrider/lottery/node_modules/solc/index.js'
implicitly has an 'any' type.
Try `npm install #types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`
Previous versions of solc supported the style of compilation you're using, but it looks like the new versions only support standard JSON in and out. You probably want something like this:
console.log(JSON.parse(solc.compile(JSON.stringify({
language: 'Solidity',
sources: {
'lottery.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['evm', 'bytecode'],
},
},
},
}))).contracts['lottery.sol'].Lottery);
Here is one way implementation for 0.5.X, together with the deploy code:
This is how I compile, there is deep nesting destruction to fetch the bytecode.
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const templatePath = path.resolve(__dirname, 'contracts', 'templatename.sol');
const source = fs.readFileSync(templatePath, 'utf8');
const input = {
language: 'Solidity',
sources: {
'yourtemplate.sol': {
content: source
}
},
settings: {
outputSelection: {
'*': {
'*': ['*']
}
}
}
}
const { abi: interface, evm: { bytecode: { object } } } = JSON.parse(solc.compile(JSON.stringify(input))).contracts['yourtemplate.sol'].Templatename; //
module.exports = { interface, object }; // object is the actual name of the bytecode
And the code for deploy:
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const { interface, object: bytecode } = require('../compile');
// i've renamed object with bytecode
const accounts = await web3.eth.getAccounts();
templatename = await new web3.eth.Contract(interface)
.deploy({ data: bytecode, arguments: [INPUT_PARAMETER_GOES_HERE] })
.send({ from: accounts[0], gas: '1000000' });
Did you try installing this package:
npm install #types/solc