Как я могу показать на web3j список всех инструкторов, добавленных в мой блокчейн?

Мне нужно показать на html список всех инструкторов, которые настроены в списке

pragma solidity ^0.4.18;

contract Owned {
address owner;

function Owned() public {
    owner = msg.sender;
}
modifier onlyOwner {
   require(msg.sender == owner);
   _;
 }
}

contract Courses is Owned {

struct Instructor {
    uint age;
    bytes16 fName;
    bytes16 lName;
}

mapping (address => Instructor) instructors;
address[] public instructorAccts;

event instructorInfo(
   bytes16 fName,
   bytes16 lName,
   uint age
);

function setInstructor(address _address, uint _age, bytes16 _fName, bytes16 _lName) onlyOwner public {
    var instructor = instructors[_address];

    instructor.age = _age;
    instructor.fName = _fName;
    instructor.lName = _lName;

    instructorAccts.push(_address)-1;
    instructorInfo(_fName, _lName, _age);
}

function getInstructors() view public returns(address[]) {
    return instructorAccts;
}

function getInstructor(address _address) view public returns (uint, bytes16, bytes16) {
    return (instructors[_address].age, instructors[_address].fName, instructors[_address].lName);
}

function countInstructors() view public returns (uint) {
    return instructorAccts.length;
}

}

ОБНОВЛЕНИЕ: мой код web3js

  <script>
       if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

web3.eth.defaultAccount = web3.eth.accounts[1];

var CoursetroContract = web3.eth.contract([
{
    "constant": true,
    "inputs": [
        {
            "name": "_address",
            "type": "address"
        }
    ],
    "name": "getInstructor",
    "outputs": [
        {
            "name": "",
            "type": "uint256"
        },
        {
            "name": "",
            "type": "bytes16"
        },
        {
            "name": "",
            "type": "bytes16"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": true,
    "inputs": [],
    "name": "getInstructors",
    "outputs": [
        {
            "name": "",
            "type": "address[]"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": true,
    "inputs": [
        {
            "name": "_index",
            "type": "uint256"
        }
    ],
    "name": "getInstructorAtIndex",
    "outputs": [
        {
            "name": "",
            "type": "uint256"
        },
        {
            "name": "",
            "type": "bytes16"
        },
        {
            "name": "",
            "type": "bytes16"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": true,
    "inputs": [
        {
            "name": "",
            "type": "uint256"
        }
    ],
    "name": "instructorAccts",
    "outputs": [
        {
            "name": "",
            "type": "address"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": true,
    "inputs": [],
    "name": "countInstructors",
    "outputs": [
        {
            "name": "",
            "type": "uint256"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": false,
    "inputs": [
        {
            "name": "_address",
            "type": "address"
        },
        {
            "name": "_age",
            "type": "uint256"
        },
        {
            "name": "_fName",
            "type": "bytes16"
        },
        {
            "name": "_lName",
            "type": "bytes16"
        }
    ],
    "name": "setInstructor",
    "outputs": [],
    "payable": false,
    "stateMutability": "nonpayable",
       "type": "function"
},
{
    "anonymous": false,
    "inputs": [
        {
            "indexed": false,
            "name": "fName",
            "type": "bytes16"
        },
        {
            "indexed": false,
            "name": "lName",
            "type": "bytes16"
        },
        {
            "indexed": false,
            "name": "age",
            "type": "uint256"
        }
    ],
    "name": "instructorInfo",
    "type": "event"
        }
     ]);

  var Coursetro = 
  CoursetroContract.at('0x13fd9e45bbd7ee860cdfc825839c9dfbd91a36cd');
  var instructorEvent = Coursetro.instructorInfo({}, 'EARLIEST');

instructorEvent.watch(function(error, result) {
    if (result) {
        if (result.blockHash != $("#insTrans").html())
             $("#loader").hide();
         $("#insTrans").html('Block hash: ' + result.blockHash);
        $("#instructor").html(web3.toAscii(result.args.fName) + ' ' + web3.toAscii(result.args.lName) + ' (' + result.args.age + ' Kb)');
    } else {
         $("#loader").hide();
    }
});

Coursetro.countInstructors((err, res) => {
    if (res)
     $("#countIns").html(res.c + ' number of files');
})

$("#button").click(function() {
     //$("#loader").show();
    Coursetro.setInstructor(web3.eth.defaultAccount, $("#age").val(), $("#fName").val(), $("#lName").val(), (err, res) => {
        if (err) {
            $("#loader").hide();
        }
    });
});

Ответы (1)

Чтобы показать список ваших инструкторов, вам нужно добавить еще одну функцию в ваш смарт-контракт:

function getInstructorAtIndex(uint _index) view public returns (uint, bytes16, bytes16) {
    Instructor storage i = instructors[instructorAccts[index]];
    return (i.age, i.fName, i.lName);
}

Затем вам нужно будет развернуть свой смарт-контракт на блокчейне Эфириума. Сначала попробуйте его в тестовой сети, такой как Ropsten. Вы можете управлять с помощью фреймворка Remix и кошелька Metamask. ( https://remix.ethereum.org/ ) ( https://metamask.io/ )

Наконец, вам нужно будет создать приложение. Web3j является основным коннектором и имеет три реализации: javascript, java и scala. Большинство людей используют Web3js ( https://github.com/ethereum/web3.js/ ) для создания Dapps. Таким образом, вы также можете использовать фреймворк Truffle ( http://truffleframework.com ). У Truffle есть несколько шаблонов для быстрой разработки типового проекта.

Надеюсь, я помогу вам. :-)

PS: Вы можете установить свое сопоставление и массив как частные в своем смарт-контракте. Как и у вас, EVM автоматически создаст для них геттеры.

PSS: вы можете установить модификатор «константа» или «чистый» для ваших функций получения.

Большое спасибо, но как мне использовать его с web3js? Я тоже использую узел.
Я обновляю пост кодом web3js
@VictorJoelCuadrosChoez извините, но я не так хорошо знаком с программированием jquery и javascript. И если вы не дадите нам весь контекст, вам будет трудно помочь. Просто найдите информацию о web3js, а также о создании циклов и элементов div с помощью jquery и js. В Интернете вы можете найти полезные примеры того и другого. Удачи :)