4

How can I initialize the Item struct and assign to a variable?

contract ArbitrableBlacklist {

    enum ItemStatus {
        Absent,                     
        Cleared,                      
    }

    struct Item {
        ItemStatus status;       
        uint lastAction;         

    }
}

Testing above (simplified for question) contract using Truffle but I couldn't find the way to initialize the Item struct.

I have tried:

let x = ArbitrableBlacklist.Item({
        status: 0,
        lastAction: 0
      });

And got

TypeError: ArbitrableBlacklist.Item is not a function

Edit: Forgot to mention, I'm writing tests from Javascript.

Ferit
  • 8,692
  • 8
  • 34
  • 59

1 Answers1

2

Check this example to create an instance of a struct in a contract.

pragma solidity ^0.4.22;

contract ArbitrableBlacklist {

    enum ItemStatus {
        Absent,                     
        Cleared                    
    }

    struct Item {
        ItemStatus status;       
        uint lastAction;         

    }

}

contract test{

    ArbitrableBlacklist.Item public item;

    function create() public {
        item = ArbitrableBlacklist.Item({
           status: ArbitrableBlacklist.ItemStatus.Absent,
           lastAction: 0
        });
    }

}

If you are trying to initialize from javascript, then it might not be possible - at least as of now. But you could pass the values of the members of the struct as parameters to the function and create an instance as shown here.

    function create(ArbitrableBlacklist.ItemStatus _status, uint _action) public {
        item = ArbitrableBlacklist.Item({
           status: _status,
           lastAction: _action
        });
    }

For Enum, pass the index 0, 1 etc from javascript

KitKarson
  • 5,211
  • 10
  • 51
  • 73
  • I'm writing tests in Javascript, so yes trying to initialize from javascript. Sorry for not mentioning that. – Ferit Jun 07 '18 at 19:03
  • @ferit, then you can not directly pass a struct object, instead pass struct member data types like integer/string/bool etc ..then in the contract using the parameters, create struct instance. – KitKarson Jun 07 '18 at 19:41
  • So we need a function that initializes the struct in the contract, to be able to initialize the struct by calling that function from Javascript test, right? – Ferit Jun 07 '18 at 19:42
  • @ferit, yes as of now. As Javascript has not idea about your struct – KitKarson Jun 07 '18 at 19:43