In Solidity, can you declare a mapping variable inside function? - function

I have only seen that the mapping variables are declared as storage variables.
I'd like to know if I can declare a mapping variable inside the function in Solidity.

No, its not possible because mappings cannot be created dynamically, you have to assign them from a state variable. Yet you can create a reference to a mapping, and assign a storage variable to it.
Yet, you can encapsulate the mapping in a contract, and use it in another by instantiating a new contract containing that mapping, this is the most approximated way of "declaring" a mapping inside a function.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0 <0.9.0;
contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) public {
balances[msg.sender] = newBalance;
}
}
contract MappingUser {
function f() public returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(address(this));
}
}
Taken form the docs:

Mappings in solidity are always stored in the storage and declared top-level as docs say.
But you declare a mapping inside a function if it refers to a top-level mapping inside a function.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract MappingInFunction {
mapping (uint => string) public Names;
uint public counter;
function addToMappingInsideFunction(string memory name) public returns (string memory localName) {
mapping (uint => string) storage localNames = Names;
counter+=1;
localNames[counter] = name;
return localNames[counter];
// we cannot return mapping in solidity
// return localNames;
}
}
Even though I am not sure what would be the use case but referring to top-level mapping inside addToMappingInsideFunction is a valid syntax.

Related

How to return a struct array in solidity with respect to web3j?

I've a smartcontract in which I've a function getLevels() that returns an array of struct type MLevel, defined at the beginning of smartcontract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
struct MLevel{
address id;
string levelPrize;
uint levelNo;
uint levelCriteria;
}
contract Test{
MLevel[] public mlevels;
function addLevel(uint _levelCriteria, string memory _levelPrize)public payable{
MLevel memory level;
level.id = msg.sender;
level.levelCriteria = _levelCriteria;
level.levelPrize = _levelPrize;
mlevels.push(level);
}
function getLevels() public view returns(MLevel [] memory){
return mlevels;
}
}
The above smartcontract works absolutely fine in Remix ide. But when I try to create its java wrapper class using web3j, wrapper class does not generate and web3j ends with a weird error part 'struct MLevel' is keyword as shown below in the image

Solidity NFT metadata loading issue

I am creating an NFT collection, and am testing on ropsten. I have my NFT metadata on my website for example boredApes.com/tokens/3.json but the issue is the contract goes to boredApes.com/tokens/3 and not the .json part. How should I change to contract to load this metadata. The current solidity function is
function _baseURI() internal pure override returns (string memory) { return "https://boredApes.com/tokens/"; }
The _baseURI() function sets just the beginning of the URI. You need to override the tokenURI() function as well, appending the .json string at the end of the returned URI.
pragma solidity ^0.8;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol";
contract MyCollection is ERC721 {
constructor() ERC721("MyCollection", "MyC") {
_mint(msg.sender, 1);
}
function _baseURI() internal pure override returns (string memory) {
return "https://boredApes.com/tokens/";
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
// the `super` keyword references the parent function of the same name
string memory uri = super.tokenURI(tokenId);
return string(abi.encodePacked(uri, ".json"));
}
}

Solidity: Data location must be "memory" or "calldata" for return parameter in function

