Truffle migration on a different network show segmentation error on bash - migration

I was migrating my contract to mumbai polygon testnet. It compiled successfully but when I run the command
truffle migrate --network mumbai
on bash it returned a segmentation fault error.
The configuration for the testnet in my truffle.config.js is as follows:
mumbai: {
provider: () => new HDWalletProvider(mnemonic, "https://polygon-mumbai.g.alchemy.com/v2/KEY"),
network_id: 80001,
confirmations: 2,
timeoutBlocks: 200,
skipDryRun: true
},
},
This is the content of my migration file:
var Tris = artifacts.require("TrisNFT");
var User = artifacts.require("UserContract");
module.exports = function (deployer) {
deployer.deploy(Tris).then(function(){
return deployer.deploy(User, { Tris.address, "0x9E7BD21f0b8e1Cc9E4bFc0C8C5d603Fd979760B6" })
});
};

Related

Migration to mumbai is failing

I'm a newbie, and I'm currently trying to migrate a contract to mumbai from my Mac, but something is wrong. Could you please let me know identify what it is. I tried several methods, such as init truffle, but the outcome is different. It should work with truffle migrate —network mumbai --reset. When I try that, I get the following error:
VSC error
Please take a look at my truffle-config.js
* Use this file to configure your truffle project. It's seeded with some
* common settings for different networks and features like migrations,
* compilation, and testing. Uncomment the ones you need or modify
* them to suit your project as necessary.
*
* More information about configuration can be found at:
*
* https://trufflesuite.com/docs/truffle/reference/configuration
*
* To deploy via Infura you'll need a wallet provider (like #truffle/hdwallet-provider)
* to sign your transactions before they're sent to a remote public node. Infura accounts
* are available for free at: infura.io/register.
*
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
* phrase from a file you've .gitignored so it doesn't accidentally become public.
*
*/
const HDWalletProvider = require('#truffle/hdwallet-provider');
//const infuraKey = "fj4jll3k.....";
//
const fs = require('fs');
const mnemonic = fs.readFileSync(".firefox.log").toString().trim();
module.exports = {
/**
* Networks define how you connect to your ethereum client and let you set the
* defaults web3 uses to send transactions. If you don't specify one, it will
* will spin up a development blockchain for you on port 9545 when you run
* run `develop` or `test`. You can ask a blockchain for its default network
* network from the command line, e.g.
*
* $ truffle test --network <network-name>
*/
networks: {
// Useful for testing. The `development` name is special - truffle uses it by default
// if it's defined here and no other network is specified at the command line.
// You should run a client (like ganache-cli or geth) in a separate terminal
// tab if you use this network and you must also set the `host`, `port` and
// options below to some value.
//
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
},
// Another network with more advanced options...
// advanced: {
// port: 8777, // Custom port
// network_id: 1342, // Custom network
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
// from: <address>, // Account to send txs from (default: accounts[0])
// websockets: true // Enable EventEmitter interface for web3 (default: false)
// },
// Useful for deploying to a public network.
// NB: It's important to wrap the provider as a function.
ropsten: {
provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/8ba19657db694241aef195cd24ccbbbb`),
network_id: 3, // Ropsten's id
gas: 8000000, // Ropsten has a lower block limit than mainnet
gasPrice: 25000000000,
confirmations: 2, // # of confirmations before a transaction is considered mined
timeoutBlocks: 200, // # of blocks before a deployment times out - was 200
skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
},
goerli: {
provider: () => new HDWalletProvider(mnemonic, `https://goerli.infura.io/v3/8ba19657db694241aef195cd24ccbbbb`),
network_id: 5, // goerli's id
gas: 15500000, // Ropsten has a lower block limit than mainnet
confirmations: 2, // # of confs to wait between deployments. (default: 0)
timeoutBlocks: 200, // # of blocks before a deployment times out - was 200
skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
},
mumbai: {
provider: function () {
return new HDWalletProvider(mnemonic, `https://matic-mumbai.chainstacklabs.com`);
//return new HDWalletProvider(mnemonic, `https://polygon-mumbai.infura.io/v3/8ba19657db694241aef195cd24ccbbbb`);
},
network_id: 80001,
gas: 5500000,
gasPrice: 40000000000,
confirmations: 2,
networkCheckTimeout: 999999,
skipDryRun: true
}
// Useful for private networks
// private: {
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
// network_id: 2111, // This network is yours, in the cloud.
// production: true // Treats this network as if it was a public network. (default: false)
// }
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.7.6", // 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"
}
}
}
}
And this is my package.json
"name": "uniswap-core",
"version": "1.0.0",
"description": "",
"main": "truffle-config.js",
"dependencies": {
"#truffle/hdwallet-provider": "^1.5.1",
"cpr": "^3.0.1",
"dotenv": "^10.0.0",
"fs": "^0.0.1-security",
"web": "1.5.0"
}
} ```

Can't deploy smart contract to hardhat network

I set up a project with hardhat for an NFT app. I modify hardhat.config.js like this:
const { ALCHEMY_KEY, ACCOUNT_PRIVATE_KEY } = process.env;
module.exports = {
solidity: "0.8.0",
defaultNetwork: "hardhat",
networks: {
hardhat: {},
rinkeby: {
url: `https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`,
accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
},
// ethereum: {
// chainId: 1,
// url: `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_KEY}`,
// accounts: [`0x${ACCOUNT_PRIVATE_KEY}`]
// },
},
}
then I created a deploy script in the scripts folder with the deploy task
// scripts/deploy.js
const { task } = require("hardhat/config");
const { getAccount } = require("./helpers");
task("deploy", "Deploys the TokenV2.sol contract").setAction(async function (taskArguments, hre) {
const tokenFactory = await hre.ethers.getContractFactory("TokenV2", getAccount());
const token = await tokenFactory.deploy();
await token.deployed()
console.log(`Contract deployed to address: ${token.address}`);
});
The problem it's when I run npx hardhat deploy it's shows this error in terminal: Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network="hardhat", code=NETWORK_ERROR, version=providers/5.5.3) What I missed? I will appreciate any help.
I never used defaultNetwork in my works so I just had the following hardhat.config File and had no issues at all:
{
"solidity":"0.8.4",
"networks":{
"rinkeby":{
"url":"`https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`",
"accounts":[
"`0x${ACCOUNT_PRIVATE_KEY}`"
]
}
}
}

UnhandledPromiseRejectionWarning: Error: Returned error: execution reverted

Here's the code I'm running to get the balance of the contract I've previously deployed to Binance Smart Chain:
let Web3 = require('web3');
const fs = require('fs');
let web3 = new Web3('https://data-seed-prebsc-1-s1.binance.org:8545');
const contractAddress = '0x43045f0Cec750eEb70478B023885d1956588438E';
const contractAbi = JSON.parse(fs.readFileSync("scripts/contract_abi.json").toString())
const contract = new web3.eth.Contract(contractAbi, contractAddress);
contract.methods.balanceOf(contractAddress).call().then(result=>console.log(result)).catch(err => console.log(err));
This code throws me the error:
Error: Returned error: execution reverted
at Object.ErrorResponse (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/web3-core-helpers/lib/errors.js:28:19)
at /home/zuber/Projects/HelloBSC/HelloCoin/node_modules/web3-core-requestmanager/lib/index.js:303:36
at XMLHttpRequest.request.onreadystatechange (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/web3-providers-http/lib/index.js:98:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
at XMLHttpRequest._setReadyState (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
at XMLHttpRequest._onHttpResponseEnd (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
at IncomingMessage.<anonymous> (/home/zuber/Projects/HelloBSC/HelloCoin/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
data: null}
The contract is copypasted from https://github.com/binance-chain/bsc-genesis-contract/blob/master/contracts/bep20_template/BEP20Token.template (only added onlyOwner modifier to line 332)
Truffle config used to deploy contract to BSC:
const HDWalletProvider = require('#truffle/hdwallet-provider');
const fs = require('fs');
const mnemonic = fs.readFileSync(".secret").toString().trim();
module.exports = {
networks: {
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard BSC port (default: none)
network_id: "*", // Any network (default: none)
},
testnet: {
provider: () => new HDWalletProvider(mnemonic, `https://data-seed-prebsc-1-s1.binance.org:8545`),
network_id: 97,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true
},
bsc: {
provider: () => new HDWalletProvider(mnemonic, `https://bsc-dataseed1.binance.org`),
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true
},
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.5.16", // A version or constraint - Ex. "^0.5.0"
}
}
}
This is a general error originating from a smart contract, when the contract throws an unhandled exception.
Even though that you didn't post the contract source code, we can get some basic info about its content from the decompiled code.
It shows that there's no balanceOf() (that you're trying to call), and that the fallback() (which is used if you're trying to call an non-existing function) always throws an exception.
From here, the most likely possibility is that you meant to deploy a different contract (that contains the balanceOf() function) but mistakenly deployed this one instead.
Or if you meant to get the BNB balance (not the token balance) of the contract address, you can use the web3 getBalance() method. Example:
const balance = await web3.eth.getBalance(contractAddress);
I was also stuck with the same error and the issue was that I was deploying on the remix local address provided by remix but not with metamask. Hope it help someone.

Truffle contract deployment failed, invalid sender

I'm trying to deploy a contract to the ropsten testnet using truffle, but I get the following error:
Deploying 'Migrations'
----------------------
Error: *** Deployment Failed ***
"Migrations" -- invalid sender.
at /home/usr/.npm/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:365:1
at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.2.5 (core: 5.2.5)
Node v10.19.0
When deploying to ganache locally, it works fine. Also I'm pretty sure my truffle-config.js is correct, it's the same as all the online tutorials, but since I'm here, I guess I'm not completely sure :). The address that hd-wallet is using is also correct (verified with the console.log statement in truffle-config.js) and it has 5 ETH balance, so more than enough. I have 2 migration scripts, it gives exactly the same error with each script.
truffle-config.js:
require("dotenv").config();
const HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
networks: {
ropsten: {
provider: () => {
var provider = new HDWalletProvider({
mnemonic: process.env.MNEMONIC,
providerOrUrl: `https://ropsten.infura.io/v3/${process.env.INFURA_KEY}`,
derivationPath: "m/44'/60'/0'/0/",
addressIndex: 0,
});
console.log(provider.getAddress());
return provider;
},
network_id: 3,
gas: 5500000,
confirmations: 2,
timeoutBlocks: 200,
skipDryRun: true,
},
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
},
},
compilers: {
solc: {
version: "0.6.0",
optimizer: {
enabled: true,
runs: 200,
},
},
},
};
1_initial_migration.js:
const Migrations = artifacts.require("Migrations");
module.exports = function (deployer) {
deployer.deploy(Migrations);
};
2_deploy.js:
const Token = artifacts.require("Token");
module.exports = (deployer) => {
deployer.deploy(Token);
};
Token.sol:
//SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Token is ERC20 {
address minter;
// minterChanged event
event minterChanged(address indexed from, address to);
constructor() public payable ERC20("Decentralized Bank Currency", "DCB") {
minter = msg.sender;
}
function transferMinterRole(address bank) public returns(bool) {
require(msg.sender == minter);
minter = bank;
emit minterChanged(msg.sender, minter);
return true;
}
function mint(address account, uint256 amount) public {
require(msg.sender == minter);
_mint(account, amount);
}
}
Escrow.sol:
//SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0 ;
contract Escrow {
address agent;
mapping(address => uint256) public deposits;
modifier onlyAgent() {
require(msg.sender == agent);
_; // return void
}
constructor() public {
// solidity heeft globale var msg
agent = msg.sender;
}
function deposit(address payee) payable public onlyAgent {
uint256 amount = msg.value;
deposits[payee] = deposits[payee] + amount;
}
function withdras(address payable payee) public onlyAgent {
uint256 payment = deposits[payee];
deposits[payee] = 0;
payee.transfer(payment);
}
}
Try a different version #truffle/hdwallet-provider
Works for me with 1.2.3
npm uninstall #truffle/hdwallet-provider
npm install #truffle/hdwallet-provider#1.2.3
With the latest version (1.2.4) there was the same error (invalid sender).
According to my observation, this issue only occurs when you try to deploy any contract on ropsten testnet. If you're deploying with a local node like running with ganache-cli, it functions well even with the latest version (>1.2.3)
The reason here is they change the constructor method to add a chainId parameter to specified which chain you're signing with your transaction.
Solution: Update your code of initializing the HDWalletProvider.
ropsten: {
provider: () =>
new HDWalletProvider({
mnemonic,
providerOrUrl:
'wss://ropsten.infura.io/ws/v3/.....',
chainId: 3,
}),
network_id: 3, // Ropsten's id
gas: 5500000, // Ropsten has a lower block limit than mainnet
confirmations: 0, // # of confs to wait between deployments. (default: 0)
timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
skipDryRun: true, // Skip dry run before migrations? (default: false for public nets )
},
This works fine with me on ropsten
Check this out:
https://github.com/trufflesuite/truffle/issues/3935
Seems that truffle may not be properly eip 155 compliant. A PR was merged to help but I don't think this issue is yet resolved from the HDWallet end.
https://github.com/trufflesuite/truffle/issues/3913
https://github.com/trufflesuite/truffle/pull/3923
I am using #truffle/hdwallet-provider 1.3.0 and still got the same error.
Got it fixed by changing the initialization of HDWalletProvider.
ropsten: {
provider: function () {
return new HDWalletProvider(
{
privateKeys: ["YourPrivateKey"],
providerOrUrl: "https://ropsten.infura.io/v3/InfuraKey",
chainId: 3,
}
)
},
network_id: '3',
}
(Replace YourPrivateKey and InfuraKey with your private key and infura api key)
As an alternative solution, inside truffle-config.js use:
const HDWalletProvider = require('truffle-hdwallet-provider');
instead of
const HDWalletProvider = require('#truffle/hdwallet-provider');
It's just another way of downgrading the #truffle/hdwallet-provider while your package.json can still have:
"dependencies": {
"#truffle/hdwallet-provider": "^1.3.1"
}

