2

I'm having trouble properly understanding Meteor's reactivity and it's relation to contracts.

I've included the Ethereum Meteor packages ethereum:web3 and ethereum:blocks and read that EthBlocks.latest is reactive but my question is, how do I make a contract's function return reactive also? Am I suppose to hook into EthBlocks.latest somehow to run custom callbacks?

In the following DAPP I have a basic getter/setter contract (pingpong.sol), a Meteor template and associated template helpers and events.

Example:

pingpong.sol

contract pingpong {

    string public pong;
    // accessor function:
    // function pong() { return pong; }

    function ping (string val) {
        pong = val;
    }
}

main.html

<head>
  <title>pingpong</title>
</head>

<body>
  <h1>Ethereum DAPP Reactivity</h1>
  {{> pingpong}}
</body>

<Template name="pingpong">
  <h2>PONG - {{pong}}</h2>
  <form class="set-pong">
    <input type="text" name="text" placeholder="Type new pong value"/>
  </form>
</Template>

main.js

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

// private chain
web3 = new Web3(new    Web3.providers.HttpProvider('http://localhost:8546'));

contract = web3.eth.contract([{"constant":false,"inputs":[{"name":"val","type":"string"}],"name":"ping","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"pong","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]);

ppInst = contract.at("0x8c3d23c31de790ac60a483ba47ea1b7fea08d67e");

EthBlocks.init();

Template.pingpong.onCreated(function pongCreated() {
    this.pong = new ReactiveVar(ppInst.pong());
})

Template.pingpong.helpers({
    pong() {
        return Template.instance().pong.get();
    }
})

Template.pingpong.events({
    'submit .set-pong'(event) {
        // Prevent default browser form submit
        event.preventDefault();

        ppInst.ping(event.target.text.value, {from:web3.eth.accounts[0]});

        //clear form
        event.target.text.value = '';
    },
})
1

Found Fabian's example of a simple meteor DAPP with excellent video tutorial and so included this in my code...

$ meteor add session

web3.eth.filter('latest').watch(function(e) {
    if(!e) {
        ppInst.pong(function(e, val) {
            Session.set('pong', val);
        });
    }
});

and changed my templates to:

Template.pingpong.onCreated(function pongCreated() {
        ppInst.pong(function(e, val) {
            Session.set('pong', val);
        });
})

Template.pingpong.helpers({
    pong() {
        return Session.get('pong');
    }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.