Commit fe19f9ea authored by Uciel's avatar Uciel

major code refactor and cleanup

parent 22845601
This diff is collapsed.
import { INITIALIZE_GLOBAL_WEB3 } from '../constants';
export const initializeGlobalWeb3 = (globalWeb3) => ({
type: INITIALIZE_GLOBAL_WEB3,
globalWeb3
})
\ No newline at end of file
import {
WEB3_CONNECTION_SUCCESSFUL,
WEB3_CONNECTION_UNSUCCESSFUL,
SET_WEB3_CONNECTION_STATUS,
SET_CURRENT_MASK_ADDRESS,
METAMASK_LOCKED,
METAMASK_UNLOCKED,
......@@ -9,21 +8,16 @@ import {
SET_NETWORK_MESSAGE,
SET_BLOCK_TIMESTAMP,
SET_EXCHANGE_TYPE,
INITIALIZE_GLOBAL_WEB3
TOGGLE_ABOUT
} from '../constants';
// this actions folder is actually full of action creators
// your asynchronous calls are going to be in redux-thunk style action creators
export const web3ConnectionSuccessful = () => ({
type: WEB3_CONNECTION_SUCCESSFUL,
connected: true
});
export const web3ConnectionUnsuccessful = () => ({
type: WEB3_CONNECTION_UNSUCCESSFUL,
connected: false
});
export const setWeb3ConnectionStatus = (connected) => ({
type: SET_WEB3_CONNECTION_STATUS,
connected
})
export const setCurrentMaskAddress = (currentMaskAddress) => ({
type: SET_CURRENT_MASK_ADDRESS,
......@@ -43,17 +37,41 @@ export const metamaskUnlocked = () => ({
export const setInteractionState = (interaction) => ({
type: SET_INTERACTION_STATE,
interaction
});
})
export const factoryContractReady = (factoryContract) => ({
type: FACTORY_CONTRACT_READY,
factoryContract
});
export const setNetworkMessage = (networkMessage) => ({
type: SET_NETWORK_MESSAGE,
networkMessage
});
export const setNetworkMessage = (networkMessage) => {
return async (dispatch) => {
let networkName;
switch (networkMessage) {
case "main":
networkName = 'Ethereum Mainet'
break;
case "morden":
networkName = 'Morden testnet'
break;
case "ropsten":
networkName = 'Ropsten testnet'
break;
case "rinkeby":
networkName = 'Rinkeby testnet'
break;
case "kovan":
networkName = 'Kovan testnet'
break;
default:
networkName = 'an unknown network'
}
dispatch ({
type: SET_NETWORK_MESSAGE,
networkMessage: networkName
})
}
};
export const setBlockTimestamp = () => {
return async (dispatch, getState) => {
......@@ -73,7 +91,7 @@ export const setExchangeType = (exchangeType) => ({
exchangeType
});
export const initializeGlobalWeb3 = (globalWeb3) => ({
type: INITIALIZE_GLOBAL_WEB3,
globalWeb3
})
export const toggleAbout = (toggle) => ({
type: TOGGLE_ABOUT,
aboutToggle: toggle
})
\ No newline at end of file
import React, { Component } from 'react';
import AboutMessage from './AboutMessage';
import scrollToComponent from 'react-scroll-to-component';
export default class About extends Component {
constructor (props) {
super(props)
this.state = { toggled: false }
}
toggleAbout = () => {
this.setState({toggled: !this.state.toggled})
setTimeout(this.scrollToAbout, 300);
}
import { connect } from 'react-redux';
scrollToAbout = () => {
scrollToComponent(this.About, { offset: 0, align: 'top', duration: 500})
}
import AboutMessage from './AboutMessage';
class About extends Component {
render () {
const { toggled } = this.state;
return(
<div>
<section className="About" ref={(section) => { this.About = section; }}>
<a onClick={() => {this.toggleAbout()}} className="link border pa2 f-a">
<section className="About" ref={(section) => { this.props.location.About = section; }}>
<a onClick={() => {this.props.toggleAbout()}} className="link border pa2 f-a">
<p className="underline">About Uniswap.</p>
<p></p>
</a>
</section>
<AboutMessage toggled={toggled} />
<AboutMessage toggled={this.props.web3Store.aboutToggle} />
</div>
)
}
}
const mapStateToProps = state => ({
web3Store: state.web3Store
});
export default connect (mapStateToProps)(About)
\ No newline at end of file
import React from 'react';
import { connect } from 'react-redux';
function ConnectionHelper(props) {
if (!props.metamask) {
......@@ -8,53 +9,53 @@ function ConnectionHelper(props) {
<b>To get started, please install <a href="https://metamask.io/">Metamask</a>.</b></p>
</div>
)
} else if (props.connected && props.interaction === 'disconnected') {
} else if (props.web3Store.connected && props.web3Store.interaction === 'disconnected') {
return (
<div className="grey-bg connection border pa2">
<p>Welcome! Uniswap is a decentralized exhange platform for ERC20 Tokens. <a onClick={() => {props.toggleAbout()}} className="f-a" >How it works </a><br /><br />
Looks like you aren't connected. <b>Please switch to the correct network.</b></p>
</div>
)
} else if (props.locked) {
} else if (props.web3Store.metamaskLocked) {
return (
<div className="grey-bg connection border pa2">
<p>Welcome! Uniswap is a decentralized exhange platform for ERC20 Tokens. <a onClick={() => {props.toggleAbout()}} className="f-a" >How it works ↘</a><br /><br />
Looks like you aren't connected. <b>Please unlock Metamask to continue.</b></p>
</div>
)
} else if (props.interaction === "error1") {
} else if (props.web3Store.interaction === "error1") {
return (
<div className="grey-bg connection border pa2">
<p>You can't swap a token for itself! <span role="img" aria-label="Crying">😂</span></p>
</div>
)
} else if (props.interaction === "submitted") {
} else if (props.web3Store.interaction === "submitted") {
return (
<div className="grey-bg connection border pa2">
<p>{"Transaction submitted! Click on the transaction hash below to check its status?"}</p>
</div>
)
} else if (props.input > props.balance/10**18 && props.inputToken.value === 'ETH') {
} else if (props.exchange.inputValue > props.exchange.inputBalance/10**18 && props.exchange.inputToken.value === 'ETH') {
return (
<div className="grey-bg red connection border pa2">
<p>This account doesn't have enough balance to make this transaction! Get more {props.inputToken.value} with the <a target="_blank" rel="noopener noreferrer" href="https://faucet.rinkeby.io/">Rinkeby Faucet.</a></p>
<p>This account doesn't have enough balance to make this transaction! Get more {props.exchange.inputToken.value} with the <a target="_blank" rel="noopener noreferrer" href="https://faucet.rinkeby.io/">Rinkeby Faucet.</a></p>
</div>
)
} else if (!props.approved && props.exchangeType === "Token to Token") {
} else if (!props.exchange.allowanceApproved && props.web3Store.exchangeType === "Token to Token") {
return (
<div className="grey-bg connection border pa2">
<p>Our smart contract has to be approved by your address to be able to swap this token for other tokens.<br /> We set a high transfer limit for the demo (<a onClick={() => {props.toggleAbout()}} className="f-a">Why?</a>).</p>
<a className="f-a" onClick={() => props.approveAllowance()}>Approve </a>
</div>
)
} else if (!props.approved && props.exchangeType === "Token to ETH") {
} else if (!props.exchange.allowanceApproved && props.web3Store.exchangeType === "Token to ETH") {
return (
<div className="grey-bg connection border pa2">
<p>Our smart contract has to be approved by your address to be able to swap this token for ETH.<br /> We set a high transfer limit for the demo (<a onClick={() => {props.toggleAbout()}} className="f-a">Why?</a>).</p>
<a className="f-a" onClick={() => props.approveAllowance()}>Approve </a>
</div>
)
} else if (!props.uniAdded && props.outputToken.value === "UNI") {
} else if (!props.uniAdded && props.exchange.outputToken.value === "UNI") {
return (
<div className="grey-bg connection border pa2">
<p>Welcome! Uniswap is a decentralized exhange platform for ERC20 Tokens. <a onClick={() => {props.toggleAbout()}} className="f-a" >How it works </a><br /><br />
......@@ -63,7 +64,7 @@ function ConnectionHelper(props) {
<a className="f-a" onClick={() => props.onCloseHelper()}>I've added the token</a>
</div>
)
} else if (!props.swapAdded && props.outputToken.value === "SWAP") {
} else if (!props.swapAdded && props.exchange.outputToken.value === "SWAP") {
return (
<div className="grey-bg connection border pa2">
<p>Welcome! Uniswap is a decentralized exhange platform for ERC20 Tokens. <a onClick={() => {props.toggleAbout()}} className="f-a" >How it works</a>.<br /><br />
......@@ -72,10 +73,10 @@ function ConnectionHelper(props) {
<a className="f-a" onClick={() => props.onCloseHelper()}>I've added the token</a>
</div>
)
} else if (props.input > props.balance/10**18) {
} else if (props.exchange.inputValue > props.exchange.inputBalance/10**18) {
return (
<div className="grey-bg red connection border pa2">
<p>{"This account doesn't have enough balance to make this transaction! You'll need to swap some ETH for " + props.inputToken.value + "."}</p>
<p>{"This account doesn't have enough balance to make this transaction! You'll need to swap some ETH for " + props.exchange.inputToken.value + "."}</p>
</div>
)
} else {
......@@ -89,4 +90,10 @@ function ConnectionHelper(props) {
}
}
export default ConnectionHelper;
const mapStateToProps = state => ({
web3Store: state.web3Store,
exchange: state.exchange
});
export default connect(mapStateToProps)(ConnectionHelper);
......@@ -2,31 +2,16 @@ import React, { Component }from 'react';
import SelectToken from './SelectToken';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { subscribe } from 'redux-subscriber';
import { setInteractionState, setExchangeType } from '../actions/web3-actions';
import {
setExchangeInputValue,
setExchangeOutputValue,
setExchangeRate,
setExchangeFee,
setInputToken,
setOutputToken,
setInputBalance,
setOutputBalance,
setAllowanceApprovalState
} from '../actions/exchange-actions';
import { setExchangeInputValue, setExchangeOutputValue, setExchangeRate, setExchangeFee, setInputToken, setOutputToken, setInputBalance, setOutputBalance, setAllowanceApprovalState } from '../actions/exchange-actions';
class Order extends Component {
constructor (props){
super(props)
}
// props and functions ready
class Exchange extends Component {
onInputChange = async (event) => {
var inputValue = event.target.value;
await this.props.setExchangeInputValue(inputValue);
this.setExchangeOutput();
}
// props ready,
onSelectToken = async (selected, type) => {
this.props.setExchangeInputValue(0);
this.props.setExchangeOutputValue(0);
......@@ -57,13 +42,12 @@ class Order extends Component {
} else if(inputValue && inputValue !== 0 && inputValue !== '0'){
this.props.setInteractionState('input');
// another function to be pulled out into HOC
this.props.getExchangeRate(inputValue);
this.getExchangeRate(inputValue);
} else {
this.props.setExchangeOutputValue(0);
this.props.setInteractionState('connected');
}
}
// props ready
// TODO: change this to use the redux-subscribe pattern
getMarketType = () => {
......@@ -83,82 +67,81 @@ class Order extends Component {
console.log('input: ', this.props.exchange.inputToken.value);
console.log('output: ', this.props.exchange.outputToken.value);
}
// we are here
// TODO: change this to use the redux-subscribe pattern
getAccountInfo = () => {
switch (this.props.web3Store.exchangeType) {
case 'ETH to Token':
this.getEthBalance('input');
this.getTokenBalance('output');
break;
case 'Token to ETH':
this.getEthBalance('output');
this.getTokenBalance('input');
this.getAllowance();
break;
case 'Token to Token':
this.getTokenBalance('input');
this.getTokenBalance('output');
this.getAllowance();
break;
default:
}
console.log("Getting account info");
}
// props ready
// TODO: TODO: TODO: TURN THIS INTO A REDUX-SUBSCRIBE LISTENER NOW!!!
getEthBalance = (type) => {
// this.props.web3Store.globalWeb3
if (type === 'input') {
this.props.web3Store.globalWeb3.eth.getBalance(this.props.web3Store.currentMaskAddress, (error, balance) => {
this.props.setInputBalance(balance);
// console.log('ETH Balance: ' + balance);
});
} else if (type === 'output') {
this.props.web3Store.globalWeb3.eth.getBalance(this.props.web3Store.currentMaskAddress, (error, balance) => {
this.props.setOutputBalance(balance);
// console.log('ETH Balance: ' + balance);
});
getExchangeRate = (input) => {
if (this.props.web3Store.exchangeType === 'ETH to Token') {
console.log('Getting Rate: ETH to ' + this.props.exchange.outputToken.value);
this.ethToTokenRate(input);
} else if (this.props.web3Store.exchangeType === 'Token to ETH') {
console.log('Getting Rate: ' + this.props.exchange.inputToken.value + ' to ETH');
this.tokenToEthRate(input);
} else if (this.props.web3Store.exchangeType === 'Token to Token') {
console.log('Getting Rate: ' + this.props.exchange.inputToken.value + ' to ' + this.props.exchange.outputToken.value);
this.tokenToTokenRate(input);
}
}
// props ready
// TODO: this might also be able to change to the redux-subscribe method
getTokenBalance = (type) => {
var token;
if (type === 'input') {
token = this.symbolToTokenContract(this.props.exchange.inputToken.value);
token.methods.balanceOf(this.props.web3Store.currentMaskAddress).call((error, balance) => {
this.props.setInputBalance(balance);
// console.log(this.props.exchange.inputToken.value + ' Balance: ' + balance);
});
} else if (type === 'output') {
token = this.symbolToTokenContract(this.props.exchange.outputToken.value);
token.methods.balanceOf(this.props.web3Store.currentMaskAddress).call((error, balance) => {
this.props.setOutputBalance(balance);
// console.log(this.props.exchange.outputToken.value + ' Balance: ' + balance);
});
}
ethToTokenRate = (ethInput) => {
var ethInMarket = +this.props.exchange.marketEth2;
var tokensInMarket = +this.props.exchange.marketTokens2;
var invar = +this.props.exchange.invariant2;
var ethIn = ethInput*10**18;
var exchangeFee = ethIn/500;
var ethSold = ethIn - exchangeFee;
var newEthInMarket = ethInMarket + ethSold;
var newTokensInMarket = invar/newEthInMarket;
var tokensOut = tokensInMarket - newTokensInMarket;
var adjustedTokensOut = tokensOut * 0.98;
var buyRate = adjustedTokensOut/ethIn;
this.props.setExchangeRate(buyRate);
this.props.setExchangeFee(exchangeFee);
this.props.setExchangeOutputValue(adjustedTokensOut);
}
// TODO: refactor to redux-subscribe
// props ready
getAllowance = () => {
var type = this.props.web3Store.exchangeType;
if(type === 'Token to ETH' || type === 'Token to Token') {
// another pair of functions to be exported to a HOC
var token = this.props.symbolToTokenContract(this.props.exchange.inputToken.value);
var exchangeAddress = this.props.symbolToExchangeAddress(this.props.exchange.inputToken.value);
token.methods.allowance(this.props.web3Store.currentMaskAddress, exchangeAddress).call().then((result, error) => {
console.log(this.props.exchange.inputToken.value + ' allowance: ' + result);
if(result === '0'){
this.props.setAllowanceApprovalState(false)
console.log(this.props.exchange.allowanceApproved)
}
})
}
tokenToEthRate = (tokenInput) => {
var ethInMarket = +this.props.exchange.marketEth1;
var tokensInMarket = +this.props.exchange.marketTokens1;
var invar = +this.props.exchange.invariant1;
var tokensIn = tokenInput*10**18;
var exchangeFee = tokensIn/500;
var tokensSold = tokensIn - exchangeFee;
var newTokensInMarket = tokensInMarket + tokensSold;
var newEthInMarket = invar/newTokensInMarket;
var ethOut = ethInMarket - newEthInMarket;
var adjustedEthOut = ethOut * 0.98;
var buyRate = adjustedEthOut/tokensIn;
this.props.setExchangeRate(buyRate);
this.props.setExchangeFee(exchangeFee);
this.props.setExchangeOutputValue(adjustedEthOut);
}
tokenToTokenRate = (tokenInput) => {
// Token to ETH on Exchange 1
var ethInMarket1 = +this.props.exchange.marketEth1;
var tokensInMarket1 = +this.props.exchange.marketTokens1;
var invar1 = +this.props.exchange.invariant1;
var tokensIn = tokenInput*10**18;
var exchangeFee1 = tokensIn/500;
var tokensSold = tokensIn - exchangeFee1;
var newTokensInMarket1 = tokensInMarket1 + tokensSold;
var newEthInMarket1 = invar1/newTokensInMarket1;
var ethToExchange2 = ethInMarket1 - newEthInMarket1;
// ETH to Token on Exchange 2
var ethInMarket2 = +this.props.exchange.marketEth2;
var tokensInMarket2 = +this.props.exchange.marketTokens2;
var invar2 = +this.props.exchange.invariant2;
var exchangeFee2 = ethToExchange2/500;
var ethSold = ethToExchange2 - exchangeFee2;
var newEthInMarket2 = ethInMarket2 + ethSold;
var newTokensInMarket2 = invar2/newEthInMarket2;
var tokensOut = tokensInMarket2 - newTokensInMarket2;
var adjustedTokensOut = tokensOut * 0.98;
var buyRate = adjustedTokensOut/tokensIn;
this.props.setExchangeRate(buyRate);
this.props.setExchangeFee(exchangeFee1);
this.props.setExchangeOutputValue(adjustedTokensOut);
}
render () {
return (
<section className="order">
......@@ -178,13 +161,12 @@ class Order extends Component {
</section>
)
}
}
const mapStateToProps = state => ({
web3Store: state.web3Store,
exchange: state.exchange
})
})
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
......@@ -202,4 +184,4 @@ const mapStateToProps = state => ({
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Order);
\ No newline at end of file
export default connect(mapStateToProps, mapDispatchToProps)(Exchange);
\ No newline at end of file
import React from 'react';
import NetworkStatus from '../components/NetworkStatus';
function Header (props){
return (
<section className="title">
<div className="logo border pa2">
<span role="img" aria-label="Unicorn">🦄</span>
</div>
<NetworkStatus metamask={props.metamask}/>
</section>
)
}
export default Header;
\ No newline at end of file
import React from 'react';
import React, { Component }from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { setWeb3ConnectionStatus, setInteractionState, setNetworkMessage } from '../actions/web3-actions';
function NetworkStatus(props) {
let isConnected = props.connected
let metamask = props.metamask
let locked = props.locked
class NetworkStatus extends Component {
componentDidMount(){
if (this.props.global.web3 !== undefined){
this.checkNetwork();
}
}
checkNetwork = () => {
this.props.global.web3.eth.net.getNetworkType((err, networkId) => {
console.log("Connected to " + networkId)
let interactionState = networkId === 'rinkeby' ? 'connected' : 'disconnected';
let connectionStatus = networkId === 'rinkeby' ? true : false;
this.props.setNetworkMessage(networkId);
this.props.setWeb3ConnectionStatus(connectionStatus);
this.props.setInteractionState(interactionState);
})
}
if (isConnected && props.interaction !== 'disconnected'){
return (
<div className="connection border pa2 green">
<a target="_blank" rel="noopener noreferrer" href={'https://rinkeby.etherscan.io/search?q=' + props.address}>{props.address}</a>
<p></p>
</div>
)
} else if (!metamask) {
return (
<div className="connection red border pa2">
<p>{"Waiting for connection to the blockchain..."}</p>
<p></p>
</div>
)
} else if (locked && !isConnected) {
return (
<div className="connection yellow border pa2">
<p>{"Waiting for Metamask to unlock..."}</p>
<p></p>
</div>
)
} else {
return (
<div className="connection yellow border pa2">
<p>{'MetaMask connected to ' + props.network + ' Switch to Rinkeby and refresh!'}</p>
<p></p>
</div>
)
render () {
if (this.props.web3Store.connected && this.props.web3Store.interaction !== 'disconnected'){
return (
<div className="connection border pa2 green">
<a target="_blank" rel="noopener noreferrer" href={'https://rinkeby.etherscan.io/search?q=' + this.props.web3Store.currentMaskAddress}>{this.props.web3Store.currentMaskAddress}</a>
<p></p>
</div>
)
} else if (!this.props.metamask) {
return (
<div className="connection red border pa2">
<p>{"Waiting for connection to the blockchain..."}</p>
<p></p>
</div>
)
} else if (this.props.web3Store.metamaskLocked && !this.props.web3Store.connected) {
return (
<div className="connection yellow border pa2">
<p>{"Waiting for Metamask to unlock..."}</p>
<p></p>
</div>
)
} else {
return (
<div className="connection yellow border pa2">
<p>{'MetaMask connected to ' + this.props.web3Store.networkMessage + ' Switch to Rinkeby and refresh!'}</p>
<p></p>
</div>
)
}
}
}
const mapStateToProps = state => ({
global: state.global,
web3Store: state.web3Store,
exchange: state.exchange
});
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
setWeb3ConnectionStatus,
setInteractionState,
setNetworkMessage,
}, dispatch)
}
export default NetworkStatus;
export default connect (mapStateToProps, mapDispatchToProps)(NetworkStatus);
\ No newline at end of file
import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import { setBlockTimestamp, setInteractionState } from '../actions/web3-actions';
import { setExchangeInputValue, setExchangeOutputValue } from '../actions/exchange-actions';
class Purchase extends Component {
purchaseTokens = async () => {
await this.props.setBlockTimestamp(this.props.global.web3);
if (this.props.web3Store.exchangeType === 'ETH to Token') {
this.ethToTokenPurchase();
} else if (this.props.web3Store.exchangeType === 'Token to ETH') {
this.tokenToEthPurchase();
} else if (this.props.web3Store.exchangeType === 'Token to Token') {
this.tokenToTokenPurchase();
}
}
ethToTokenPurchase = () => {
var exchange = this.props.symbolToExchangeContract(this.props.exchange.outputToken.value);
var minTokens = (this.props.exchange.outputValue/10**18).toString();
var minTokensInt = this.props.global.web3.utils.toWei(minTokens);
var ethSold = this.props.exchange.inputValue;
var weiSold = this.props.global.web3.utils.toWei(ethSold);
var timeout = this.props.web3Store.blockTimestamp + 300; //current block time + 5mins
// console.log(minTokensInt, weiSold, timeout);
exchange.methods.ethToTokenSwap(minTokensInt, timeout).send({from: this.props.web3Store.currentMaskAddress, value: weiSold})
.on('transactionHash', (result) => {
// console.log('Transaction Hash created'
// let transactions = this.state.transactions
// transactions.push(result);
// transactions is cookie stuff, we'll keep that in state
// this.setState({ transactions: transactions })
// any particular reason why there are initialized as 0, but get turned to empty strings after the transaction is over?
this.props.setExchangeInputValue('');
this.props.setExchangeOutputValue('');
this.props.setInteractionState('submitted');
// cookie.save('transactions', transactions, { path: '/' })
})
.on('receipt', (receipt) => {
console.log(receipt)
}) //Transaction Submitted to blockchain
.on('confirmation', (confirmationNumber, receipt) => {
console.log("Block Confirmations: " + confirmationNumber)
if(confirmationNumber === 1) {
this.getAccountInfo();
}
}) //Transaction Mined
.on('error', console.error);
}
tokenToEthPurchase = () => {
var exchange = this.props.symbolToExchangeContract(this.props.exchange.inputToken.value);
var minEth = (this.props.exchange.outputValue/10**18).toString();
var minEthInt = this.props.global.web3.utils.toWei(minEth);
var tokensSold = this.props.exchange.inputValue;
var tokensSoldInt = this.props.global.web3.utils.toWei(tokensSold);
var timeout = this.props.web3Store.blockTimestamp + 300; //current block time + 5mins
exchange.methods.tokenToEthSwap(tokensSoldInt, minEthInt, timeout).send({from: this.props.web3Store.currentMaskAddress})
.on('transactionHash', (result) => {
// console.log('Transaction Hash created')
// let transactions = this.state.transactions
// transactions.push(result)
// this.setState({ transactions: transactions });
this.props.setExchangeInputValue('');
this.props.setExchangeOutputValue('');
this.props.setInteractionState('submitted');
// cookie.save('transactions', transactions, { path: '/' })
})
.on('receipt', (receipt) => {console.log(receipt)}) //Transaction Submitted to blockchain
.on('confirmation', (confirmationNumber, receipt) => {console.log("Block Confirmations: " + confirmationNumber)}) //Transaction Mined
.on('error', console.error);
}
tokenToTokenPurchase = () => {
var exchange = this.props.symbolToExchangeContract(this.props.exchange.inputToken.value);
var tokenOutAddress = this.props.symbolToTokenAddress(this.props.exchange.outputToken.value);
var minTokens = (this.props.exchange.outputValue/10**18).toString();
var minTokensInt = this.props.global.web3.utils.toWei(minTokens);
var tokensSold = this.props.exchange.inputValue;
var tokensSoldInt = this.props.global.web3.utils.toWei(tokensSold);
var timeout = this.props.web3Store.blockTimestamp + 300; //current block time + 5mins
console.log('tokenOutAddress', tokenOutAddress);
console.log('minTokensInt', minTokensInt);
console.log('tokensSoldInt', tokensSoldInt);
console.log('timeout', timeout);
exchange.methods.tokenToTokenSwap(tokenOutAddress, tokensSoldInt, minTokensInt, timeout).send({from: this.props.web3Store.currentMaskAddress})
.on('transactionHash', (result) => {
// console.log('Transaction Hash created')
// let transactions = this.state.transactions
// transactions.push(result)
// this.setState({ transactions: transactions });
this.props.setExchangeInputValue('');
this.props.setExchangeOutputValue('');
this.props.setInteractionState('submitted');
// cookie.save('transactions', transactions, { path: '/' })
})
.on('receipt', (receipt) => {console.log(receipt)}) //Transaction Submitted to blockchain
.on('confirmation', (confirmationNumber, receipt) => {console.log("Block Confirmations: " + confirmationNumber)}) //Transaction Mined
.on('error', console.error);
}
render() {
if (this.props.web3Store.interaction === 'input') {
return (
<a className="swap border pa2" role="button" onClick={() => {this.purchaseTokens()}}>
<b>{"I want to swap " + this.props.exchange.inputValue + " " + this.props.exchange.inputToken.value + " for " + this.props.exchange.outputValue/10**18 + " " + this.props.exchange.outputToken.value}</b>
</a>
)
} else {
return (<a className="swap grey-bg hidden border pa2"></a>)
}
}
}
const mapStateToProps = state => ({
global: state.global,
web3Store: state.web3Store,
exchange: state.exchange
})
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
setBlockTimestamp,
setExchangeInputValue,
setExchangeOutputValue,
setInteractionState
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Purchase);
import React from 'react';
function Swap ({ interaction, inputValue, inputTokenValue, outputValue, outputTokenValue, purchaseTokens }) {
if (interaction === 'input') {
return (
<a className="swap border pa2" role="button" onClick={() => {purchaseTokens()}}>
<b>{"I want to swap " + inputValue + " " + inputTokenValue + " for " + outputValue/10**18 + " " + outputTokenValue}</b>
</a>
)
} else {
return (<a className="swap grey-bg hidden border pa2"></a>)
}
}
export default Swap;
// import React from 'react';
// import NetworkStatus from '../components/NetworkStatus';
// function Title (){
// return (
// <section className="title">
// <div className="logo border pa2">
// <span role="img" aria-label="Unicorn">🦄</span>
// </div>
// <NetworkStatus
// network={this.props.web3Store.networkMessage}
// connected={this.props.web3Store.connected}
// metamask={this.props.metamask}
// interaction={this.props.web3Store.interaction}
// address={this.props.web3Store.currentMaskAddress}
// locked={this.props.web3Store.metamaskLocked}
// balance={this.props.exchange.inputBalance}
// />
// </section>
// )
// }
// export default Title;
\ No newline at end of file
import React from 'react';
import {Helmet} from "react-helmet";
import { Helmet } from "react-helmet";
import unicorn from '../images/🦄.png'
function Head(props) {
function UniHead(props) {
return (
<Helmet>
<meta charSet="utf-8" />
......@@ -13,4 +13,4 @@ function Head(props) {
);
}
export default Head;
export default UniHead;
......@@ -2,9 +2,8 @@
// maybe there's an action to see if you've been connected to web3
// web3 actions, all set from action creator to reducer to app
export const SET_WEB3_CONNECTION_STATUS = 'WEB3_CONNECTION_STATUS';
export const CHECK_WEB3_CONNECTION = 'CHECK_WEB3_CONNECTION';
export const WEB3_CONNECTION_SUCCESSFUL = 'WEB3_CONNECTION_SUCCESSFUL';
export const WEB3_CONNECTION_UNSUCCESSFUL = 'WEB3_CONNECTION_UNSUCCESSFUL';
export const SET_CURRENT_MASK_ADDRESS = 'SET_CURRENT_MASK_ADDRESS';
export const METAMASK_LOCKED = 'METAMASK_LOCKED';
......@@ -15,6 +14,9 @@ export const SET_NETWORK_MESSAGE = 'SET_NETWORK_MESSAGE';
export const SET_BLOCK_TIMESTAMP = 'SET_BLOCK_TIMESTAMP';
export const SET_EXCHANGE_TYPE = 'SET_EXCHANGE_TYPE';
// action to toggle the 'about' div
export const TOGGLE_ABOUT = 'TOGGLE_ABOUT';
// factory contract action, also set
export const FACTORY_CONTRACT_READY = 'FACTORY_CONTRACT_READY';
......
import { INITIALIZE_GLOBAL_WEB3 } from '../constants';
export default (state = {}, action) => {
const { globalWeb3 } = action;
switch(action.type) {
case INITIALIZE_GLOBAL_WEB3:
return Object.assign({}, state, { web3: globalWeb3 });
default: return state
}
}
\ No newline at end of file
import { combineReducers } from 'redux';
import global from './global-reducer';
import web3Store from './web3-reducer';
import exchangeContracts from './exchangeContract-reducer';
import tokenContracts from './tokenContract-reducer';
import exchange from './exchange-reducer';
export default combineReducers({
global,
web3Store,
exchangeContracts,
tokenContracts,
......
// these will take in an action, have a default state set in the arguments and return a new state
import {
WEB3_CONNECTION_SUCCESSFUL,
WEB3_CONNECTION_UNSUCCESSFUL,
SET_WEB3_CONNECTION_STATUS,
SET_CURRENT_MASK_ADDRESS,
METAMASK_LOCKED,
METAMASK_UNLOCKED,
......@@ -10,15 +9,14 @@ import {
SET_NETWORK_MESSAGE,
SET_BLOCK_TIMESTAMP,
SET_EXCHANGE_TYPE,
INITIALIZE_GLOBAL_WEB3
INITIALIZE_GLOBAL_WEB3,
TOGGLE_ABOUT
} from '../constants';
export default (state = {}, action) => {
const { connected, currentMaskAddress, metamaskLocked, interaction, factoryContract, networkMessage, timestamp, exchangeType, globalWeb3 } = action
const { connected, currentMaskAddress, metamaskLocked, interaction, factoryContract, networkMessage, timestamp, exchangeType, globalWeb3, aboutToggle } = action
switch (action.type) {
case WEB3_CONNECTION_SUCCESSFUL:
return Object.assign({}, state, { connected: connected });
case WEB3_CONNECTION_UNSUCCESSFUL:
case SET_WEB3_CONNECTION_STATUS:
return Object.assign({}, state, { connected: connected });
case SET_CURRENT_MASK_ADDRESS:
return Object.assign({}, state, { currentMaskAddress: currentMaskAddress });
......@@ -38,6 +36,8 @@ export default (state = {}, action) => {
return Object.assign({}, state, { exchangeType: exchangeType });
case INITIALIZE_GLOBAL_WEB3:
return Object.assign({}, state, { globalWeb3: globalWeb3 });
case TOGGLE_ABOUT:
return Object.assign({}, state, { aboutToggle: aboutToggle })
default: return state;
}
}
// what states do you need upon initialization?
// connected: are you connnected? default state = false
// props.metamask --> maybe we should keep this in global state too?
// both of these are set to false in the default state
// fire dispatch functions to check for installation and connection in the default store
// you are probably going to be storing stuff like invariants and all that jazz here
export default {
// lets check if metamask is installed
// also, lets assume that we're disconnected initially
// we're going to need to include a seperate nest for exchange actions
global: {},
web3Store: {
connected: false,
aboutToggle: false,
globalWeb3: {},
currentMaskAddress: '',
metamaskLocked: true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment