how can i pass constructor values when deploying through truffle? - constructor

How can I deploy a smart contract with constructor predefined parameters values, I am using truffle, ganache!!
constructor (uint256 _targetAmount, uint256 _setDeadline) public {
totalAmount = _targetAmount;
deadline = block.timestamp + _setDeadline;
minDepositAmount = 1 ether;
manager = payable(msg.sender);
}

You can pass the constructor params after the first argument of deployer.deploy().
deployer.deploy(MyContract, targetAmount, setDeadline);

Related

Solidity 0.5.1, when creating a contract object, why do we have to pass the token to that contract's constructor even if there is no constructor

Here is the code:
pragma solidity 0.5.1;
contract ERC20Token{
string public name;
mapping(address => uint256) public balances;
function mint() public{
balances[tx.origin] += 1;
}
}
contract MyContract {
address payable wallet;
address public token;
constructor(address payable _wallet, address _token) public {
wallet = _wallet;
token = _token;
}
function() external payable {
buyToken();
}
function buyToken() public payable{
ERC20Token _token = ERC20Token(address(token));
_token.mint();
wallet.transfer(msg.value);
}
}
Process:
First, we are getting the ERC20Token contract address by deploying the ERC20Token contract in the first place.
Secondly, MyContract constructor takes (a wallet address and the ERC20Token contract address) as two parameters.
Then, we create a ERC20Token contract object from this line
ERC20Token _token = ERC20Token(address(token));
I got confused by how this line worked. Even the ERC20Token contract does not contain any constructor, where the above code passes the token as a parameter to the ERC20Token constructor.
If i delete the token parameter from the above code:
ERC20Token _token = ERC20Token();
I will get an error called
Exactly one argument expected for explicit type conversion
Could anyone explain to me why this happens in solidity?
Without the new keyword, you're making a pointer to an already deployed instance of the ERC20Token contract, passing its address in the argument. Since the contract is already deployed and the constructor has been already executed, you do not pass its constructor params.
// address of existing instance
ERC20Token _token = ERC20Token(address(token));
With the new keyword, you'd be deploying a new instance of ERC20Token, specifying its constructor params. Its address is then available by typecasting the variable to address type.
// creating new instance
// passing constructor params (in your case empty)
ERC20Token _token = new ERC20Token();
// address of the newly deployed contract
address tokenAddress = address(_token);

ERC721 contract deployed with create2 stops working after a particular function is called

