Migration to mumbai is failing - migration

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"
}
} ```

Related

Etherscan has no support for network sepolia with chain id 11155111

I am trying to verify my deployed contract from truffle and getting "Etherscan has no support for network sepolia with chain id 11155111" error. So I am working with Etherscan and I deployed my contract on sepolia testnet.
How can I solve this problem?
My truffle-config.js
const apikeys = require("./chains/apikeys");
const keys = require("./keys.json");
module.exports = {
plugins: ["truffle-plugin-verify"],
api_keys:{
etherscan: "myApiEtherScan"
},
contracts_build_directory: "./public/contracts",
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
},
sepolia: {
provider: () =>
new HDWalletProvider(
keys.PRIVATE_KEY,
keys.INFURA_SEPOLIA_URL,
),
network_id: 11155111,
gas:5221975,
gasPrice:20000000000,
confirmations: 3,
timeoutBlocks:200,
skipDryRun: true
}
},
compilers: {
solc: {
version: "0.8.16",
settings: {
optimizer: {
enabled: true, // Default: false
runs: 1000 // Default: 200
}
}
}
},
};
Plugin truffle-plugin-verify doesn't have Sepolia chain support
I added the sepolia api url and etherscan url to constants and it works
const API_URLS = {
...
11155111: 'https://api-sepolia.etherscan.io/api',
...
}
const EXPLORER_URLS = {
...
11155111: 'https://sepolia.etherscan.io/address',
...
}
https://github.com/tafonina/truffle-plugin-verify

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

Expo App environments for Dev, UAT and Production

I have a React Native app built in Expo that connects to a Rest API. There are three environments for the rest api - dev, uat and production as below (example).
dev = https://dev.myapi.com/api
uat = https://uat.myapi.com/api
prod = https://prod.myapi.com/api
Depending on where the app is being used it needs to connect to the correct environment.
Running in the Expo Client = Dev API
Running in TestFlight or Internal Testing for the Play Store = UAT API
Running in the App Store or Play Store = Production API
What is the simplest way to achieve this?
Follow below Steps
Install expo-constants package. To install the package run the below command.
npm i expo-constants
Add environment.js file and paste below code.
import Constants from 'expo-constants';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'localhost:8080' : '10.0.2.2:8080';
const ENV = {
dev: {
apiUrl: 'https://dev.myapi.com/api',
amplitudeApiKey: null,
},
staging: {
apiUrl: 'https://uat.myapi.com/api',
amplitudeApiKey: '[Enter your key here]',
// Add other keys you want here
},
prod: {
apiUrl: 'https://prod.myapi.com/api',
amplitudeApiKey: '[Enter your key here]',
// Add other keys you want here
},
};
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__) {
return ENV.dev;
} else if (env === 'staging') {
return ENV.staging;
} else if (env === 'prod') {
return ENV.prod;
}
};
export default getEnvVars;
Accessing Environment Variables
// Import getEnvVars() from environment.js
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
/******* SESSIONS::LOG IN *******/
// LOG IN
// credentials should be an object containing phone number:
// {
// "phone" : "9876342222"
// }
export const logIn = (credentials, jsonWebToken) =>
fetch(`${apiUrl}/phone`, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + jsonWebToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
});
To create the builds use the below commands.
Dev - expo build:ios --release-channel dev
Staging - expo build:ios --release-channel staging
Production - expo build:ios --release-channel prod
Now that Expo supports config file as app.config.js or app.config.ts, we can use the dotenv. Check this: https://docs.expo.io/guides/environment-variables/#using-a-dotenv-file
Refer link
This can be done using different Release Channel names,
lets say you have created 3 release channels this way:
expo publish --release-channel prod
expo publish --release-channel staging
expo publish --release-channel dev
then you can have a function to set environment vars accordingly:
import * as Updates from 'expo-updates';
function getEnvironment() {
if (Updates.releaseChannel.startsWith('prod')) {
// matches prod*
return { envName: 'PRODUCTION', dbUrl: 'ccc', apiKey: 'ddd' }; // prod env settings
} else if (Updates.releaseChannel.startsWith('staging')) {
// matches staging*
return { envName: 'STAGING', dbUrl: 'eee', apiKey: 'fff' }; // stage env settings
} else {
// assume any other release channel is development
return { envName: 'DEVELOPMENT', dbUrl: 'aaa', apiKey: 'bbb' }; // dev env settings
}
}
Refer to expo documentation for more info!
For those who are using Expo sdk 46(or any newer version), you can do the following way
Rename the app.json to app.config.js
Add API URL under extra property
export default () => ({
expo: {
name: '',
slug: ''
extra: {
API_URL: process.env.API_URL || null,
},
// ...
},
});
We can access this API using expo constants like this(wherever we want).
Don't forget to import constants from Expo.
const myApi = Constants.expoConfig.extra.API_URL
axios.get(myApi).... // using API END POINT
For Local development to access API you can do it in two ways
API_URL="http:// localhost:3000" expo start
Just comment the Contants.expoConfig..... and directly paste local URL
like const myApi = "http:// localhost:3000"
And in eas.json
{
"production": {
"env": {
"API_URL": "https://prod.example.com"
}
},
"staging": {
"env": {
"API_URL": "https://staging.example.com"
}
}
}
Once we run eas build the appropriate API endpoint will be set.
Refer to the same in Expo documentation
https://docs.expo.dev/eas-update/environment-variables/

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