Gas savings on hardcoded addresses vs setting in constructor - optimization

In contracts I often come along hardcoded constant address such as WETH:
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
I am now curious, whats the difference between this style and the initialization by the constructor, e.g.:
address internal immutable WETH;
constructor(uint256 _WETH){
WETH = _WETH;
}
Especially, in terms of security and gas used during deployment and runtime.

In terms of gas and security there is not much of a difference in the two approaches. I verified this by writing two simple contracts on remix and using the debugger mode. If you closely look at the screenshots attached for the two approaches you will see the gas limit is almost equal (although the constructor approach has a little higher value but almost equal).
Now talking about why constructors could be used to initialize value, it is used when you want to deploy a contract from another contract or use a deployment script to publish a common code but with different values for some variables (The most common use case of constructors in programming in general - Make different objects of same class but with different configuration, that applies here as well)
First contract (hardcoded value):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Debugging2 {
uint256 counter = 200;
}
Second contract (constructor initialization):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Debugging {
uint256 counter;
constructor(uint256 _counter) {
counter = _counter;
}
}
Screenshot of first contract (hardcoded value) debugger :
Screenshot of second contract (constructor initialization) debugger :

Related

Why Openzeppelin ERC721 defines two 'safeTransferFrom'?

Source code:
/**
* #dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* #dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
Hi everyone.
While reading the Openzeppelin ERC-721 source code, I found that it defined two safeTransferFrom method with different implementations.
I am curious why it's made in this way. Could anyone help me with it?
Many thanks.
It follows the ERC-721 standard that also defines two functions with the same name - but with different input params. Generally in OOP, this is called function overloading.
As you can see in the OpenZeppelin implementation, when you call the function without the data param, it passes an empty value.
I can't speak for the authors of the standard, but to me it seems like a more developer friendly approach compared to having to explicitly pass the empty value, since Solidity doesn't allow specifying a default param value.

ERC20 totalSupply Best practice

Best Practice Advice:
Is it acceptable to override the totalSupply() of an ERCToken if you're using a different variable to hold some of the supply and not holding all the tokens in the totalSupply variable directly?
example:
...
uint _extraSupplyForGivingAway = 1e27; //decimal 1e18 * 1M just an example
function totalSupply() public view override returns(uint totalSupply){
totalSupply = super.totalSupply() + _extraSupplyForGivingAway);
return (totalSupply);
}
The total value of the contract is not only the _totalSupply, it's also the _totalSupply and the extra tokens.
Question: Does the community and/or exchanges find this acceptable or not?
There are two different issues here. One is, are you conforming to the EIP-20 (ERC-20) standard in a way that will be understood by the community-at-large? Another is, is this a reasonable implementation for your business logic?
The latter issue is out-of-scope here since you haven't really provided enough information. So I will address the first, which is what I believe you wanted to know.
The reason I spell this out is because you fixate on implementation details but ERC20 is an interface standard, so it doesn't by-and-large dictate how things ought to be implemented.
In the case of totalSupply, all the standard says is:
totalSupply
Returns the total token supply.
function totalSupply() public view returns (uint256)
If it's not clear what that means, the EIP does link to the OpenZeppelin contract as an example implementation, which has:
/**
* #dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
So as long as the total number of minted tokens is returned, you are fine. It doesn't matter if you internally have it computed as the sum of two other private variables. I do have some lingering doubts about your implementation from what you wrote, but as I said, that's out-of-scope :)
I hesitate to add this and possibly muddy the waters but.. "tokens in existence" is somewhat ambiguous. Sometimes people have their burn function do an actual transfer to the zero address (not just the event), effectively removing them from the circulating supply, and adjust the total supply accordingly. So their totalSupply will then return the number of tokens held only by non-zero addresses. Block explorers may or may not account for this. I would avoid doing this unless you absolutely know what you're doing.

Questions about ERC-20 tokens

I know what they are but I don't quite understand the raw fundamentals of how they're expressed, recorded, and sent on the blockchain.
If tokens are just smart contracts, then how do you send them exactly? How do those token transactions get recorded on the blockchain? What are the raw fundamentals of how a token is created from a smart contract?
Token balance of an address is recorded on the token contract. A token contract is considered a contract that meets all criteria required by the ERC-20 standard, such as implementing the specified interface and emitting events when required by the standard.
Balances are mostly stored in the form of a mapping where the key is the holder address, and the value is the amount of tokens they own, because it's convenient for most cases. However the standard does not specify and particular way so if it suits your needs, you can store the balances in an array, or any other way.
Token transfer is an interaction with the token contract transfer() function (standardized in ERC-20), which should perform validations (my example skips that for simplicity), update the local variables storing balances, and emit the (again standardized) Transfer event.
Offchain apps, such as Etherscan, can listen to these events and update their own database of token holders. This allows them to filter all tokens by an address in their own database and show them on the website. But again, this is not part of the blockchain data, it's an aggregated database built on top of blockchain.
Example: Address 0x123 owns 1 USDT and 2 DAI. The USDT balance is stored in the USDT contract, and the DAI balance is stored in the DAI contract. There's no global property of the 0x123 address keeping track of its tokens.
contract USDT {
// for the key `0x123`, the value is 1 (and decimals)
mapping (address => uint256) balances;
event Transfer(address indexed from, address indexed to, uint256 amount);
function transfer(address to, uint256 amount) public {
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
}
}
contract DAI {
// for the key `0x123`, the value is 2 (and decimals)
mapping (address => uint256) balances;
}
For a full code example, see the OpenZeppelin implementation, and their docs related to this specific implementation. Just to clarify, OpenZeppelin is an organization that publishes open source code, but you can also build your own implementation of the standard or use another one, if that fits your use case.

I'm creating a smart contract to interact with specific NFTs. Is there a function to filter a specific NFT contract address?

I wanted to create a smart contract that only interacts with a specific NFT. I know there is a "tokenID" attribute I don't think this is unique. Cronoscan shows multiple collections that have the same tokenIDs. Does anyone know if smart contracts can filter based on a contract address? I'd like to accomplish this with as little gas as possible.
Sorry if this is a basic question but I've Googled and searched this message board for the answer but was not able to find on other that someone trying to sell their service.
I Google and search Stack Overflow but could not find an answer.
Yes, each contract will have their own set of ids and therefore they are not unique between contracts only unique for each contract.
This checks if the code size for the address is > 0. This will have to be implemented on a new contract or you will have to find an existing contract with this functionality to view/execute it
function isContract(address addressValue) public view returns (bool) {
uint size;
assembly { size := extcodesize(addressValue) }
return size > 0;
}
Also notice this is a view function and for that reason wont cost any gas to execute.
In regards to someone selling it as a service, you can get it yourself by just deploying this contract on whatever main net you want (by the sounds of it Cronos).
'// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract ContractIdentifier{
function isContract(address addressValue) public view returns (bool) {
uint size;
assembly { size := extcodesize(addressValue) }
return size > 0;
}
}

Solidity Blockchain - Memory,Storage and mapping explanation brief explanation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Kindly someone can explain me about mapping,storage and memory breifly with examples ? I am not clear with some articles
Thanks!!
STORAGE AND MEMORY
Storage and Memory keywords in Solidity are analogous to Computer’s hard drive and Computer’s RAM. Much like RAM, Memory in Solidity is a temporary place to store data whereas Storage holds data between function calls. The Solidity Smart Contract can use any amount of memory during the execution but once the execution stops, the Memory is completely wiped off for the next execution.
Whereas Storage on the other hand is persistent, each execution of the Smart contract has access to the data previously stored on the storage area.
Every transaction on Ethereum Virtual Machine costs us some amount of Gas. The lower the Gas consumption the better is your Solidity code. The Gas consumption of Memory is not very significant as compared to the gas consumption of Storage. Therefore, it is always better to use Memory for intermediate calculations and store the final result in Storage.
State variables and Local Variables of structs, array are always
stored in storage by default.
Function arguments are in memory.
Whenever a new instance of an array is created using the keyword
‘memory’, a new copy of that variable is created.
Changing the array value of the new instance does not affect the
original array.
Example#1: In the below example, a contract is created to demonstrate the ‘storage’ keyword.
pragma solidity ^0.4.17;
// Creating a contract
contract helloGeeks
{
// Initialising array numbers
int[] public numbers;
// Function to insert values
// in the array numbers
function Numbers() public
{
numbers.push(1);
numbers.push(2);
//Creating a new instance
int[] storage myArray = numbers;
// Adding value to the
// first index of the new Instance
myArray[0] = 0;
}
}
Output:
When we retrieve the value of the array numbers in the above code, Note that the output of the array is [0,2] and not [1,2].
Example#2: In the below example, a contract is created to demonstrate the keyword ‘memory’.
pragma solidity ^0.4.17;
// Creating a contract
contract helloGeeks
{
// Initialising array numbers
int[] public numbers;
// Function to insert
// values in the array
// numbers
function Numbers() public
{
numbers.push(1);
numbers.push(2);
//creating a new instance
int[] memory myArray = numbers;
// Adding value to the first
// index of the array myArray
myArray[0] = 0;
}
}
Output:
When we retrieve the value of the array numbers in the above code, Note that the output of the array is [1,2]. In this case, changing the value of myArray does not affect the value in the array numbers, this because the function stopped, the the array wasn't saved
MAPPINGS
Mappings are a totally different thing.
These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type.
Mappings are mostly (but not limited to) used to associate the unique Ethereum address with the associated value type.
The mappings are quite similar to an array
mapping(key => value) <name>;
Example#1:
pragma solidity ^0.4.17;
// Creating a contract
contract helloGeeks
{
// Initialising mapping of user balance
mapping(address => uint) balance;
// Function to insert user balance
function Insert(address _user, uint _amount) public
{
//insert the amount to a specific user
balance[_user] = _amount
}
//function to view the balance
function View(address _user) public view returns(uint)
{
//see the value inside the mapping, it will return the balance of _user
return balance[_user];
}
}