Hot answers tagged

52

Yes, just use fooStruct myStruct = fooStruct(1,2); Or fooStruct myStruct = fooStruct({foo:1, fighter:2}); Or fooStruct memory myStruct; // for temporary data myStruct.figther = 2; // will only write to memory fooStruct storage myStruct = ...; // for persistent data, has to be initialized from a state variable. `storage` is the default and a warning ...


44

Summary Return the fields of the struct as separate return variables. Example I'm running this code in my local dev blockchain using the following command: geth --datadir ~/devdata --dev --nodiscover \ --mine --minerthreads 1 --port 30301 \ --maxpeers 0 --verbosity 3 --rpc console Your web frontend should be able to send transactions to insert ...


34

You can not return a struct because Solidity implements them only as a loose bag of variables, they are not real objects. You can use a solution from this answer: https://ethereum.stackexchange.com/a/3614/264 Update Since 0.4.17 you can use pragma experimental ABIEncoderV2 to return structs. Of course, until the experimental keyword is removed, it's not ...


34

You check that a value is defined in the mapping by checking it is not zero. If an explicit setting of zero has meaning for your application, you need auxiliary data (or structure) to track when a value of zero has been explicitly set. A lightweight approach would be to add a bool property to the struct (say named initialized), and to set it to true when ...


29

You can store structs as the values of your mapping, not as the key. Here is some more info: http://solidity.readthedocs.org/en/latest/types.html#structs struct Funder { address addr; uint amount; } struct Campaign { address beneficiary; uint fundingGoal; uint numFunders; uint amount; mapping (uint => Funder) funders; } uint numCampaigns; ...


28

The former doesn't work because a SomeStruct storage is a pointer to the contract's storage space, and the way Solidity handles storage requires deriving that address from the organization of the structs you're writing it to - that is, its address in storage is directly dependent on the variable you're going to store it in. Without knowing what variable it's ...


25

One way is to check for the length of a String: if (bytes(m1[msg.sender]).length != 0 && bytes(m2[msg.sender].someString).length != 0) // do your thing See the answer I posted here


25

Yes, delete user[someAddress]; will work with structs that do not contain a mapping. For this question, because name and nickname are not mappings, they will be deleted (set to zero) automatically: there is no need to do something like "delete user[someAddress].name". http://solidity.readthedocs.io/en/develop/types.html#delete if you delete a struct, it ...


21

Under most circumstances, data structures, even complicated ones, should be structs. Here are some reasons to choose structs: Contracts are more expensive. You'll have to pay for the contract's creation initially, and every time you access it, you'll need to pay for a call to another contracts. This is much, much more expensive than a sha3 for a lookup ...


20

