Solidity – How to Send Array of Structs as Arguments

arrayssoliditystruct

I want to send to my contract an array of currency and its price so it will store it:

pragma solidity ^0.4.24;

contract ExchangeContract {
    enum CurrencyType { USD, TWOKEY, BTC, ETH, DAI, USDT, TUSD, EUR, JPY, GBP}

    mapping(uint256 => CurrencyPrice) public priceByCurrencyType;

    struct Price{
        uint price;
        uint decimals;
    }

    struct CurrencyPrice{
        uint currencyInt;
        Price price;
    }

    function updatePrices(CurrencyPrice[] memory _array) public {
        for(i=0; i<_array.length; i++){
            priceByCurrencyType[_array[0][0]]=_array[0][1];
        }
    }
}

as I saw in the answer here – Passing in an array of complex structs
its suggest to send one at a time and not worry about multiple calls.

So went back to my question, it does not have to be a struct – is there a way to send a bulk of data, structures parse it in the function so it will fit into one call.

Best Answer

This compiles for me:

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract ExchangeContract {
  enum CurrencyType { USD, TWOKEY, BTC, ETH, DAI, USDT, TUSD, EUR, JPY, GBP}

  mapping(uint256 => CurrencyPrice) public priceByCurrencyType;

  struct Price{
    uint price;
    uint decimals;
  }

  struct CurrencyPrice{
    uint currencyInt;
    Price price;
  }

  function updatePrices(CurrencyPrice[] memory _array) public {
    for(uint i=0; i<_array.length; i++){
      priceByCurrencyType[_array[0].currencyInt].price=_array[i].price;
    }
  }
}

I had to add pragma experimental ABIEncoderV2; and fix couple of minor mistakes.

Related Topic