Truffle contract verify not working on BSC testnet

I am trying to verify my deployed contract from truffle and getting "Etherscan has no support for network testnet with id 97" error. So I am working with Bscscan and I deployed my contract on bsc testnet.
How can I solve this problem?
My truffle-config.js
const HDWalletProvider = require('truffle-hdwallet-provider');
const fs = require('fs');
const mnemonic = fs.readFileSync(".secret").toString().trim();
const BSCSCANAPIKEY = fs.readFileSync("apikey").toString().trim();
module.exports = {
networks: {
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard BSC port (default: none)
network_id: "*", // Any network (default: none)
},
testnet: {
provider: () => new HDWalletProvider(mnemonic, `https://data-seed-prebsc-1-s1.binance.org:8545`),
network_id: 97,
confirmations: 1,
timeoutBlocks: 200,
skipDryRun: true
},
bsc: {
provider: () => new HDWalletProvider(mnemonic, `https://bsc-dataseed1.binance.org`),
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true
},
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.6.12"
}
},
plugins: [
'truffle-plugin-verify'
],
api_keys: {
bscscan: BSCSCANAPIKEY
},
}
Result:
> truffle run verify MyToken#{address}--network testnet
Etherscan has no support for network testnet with id 97
Install the latest version of truffle-plugin-verify.
Now the latest version is 0.5.4.
npm install truffle-plugin-verify#^0.5.4 -D
Why this happens?
In this file (https://github.com/rkalis/truffle-plugin-verify/blob/32ab0f698b1e151849ab463357cded664c5cffa3/constants.js)
You can see the last two API_URLs (56 & 97). This is added to the upper version rather than what you installed.
const API_URLS = {
1: 'https://api.etherscan.io/api',
3: 'https://api-ropsten.etherscan.io/api',
4: 'https://api-rinkeby.etherscan.io/api',
5: 'https://api-goerli.etherscan.io/api',
42: 'https://api-kovan.etherscan.io/api',
56: 'https://api.bscscan.com/api',
97: 'https://api-testnet.bscscan.com/api'
}