So I'm working on an NFT marketplace smart contract and one of the features in this marketplace allows users to deploy their own collection (this is basically a smart contract that extends the ERC721 specification). For this, I'm leveraging the create2 opcode. It deploys well while testing on the testnet (except for the insanely huge gas requirement) but the problem is, I can only call a function once in this contract. This is the contract that extends ERC721:
pragma solidity ^0.8.0;
import '#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
import '#openzeppelin/contracts/token/ERC721/IERC721.sol';
import '#openzeppelin/contracts/security/ReentrancyGuard.sol';
import '#openzeppelin/contracts/utils/Counters.sol';
import './interfaces/IDeployableCollection.sol';
contract DeployableCollection is IDeployableCollection, ERC721URIStorage, ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address public _collectionOwner;
bytes32 public _category;
address payable public _paymentReceiver;
string public _collectionURI;
mapping(address => uint256) public lastMintedForIDs;
constructor(
string memory name_,
string memory symbol_,
address collectionOwner_,
string memory category_,
address paymentReceiver_,
string memory collectionURI_
) ERC721(name_, symbol_) {
_collectionOwner = collectionOwner_;
_category = keccak256(abi.encode(category_));
_paymentReceiver = payable(paymentReceiver_);
_collectionURI = collectionURI_;
}
function mintFor(string memory _tokenURI, address to) external nonReentrant returns (uint256 _tokenId) {
_tokenIds.increment();
_tokenId = _tokenIds.current();
_mint(to, _tokenId);
_setTokenURI(_tokenId, _tokenURI);
lastMintedForIDs[to] = _tokenId;
}
}
This is the line that deploys the contract:
function deployCollection(
string memory name_,
string memory symbol_,
string memory category_,
address paymentReceiver_,
string memory _collectionURI
) external payable nonReentrant {
uint256 _fee = _utilityToken != address(0) && IERC20(_utilityToken).balanceOf(_msgSender()) >= _requiredHold
? _collectionDeployFeeInEther.sub((uint256(_percentageDiscount).mul(_collectionDeployFeeInEther)).div(100))
: _collectionDeployFeeInEther;
require(msg.value >= _fee, 'FEE_TOO_LOW');
bytes memory _byteCode = abi.encodePacked(
type(DeployableCollection).creationCode,
abi.encode(name_, symbol_, _msgSender(), category_, paymentReceiver_, _collectionURI)
);
bytes32 _salt = keccak256(abi.encode(name_, _msgSender()));
address _collection;
assembly {
_collection := create2(0, add(_byteCode, 32), mload(_byteCode), _salt)
}
emit CollectionDeployed(_collection, _msgSender(), block.timestamp, name_, category_, symbol_);
}
Now this works fine, except once I call mintFor and an NFT gets minted, the contract stops working. It shows a total supply of zero (0) on the block explorer even though an NFT has been created (I'm only able to create an NFT with an ID of 1). I also am not able to call any function again as it raises an exception (the cause of which is unknown). This is the line in the factory contract that does the actual minting:
function mintNFT(
address collection,
string memory tokenURI_,
address _for
) external payable nonReentrant returns (bool) {
uint256 _fee = _utilityToken != address(0) && IERC20(_utilityToken).balanceOf(_msgSender()) >= _requiredHold
? _mintFeeInEther.sub((uint256(_percentageDiscount).mul(_mintFeeInEther)).div(100))
: _mintFeeInEther;
require(msg.value >= _fee, 'FEE_TOO_LOW');
address _paymentReceiver = IDeployableCollection(collection)._paymentReceiver();
uint256 _feeForOwner = (uint256(_percentageForCollectionOwners).mul(_fee)).div(100);
_safeMintFor(collection, tokenURI_, _for);
_safeTransferETH(_paymentReceiver, _feeForOwner);
uint256 _tokenId = IDeployableCollection(collection).lastMintedForIDs(_msgSender());
emit Mint(collection, _tokenId, block.timestamp, tokenURI_, _msgSender());
return true;
}
I'm guessing an optimization with a runs of 1 is applied upon deployment using create2 (forgive me if this is stupid) but I also think it isn't likely as I'm also watching for events on the smart contract with a Nodejs back-end and I'm able to call '_collectionURI()' when the event data is propagated to my back-end app and this is before calling mintFor. I'm confused! Please help!
This is a link to the contract info on the explorer: https://testnet.bscscan.com/token/0x6dd5bd0072cdc5e8c24f262a9631c175bc2356a0

contract to trade Usdt To Dai ON n on sushiswap on kovan testneT keeps failing

pragma solidity >=0.6.0 <0.7.0;
contract unisimple {
event unirouterAddress(address);
event suishirouterAddress(address);
using SafeMath for uint256;
address immutable factory;
IUniswapV2Router01 public immutable sushirouter ;
// IERC20 public TOKEN0_ERC20;
uint deadline;
//IERC20 public TOKEN1_ERC20;
constructor(address _factory,IUniswapV2Router01 sushirouter_ ) public {
factory = _factory;
sushirouter = IUniswapV2Router01(address(sushirouter_));
emit suishirouterAddress(address(sushirouter_));
deadline = block.timestamp + 300;
} // constructor
function arbitrage(address tokenin , address tokenout, uint Tradeamount) public {
address[] memory path = new address[](2);
path[0] = tokenin ;
path[1] = tokenout ;
IERC20 TOKEN0_ERC20 = IERC20(tokenin); // ierc20 instance of the contract
TOKEN0_ERC20.approve(address(sushirouter),Tradeamount);
uint amountRequired = sushirouter.getAmounsIn(Tradeamount, path)[0]; =
sushirouter.swapExactTokensForTokens(Tradeamount, amountRequired , path, address(this), deadline ); /* interacting with router to trade tokens in paths */
}
}
the code above doesn'twork
although it does deploy to the kovan testnet
not sure why though . Really need help with this , cant seem to make this work . This would be extremely appreciated .

How to declare constants in Solidity

I am really new to Solidity and smart contracts and would really appreciate some help. I am following a tutorial and this is the exact code they use. But when I compile the code I get this error:
ParserError: Expected primary expression.
address public constant approver = ;
pragma solidity ^0.6.0;
contract ApprovalContract {
address public sender;
address public receiver;
address public constant approver = ;
function deposit(address _receiver) external payable {
require(msg.value > 0);
sender = msg.sender;
receiver = _receiver;
}
function viewApprover() external pure returns(address) {
return(approver);
}
function approve() external {
require(msg.sender == approver);
receiver.transfer(address(this).balance);
}
}
The constant needs to be initialized
address public constant approver = YOURADDRESS;
There are 2 types of constant variables in Solidity:
Constants: a variable that is hardcoded in the smart contract and that you cannot change the value
Immutables: variables you can only define the value in the constructor and that cannot be updated afterwards
Here is an example:
uint256 public constant EXAMPLE_NUMBER = 123;
unit256 public immutable EXAMPLE_NUMBER_2;
constructor(uint256 _number) {
EXAMPLE_NUMBER_2 = _number;
}
You can read more about it here.

How Do I Add A checkBalance Function To This ERC20 Smart Contract

I Need To Know The Balance Of This Token After I Deploy It In Remix Ethereum Firefox. I Want To Know Where Do I Add The checkBalance Function. Plz Help Guys. This Is My First ERC20 Smart Contract.
pragma solidity ^0.5.0;
contract TusharCoin {
uint256 public totalSupply;
string public name;
string public symbol;
uint32 public decimals;
address public owner;
mapping(address => uint256 ) balances;
event Transfer(address to, uint256 amount);
constructor () public {
symbol = "TUSHAR";
name = "TusharCoin";
decimals = 5;
totalSupply = 100000000000;
owner = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(msg.sender, totalSupply);
}
}
Your token currently isn't an ERC20 token as it doesn't fully implement the ERC20 standard yet.
To just add a balanceOf function to your existing contract you can add the following:
function balanceOf(address account) public view returns (uint256) {
return balances[account];
}
If you are creating your own ERC20 implementation then you should consider using SafeMath, see the documentation for details: https://docs.openzeppelin.com/contracts/2.x/utilities#math
If you are creating ERC20 tokens you may want to look at the OpenZeppelin Contracts implementation to see if this meets your needs. See the documentation for details: https://docs.openzeppelin.com/contracts/2.x/tokens#ERC20
An example ERC20 Token that you can deploy with Remix inheriting from the OpenZeppelin Contracts implementation is below using your specified name, symbol, decimals and totalSupply:
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC20/ERC20Detailed.sol";
contract Token is ERC20, ERC20Detailed {
constructor () public ERC20Detailed("Tushar Token", "TUSHAR", 5) {
_mint(msg.sender, 1000000 * (10 ** uint256(decimals())));
}
}
If you have questions on using OpenZeppelin you can ask in the Community Forum: https://forum.openzeppelin.com/
Disclosure: I am the Community Manager at OpenZeppelin
Below, I have mention checkBalance function. In ERC20 standards checkBalance function to be stated as a balanceOf function.
In function, view means one can only read not write
function balanceOf(address accountAddress) public view returns (uint256) {
return balances[accountAddress];
}
Full source code.
pragma solidity ^0.5.0;
contract TusharCoin {
uint256 public totalSupply;
string public name;
string public symbol;
uint32 public decimals;
address public owner;
mapping(address => uint256 ) balances;
event Transfer(address to, uint256 amount);
constructor () public {
symbol = "TUSHAR";
name = "TusharCoin";
decimals = 5;
totalSupply = 100000000000;
owner = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(msg.sender, totalSupply);
}
function balanceOf(address accountAddress) public view returns (uint256) {
return balances[accountAddress];
}
}
If you want whole code for ERC20. Let me know.