Передайте String [] в конструктор в Solidity - PullRequest
0 голосов
/ 11 мая 2018

я использую remix IDE для развертывания смарт-контракта и передаю строку [], которая будет содержать имена кандидатов, например [alice, bob] ...

это мой смарт-контракт

pragma solidity ^0.4.18;
// We have to specify what version of compiler this code will compile with

contract Voting {
  /* mapping field below is equivalent to an associative array or hash.
  The key of the mapping is candidate name stored as type bytes32 and value is
  an unsigned integer to store the vote count
  */

  mapping (bytes32 => uint8) public votesReceived;

  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).
  We will use an array of bytes32 instead to store the list of candidates
  */

  bytes32[] public candidateList;


  /* This is the constructor which will be called once when you
  deploy the contract to the blockchain. When we deploy the contract,
  we will pass an array of candidates who will be contesting in the election
  */
  function Voting(string[] candidateNames) public {
        for(uint i = 0; i < candidateNames.length; i++) {
            candidateList[i]= stringToBytes32(candidateNames[i]);

        }

 }
  function totalVotesFor(bytes32 candidate) view public returns (uint8) {

    return votesReceived[candidate];
  }

  function stringToBytes32(string memory source) returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;
    }

    assembly {
        result := mload(add(source, 32))
    }
}


  function voteForCandidate(bytes32 candidate) public {

    votesReceived[candidate] += 1;
  }


}

но у меня возникла эта ошибка, которую я не знал, как решить

UnimplementedFeatureError: Nested arrays not yet implemented.

Может кто-нибудь помочь мне, плз

Ответы [ 3 ]

0 голосов
/ 12 мая 2018

Вы не можете передать строку [] в твердости, но вы можете передать несколько строк!моя идея состоит в том, чтобы передать вашу строку (string1 string2, string3, string4 ....), а затем преобразовать строку в byte32 с помощью этой функции

function stringToBytes32(string memory source)view public returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;
    }

    assembly {
        result := mload(add(source, 32))
    }
}

, а затем поместить преобразованный stringtobyte32 в Byte32 []!

0 голосов
/ 21 июня 2019

Вы можете попробовать

Набор:

function something(bytes32[] _thing) public{
  for(i=0; i<Array.length ; i++){
    StructArray.push({ thing = _thing[i]});
  }
}

Получить:

function getThing()
    public
    returns (bytes32[] memory)
{
    bytes32[] memory addrs = new address[](indexes.length);        
    for (uint i = 0; i < StructArray.length; i++) {
        Struct storage structs = StructArray[array[i]];
        thing[i] = structs.thing;    
    }
    return (thing);
}

исправить это, поскольку это было написано мгновенно для ответа цели

0 голосов
/ 11 мая 2018

Как показывает ошибка, Solidity не поддерживает передачу в массив массивов (a string - это просто байтовый массив).

Из документов Solidity :

Можно ли вернуть массив строк (string []) из функции Solidity?

Пока нет, поскольку для этого требуются два уровня динамических массивов (строка сама является динамическим массивом).).

То, что вы МОЖЕТЕ сделать, это изменить его на массив байтов32 (которые являются строками) и отправить массив hex для ваших параметров:

pragma solidity ^0.4.19;

contract Names {
    bytes32[] public names;

    function Names(bytes32[] _names) public {
        names = _names;
    }

    function get(uint i) public constant returns (bytes32) {
        return names[i];
    }
}

Развернуть с помощью

["0x616c696365000000000000000000000000000000000000000000000000000000","0x626f620000000000000000000000000000000000000000000000000000000000"]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...