truffle | Crafted with the finest cacaos | Blockchain library
kandi X-RAY | truffle Summary
Support
Quality
Security
License
Reuse
- Create the step selector for a step .
- Set transaction log actions
- Update code storage .
- Contract instance
- Maps the action and updates the new path to the new one .
- Compiles JSON files into an object that can be written to JSON .
- recursively process all build contracts
- Runs provided sources
- Creates the step selector for the step selector .
- Process a target
truffle Key Features
truffle Examples and Code Snippets
import Web3 from 'web3' import { GhostMarketSDK, Chain, TESTNET_API_URL, MAINNET_API_URL } from 'ghostmarket-sdk-js'; // if using EVM private key or mnemonic hdwallet-provider is required // import HDWalletProvider from '@truffle/hdwallet-provider' // Variables const apiKey = process.env.GM_API_KEY // GhostMarket API KEY if you have one const privateKey = process.env.PRIVATE_KEY // private key to use - only for private key provider const rpcUrl = process.env.RPC_URL // RPC to use, ex 'https://mainnet.infura.io' const environment = MAINNET_API_URL // GhostMarket Infrastructure - MAIN_ENVIRONMENT or TEST_ENVIRONMENT const chainName = Chain.ETHEREUM // see below for chain values /* chainName values : Chain.ETHEREUM / Chain.ETHEREUM_TESTNET Chain.POLYGON / Chain.POLYGON_TESTNET Chain.BSC / Chain.BSC_TESTNET Chain.AVALANCHE / Chain.AVALANCHE_TESTNET */ // SDK config options. const sdkConfig = { apiKey, rpcUrl, environment, chainName, } // Option 1 - readonly provider, only reads the network state. Can not sign transactions const customProvider = new Web3.providers.HttpProvider(rpcUrl) const address = '' // Option 2 - metamask provider const customProvider = window.ethereum const address = await ethereum.request({ method: 'eth_requestAccounts', })[0]; // Option 3 - private key const customProvider = new HDWalletProvider(KEY, rpcUrl) const address = customProvider.addresses[0] // Create instance of GhostMarketSDK - EVM const gmSDK = new GhostMarketSDK(customProvider, sdkConfig); // Start and stop provider engine - when using HDWalletProvider // customProvider.engine.start(); // your code here // customProvider.engine.stop(); // All set - use the object gmSDK to access GhostMarket SDK
npm install -g truffle@5.4.29
PS C:\Windows\system32> npm list -g
C:\Users\*****\AppData\Roaming\npm
+-- ganache-cli@6.12.2
+-- node-gyp@8.2.0
+-- npm@8.0.0
+-- **truffle@5.4.29**
`-- yarn@1.22.17
PS C:\Windows\system32> truffle
Truffle v5.4.29 - a development framework for Ethereum
Usage: truffle [options]
Commands:
build Execute build pipeline (if configuration present)
compile Compile contract source files
config Set user-level configuration options
console Run a console with contract abstractions and commands available
create Helper to create new contracts, migrations and tests
db Database interface commands
debug Interactively debug any transaction on the blockchain
deploy (alias for migrate)
develop Open a console with a local development blockchain
exec Execute a JS module within this Truffle environment
help List all commands or provide information about a specific command
init Initialize new and empty Ethereum project
install Install a package from the Ethereum Package Registry
migrate Run migrations to deploy contracts
networks Show addresses for deployed contracts on each network
obtain Fetch and cache a specified compiler
opcode Print the compiled opcodes for a given contract
preserve Save data to decentralized storage platforms like IPFS and Filecoin
publish Publish a package to the Ethereum Package Registry
run Run a third-party command
test Run JavaScript and Solidity tests
unbox Download a Truffle Box, a pre-built Truffle project
version Show version number and exit
watch Watch filesystem for changes and rebuild the project automatically
See more at http://trufflesuite.com/docs
...
testnet: {
provider: () => new HDWalletProvider({
mnemonic: {
phrase: testnetSeedPhrase,
},
providerOrUrl: 'https://public-node.testnet.rsk.co/',
// Higher polling interval to check for blocks less frequently
pollingInterval: 15e3,
}),
// Ref: http://developers.rsk.co/rsk/architecture/account-based/#chainid
network_id: 31,
gasPrice: gasPriceTestnet,
networkCheckTimeout: 1e6,
timeoutBlocks: 100,
// Higher polling interval to check for blocks less frequently
// during deployment
deploymentPollingInterval: 15e3,
},
...
truffle migrate --network testnet
const showAccount = document.querySelector('.showAccount');
const showBalance = document.querySelector('.showBalance');
getAccount();
loadBalance();
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
}
function loadBalance(){
web3Provider = null;
contracts = {};
account = '0x0';
const Web3 = require("web3");
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
return true;
}
}
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
$.getJSON("Market.json", function (market) {
console.log("initializing Market contract")
// Instantiate a new truffle contract from the artifact
contracts.Market = TruffleContract(market);
// Connect provider to interact with contract
contracts.Market.setProvider(web3Provider);
});
$.getJSON("Users.json", function (users) {
console.log("initializing User contract")
// Instantiate a new truffle contract from the artifact
contracts.Users = TruffleContract(users);
// Connect provider to interact with contract
contracts.Users.setProvider(App.web3Provider);
});
var marketInstance;
var userInstance;
var loader = $("#loader");
var content = $("#content");
//loader.show();
content.show();
// Load account data
console.log("loading account data")
var currentAccount;
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
console.log("Your Account: " + account)
account = account;
currentAccount = account;
web3.eth.getBalance(account, function(err, balance) {
if (err === null) { //Note:set id="accountBalance" in your html page
$("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
}
});
}
});
}
sudo rm -rf /Library/Developer/CommandLineTools
sudo Xcode-select --install
sudo npm install -g truffle
module.exports = {
// See
// for more about customizing your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 8545
},
nftWallet: {
provider: () => new PrivateKeyProvider(privateKey, "http://localhost:8545"),
network_id: "*",
type: "quorum",
gasPrice: 0
}
},
//Configure your compilers
compilers: {
solc: {
version: "0.8", // Fetch exact version from solc-bin (default: truffle's version)
}
}
};
npm install --save-peer pm2 truffle
$ npx truffle -v
npx truffle -v
Truffle v5.3.0 - a development framework for Ethereum
Usage: truffle [options]
Commands:
build Execute build pipeline (if configuration present)
compile Compile contract source files
config Set user-level configuration options
console Run a console with contract abstractions and commands available
create Helper to create new contracts, migrations and tests
db Database interface commands
debug Interactively debug any transaction on the blockchain
deploy (alias for migrate)
develop Open a console with a local development blockchain
exec Execute a JS module within this Truffle environment
help List all commands or provide information about a specific command
init Initialize new and empty Ethereum project
install Install a package from the Ethereum Package Registry
migrate Run migrations to deploy contracts
networks Show addresses for deployed contracts on each network
obtain Fetch and cache a specified compiler
opcode Print the compiled opcodes for a given contract
preserve Save data to decentralized storage platforms like IPFS and Filecoin
publish Publish a package to the Ethereum Package Registry
run Run a third-party command
test Run JavaScript and Solidity tests
unbox Download a Truffle Box, a pre-built Truffle project
version Show version number and exit
watch Watch filesystem for changes and rebuild the project automatically
See more at http://trufflesuite.com/docs
$
Trending Discussions on truffle
Trending Discussions on truffle
QUESTION
compiled code by py-solc-x, then deployed it to the ganache local network using web3py api. first, call a get_balance function and it return as expected. second, call the transfer function and it return without error, but the balance have not changed when I call get_balance later. try to call transfer by sending a raw transaction but it still no effect...
metacoin.sol (provided by truffle doc)
pragma solidity ^0.8.0;
contract MetaCoin {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint _value);
constructor() public {
balances[msg.sender] = 10000;
}
function transfer(address receiver, uint amount) public returns(bool sufficient) {
if (balances[msg.sender] >= amount)
return false;
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Transfer(msg.sender, receiver, amount);
return true;
}
function get_balance(address account) public view returns(uint) {
return balances[account];
}
}
interacting.py
# deploy contract by w3.eth.accounts[0]
# the balance of the accounts[0] is 10000 (call get_balance() return 10000)
# then transfer 1000 from accounts[0] to accounts[1]
deployed_address = '0x538574C591F6e01E22eFa951153a29e6Fc505735'
contract = w3.eth.contract(address=HexBytes(deployed_address), abi=abi)
tx_hash = contract.functions.transfer(w3.eth.accounts[1], 1000).transact()
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(tx_receipt.contractAddress)
balance = contract.functions.get_balance(w3.eth.accounts[0]).call()
print(balance)
# still 10000, expect 9000.
the transfer transaction looks good. both gas/gasPrice and dynamic fee transaction have been tried but the balance still the same. it's the problem from the ganache local network setting ? or some required configured steps I missed.
ANSWER
Answered 2022-Apr-08 at 08:47Check that the transaction went through
assert tx_receipt.status == 1
Also if Ganache does not work then try Ethereum Tester based tests. Example token tests here.
QUESTION
i want to create a token on ERC-20 network.
i want to inheritance from interface in my contract .
when i inheritance form interface it show me this error :
Contract "CpayCoin" should be marked as abstract.
solc
version in truffle :
compilers: {
solc: {
version: "0.8.10", // Fetch exact version from solc-bin (default: truffle's version)
docker: false, // 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"
}
}
},
whats the problem ? how can i solve this problem ???
this is my interface :
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract :
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "./IERC-20.sol";
contract CpayCoin is IERC20 {
//mapping
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
//Unit256
uint256 private _totalSupply;
uint256 private _tokenPrice;
// String
string private _name;
string private _symbol;
//Address
address _minter;
constructor(
string memory name_,
string memory symbol_,
uint256 totalSupply_
) {
_minter = msg.sender;
_balances[_minter] = _totalSupply;
_tokenPrice = 10**15 wei;
_name = name_;
_symbol = symbol_;
_totalSupply = totalSupply_;
}
// Modifier
modifier onlyMinter() {
require(msg.sender == _minter, "Only Minter can Mint!");
_;
}
modifier enoughBalance(address adr, uint256 amount) {
require(_balances[adr] >= amount, "Not enough Balance!");
_;
}
modifier enoughValue(uint256 amount) {
require(msg.value == amount * _tokenPrice, "Not enough Value!");
_;
}
modifier checkZeroAddress(address adr) {
require(adr != address(0), "ERC20: mint to the zero address");
_;
}
// Functions
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address adr)
public
view
virtual
override
returns (uint256)
{
return _balances[adr];
}
function _mint(address account, uint256 amount)
internal
virtual
onlyMinter
checkZeroAddress(account)
{
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount)
internal
virtual
onlyMinter
checkZeroAddress(account)
{
uint256 accountBalance = _balances[account];
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply += amount;
emit Transfer(account, address(0), amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
ANSWER
Answered 2021-Dec-04 at 13:22Solidity currently (v0.8) doesn't have a way to tell that a class (a contract) implements an interface. Instead, the is
keyword is used to mark an inheritance, as "derives from".
So the CpayCoin is IERC20
expression marks the CpayCoin
as a child and IERC20
as a parent - not as an interface.
The IERC20
(parent) defines few functions (e.g. decimals()
and transfer()
) that the CpayCoin
(child) doesn't implement, which makes the CpayCoin
an abstract class.
Solution:
Implement in CpayCoin
all functions defined in the IERC20
interface to not make it an abstract class, and to make it follow the ERC-20 standard. Then you're free to remove the inheritance as it becomes redundant.
Or just remove the inheritance to not have any unimplemented function definitions (but then the contract won't follow the ERC-20 standard).
Mind that in your current code, the _transfer()
internal function is unreachable. I'd recommend to implement a transfer()
external function that invokes this internal _transfer()
.
QUESTION
When i tried to install truffle i got these errors :-
I have installed Node.js earlier and also i have pip installed.
PS C:\Users\pk199\Documents> npm install -g truffle
npm ERR! code 1
npm ERR! path C:\Users\pk199\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\leveldown
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node-gyp rebuild
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.3.0
npm ERR! gyp info using node@16.13.1 | win32 | x64
npm ERR! gyp info find Python using Python version 3.10.1 found at "C:\Users\pk199\AppData\Local\Programs\Python\Python310\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version was set from command line or npm config
npm ERR! gyp ERR! find VS - looking for Visual Studio version 2022
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS unknown version "undefined" found at "C:\Program Files\Microsoft Visual Studio\2022\Community"
npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS valid versions for msvs_version:
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:404:5)
npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1064:16)
npm ERR! gyp ERR! System Windows_NT 10.0.19044
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\pk199\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\leveldown
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! node-gyp -v v8.3.0
npm ERR! gyp ERR! not ok
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\pk199\AppData\Local\npm-cache\_logs\2022-01-24T15_16_27_276Z-debug.log
I have installed C++ Desktop development in visual studio 2022 as well but still getting this error
ANSWER
Answered 2022-Jan-26 at 17:42Here are some references that might help:
Try installing Truffle via PowerShell in Admin mode (very important that you're in Admin mode)
You'll need to allow scripts to run as an Admin in PowerShell. To do this, here are some references in the threads in Stack Overflow:
Enable Execution of PowerShell Scripts
I ran the command Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force
in PowerShell to get this to work, but please reference the threads above before doing this.
QUESTION
I am looking for a way to create an automated test suite with Truffle that can test my smart contract's interactions with Uniswap V2. The Uniswap docs briefly mention testing with Truffle but do not provide any examples. I am looking to test it using a mainnet fork with ganache.
I'm guessing it's a similar process to the accepted answer for this question, but I'm specifically looking for a way to do it using Truffle and web3.js.
As an example, if I were testing the following contract:
pragma solidity ^0.6.6;
interface IUniswap {
function swapExactETHForTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline)
external
payable
returns (uint[] memory amounts);
function WETH() external pure returns (address);
}
contract MyContract {
IUniswap uniswap;
constructor(address _uniswap) public {
uniswap = IUniswap(_uniswap);
}
function swapExactETHForTokens(uint amountOutMin, address token) external payable {
address[] memory path = new address[](2);
path[0] = uniswap.WETH();
path[1] = token;
uniswap.swapExactETHForTokens{value: msg.value}(
amountOutMin,
path,
msg.sender,
now
);
}
}
How would I create a unit test to verify that swapExactETHForTokens()
swaps ETH for say, DAI? For the value of _uniswap
I've been using UniswapV2Router02.
Any help would be greatly appreciated.
ANSWER
Answered 2022-Feb-12 at 12:48If you use Uniswap platform to swap a token, you are going to have 2 steps. You are going to approve the token, in this step metamask will pop-up and you are going to confirm it. Then Uniswap will do the actual swap, it takes the tokens out of your wallet and does the exchange for you.
This is the swapExactETHForTokens
function
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
last function _swap
calls the swap
function:
It is also important to ensure that your contract controls enough ETH/tokens to make the swap, and has granted approval to the router to withdraw this many tokens.
Imagine you want to swap 50 DAI for as much ETH as possible from your smart contract.
transferFromBefore swapping, our smart contracts needs to be in control of 50 DAI. The easiest way to accomplish this is by calling transferFrom on DAI with the owner set to msg.sender:
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
Eventually Uniswap will transferFrom
, but before your token has to approve the transaction, it has to add uniswap address
to its allowance
mapping.
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
You cannot test the current implementation of your contract unless you have a swap token set and your swap token has to call approve
.
If you had front end app, when you call your contract's swap function, metamask would pop up and you would confirm it. However in a test environment you need the actual ERC20 contract, you deploy it and you call the approve
. In front end you would have two functions swapToken
and approve
. You would call them in this order?
const startSwap = async () => {
await approve()
await swapToken()
}
In test suite:
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");
// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => {
let myContract,dai;
// intialize the contracts before each test
before(async () => {
myContract = await myContract.new();
dai = await Dai.new();
})
describe("Swapping", async () => {
it("swap tokens", async () => {
let result;
// first ask for approval of 100 token transfer
await dai.approve(myContract.address, tokens("100"), {
from:ganachProvidedAccounts[0] ,
});
// // check staking for customer
await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
// make your assetion
})})
QUESTION
When trying to run truffle migrate --network bsc
, truffle usually (not always) manages to deploy the migrations contract, then fails with an error: header not found.
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ code: -32000, message: 'header not found' })
at new NodeError (node:internal/errors:363:5)
at Web3ProviderEngine.emit (node:events:354:17)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:54:14
at afterRequest (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:148:21)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:174:21
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:232:9
at D:\Contracts\novaria\node_modules\async\internal\once.js:12:16
at replenish (D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:61:25)
at D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:71:9
at eachLimit (D:\Contracts\novaria\node_modules\async\eachLimit.js:43:36)
at D:\Contracts\novaria\node_modules\async\internal\doLimit.js:9:16
at end (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:211:5)
at Request._callback (D:\Contracts\novaria\node_modules\web3-provider-engine\subproviders\rpc.js:70:28)
at Request.self.callback (D:\Contracts\novaria\node_modules\request\request.js:185:22)
at Request.emit (node:events:365:28)
at Request. (D:\Contracts\novaria\node_modules\request\request.js:1154:10)
at Request.emit (node:events:365:28)
at IncomingMessage. (D:\Contracts\novaria\node_modules\request\request.js:1076:12)
at Object.onceWrapper (node:events:471:28)
at IncomingMessage.emit (node:events:377:35)
at endReadableNT (node:internal/streams/readable:1312:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Here's the config for bsc network:
bsc: {
provider: () => { return new HDWalletProvider(mnemonic, `https://bsc-dataseed2.binance.org/`)},
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true,
},
compilers: {
solc: {
version: "0.8.7", // 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: true,
runs: 200
},
Deploying to testnet and development works without issue. I have in the past deployed to bsc with truffle (been a while though). I've tried changing RPC urls, and messed around with timeout and confirmations (pretty sure that doesn't make a difference for this error). After searching the internet for solutions, the only answer that seems to have worked for people is to change the RPC, but I haven't had any luck with that. Does anyone have any suggestions?
ANSWER
Answered 2022-Mar-02 at 20:44I had the same problem today. Fixed it by using the Websocket endpoint wss://bsc-ws-node.nariox.org:443 from the smart chain docs https://docs.binance.org/smart-chain/developer/rpc.html
QUESTION
while installing truffle on my desktop.An anonymes error ...
first its showing the error related to python which is strange but then i install python now this error `
npm ERR! code 1
npm ERR! path C:\Users\Tanuj Sharma\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\leveldown
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.3.0
npm ERR! gyp info using node@16.13.2 | win32 | x64
npm ERR! gyp info find Python using Python version 3.10.2 found at "C:\Python310\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS checking VS2019 (16.11.31829.152) found at:
npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools"
npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features"
npm ERR! gyp ERR! find VS - found VC++ toolset: v142
npm ERR! gyp ERR! find VS - missing any Windows SDK
npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:404:5)
npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1064:16)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\Tanuj Sharma\AppData\Roaming\npm\node_modules\truffle\node_modules\ganache\node_modules\leveldown
npm ERR! gyp ERR! node -v v16.13.2
npm ERR! gyp ERR! node-gyp -v v8.3.0
npm ERR! gyp ERR! not ok
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Tanuj Sharma\AppData\Local\npm-cache\_logs\2022-01-23T11_22_31_900Z-debug.log
ANSWER
Answered 2022-Jan-31 at 04:58You have to install Visual Studio Community 2022 as well as Visual Studio Code. And when installing Visual Studio Community, you have to install desktop development with C++ with some optional packages.
QUESTION
I am writing an automated test suite that needs to test functions against Uniswap v2 style automated market marker: do swaps and use different order routing. Thus, routers need to be deployed.
Are there any existing examples of how to deploy a testable Uniswap v2 style exchange in Brownie? Because Brownie is a minority of smart contract developers, are there any examples for Truffle or Hardhat?
I am also exploring the option of using a mainnet fork, but I am not sure if this operation is too expensive (slow) to be used in unit testing.
ANSWER
Answered 2022-Feb-10 at 14:30Using a local testnet allows you to control very precisely the state of the blockchain during your test. However, it will require you to deploy every contract you need manually.
A fork of the mainnet will save you from having to deploy every contract already deployed on the mainnet. However you will sacrifice control over the environment and will require a connection to a node.
I've deployed Uniswap 2V on a testnet a few times. To do it you will need the bytecode and ABI for the following contracts: UniswapV2Factory, UniswapV2Pair, UniswapV2Router02 (I suppose you want the second version of the router). The Uniswap docs explains very well how to download them from NPM. For the router to work properly you will also need to deploy a WETH contract. I suggest deploying the one from this github page.
Before running this code, just make sure that your chain is running. For hardhat run the following command:
npx hardhat node
Start by connecting your signer to your dev chain:
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
Using the ethers.js library, you first deploy the factory:
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
Then the WETH contract:
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
You can now deploy the router.
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
You will also need to deploy the ERC20 tokens you need (Here is an example with tokens I've written):
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);
var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
The parameters of the deploy function will depend on the constructor of the token you wish to deploy.
You will also want to create pairs using the createPair method of the Uniswap factory.
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
Keep in mind that in the pair the tokens will be ordered arbitrarly by the contract. ERC20_0 might not be the first of the two.
After that just wait for all the transactions to go through and you should be good to start your test.
QUESTION
enter image description hereI've installed latest version of visual studio with desktop development c++ workload but still they are asking for it when i try to install truffle. I entered command :npm install -g truffle and lot of messages appear after 2 to 3 minutes of some kind of installation process. they are asking for Latest version of Visual Studio with "Desktop development with c++ workload" whereas i just installed my Visual studio with the same requirements. node.js and ganache are already installed. Is there any other way to install truffle?
ANSWER
Answered 2022-Feb-17 at 16:59If you are installing it using npm package manager. Downgrade your npm to 7.24.2 it worked for me I hope it will also work for you. Use the following command to downgrade npm
npm install -g npm@7.24.2
QUESTION
I am working with dataset of the number of truffles found in 288 search areas. I am planning to test the null hypothesis that the truffles are distributed randomly, thus I am using dpois()
to to calculate the expected probability densities. There are 4 categories (0, 1, 2, or 3 truffles per plot). The expected probabilities will later be converted to expected proportions and incorporated into a chisq.test
analysis.
The problem is that the expected probabilities that I get with the following code don't make sense. They should sum to 1, but are much too small. I run the same exact code with another dataset and it produces normal values. What is going on here?
trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
trufflesTable<-table(trufflesFound)
trufflesTable
mean(trufflesTable)
expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesTable))
expTruffPois
These are the probabilities it gives me, which are much too low!
0: 0.00000000000000000000000000000005380186
1: 0.00000000000000000000000000000387373404
2: 0.00000000000000000000000000013945442527
3: 0.00000000000000000000000000334690620643
In contrast, this dataset works just fine:
extinctData<-c(rep(1,13),rep(2,15),rep(3,16),rep(4,7),rep(5,10),rep(6,4),7,7,8,9,9,10,11,14,16,16,20)
extinctFreqTable <- table(extinctData)
extinctFreqTable
mean(extinctFreqTable)
expPois <- dpois(x = 0:20, lambda = mean(extinctFreqTable))
expPois
sum(expPois)
The sum is 0.9999997, which is close to the expected value of 1
Thoughts?
ANSWER
Answered 2022-Feb-09 at 00:03Lambda should be the average frequency, but taking mean(trufflesTable)
returns the average of the counts of frequencies. Use mean(trufflesFound)
instead. The reason the second one looks "right" is because mean(extinctData)
is relatively close to mean(extinctFreqTable)
. Note that the probabilities don't sum exactly to 1, because given the mean it is conceivable that we'd observe more than 4 truffles in a future search area.
trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesFound))
expTruffPois
#> [1] 0.57574908 0.31786147 0.08774301 0.01614715
sum(expTruffPois)
#> [1] 0.9975007
Created on 2022-02-08 by the reprex package (v2.0.1)
QUESTION
I export JSON interface from compile.js file but deploy.js file not work it shows error as
RuntimeError: abort(Error: You must provide the JSON interface of the contract when instantiating a contract object.). Build with -s ASSERTIONS=1 for more info.
here is compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf-8');
//console.log(solc.compile(source,1));
var input = JSON.stringify({
language: 'Solidity',
sources: {
'lottery.sol': {
content: source
}
},
settings: {
outputSelection: {
// Enable the metadata and bytecode outputs of every single contract.
"*": {
"*": ["metadata", "evm.bytecode"]
},
// Enable the abi and opcodes output of MyContract defined in file def.
"def": {
"Lottery": ["abi"]
},
}
}
})
const output = JSON.parse(solc.compile(input));
const interface = output.contracts['lottery.sol'].Lottery.abi;
const bytecode = output.contracts['lottery.sol'].Lottery.evm.bytecode.object;
module.exports = {
interface,
bytecode,
};
after that export this to deploy.js file
const HDwalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const {interface,bytecode}= require('./compile.js');
const provider = new HDwalletProvider(
'',
'https://ropsten.infura.io/v3/9ba5113757f648aaaab4d53e65898119'
);
const web3 = new Web3(provider);
const deploy = async()=>{
const accounts = await web3.eth.getAccounts();
console.log(accounts);
console.log("contract is deployed by manager with address",accounts[0]);
const result = await new web3.eth.Contract(interface)
.deploy({data : '0x'+bytecode})
.send({gas : '2000000' , from : accounts[0]});
console.log('contract deployed to address ', result.options.address);
}
deploy();
finally, show error JSON interface error Please help me,I am just a beginner at web3.js.I follow old tutorial to know the workflow But it does not match with updated versions here is depend
"dependencies": {
"next": "^11.1.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.6",
"truffle-hdwallet-provider": "^1.0.17",
"web3": "^1.5.2"
}
I need someone help to get deployed address to set here lottery.js file
import web3 from './web3.js';
const address = '';
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"enterLottery","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"participants","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pickWinner","outputs":[],"stateMutability":"nonpayable","type":"function"}];
export default new web3.eth.Contract(abi,address);
thanks you
ANSWER
Answered 2021-Sep-21 at 17:11in compile.js
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface
module.exports = output.contracts["Lottery.sol"]["Lottery"];
in deploy.js
const { abi, evm } = require("./compile");
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install truffle
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page