Skip to main content

5 posts tagged with "language-tricks"

View All Tags

· One min read
Rahul Saxena

Convert address to uint and back

This conversion exploits the fact that addresses take up 20 bytes and so does a uint160 (20 * 8).


// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

// The theory behind this is that addresses take up 20 bytes in a word which is equivalent to (20*8) 160 bits and hence should be correctly casted to and from uint160.

contract AddressToUint {

address public targetAddress;
uint256 public targetUint;

function convertAddressToUint(address _targetAddress) external returns(uint256) {
targetAddress = _targetAddress;
targetUint = uint256(uint160(_targetAddress));
return targetUint;
}

function convertUintToAddress(uint256 _targetUint) external returns(address) {
targetUint = _targetUint;
targetAddress = address(uint160(_targetUint));
return targetAddress;
}

}

// 0xabD0127D996A468A79a0a8e88F4D419E40402e95
// 980877587572537262620952019491558306941665029781

· 2 min read
Rahul Saxena

Function Types

For official documentations follow this link.

So, in Solidity, you can pass functions themselves as parameters to other functions. These type of parameters are called function types.

These function types can be used to pass and return functions from function calls.

Example

1. Format of function types is the following:

function (<parameter types>) {internal | external} [pure | view | payable] [returns(<return types>)]

Note : Function types can only be internal or external. Also, the return types cannot be empty if the function in question does not return anything, in this case, completely omit the returns keyword.

· One min read
Rahul Saxena

Code snippets depicting modern Solidity

//SPDX-License-Identifier: MIT

pragma solidity 0.8.14;

contract ModernSolidityFeatures {
TestContract tcInstance = new TestContract();

function modernFunctionSelector() public view returns(bytes4) {
return tcInstance.square.selector;
}

function modernIsContract(address addr) public view returns(bool) {
return (addr.code.length > 0 ? true : false);
}

function conventionalIsContract(address addr) public view returns(bool) {
uint32 sizeOfAddressCodeSection;
assembly {
sizeOfAddressCodeSection := extcodesize(addr)
}
return (sizeOfAddressCodeSection > 0);
}

function conventionalFunctionSelector(string memory functionSignature) public pure returns(bytes4) {
return bytes4(keccak256(bytes(functionSignature)));
}
}

contract TestContract {
uint256 public number;

function square(uint256 a) public pure returns(uint256) {
return a*a;
}
}