Entonces, he estado leyendo MUCHAS páginas sobre eventos en Solidity y cómo interactuar con ellos en la interfaz, pero todavía soy bastante nuevo en esto y parece que ha habido múltiples cambios, ya que muchos sitios que vi usaban métodos obsoletos para Esté atento a los cambios en los eventos de Solidity. Lo tuve funcionando en algún momento, pero de repente dejó de funcionar sin razón aparente.
Intenté esto con todos mis 4 eventos de Solidity, por simplicidad, solo mostraré mi ejemplo con un método
pragma solidity ^0.5.0;
contract Platoonfactory {
event PlatoonCreated(address owner, uint256 platoonId);
uint256 public currentPlatoonID = 1;
uint256 public contractBalance = address(this).balance;
/**
* A platoon has atleast one truck driving in front and 0..n trucks following
*/
struct Platoon {
uint256 platoonId;
address payable owner;
uint costPerMinute;
uint startDate;
uint endDate;
// participants contains all joined trucks inside this platoon
mapping(uint /* index */ => TruckInPlatoon) participants;
uint participantsSize;
}
/**
* A TruckInPlatoon struct describes exactly one truck inside a platoon *besides* the leaders
*/
struct TruckInPlatoon {
uint platoonId;
address truckOwner;
uint startDate;
uint allowedParticipationUntilDate;
uint payedAmountOfWei;
}
// map the owner of a platoon to the unique ID
mapping(address => uint) public platoonOwners;
// map the unique ID to each platoon
mapping(uint => Platoon) public platoons;
/**
* Create a new platoon with required cost to join and the amount of hours in which this platoon is available
*/
function createPlatoon(uint cpm, uint endDate) public returns (uint) {
require(platoonOwners[msg.sender] == 0, "You have already started a platoon");
require(endDate >= 1, "Platoon must at least be available for one hour");
// create a new platoon and push it to the storage
platoons[currentPlatoonID] = Platoon({platoonId: currentPlatoonID, owner: msg.sender, costPerMinute: cpm, startDate: now, endDate: (now + endDate*3600), participantsSize:0});
platoonOwners[msg.sender] = currentPlatoonID;
//Increment current ID
currentPlatoonID++;
// fire event
emit PlatoonCreated(msg.sender, currentPlatoonID);
return currentPlatoonID - 1;
}
}
JavaScript:
App = {
contracts: {},
address: "",
web3js: null,
PlatoonContract: null,
init: function () {
return App.initWeb3();
},
initWeb3: function () {
if (typeof web3 !== 'undefined') {
App.web3js = new Web3(web3.currentProvider);
} else {
App.web3js = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}
return App.initHTML();
},
initHTML: function () {
App.web3js.eth.getAccounts((err, accounts) => {
if (!err) {
document.getElementById("account-id").innerHTML = accounts[0];
App.address = accounts[0];
} else {
console.log(err);
}
});
return App.initContract();
},
initContract: function () {
$.getJSON('../build/contracts/Platoonfactory.json', function (data) {
var PlatoonArtifact = data;
App.contracts.Platoonfactory = TruffleContract(PlatoonArtifact);
App.contracts.Platoonfactory.setProvider(web3.currentProvider);
App.contracts.Platoonfactory.deployed().then(function (instance) {
App.PlatoonContract = instance;
return App.listenFor();
});
});
},
listenFor: function () {
App.PlatoonContract.PlatoonCreated({}, {fromBlock:0, toBlock: 'latest'}).watch(function(err, result) {
if (err) {
console.log(err);
}
if (result) {
console.log(result);
document.getElementById("platoonList").innerText = "ID: " + res.args.platoonId.c[0] + " Owner: " + res.args.owner;
}
});
return App.bindEvents();
},
bindEvents: function () {
$("#btnCreatePlatoon").click(event => {
event.preventDefault();
let cpm = document.getElementById("costPerMinute").value;
let duration = document.getElementById("hoursAvailable").value;
App.PlatoonContract.createPlatoon(cpm, duration);
});
$("#btnContractBalance").click(event => {
event.preventDefault();
App.PlatoonContract.contractBalance().then(result => console.log(result.c[0]));
});
},
};
$(function () {
$(window).load(function () {
App.init();
});
});
El HTML no debería importar en este caso. He estado tratando de arreglar esto desde hace casi una semana y ya comencé a volverme loco porque hay tantas publicaciones desactualizadas. Estaría extremadamente agradecido si uno pudiera finalmente encontrar lo que está mal. Probé el código de Solidity en Remix y todos los métodos funcionaron bien y Ganache incluso reconoció los eventos en la pestaña Contrato, el error parece estar en el punto en el que estoy adjuntando el oyente.
ADICIÓN: estoy usando Truffle, Ganache y Metamask para probar mi DApp
¡Así que finalmente lo arreglé! Parece que el segundo parámetro en el controlador de eventos que especificó fromBlock y toBlock no es compatible con Metamask. Funcionó después de que eliminé el parámetro toBlock. Fragmento de trabajo:
App.PlatoonContract.PlatoonCreated({}, {fromBlock:0}).watch(function(err, result) {
if (err) {
console.log(err);
}
if (result) {
console.log(result);
document.getElementById("platoonList").innerText = "ID: " + res.args.platoonId.c[0] + " Owner: " + res.args.owner;
}
});
ismael
Xore
ismael
Xore