Accessing struct fields in Web3 returned by a promise in Truffle

by maurelian   Last Updated August 14, 2019 04:28 AM

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.



Answers 2


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.

Tim Coulter
Tim Coulter
November 30, 2016 21:48 PM

When you want to access Promise object field you could use then such as :

If you call

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

Then you could access real object myEntryObject :

var myEntryObject
myEntry.then(a => myEntryObject = a)
myEntryObject[0]
leo5th
leo5th
August 14, 2019 03:35 AM

Related Questions


Updated February 27, 2018 06:28 AM

Updated February 27, 2019 07:28 AM

Updated April 02, 2018 23:28 PM

Updated July 26, 2018 06:28 AM

Updated September 17, 2018 14:28 PM