Update Sep 18 2018 I just re-tested and the following works: pragma solidity ^0.4.25; contract Test { struct User{ uint256 uuid; bytes32 first_name; bytes32 last_name; bytes32 sex; bytes32 age; bytes32 birth_day; bytes32 addr; bytes32 mail_address; bytes32 phone_number; } ...


17

The following will work: contract Test { struct Object { uint a; string b; string[] c; mapping(uint => uint) d; } Object field; function Test() { field = Object({ a: 1, b: "abc", c: new string[](0) }); } }


16

There is no need to initialize storage arrays in Solidity. Only memory arrays has to be initialized before usage. So in your case, no need to initialize x inside Bar as long as you are not assigning a value to one of the x indexes inside your foobar. Actually, making initialization in your code will consume gas for no reason. The following code works well ...


12

Some issues: The compiler does not yet support copying memory struct arrays to storage, so things[id] = thing; will fail. Thing thing; will initialize thing to a Thing with thing.items set to an empty array, so there's no need to use the constructor at all. Since all elements of mappings come pre-initialized to their "zero" values, there's no need to ...


10

You could just store the index of the mapping in an array. uint[] indexes; mapping (uint => uint) example; function add(uint x){ example[indexes.length] = x; indexes.push(indexes.length); } Then just iterate over the array index as key. if you want custom unordered keys, it's the same. You would just need to pass the key in the add function ...


10

I suppose customStruct is a struct with timestamp property. Then your code should work. However here my test scenario: import "dapple/test.sol"; contract MyTest is Test { struct Struct { uint timestamp; } // Mapping test mapping(uint => mapping(uint => uint)) mymap; mapping(address => mapping(uint => Struct[])) someName; ...


10

You can store a struct in a struct. pragma solidity ^0.4.11; contract Nest { struct IpfsHash { bytes32 hash; uint hashSize; } struct Member { IpfsHash ipfsHash; } mapping(uint => Member) members; function addMember(uint id, bytes32 hash, uint size) public returns(bool success) { members[id].ipfsHash.hash = hash; ...


9

You currently cannot return structs in Soldity as the answer to the question that you linked correctly outlines. But you can take your struct apart and return the individual elements (Solidity does support multiple return values): function getAssetStructById(uint256 assetId) constant returns ( uint256 assetId, uint256 next, uint256 prev, uint256 ...


8

Yes, you can. For example, in the solidity code below. There is a struct User that has a mapping of friends, from address to another struct Friend. Then there's a mapping of users, from address to User [note that User is a struct]. struct Friend { string name; string email; string phoneNumber; } struct User { string name; string email;...


8

Question is possibly a duplicate of this: What is the zero, empty or null value of a struct? There are a few ways. You can check a value if you're sure it implicitly indicates a set/not set condition. if(tx.to > 0) {} // the address is set You can be explicit if you prefer: struct Transaction { address to; uint value; bytes data; ...


8

Source: https://github.com/su-squares/ethereum-contract/blob/master/contracts/SuNFT.sol Here you go: Algorithm: uint[] assets; mapping(uint=>uint) indexOfAsset; function removeAssetFromArray(uint _assetToDelete) { uint index = indexOfAsset[_assetToDelete]; if (!index) return; if (assets.length > 1) { assets[index] = assets[assets.length-...


8

By using abi.encodeWithSignature, your struct successfully to the low-level call. The code below is modified based on what you provided. pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; library Test { struct TStruct { int x; int y; } } contract A { function SetStruct (Test.TStruct sin) public returns (int) { Test.TStruct ...


7

There's really no such thing as "empty". An uninitialized index of the mapping is simply equal to the " zero" value of the proper type. To check if a value has been assigned, just check if balances[msg.sender]== 0. If a user accesses the contract, but the balance should be 0, you can use a address => int256 mapping, and use -1 for 0 balances


7

The other answer which didnt work brought me on track to find it out myself: contract testStruct { struct stru{ string[] s; } stru myStru; function add(string s) { myStru.s.push(s); } function getAt(uint256 i) constant returns (string s) { s = myStru.s[i]; } }


7

I would go with: if (reg[sender].first != "" || reg[sender].last != "") { throw; }


6

Here's an example from my work: function getChannel(bytes32 channelId) returns( address addr0, address addr1, uint8 phase, uint challengePeriod, uint closingBlock, bytes state, uint sequenceNumber, bytes evidence0, bytes evidence1 ) { addr0 = channels[channelId].addr0; addr1 = channels[channelId].addr1; phase =...


6

In the constructor for Student, the mapping studentNames and the uint ID are not initialised. If you try to do stu s = studentNames[ID], you will just get 0. You want something like the following: contract Student{ struct stu{ string name; uint age; bool tookTest; } mapping(uint => stu) public studentNames; ...


6

The void key values in a mapping are set virtualy to 0 for example if there is no voter with the adddress 0X01 if we request the key value corresponding to this address we will get : bool voted: false uint256 vote: 0 uint256 votetime: 0 bytes32 remark: 0x0000000000000000000000000000000000000000000000000000000000000000 so depending on how the voting ...


6

A contract is created (also called deployed) by sending the contract's byte code to Ethereum address 0x0 (that is, the to field will be 0x0). If the contract creation succeeds, then (and only then) will there be a value in the contractAddress field of the transaction's receipt. That value will the the address of the newly created contract. Subsequent calls ...


6

There is no way to have a default value for a state variable, especially for a mapping as there is no way for the EVM to know prior to assignment where it will be stored. The next best thing for setting up storage values is the constructor. So there is no way to assign default struct values in Solidity, however in analysing compiled traces of the following ...


6

Update: See here. We can return structs but only for internal calls. Returning structs in new version in Solidity In this snippet, function tryIt() returns true after a successful compile. It's just making an internal call (success). getAssetStructById() fails when called from outside. pragma solidity 0.4.17; contract Test { enum assetState{...


Only top voted, non community-wiki answers of a minimum length are eligible