solidity – Understanding Mappings and Dynamic Arrays – In-Depth Guide

solidity

I have the following contract:

pragma solidity ^0.4.18;

contract ReferralProgram {
    // referrer => array of referrals
    mapping (address=>address[]) private referrals;

    function becomeReferral(address referrer) public {
        require(referrer != 0x0);
        referrals[referrer].push(msg.sender);
    }

    function getReferrals() public view returns (address[]) {
        return referrals[msg.sender];
    }
}

I call method becomeReferral multiple times from different accounts and specifying the same referrer address (function parameter).

Then I call getReferrals from referrer address and it returns empty array. It is possible use dynamic arrays in mappings? Documentation says:

_ValueType can actually be any type, including mappings.

What am I doing wrong? Thanks.

P.S Testing in remix browser

Best Answer

Your code looks correct. I tested it in Remix and only thing that comes to my mind is the way you pass the address as an argument to becomeReferral(...).

Try adding quotes around the address when you pass it in (e.g. becomeReferral("0xca35b7d915458ef540ade6068dfe2f44e8fa733c") instead of becomeReferral(0xca35b7d915458ef540ade6068dfe2f44e8fa733c).

Whenever I don't add quotes I get your behaviour, however with added quotes the type is correctly parsed to an address and I get the list with all addresses back from getReferrals()

Related Topic