Solidity – Accessing Struct Fields in Web3 Returned by a Promise in Truffle

enssoliditytruffleweb3js

I'm using web3js (via Truffle) to make a call to a contract, to access a struct in a mapping.

mapping (bytes32 => entry) public entries; 

struct entry {
    Mode status;
    Deed deed;
    uint registrationDate;
    uint value;
    uint highestBid;
}

Here is the call:

var myEntry = Registrar.deployed().entries.call("0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4af")

Which returns:

[ { [String: '1'] s: 1, e: 0, c: [ 1 ] },
  '0x0000000000000000000000000000000000000000',
  { [String: '1482956489'] s: 1, e: 9, c: [ 1482956489 ] },
  { [String: '0'] s: 1, e: 0, c: [ 0 ] },
  { [String: '0'] s: 1, e: 0, c: [ 0 ] } ]

Which looks to me like an array, but:

truffle(default)> myEntry;
// [ { [String: '1'] s: 1, e: 0, c: [ 1 ] },
//   '0x0000000000000000000000000000000000000000',
//   { [String: '1482956489'] s: 1, e: 9, c: [ 1482956489 ] },
//   { [String: '0'] s: 1, e: 0, c: [ 0 ] },
//   { [String: '0'] s: 1, e: 0, c: [ 0 ] } ]

truffle(default)> myEntry[0];
// undefined

truffle(default)> myEntry[1];
// undefined

truffle(default)> typeof(myEntry);
'object'

How can I access any of the properties (members?) of this object?

Note: I can't update the contract, it's the ENS' Initial Registrar.

Best Answer

The issue is here:

var myEntry = Registrar.deployed().entries.call("0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4af")

.call() returns a Promise. The Truffle console is "smart" and knows when you write an expression that returns a Promise[1]. When this happens, it will automatically resolve it for you and print out the result, or print out any error that occurred. What you're seeing in the output is the printed out result, and not the actual value of myEntry. Instead, what you need to do is the following.

truffle(default)> var myEntry;
truffle(default)> Registrar.deployed().entries.call(...).then(function(result) {myEntry = result;})
truffle(default)> myEntry

It's a little bit of a hassle but such is life with a console and promise objects.


[1] Note that setting a variable to a Promise in the Truffle console is still interpreted as an expression whose result is the value of the variable.

Related Topic