I am learning Ethereum dev in Solidity and trying to run a simple HelloWorld program but ran into the following error:
Data location must be "memory" or "calldata" for return parameter in function, but none was given.
My code:
pragma solidity ^0.8.5;
contract HelloWorld {
string private helloMessage = "Hello world";
function getHelloMessage() public view returns (string){
return helloMessage;
}
}
You need to return string memory instead of string.
Example:
function getHelloMessage() public view returns (string memory) {
return helloMessage;
}
The memory keyword is the variable data location.
For those reading this who have similar code, 'memory' may not necessarily be the correct word to use for you. You may need to use the words 'calldata' or 'storage' instead. Here is an explanation:
Memory, calldata (and storage) refer to how Solidity variables store values.
For example:
1. Memory: here is an example using the word 'memory':
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import 'hardhat/console.sol'; // to use console.log
contract MemoryExample {
uint[] public values;
function doSomething() public
{
values.push(5);
values.push(10);
console.log(values[0]); // logged as: 5
modifyArray(values);
}
function modifyArray(uint[] memory arrayToModify) pure private {
arrayToModify[0] = 8888;
console.log(arrayToModify[0]) // logged as: 8888
console.log(values[0]) // logged as: 5 (unchanged)
}
}
Notice how the 'values' array was not changed in the private function because 'arrayToModify' is a copy of the array and does not reference (or point to the array that was passed in to the private function.
2. Calldata is different and can be used to pass a variable as read-only:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
contract CallDataExample {
uint[] public values;
function doSomething() public
{
values.push(5);
values.push(10);
modifyArray(values);
}
function modifyArray(uint[] calldata arrayToModify) pure private {
arrayToModify[0] = 8888; // you will get an error saying the array is read only
}
}
3. Storage: a third option here is to use the 'storage' keyword:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import 'hardhat/console.sol'; // to use console.log
contract MemoryExample {
uint[] public values;
function doSomething() public
{
values.push(5);
values.push(10);
console.log(values[0]); // logged as: 5
modifyArray(values);
}
function modifyArray(uint[] storage arrayToModify) private {
arrayToModify[0] = 8888;
console.log(arrayToModify[0]) // logged as: 8888
console.log(values[0]) // logged as: 8888 (modifed)
}
}
Notice how by using the memory keyword, the arrayToModify variable references the array that was passed in and modifies it.
use string memory instead of string.
storage - variable is a state variable (store on blockchain)
memory - variable
List item - is in memory and it exists while a function is being called
calldata - special data location that contains function arguments, only available for external functions
example code : Data Locations

I get a declaration error in solidity when I create a variable with "var"

I'm trying to create a variable "project" to store data from a mapping but I get "Decalration error, undefined identifier" on project = projects[addr]
function getProjectInfo(address addr) public view returns (string memory name, string memory url, uint funds){
var project = projects[addr];
}```
Use explicit variable type definition:
pragma solidity ^0.5.8;
contract Test
{
struct Project
{
bytes32 name ;
}
mapping (address => Project) projects ;
constructor () public {
}
function getProjectInfo(address addr) public view returns (string memory name, string memory url, uint funds)
{
Project memory project = projects[addr];
// ...
}
}

Returning Struct Array in solidity

This is my contract code. Here I'm trying to store the coordinates of a particular trip. While storing the information contract executing fine. But When I retrieve the data, It should give the array of coordinates. But it is throwing an error.
reason: 'insufficient data for uint256 type'
contract TripHistory {
struct Trip {
string lat;
string lon;
}
mapping(string => Trip[]) trips;
function getTrip(string _trip_id) public view returns (Trip[]) {
return trips[_trip_id];
}
function storeTrip(string _trip_id, string _lat, string _lon) public {
trips[_trip_id].push(Trip(_lat, _lon));
}
}
What I'm missing here. Is there any other way to achieve what I'm trying here?
P.S: I'm new to solidity.
First of returning structs is not supported in Solidity directly. Instead you need to return every individual element in the struct as below.
Function xyz(uint256 _value) returns(uint256 User.x, uint256 User.y)
public {}
But then there’s an experimental feature that will help you with returning struct. All that you need to do is add the following after your first pragma line
pragma experimental ABIEncoderV2;
then continue with your code. That should work with no changes to your code.
An example of abiencoderv2 returning struct can be found at this link
It is not possible in solidity to return struct array.
As jlo said in this link, after version 0.8.0, it is possible to return a struct. jlo describes how to set and return an element of array of struct. Here I describe how to set, reset, and return a struct type variable.
I tested it and my test environment is:
private Ethereum network
Geth version 1.10.9-stable (for private network)
Slocjs Compiler version 0.8.7
web3js version 1.5.1
Note, you have to first define the struct type outside of any function inside the contract.
A supper intuitive example code is as follows:
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract testContract {
struct funcResultType {
uint[] var1;
string[] var2;
string message;
}
funcResultType private funcResult;
function testSetFunc(string memory inputVar) public payable {
funcResult.var1.push(123);
funcResult.var2.push(inputVar);
funcResult.message = "Done!";
}
function testResetFunc() public payable {
delete funcResult; // reset variales
}
function testGetFunc() public view returns (funcResultType memory){
return funcResult;
}
}
The result of the test with Web3js in the console is as follow:
As you can see the whole variables are accessible. I upload its web3js code in Github in this link.