How do I call showLottery
to display on my webpage?
Front-End
class App extends React.Component {
state = {
address: '',
lottery: '',
events: '',
}
async componentDidMount() {
await window.ethereum.enable()
this.w3 = new Web3(window.ethereum)
const address = (await this.w3.eth.getAccounts())[0]
this.setState({ address })
this.contract = new this.w3.eth.Contract([
{
"constant": false,
"inputs": [],
"name": "implement",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"name": "_lottery",
"type": "uint256"
}
],
"name": "showLottery",
"type": "event"
},
{
"constant": true,
"inputs": [],
"name": "num",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
], "0xF666108e057d5CA30a962eEf43Ef25ff52b70364")
const lottery = await this.contract.methods.num().call()
this.setState({lottery})
}
async randLottery() {
await this.contract.methods.implement().send({from : (await this.w3.eth.getAccounts())[0]});
}
render() {
return (
<div className="App">
<p>Address KUU: {this.state.address}</p>
<button onClick={this.randLottery.bind(this)}>Rand</button>
<p>Lottery Number: {this.state.lottery}</p>
<p>History Number: {this.state.events}</p>
</div>
);
}
}
Smart Contract
contract testRand {
uint256 public num;
event showLottery(uint256 _lottery);
function rand() private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, now , block.coinbase)))%(10**6);
}
function implement() public {
num = rand();
emit showLottery(num);
}
}
return
at the beginning of functionrandLottery
, and do some debugging to see what it returns when you call it. Being that this function isasync
, you'll have to call it withawait
of course. When you do so, you'll notice that your event is embedded in the response object. See exactly where it is stored within that object, and add in to your webpage code (which you haven't bothered to post here). – goodvibration Nov 15 '19 at 15:47