BSC Testnet addLiquiditiyETH TRANSFER_FROM_FAILED - ethereum

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

Related

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,
}
}
}

Switch Metamask Network to chain 1 (Ethereum Mainnet)

This past week Metamask introduced a new function called "wallet_addEthereumChain" which allows the user to automatically add a new Etheruem RPC to their wallet when prompted. This function also allows the user to change the network they are connected to, for example, if I already have Binance Smart Chain connected to metamask, calling wallet_addEthereumChain changes the active network to BSC. However, when trying this for the Ethereum chain, it gives an error that you cannot add mainnet RPC.
I have used the following code to change to change from Ethereum Mainnet to Binance Smart Chain, and it works fine:
switchToBinance: async function () {
let ethereum = window.ethereum;
const data = [{
chainId: '0x38',
chainName: 'Binance Smart Chain',
nativeCurrency:
{
name: 'BNB',
symbol: 'BNB',
decimals: 18
},
rpcUrls: ['https://bsc-dataseed.binance.org/'],
blockExplorerUrls: ['https://bscscan.com/'],
}]
/* eslint-disable */
const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
if (tx) {
console.log(tx)
}
},
However when I try the Exact thing, metamask throws an exception saying I cannot add a mainnet RPC:
switchToEthereum: async function () {
let ethereum = window.ethereum;
const data = [{
chainId: '0x1',
chainName: 'Ethereum',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://mainnet.infura.io/v3/undefined'],
blockExplorerUrls: ['https://etherscan.io'],
}]
/* eslint-disable */
const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
if (tx) {
console.log(tx)
}
},
However, the request for adding a new RPC connection, and changing the active RPC connection is the same. So is there a way to change the active Ethereum provider from a custom chain to Mainnet (chain ID-1)
as this issue comment point, for security reason wallet_addEthereumChain not support mainnet. But there a new EIP to resolve this issue, follow EIP-3326 to find release info, and this discuss to see draft progrss.
chainId: '0x38' // error because await not decimal
Number('0x38').toString(10) //56 - chain ID of BSC
Right:
chainId: `0x${Number(56).toString(16)}`
OR:
chainId: `0x86`
Simply you have to prefix 0x with the chainId.
Example:
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x1' }],
})

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;
}
}

Why the function of address.transfer() only can send 1ether in my contract?

Why the function of address.transfer() only can send 1ether in my contract? It will report errors when the value greater than 1 ether or less than 1 ether.
My code:
pragma solidity ^0.4.24;
contract Lottery{
uint public winn;
//抽奖者
struct lottery{
uint money; //奖金
address name; //名字(地址)
}
//庄家地址
address private bankerAddress = 0x8b3234612c7D3b805F4c9CF1Aa55Cc47B82A0769;
//得奖者数量
uint32 public count;
//得奖者集合
lottery public l;
//初始化
constructor()public {
count=0;
}
event getRandom (
uint indexed _win);
//开始抽奖的函数,返回奖金
function start() public payable{
//随机数生成
uint win= uint(keccak256(now, msg.sender, now)) % 100;
win = win % 12 +1;
winn = win;
l.money = winn;
l.name = msg.sender;
//发奖金操作
msg.sender.transfer(winn*10000000000000000);
//监听事件
getRandom(winn);
}
function () public payable{}
}
Below is javascript code:
lotteryInstance.start.sendTransaction({
from: '0x8b3234612c7D3b805F4c9CF1Aa55Cc47B82A0769',
value: 10000000000000000,
gas: 210000,
gasPrice: web3.toWei('1000', 'gwei')
});
And the error messages:
MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with payload {"id":7309825988666,"jsonrpc":"2.0","params":["0xf8721f85e8d4a510008303345094bcd5d351e5850774d1f720328dac1c8732d68eb7872386f26fc1000084be9a6555822d45a0a07b903c493ba6dee96a54bc74344d1c668cd3d9e8a7c757fdc5daa664ff4271a01bb6799a02054ecf1c8c5be51d6748b2c086eb330091b2e0500d43e756666f69"],"method":"eth_sendRawTransaction"} Error: VM Exception while processing transaction: revert
Uncaught (in promise) Error: Error: Error: [ethjs-rpc] rpc error with payload {"id":7309825988666,"jsonrpc":"2.0","params":["0xf8721f85e8d4a510008303345094bcd5d351e5850774d1f720328dac1c8732d68eb7872386f26fc1000084be9a6555822d45a0a07b903c493ba6dee96a54bc74344d1c668cd3d9e8a7c757fdc5daa664ff4271a01bb6799a02054ecf1c8c5be51d6748b2c086eb330091b2e0500d43e756666f69"],"method":"eth_sendRawTransaction"} Error: VM Exception while processing transaction: revert
In your JS code below:
lotteryInstance.start.sendTransaction({
from: '0x8b3234612c7D3b805F4c9CF1Aa55Cc47B82A0769',
value: 10000000000000000, // Here is the amount of ETH you give to start fuction
gas: 210000,
gasPrice: web3.toWei('1000', 'gwei')
});
The tx is failing maybe because you're giving (ETH) an amount that you may not have! Do you have value: 10000000000000000 many Ethers?
If no, then pass some amount you have, as you haven't given any conditions about the amount in your contract, you can give the smallest possible amount.
PS: The ETH your contract is receiving is not stored anywhere, it may lead to loss of Ethers.

the tx doesn't have the correct nonce. account has nonce of: 5 tx has nonce of: 15

Using truffle (3.4.6), metamask (3.9.2) and testrpc (4.0.1), I call a transaction and get "Error: the tx doesn't have the correct nonce. account has nonce of: 5 tx has nonce of: 15". I have cut down the body of my contract method to something trivial and I still get this. Any idea what causes it?
contract MyContract {
mapping (address => bool) authorized;
function myMethod (uint element, uint price) whenNotPaused returns (bool) {
if (!authorized[msg.sender]) throw;
return true;
}
}
I call the method like this (using truffle):
MyContract.deployed().then((instance) => {
instance.myMethod (id, price, {from: account}).then (...)
In this thread i saw a suggestion of switching networks back and forth and the error self correcting.
¯\_(ツ)_/¯
#okwme is right, but you can also change your configuration of the network to fix the issue. Assume you're running a dev network on localhost with a HDWallet provider, then you can fix the error by commenting out that config property and add host and port properties to it.
It looks like follows:
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 6721975
// networkCheckTimeout: 10000,
// provider: function() {
// return new HDWalletProvider(mnemonic, 'http://127.0.0.1:8545/', 0, 10);
// },
// network_id: '*',
// gas: 6721975,
},
},