Skip to content

Commit

Permalink
Include contract details in the UI.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jim Posen committed Oct 27, 2017
1 parent 43b6430 commit ce54285
Show file tree
Hide file tree
Showing 6 changed files with 232 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Next, in order to specifiy to MyEtherWallet which contract you want to look at,

You should now see a drop down with a list of methods you can call. For example, if you select "pressTimes", copy your Metamask account address into the box, and click "Read", it will tell you how many seconds your press was from the one before it. You can even try executing the "press" method.

<img src="images/myetherwallet-access-contract.png" width="50%">
<img src="images/myetherwallet-access-contract.png" width="100%">

### The source code

Expand Down
2 changes: 1 addition & 1 deletion the-button/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
<script src="/assets/app.bundle.js"></script>
</head>
<body>
<div id="main"></div>
<div id="main" data-contract-address="0x8a24b65bcf87bf424aee1ac3b027c8873483684b"></div>
</body>
</html>
2 changes: 1 addition & 1 deletion the-button/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import React from 'react';
import ReactDOM from 'react-dom';

import ApplicationView from './components/application';
import {initialize, onPress} from './contract';
import {initialize, onPress} from './state';


class Application extends React.Component {
Expand Down
34 changes: 33 additions & 1 deletion the-button/src/components/button.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,38 @@ function Timer({remainingTime, totalTime}) {
);
}

export default function BoxView({initialized, error, pressTime, remainingTime, totalTime, onPress, waiting}) {
class ContractInfo extends React.Component {
constructor(props) {
super(props);
this.state = {isShown: false};
}

onClick(e) {
e.preventDefault();
this.setState(({isShown}) => ({isShown: !isShown})); // Toggle isShown
}

render() {
const {contract} = this.props;
return (
<div className="contract-details">
<a onClick={this.onClick.bind(this)}>
{this.state.isShown ? 'Hide ' : 'Show '} contract details
</a>
<div className={this.state.isShown ? '' : 'hidden'}>
<h4>Contract Address</h4>
<pre><code>{contract.address}</code></pre>
<h4>Contract ABI</h4>
<pre><code>
{JSON.stringify(contract.abi)}
</code></pre>
</div>
</div>
);
}
}

export default function BoxView({initialized, error, pressTime, remainingTime, totalTime, onPress, waiting, contract}) {
let child;
if (initialized) {
let waitingAlert;
Expand All @@ -61,6 +92,7 @@ export default function BoxView({initialized, error, pressTime, remainingTime, t
<Timer remainingTime={remainingTime} totalTime={totalTime}/>
</div>
</div>
<ContractInfo contract={contract}/>
</div>
);
} else if (error) {
Expand Down
192 changes: 192 additions & 0 deletions the-button/src/state.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// web3 is the library used to interact with Ethereum.
import Web3 from 'web3';

const THE_BUTTON_CONTRACT_ABI = [{"constant":true,"inputs":[],"name":"lastPress","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"pressTimes","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"expectLastPress","type":"uint256"}],"name":"press","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"timeLimit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"timeLimit_","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"pressedBy","type":"address"},{"indexed":false,"name":"time","type":"uint256"}],"name":"ButtonPress","type":"event"}];

function web3Connected(setState) {
return new Promise((resolve) => {
let intervalID;

const checkForConnected = () => {
if (!web3.isConnected()) {
setState({error: 'Not connected to Ethereum network'});
} else {
setState({error: null});
clearInterval(intervalID);
resolve();
}
};

intervalID = setInterval(checkForConnected, 500);
});;
}

function calculateRemainingTime(lastPress, totalTime) {
const now = Math.floor(Date.now() / 1000);
let remainingTime = lastPress + totalTime - now;
if (remainingTime < 0) {
remainingTime = 0;
}
return remainingTime;
}

function startCountdown(setState) {
const updateRemainingTime = () => {
setState(({lastPress, totalTime}) => {
return {remainingTime: calculateRemainingTime(lastPress, totalTime)};
});
};
setInterval(updateRemainingTime, 100);
}

function watchPresses(setState) {
const theButton = theButtonContract();
theButton.ButtonPress({}, {fromBlock: 0}, (err, {args: {time}}) => {
if (err) {
console.error(err);
return;
}

setState({lastPress: time.toNumber()});
});
}

function theButtonContract() {
const TheButton = web3.eth.contract(THE_BUTTON_CONTRACT_ABI);
return TheButton.at(window.contractAddress);
}

function transactionConfirmed(txID) {
return new Promise((resolve, reject) => {
const filter = web3.eth.filter('latest');
let returned = false;

filter.watch((err, blockHash) => {
if (returned) {
return;
}

if (err) {
reject(err);
filter.stopWatching();
returned = true;
return;
}

web3.eth.getTransactionReceipt(txID, (err, receipt) => {
if (returned) {
return;
}

if (err) {
reject(err);
filter.stopWatching();
returned = true;
return;
}

if (receipt) {
resolve();
filter.stopWatching();
returned = true;
return;
}
});
});
});
}

export async function initialize(setState) {
// Metamask Chrome extension injects a web3 object into the global data.
if (typeof window.web3 === 'undefined') {
setState({error: 'You need to install Metamask, then reload the page'});
return;
}

// Even though there is a global web3 instance, we don't know what version it
// so we wrap it in our updated web3 library installed with npm.
window.web3 = new Web3(window.web3.currentProvider);

await web3Connected(setState);

try {
const account = web3.eth.accounts[0];
if (!account) {
throw "No Ethereum account connected. You may have to unlock Metamask and reload the page.";
}

const theButton = theButtonContract();

const totalTimePromise = new Promise((resolve, reject) => {
theButton.timeLimit((err, totalTime) => {
if (err) return reject(err);
resolve(totalTime.toNumber());
});
});

const lastPressPromise = new Promise((resolve, reject) => {
theButton.lastPress((err, lastPress) => {
if (err) return reject(err);
resolve(lastPress.toNumber());
});
});

const pressTimePromise = new Promise((resolve, reject) => {
theButton.pressTimes.call(account, (err, pressTime) => {
if (err) return reject(err);
resolve(pressTime.toNumber());
});
});

const [totalTime, lastPress, pressTime] = await Promise.all([
totalTimePromise, lastPressPromise, pressTimePromise
]);

setState({
initialized: true,
contract: theButton,
account: account,
pressTime: pressTime,
lastPress: lastPress,
totalTime: totalTime,
remainingTime: calculateRemainingTime(lastPress, totalTime)
});

startCountdown(setState);
watchPresses(setState);
}
catch (err) {
if (err instanceof Error) {
console.error(err);
err = `Unexpected error: ${err.message}`;
}
setState({error: err});
}
}

export async function onPress(setState, account, lastPress) {
const theButton = theButtonContract();

const txID = await new Promise((resolve, reject) => {
theButton.press(lastPress, {from: account}, (err, txID) => {
if (err) return reject(err);
resolve(txID);
});
});

setState({waiting: true});
await transactionConfirmed(txID);

const pressTime = await new Promise((resolve, reject) => {
theButton.pressTimes.call(account, (err, pressTime) => {
if (err) return reject(err);
resolve(pressTime.toNumber());
});
});

if (pressTime === 0) {
alert("Someone else beat you to it. You can try again when you are ready.");
}

setState({pressTime: pressTime, waiting: false});
}
4 changes: 4 additions & 0 deletions the-button/src/style.less
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ html, body, #main {
.alert-uninitialized {
margin: 0;
}

.contract-details {
margin-top: 30px;
}

0 comments on commit ce54285

Please sign in to comment.