aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src
diff options
context:
space:
mode:
Diffstat (limited to 'packages/instant/src')
-rw-r--r--packages/instant/src/components/amount_input.tsx12
-rw-r--r--packages/instant/src/components/animations/slide_animations.tsx54
-rw-r--r--packages/instant/src/components/animations/slide_up_and_down_animation.tsx96
-rw-r--r--packages/instant/src/components/asset_amount_input.tsx38
-rw-r--r--packages/instant/src/components/buy_button.tsx58
-rw-r--r--packages/instant/src/components/instant_heading.tsx62
-rw-r--r--packages/instant/src/components/order_details.tsx110
-rw-r--r--packages/instant/src/components/sliding_error.tsx24
-rw-r--r--packages/instant/src/components/zero_ex_instant.tsx3
-rw-r--r--packages/instant/src/components/zero_ex_instant_container.tsx17
-rw-r--r--packages/instant/src/constants.ts6
-rw-r--r--packages/instant/src/containers/latest_buy_quote_order_details.ts27
-rw-r--r--packages/instant/src/containers/latest_error.tsx35
-rw-r--r--packages/instant/src/containers/selected_asset_amount_input.ts89
-rw-r--r--packages/instant/src/containers/selected_asset_amount_input.tsx36
-rw-r--r--packages/instant/src/containers/selected_asset_buy_button.ts55
-rw-r--r--packages/instant/src/containers/selected_asset_instant_heading.ts30
-rw-r--r--packages/instant/src/data/asset_meta_data.ts15
-rw-r--r--packages/instant/src/redux/actions.ts46
-rw-r--r--packages/instant/src/redux/async_data.ts22
-rw-r--r--packages/instant/src/redux/reducer.ts67
-rw-r--r--packages/instant/src/redux/store.ts3
-rw-r--r--packages/instant/src/types.ts36
-rw-r--r--packages/instant/src/util/asset_buyer.ts9
-rw-r--r--packages/instant/src/util/asset_data.ts21
-rw-r--r--packages/instant/src/util/coinbase_api.ts10
-rw-r--r--packages/instant/src/util/error.ts62
-rw-r--r--packages/instant/src/util/format.ts53
-rw-r--r--packages/instant/src/util/provider.ts12
-rw-r--r--packages/instant/src/util/util.ts5
-rw-r--r--packages/instant/src/util/web3_wrapper.ts5
31 files changed, 898 insertions, 220 deletions
diff --git a/packages/instant/src/components/amount_input.tsx b/packages/instant/src/components/amount_input.tsx
index 38810063d..7644f5f67 100644
--- a/packages/instant/src/components/amount_input.tsx
+++ b/packages/instant/src/components/amount_input.tsx
@@ -3,6 +3,7 @@ import * as _ from 'lodash';
import * as React from 'react';
import { ColorOption } from '../style/theme';
+import { util } from '../util/util';
import { Container, Input } from './ui';
@@ -10,10 +11,13 @@ export interface AmountInputProps {
fontColor?: ColorOption;
fontSize?: string;
value?: BigNumber;
- onChange?: (value?: BigNumber) => void;
+ onChange: (value?: BigNumber) => void;
}
export class AmountInput extends React.Component<AmountInputProps> {
+ public static defaultProps = {
+ onChange: util.boundNoop,
+ };
public render(): React.ReactNode {
const { fontColor, fontSize, value } = this.props;
return (
@@ -24,7 +28,7 @@ export class AmountInput extends React.Component<AmountInputProps> {
onChange={this._handleChange}
value={!_.isUndefined(value) ? value.toString() : ''}
placeholder="0.00"
- width="2em"
+ width="2.2em"
/>
</Container>
);
@@ -40,8 +44,6 @@ export class AmountInput extends React.Component<AmountInputProps> {
return;
}
}
- if (!_.isUndefined(this.props.onChange)) {
- this.props.onChange(bigNumberValue);
- }
+ this.props.onChange(bigNumberValue);
};
}
diff --git a/packages/instant/src/components/animations/slide_animations.tsx b/packages/instant/src/components/animations/slide_animations.tsx
new file mode 100644
index 000000000..1f10a2ed6
--- /dev/null
+++ b/packages/instant/src/components/animations/slide_animations.tsx
@@ -0,0 +1,54 @@
+import * as React from 'react';
+
+import { keyframes, styled } from '../../style/theme';
+
+const slideKeyframeGenerator = (fromY: string, toY: string) => keyframes`
+ from {
+ position: relative;
+ top: ${fromY};
+ }
+
+ to {
+ position: relative;
+ top: ${toY};
+ }
+`;
+
+export interface SlideAnimationProps {
+ keyframes: string;
+ animationType: string;
+ animationDirection?: string;
+}
+
+export const SlideAnimation =
+ styled.div <
+ SlideAnimationProps >
+ `
+ animation-name: ${props => props.keyframes};
+ animation-duration: 0.3s;
+ animation-timing-function: ${props => props.animationType};
+ animation-delay: 0s;
+ animation-iteration-count: 1;
+ animation-fill-mode: ${props => props.animationDirection || 'none'};
+ position: relative;
+`;
+
+export interface SlideAnimationComponentProps {
+ downY: string;
+}
+
+export const SlideUpAnimation: React.StatelessComponent<SlideAnimationComponentProps> = props => (
+ <SlideAnimation animationType="ease-in" keyframes={slideKeyframeGenerator(props.downY, '0px')}>
+ {props.children}
+ </SlideAnimation>
+);
+
+export const SlideDownAnimation: React.StatelessComponent<SlideAnimationComponentProps> = props => (
+ <SlideAnimation
+ animationDirection="forwards"
+ animationType="cubic-bezier(0.25, 0.1, 0.25, 1)"
+ keyframes={slideKeyframeGenerator('0px', props.downY)}
+ >
+ {props.children}
+ </SlideAnimation>
+);
diff --git a/packages/instant/src/components/animations/slide_up_and_down_animation.tsx b/packages/instant/src/components/animations/slide_up_and_down_animation.tsx
deleted file mode 100644
index 9c18e0933..000000000
--- a/packages/instant/src/components/animations/slide_up_and_down_animation.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import * as React from 'react';
-
-import { keyframes, styled } from '../../style/theme';
-
-const slideKeyframeGenerator = (fromY: string, toY: string) => keyframes`
- from {
- position: relative;
- top: ${fromY};
- }
-
- to {
- position: relative;
- top: ${toY};
- }
-`;
-
-export interface SlideAnimationProps {
- keyframes: string;
- animationType: string;
- animationDirection?: string;
-}
-
-export const SlideAnimation =
- styled.div <
- SlideAnimationProps >
- `
- animation-name: ${props => props.keyframes};
- animation-duration: 0.3s;
- animation-timing-function: ${props => props.animationType};
- animation-delay: 0s;
- animation-iteration-count: 1;
- animation-fill-mode: ${props => props.animationDirection || 'none'};
- position: relative;
-`;
-
-export interface SlideAnimationComponentProps {
- downY: string;
-}
-
-export const SlideUpAnimationComponent: React.StatelessComponent<SlideAnimationComponentProps> = props => (
- <SlideAnimation animationType="ease-in" keyframes={slideKeyframeGenerator(props.downY, '0px')}>
- {props.children}
- </SlideAnimation>
-);
-
-export const SlideDownAnimationComponent: React.StatelessComponent<SlideAnimationComponentProps> = props => (
- <SlideAnimation
- animationDirection="forwards"
- animationType="cubic-bezier(0.25, 0.1, 0.25, 1)"
- keyframes={slideKeyframeGenerator('0px', props.downY)}
- >
- {props.children}
- </SlideAnimation>
-);
-
-export interface SlideUpAndDownAnimationProps extends SlideAnimationComponentProps {
- delayMs: number;
-}
-
-enum SlideState {
- Up = 'up',
- Down = 'down',
-}
-interface SlideUpAndDownState {
- slideState: SlideState;
-}
-
-export class SlideUpAndDownAnimation extends React.Component<SlideUpAndDownAnimationProps, SlideUpAndDownState> {
- public state = {
- slideState: SlideState.Up,
- };
-
- private _timeoutId?: number;
- public render(): React.ReactNode {
- return this._renderSlide();
- }
- public componentDidMount(): void {
- this._timeoutId = window.setTimeout(() => {
- this.setState({
- slideState: SlideState.Down,
- });
- }, this.props.delayMs);
-
- return;
- }
- public componentWillUnmount(): void {
- if (this._timeoutId) {
- window.clearTimeout(this._timeoutId);
- }
- }
- private _renderSlide(): React.ReactNode {
- const SlideComponent = this.state.slideState === 'up' ? SlideUpAnimationComponent : SlideDownAnimationComponent;
-
- return <SlideComponent downY={this.props.downY}>{this.props.children}</SlideComponent>;
- }
-}
diff --git a/packages/instant/src/components/asset_amount_input.tsx b/packages/instant/src/components/asset_amount_input.tsx
new file mode 100644
index 000000000..db3dbe7f3
--- /dev/null
+++ b/packages/instant/src/components/asset_amount_input.tsx
@@ -0,0 +1,38 @@
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
+import * as React from 'react';
+
+import { assetDataUtil } from '../util/asset_data';
+
+import { ColorOption } from '../style/theme';
+import { util } from '../util/util';
+
+import { AmountInput, AmountInputProps } from './amount_input';
+import { Container, Text } from './ui';
+
+export interface AssetAmountInputProps extends AmountInputProps {
+ assetData?: string;
+ onChange: (value?: BigNumber, assetData?: string) => void;
+}
+
+export class AssetAmountInput extends React.Component<AssetAmountInputProps> {
+ public static defaultProps = {
+ onChange: util.boundNoop,
+ };
+ public render(): React.ReactNode {
+ const { assetData, onChange, ...rest } = this.props;
+ return (
+ <Container>
+ <AmountInput {...rest} onChange={this._handleChange} />
+ <Container display="inline-block" marginLeft="10px">
+ <Text fontSize={rest.fontSize} fontColor={ColorOption.white} textTransform="uppercase">
+ {assetDataUtil.bestNameForAsset(this.props.assetData, '???')}
+ </Text>
+ </Container>
+ </Container>
+ );
+ }
+ private readonly _handleChange = (value?: BigNumber): void => {
+ this.props.onChange(value, this.props.assetData);
+ };
+}
diff --git a/packages/instant/src/components/buy_button.tsx b/packages/instant/src/components/buy_button.tsx
index 5a32b9575..0706817c9 100644
--- a/packages/instant/src/components/buy_button.tsx
+++ b/packages/instant/src/components/buy_button.tsx
@@ -1,19 +1,53 @@
+import { BuyQuote } from '@0xproject/asset-buyer';
+import * as _ from 'lodash';
import * as React from 'react';
import { ColorOption } from '../style/theme';
+import { assetBuyer } from '../util/asset_buyer';
+import { util } from '../util/util';
+import { web3Wrapper } from '../util/web3_wrapper';
import { Button, Container, Text } from './ui';
-export interface BuyButtonProps {}
+export interface BuyButtonProps {
+ buyQuote?: BuyQuote;
+ onClick: (buyQuote: BuyQuote) => void;
+ onBuySuccess: (buyQuote: BuyQuote, txnHash: string) => void;
+ onBuyFailure: (buyQuote: BuyQuote, tnxHash?: string) => void;
+ text: string;
+}
-export const BuyButton: React.StatelessComponent<BuyButtonProps> = props => (
- <Container padding="20px" width="100%">
- <Button width="100%">
- <Text fontColor={ColorOption.white} fontWeight={600} fontSize="20px">
- Buy
- </Text>
- </Button>
- </Container>
-);
-
-BuyButton.displayName = 'BuyButton';
+export class BuyButton extends React.Component<BuyButtonProps> {
+ public static defaultProps = {
+ onClick: util.boundNoop,
+ onBuySuccess: util.boundNoop,
+ onBuyFailure: util.boundNoop,
+ };
+ public render(): React.ReactNode {
+ const shouldDisableButton = _.isUndefined(this.props.buyQuote);
+ return (
+ <Container padding="20px" width="100%">
+ <Button width="100%" onClick={this._handleClick} isDisabled={shouldDisableButton}>
+ <Text fontColor={ColorOption.white} fontWeight={600} fontSize="20px">
+ {this.props.text}
+ </Text>
+ </Button>
+ </Container>
+ );
+ }
+ private readonly _handleClick = async () => {
+ // The button is disabled when there is no buy quote anyway.
+ if (_.isUndefined(this.props.buyQuote)) {
+ return;
+ }
+ this.props.onClick(this.props.buyQuote);
+ let txnHash;
+ try {
+ txnHash = await assetBuyer.executeBuyQuoteAsync(this.props.buyQuote);
+ await web3Wrapper.awaitTransactionSuccessAsync(txnHash);
+ this.props.onBuySuccess(this.props.buyQuote, txnHash);
+ } catch {
+ this.props.onBuyFailure(this.props.buyQuote, txnHash);
+ }
+ };
+}
diff --git a/packages/instant/src/components/instant_heading.tsx b/packages/instant/src/components/instant_heading.tsx
index be0414b8d..f57b59b73 100644
--- a/packages/instant/src/components/instant_heading.tsx
+++ b/packages/instant/src/components/instant_heading.tsx
@@ -1,11 +1,58 @@
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
import * as React from 'react';
import { SelectedAssetAmountInput } from '../containers/selected_asset_amount_input';
import { ColorOption } from '../style/theme';
+import { AsyncProcessState } from '../types';
+import { format } from '../util/format';
import { Container, Flex, Text } from './ui';
-export interface InstantHeadingProps {}
+export interface InstantHeadingProps {
+ selectedAssetAmount?: BigNumber;
+ totalEthBaseAmount?: BigNumber;
+ ethUsdPrice?: BigNumber;
+ quoteState: AsyncProcessState;
+}
+
+const Placeholder = () => (
+ <Text fontWeight="bold" fontColor={ColorOption.white}>
+ &mdash;
+ </Text>
+);
+const displaytotalEthBaseAmount = ({
+ selectedAssetAmount,
+ totalEthBaseAmount,
+}: InstantHeadingProps): React.ReactNode => {
+ if (_.isUndefined(selectedAssetAmount)) {
+ return '0 ETH';
+ }
+ return format.ethBaseAmount(totalEthBaseAmount, 4, <Placeholder />);
+};
+
+const displayUsdAmount = ({
+ totalEthBaseAmount,
+ selectedAssetAmount,
+ ethUsdPrice,
+}: InstantHeadingProps): React.ReactNode => {
+ if (_.isUndefined(selectedAssetAmount)) {
+ return '$0.00';
+ }
+ return format.ethBaseAmountInUsd(totalEthBaseAmount, ethUsdPrice, 2, <Placeholder />);
+};
+
+const loadingOrAmount = (quoteState: AsyncProcessState, amount: React.ReactNode): React.ReactNode => {
+ if (quoteState === AsyncProcessState.PENDING) {
+ return (
+ <Text fontWeight="bold" fontColor={ColorOption.white}>
+ &hellip;loading
+ </Text>
+ );
+ } else {
+ return amount;
+ }
+};
export const InstantHeading: React.StatelessComponent<InstantHeadingProps> = props => (
<Container backgroundColor={ColorOption.primaryColor} padding="20px" width="100%" borderRadius="3px 3px 0px 0px">
@@ -22,22 +69,15 @@ export const InstantHeading: React.StatelessComponent<InstantHeadingProps> = pro
</Text>
</Container>
<Flex direction="row" justify="space-between">
- <Container>
- <SelectedAssetAmountInput fontSize="45px" />
- <Container display="inline-block" marginLeft="10px">
- <Text fontSize="45px" fontColor={ColorOption.white} textTransform="uppercase">
- rep
- </Text>
- </Container>
- </Container>
+ <SelectedAssetAmountInput fontSize="45px" />
<Flex direction="column" justify="space-between">
<Container marginBottom="5px">
<Text fontSize="16px" fontColor={ColorOption.white} fontWeight={500}>
- 0 ETH
+ {loadingOrAmount(props.quoteState, displaytotalEthBaseAmount(props))}
</Text>
</Container>
<Text fontSize="16px" fontColor={ColorOption.white} opacity={0.7}>
- $0.00
+ {loadingOrAmount(props.quoteState, displayUsdAmount(props))}
</Text>
</Flex>
</Flex>
diff --git a/packages/instant/src/components/order_details.tsx b/packages/instant/src/components/order_details.tsx
index dbf2c1f0b..a15ff411b 100644
--- a/packages/instant/src/components/order_details.tsx
+++ b/packages/instant/src/components/order_details.tsx
@@ -1,53 +1,90 @@
+import { BuyQuoteInfo } from '@0xproject/asset-buyer';
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
import * as React from 'react';
+import { oc } from 'ts-optchain';
import { ColorOption } from '../style/theme';
+import { format } from '../util/format';
import { Container, Flex, Text } from './ui';
-export interface OrderDetailsProps {}
-
-export const OrderDetails: React.StatelessComponent<OrderDetailsProps> = props => (
- <Container padding="20px" width="100%">
- <Container marginBottom="10px">
- <Text
- letterSpacing="1px"
- fontColor={ColorOption.primaryColor}
- fontWeight={600}
- textTransform="uppercase"
- fontSize="14px"
- >
- Order Details
- </Text>
- </Container>
- <OrderDetailsRow name="Token Price" primaryValue=".013 ETH" secondaryValue="$24.32" />
- <OrderDetailsRow name="Fee" primaryValue=".005 ETH" secondaryValue="$1.04" />
- <OrderDetailsRow name="Total Cost" primaryValue="1.66 ETH" secondaryValue="$589.56" shouldEmphasize={true} />
- </Container>
-);
-
-OrderDetails.displayName = 'OrderDetails';
-
-export interface OrderDetailsRowProps {
- name: string;
- primaryValue: string;
- secondaryValue: string;
+export interface OrderDetailsProps {
+ buyQuoteInfo?: BuyQuoteInfo;
+ ethUsdPrice?: BigNumber;
+}
+
+export class OrderDetails extends React.Component<OrderDetailsProps> {
+ public render(): React.ReactNode {
+ const { buyQuoteInfo, ethUsdPrice } = this.props;
+ const buyQuoteAccessor = oc(buyQuoteInfo);
+ const ethAssetPrice = buyQuoteAccessor.ethPerAssetPrice();
+ const ethTokenFee = buyQuoteAccessor.feeEthAmount();
+ const totalEthAmount = buyQuoteAccessor.totalEthAmount();
+ return (
+ <Container padding="20px" width="100%">
+ <Container marginBottom="10px">
+ <Text
+ letterSpacing="1px"
+ fontColor={ColorOption.primaryColor}
+ fontWeight={600}
+ textTransform="uppercase"
+ fontSize="14px"
+ >
+ Order Details
+ </Text>
+ </Container>
+ <EthAmountRow
+ rowLabel="Token Price"
+ ethAmount={ethAssetPrice}
+ ethUsdPrice={ethUsdPrice}
+ isEthAmountInBaseUnits={false}
+ />
+ <EthAmountRow rowLabel="Fee" ethAmount={ethTokenFee} ethUsdPrice={ethUsdPrice} />
+ <EthAmountRow
+ rowLabel="Total Cost"
+ ethAmount={totalEthAmount}
+ ethUsdPrice={ethUsdPrice}
+ shouldEmphasize={true}
+ />
+ </Container>
+ );
+ }
+}
+
+export interface EthAmountRowProps {
+ rowLabel: string;
+ ethAmount?: BigNumber;
+ isEthAmountInBaseUnits?: boolean;
+ ethUsdPrice?: BigNumber;
shouldEmphasize?: boolean;
}
-export const OrderDetailsRow: React.StatelessComponent<OrderDetailsRowProps> = props => {
- const fontWeight = props.shouldEmphasize ? 700 : 400;
+export const EthAmountRow: React.StatelessComponent<EthAmountRowProps> = ({
+ rowLabel,
+ ethAmount,
+ isEthAmountInBaseUnits,
+ ethUsdPrice,
+ shouldEmphasize,
+}) => {
+ const fontWeight = shouldEmphasize ? 700 : 400;
+ const usdFormatter = isEthAmountInBaseUnits ? format.ethBaseAmountInUsd : format.ethUnitAmountInUsd;
+ const ethFormatter = isEthAmountInBaseUnits ? format.ethBaseAmount : format.ethUnitAmount;
+ const usdPriceSection = _.isUndefined(ethUsdPrice) ? null : (
+ <Container marginRight="3px" display="inline-block">
+ <Text fontColor={ColorOption.lightGrey}>({usdFormatter(ethAmount, ethUsdPrice)})</Text>
+ </Container>
+ );
return (
<Container padding="10px 0px" borderTop="1px dashed" borderColor={ColorOption.feintGrey}>
<Flex justify="space-between">
<Text fontWeight={fontWeight} fontColor={ColorOption.grey}>
- {props.name}
+ {rowLabel}
</Text>
<Container>
- <Container marginRight="3px" display="inline-block">
- <Text fontColor={ColorOption.lightGrey}>({props.secondaryValue}) </Text>
- </Container>
+ {usdPriceSection}
<Text fontWeight={fontWeight} fontColor={ColorOption.grey}>
- {props.primaryValue}
+ {ethFormatter(ethAmount)}
</Text>
</Container>
</Flex>
@@ -55,8 +92,9 @@ export const OrderDetailsRow: React.StatelessComponent<OrderDetailsRowProps> = p
);
};
-OrderDetailsRow.defaultProps = {
+EthAmountRow.defaultProps = {
shouldEmphasize: false,
+ isEthAmountInBaseUnits: true,
};
-OrderDetailsRow.displayName = 'OrderDetailsRow';
+EthAmountRow.displayName = 'EthAmountRow';
diff --git a/packages/instant/src/components/sliding_error.tsx b/packages/instant/src/components/sliding_error.tsx
index 0237fb7e9..3865a8797 100644
--- a/packages/instant/src/components/sliding_error.tsx
+++ b/packages/instant/src/components/sliding_error.tsx
@@ -2,7 +2,7 @@ import * as React from 'react';
import { ColorOption } from '../style/theme';
-import { SlideUpAndDownAnimation } from './animations/slide_up_and_down_animation';
+import { SlideDownAnimation, SlideUpAnimation } from './animations/slide_animations';
import { Container, Text } from './ui';
@@ -20,8 +20,8 @@ export const Error: React.StatelessComponent<ErrorProps> = props => (
borderRadius="6px"
marginBottom="10px"
>
- <Container marginRight="5px" display="inline">
- {props.icon}
+ <Container marginRight="5px" display="inline" top="3px" position="relative">
+ <Text fontSize="20px">{props.icon}</Text>
</Container>
<Text fontWeight="500" fontColor={ColorOption.darkOrange}>
{props.message}
@@ -29,8 +29,16 @@ export const Error: React.StatelessComponent<ErrorProps> = props => (
</Container>
);
-export const SlidingError: React.StatelessComponent<ErrorProps> = props => (
- <SlideUpAndDownAnimation downY="120px" delayMs={5000}>
- <Error icon={props.icon} message={props.message} />
- </SlideUpAndDownAnimation>
-);
+export type SlidingDirection = 'up' | 'down';
+export interface SlidingErrorProps extends ErrorProps {
+ direction: SlidingDirection;
+}
+export const SlidingError: React.StatelessComponent<SlidingErrorProps> = props => {
+ const AnimationComponent = props.direction === 'up' ? SlideUpAnimation : SlideDownAnimation;
+
+ return (
+ <AnimationComponent downY="120px">
+ <Error icon={props.icon} message={props.message} />
+ </AnimationComponent>
+ );
+};
diff --git a/packages/instant/src/components/zero_ex_instant.tsx b/packages/instant/src/components/zero_ex_instant.tsx
index 0e6230d1b..f6472e811 100644
--- a/packages/instant/src/components/zero_ex_instant.tsx
+++ b/packages/instant/src/components/zero_ex_instant.tsx
@@ -1,6 +1,7 @@
import * as React from 'react';
import { Provider } from 'react-redux';
+import { asyncData } from '../redux/async_data';
import { store } from '../redux/store';
import { fonts } from '../style/fonts';
import { theme, ThemeProvider } from '../style/theme';
@@ -8,6 +9,8 @@ import { theme, ThemeProvider } from '../style/theme';
import { ZeroExInstantContainer } from './zero_ex_instant_container';
fonts.include();
+// tslint:disable-next-line:no-floating-promises
+asyncData.fetchAndDispatchToStore();
export interface ZeroExInstantProps {}
diff --git a/packages/instant/src/components/zero_ex_instant_container.tsx b/packages/instant/src/components/zero_ex_instant_container.tsx
index a384c5f1b..cf918d890 100644
--- a/packages/instant/src/components/zero_ex_instant_container.tsx
+++ b/packages/instant/src/components/zero_ex_instant_container.tsx
@@ -1,16 +1,21 @@
import * as React from 'react';
+import { LatestBuyQuoteOrderDetails } from '../containers/latest_buy_quote_order_details';
+import { LatestError } from '../containers/latest_error';
+import { SelectedAssetBuyButton } from '../containers/selected_asset_buy_button';
+import { SelectedAssetInstantHeading } from '../containers/selected_asset_instant_heading';
+
import { ColorOption } from '../style/theme';
-import { BuyButton } from './buy_button';
-import { InstantHeading } from './instant_heading';
-import { OrderDetails } from './order_details';
import { Container, Flex } from './ui';
export interface ZeroExInstantContainerProps {}
export const ZeroExInstantContainer: React.StatelessComponent<ZeroExInstantContainerProps> = props => (
<Container width="350px">
+ <Container zIndex={1} position="relative">
+ <LatestError />
+ </Container>
<Container
zIndex={2}
position="relative"
@@ -19,9 +24,9 @@ export const ZeroExInstantContainer: React.StatelessComponent<ZeroExInstantConta
hasBoxShadow={true}
>
<Flex direction="column" justify="flex-start">
- <InstantHeading />
- <OrderDetails />
- <BuyButton />
+ <SelectedAssetInstantHeading />
+ <LatestBuyQuoteOrderDetails />
+ <SelectedAssetBuyButton />
</Flex>
</Container>
</Container>
diff --git a/packages/instant/src/constants.ts b/packages/instant/src/constants.ts
new file mode 100644
index 000000000..1fd321c5a
--- /dev/null
+++ b/packages/instant/src/constants.ts
@@ -0,0 +1,6 @@
+import { BigNumber } from '@0xproject/utils';
+export const BIG_NUMBER_ZERO = new BigNumber(0);
+export const sraApiUrl = 'https://api.radarrelay.com/0x/v2/';
+export const zrxAssetData = '0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498';
+export const zrxDecimals = 18;
+export const ethDecimals = 18;
diff --git a/packages/instant/src/containers/latest_buy_quote_order_details.ts b/packages/instant/src/containers/latest_buy_quote_order_details.ts
new file mode 100644
index 000000000..b354c78fa
--- /dev/null
+++ b/packages/instant/src/containers/latest_buy_quote_order_details.ts
@@ -0,0 +1,27 @@
+import { BuyQuoteInfo } from '@0xproject/asset-buyer';
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
+import * as React from 'react';
+import { connect } from 'react-redux';
+import { oc } from 'ts-optchain';
+
+import { State } from '../redux/reducer';
+
+import { OrderDetails } from '../components/order_details';
+
+export interface LatestBuyQuoteOrderDetailsProps {}
+
+interface ConnectedState {
+ buyQuoteInfo?: BuyQuoteInfo;
+ ethUsdPrice?: BigNumber;
+}
+
+const mapStateToProps = (state: State, _ownProps: LatestBuyQuoteOrderDetailsProps): ConnectedState => ({
+ // use the worst case quote info
+ buyQuoteInfo: oc(state).latestBuyQuote.worstCaseQuoteInfo(),
+ ethUsdPrice: state.ethUsdPrice,
+});
+
+export const LatestBuyQuoteOrderDetails: React.ComponentClass<LatestBuyQuoteOrderDetailsProps> = connect(
+ mapStateToProps,
+)(OrderDetails);
diff --git a/packages/instant/src/containers/latest_error.tsx b/packages/instant/src/containers/latest_error.tsx
new file mode 100644
index 000000000..08ea418e7
--- /dev/null
+++ b/packages/instant/src/containers/latest_error.tsx
@@ -0,0 +1,35 @@
+import * as React from 'react';
+
+import { connect } from 'react-redux';
+
+import { SlidingError } from '../components/sliding_error';
+import { LatestErrorDisplay, State } from '../redux/reducer';
+import { errorUtil } from '../util/error';
+
+export interface LatestErrorComponentProps {
+ assetData?: string;
+ latestError?: any;
+ slidingDirection: 'down' | 'up';
+}
+
+export const LatestErrorComponent: React.StatelessComponent<LatestErrorComponentProps> = props => {
+ if (!props.latestError) {
+ return <div />;
+ }
+ const { icon, message } = errorUtil.errorDescription(props.latestError, props.assetData);
+ return <SlidingError direction={props.slidingDirection} icon={icon} message={message} />;
+};
+
+interface ConnectedState {
+ assetData?: string;
+ latestError?: any;
+ slidingDirection: 'down' | 'up';
+}
+export interface LatestErrorProps {}
+const mapStateToProps = (state: State, _ownProps: LatestErrorProps): ConnectedState => ({
+ assetData: state.selectedAssetData,
+ latestError: state.latestError,
+ slidingDirection: state.latestErrorDisplay === LatestErrorDisplay.Present ? 'up' : 'down',
+});
+
+export const LatestError = connect(mapStateToProps)(LatestErrorComponent);
diff --git a/packages/instant/src/containers/selected_asset_amount_input.ts b/packages/instant/src/containers/selected_asset_amount_input.ts
new file mode 100644
index 000000000..0873f1ab6
--- /dev/null
+++ b/packages/instant/src/containers/selected_asset_amount_input.ts
@@ -0,0 +1,89 @@
+import { BuyQuote } from '@0xproject/asset-buyer';
+import { BigNumber } from '@0xproject/utils';
+import { Web3Wrapper } from '@0xproject/web3-wrapper';
+import * as _ from 'lodash';
+import * as React from 'react';
+import { connect } from 'react-redux';
+import { Dispatch } from 'redux';
+
+import { zrxDecimals } from '../constants';
+import { Action, actions } from '../redux/actions';
+import { State } from '../redux/reducer';
+import { ColorOption } from '../style/theme';
+import { AsyncProcessState } from '../types';
+import { assetBuyer } from '../util/asset_buyer';
+import { errorUtil } from '../util/error';
+
+import { AssetAmountInput } from '../components/asset_amount_input';
+
+export interface SelectedAssetAmountInputProps {
+ fontColor?: ColorOption;
+ fontSize?: string;
+}
+
+interface ConnectedState {
+ value?: BigNumber;
+ assetData?: string;
+}
+
+interface ConnectedDispatch {
+ onChange: (value?: BigNumber, assetData?: string) => void;
+}
+
+const mapStateToProps = (state: State, _ownProps: SelectedAssetAmountInputProps): ConnectedState => ({
+ value: state.selectedAssetAmount,
+ assetData: state.selectedAssetData,
+});
+
+const updateBuyQuoteAsync = async (
+ dispatch: Dispatch<Action>,
+ assetData: string,
+ assetAmount: BigNumber,
+): Promise<void> => {
+ // get a new buy quote.
+ const baseUnitValue = Web3Wrapper.toBaseUnitAmount(assetAmount, zrxDecimals);
+
+ // mark quote as pending
+ dispatch(actions.updateBuyQuoteStatePending());
+
+ let newBuyQuote: BuyQuote | undefined;
+ try {
+ newBuyQuote = await assetBuyer.getBuyQuoteAsync(assetData, baseUnitValue);
+ } catch (error) {
+ dispatch(actions.updateBuyQuoteStateFailure());
+ errorUtil.errorFlasher.flashNewError(dispatch, error);
+ return;
+ }
+ // We have a successful new buy quote
+ errorUtil.errorFlasher.clearError(dispatch);
+ // invalidate the last buy quote.
+ dispatch(actions.updateLatestBuyQuote(newBuyQuote));
+};
+
+const debouncedUpdateBuyQuoteAsync = _.debounce(updateBuyQuoteAsync, 200, { trailing: true });
+
+const mapDispatchToProps = (
+ dispatch: Dispatch<Action>,
+ _ownProps: SelectedAssetAmountInputProps,
+): ConnectedDispatch => ({
+ onChange: (value, assetData) => {
+ // Update the input
+ dispatch(actions.updateSelectedAssetAmount(value));
+ // invalidate the last buy quote.
+ dispatch(actions.updateLatestBuyQuote(undefined));
+ // reset our buy state
+ dispatch(actions.updatebuyOrderState(AsyncProcessState.NONE));
+
+ if (!_.isUndefined(value) && !_.isUndefined(assetData)) {
+ // even if it's debounced, give them the illusion it's loading
+ dispatch(actions.updateBuyQuoteStatePending());
+ // tslint:disable-next-line:no-floating-promises
+ debouncedUpdateBuyQuoteAsync(dispatch, assetData, value);
+ }
+ },
+});
+
+export const SelectedAssetAmountInput: React.ComponentClass<SelectedAssetAmountInputProps> = connect(
+ mapStateToProps,
+ mapDispatchToProps,
+)(AssetAmountInput);
diff --git a/packages/instant/src/containers/selected_asset_amount_input.tsx b/packages/instant/src/containers/selected_asset_amount_input.tsx
deleted file mode 100644
index 800a4c568..000000000
--- a/packages/instant/src/containers/selected_asset_amount_input.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { BigNumber } from '@0xproject/utils';
-import * as React from 'react';
-import { connect } from 'react-redux';
-import { Dispatch } from 'redux';
-
-import { State } from '../redux/reducer';
-import { ColorOption } from '../style/theme';
-import { Action, ActionTypes } from '../types';
-
-import { AmountInput } from '../components/amount_input';
-
-export interface SelectedAssetAmountInputProps {
- fontColor?: ColorOption;
- fontSize?: string;
-}
-
-interface ConnectedState {
- value?: BigNumber;
-}
-
-interface ConnectedDispatch {
- onChange?: (value?: BigNumber) => void;
-}
-
-const mapStateToProps = (state: State, _ownProps: SelectedAssetAmountInputProps): ConnectedState => ({
- value: state.selectedAssetAmount,
-});
-
-const mapDispatchToProps = (dispatch: Dispatch<Action>): ConnectedDispatch => ({
- onChange: value => dispatch({ type: ActionTypes.UPDATE_SELECTED_ASSET_AMOUNT, data: value }),
-});
-
-export const SelectedAssetAmountInput: React.ComponentClass<SelectedAssetAmountInputProps> = connect(
- mapStateToProps,
- mapDispatchToProps,
-)(AmountInput);
diff --git a/packages/instant/src/containers/selected_asset_buy_button.ts b/packages/instant/src/containers/selected_asset_buy_button.ts
new file mode 100644
index 000000000..7d3919468
--- /dev/null
+++ b/packages/instant/src/containers/selected_asset_buy_button.ts
@@ -0,0 +1,55 @@
+import { BuyQuote } from '@0xproject/asset-buyer';
+import * as _ from 'lodash';
+import * as React from 'react';
+import { connect } from 'react-redux';
+import { Dispatch } from 'redux';
+
+import { Action, actions } from '../redux/actions';
+import { State } from '../redux/reducer';
+import { AsyncProcessState } from '../types';
+
+import { BuyButton } from '../components/buy_button';
+
+export interface SelectedAssetBuyButtonProps {}
+
+interface ConnectedState {
+ text: string;
+ buyQuote?: BuyQuote;
+}
+
+interface ConnectedDispatch {
+ onClick: (buyQuote: BuyQuote) => void;
+ onBuySuccess: (buyQuote: BuyQuote) => void;
+ onBuyFailure: (buyQuote: BuyQuote) => void;
+}
+
+const textForState = (state: AsyncProcessState): string => {
+ switch (state) {
+ case AsyncProcessState.NONE:
+ return 'Buy';
+ case AsyncProcessState.PENDING:
+ return '...Loading';
+ case AsyncProcessState.SUCCESS:
+ return 'Success!';
+ case AsyncProcessState.FAILURE:
+ return 'Failed';
+ default:
+ return 'Buy';
+ }
+};
+
+const mapStateToProps = (state: State, _ownProps: SelectedAssetBuyButtonProps): ConnectedState => ({
+ text: textForState(state.buyOrderState),
+ buyQuote: state.latestBuyQuote,
+});
+
+const mapDispatchToProps = (dispatch: Dispatch<Action>, ownProps: SelectedAssetBuyButtonProps): ConnectedDispatch => ({
+ onClick: buyQuote => dispatch(actions.updatebuyOrderState(AsyncProcessState.PENDING)),
+ onBuySuccess: buyQuote => dispatch(actions.updatebuyOrderState(AsyncProcessState.SUCCESS)),
+ onBuyFailure: buyQuote => dispatch(actions.updatebuyOrderState(AsyncProcessState.FAILURE)),
+});
+
+export const SelectedAssetBuyButton: React.ComponentClass<SelectedAssetBuyButtonProps> = connect(
+ mapStateToProps,
+ mapDispatchToProps,
+)(BuyButton);
diff --git a/packages/instant/src/containers/selected_asset_instant_heading.ts b/packages/instant/src/containers/selected_asset_instant_heading.ts
new file mode 100644
index 000000000..be31527f1
--- /dev/null
+++ b/packages/instant/src/containers/selected_asset_instant_heading.ts
@@ -0,0 +1,30 @@
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
+import * as React from 'react';
+import { connect } from 'react-redux';
+import { oc } from 'ts-optchain';
+
+import { State } from '../redux/reducer';
+import { AsyncProcessState } from '../types';
+
+import { InstantHeading } from '../components/instant_heading';
+
+export interface InstantHeadingProps {}
+
+interface ConnectedState {
+ selectedAssetAmount?: BigNumber;
+ totalEthBaseAmount?: BigNumber;
+ ethUsdPrice?: BigNumber;
+ quoteState: AsyncProcessState;
+}
+
+const mapStateToProps = (state: State, _ownProps: InstantHeadingProps): ConnectedState => ({
+ selectedAssetAmount: state.selectedAssetAmount,
+ totalEthBaseAmount: oc(state).latestBuyQuote.worstCaseQuoteInfo.totalEthAmount(),
+ ethUsdPrice: state.ethUsdPrice,
+ quoteState: state.quoteState,
+});
+
+export const SelectedAssetInstantHeading: React.ComponentClass<InstantHeadingProps> = connect(mapStateToProps)(
+ InstantHeading,
+);
diff --git a/packages/instant/src/data/asset_meta_data.ts b/packages/instant/src/data/asset_meta_data.ts
new file mode 100644
index 000000000..e4d3e8f73
--- /dev/null
+++ b/packages/instant/src/data/asset_meta_data.ts
@@ -0,0 +1,15 @@
+import { AssetProxyId, ObjectMap } from '@0xproject/types';
+
+import { zrxAssetData } from '../constants';
+import { AssetMetaData } from '../types';
+
+// Map from assetData string to AssetMetaData object
+// TODO: import this from somewhere else.
+export const assetMetaData: ObjectMap<AssetMetaData> = {
+ [zrxAssetData]: {
+ assetProxyId: AssetProxyId.ERC20,
+ decimals: 18,
+ primaryColor: 'rgb(54, 50, 60)',
+ symbol: 'zrx',
+ },
+};
diff --git a/packages/instant/src/redux/actions.ts b/packages/instant/src/redux/actions.ts
new file mode 100644
index 000000000..bec847742
--- /dev/null
+++ b/packages/instant/src/redux/actions.ts
@@ -0,0 +1,46 @@
+import { BuyQuote } from '@0xproject/asset-buyer';
+import { BigNumber } from '@0xproject/utils';
+import * as _ from 'lodash';
+
+import { ActionsUnion, AsyncProcessState } from '../types';
+
+export interface PlainAction<T extends string> {
+ type: T;
+}
+
+export interface ActionWithPayload<T extends string, P> extends PlainAction<T> {
+ data: P;
+}
+
+export type Action = ActionsUnion<typeof actions>;
+
+function createAction<T extends string>(type: T): PlainAction<T>;
+function createAction<T extends string, P>(type: T, data: P): ActionWithPayload<T, P>;
+function createAction<T extends string, P>(type: T, data?: P): PlainAction<T> | ActionWithPayload<T, P> {
+ return _.isUndefined(data) ? { type } : { type, data };
+}
+
+export enum ActionTypes {
+ UPDATE_ETH_USD_PRICE = 'UPDATE_ETH_USD_PRICE',
+ UPDATE_SELECTED_ASSET_AMOUNT = 'UPDATE_SELECTED_ASSET_AMOUNT',
+ UPDATE_SELECTED_ASSET_BUY_STATE = 'UPDATE_SELECTED_ASSET_BUY_STATE',
+ UPDATE_LATEST_BUY_QUOTE = 'UPDATE_LATEST_BUY_QUOTE',
+ UPDATE_BUY_QUOTE_STATE_PENDING = 'UPDATE_BUY_QUOTE_STATE_PENDING',
+ UPDATE_BUY_QUOTE_STATE_FAILURE = 'UPDATE_BUY_QUOTE_STATE_FAILURE',
+ SET_ERROR = 'SET_ERROR',
+ HIDE_ERROR = 'HIDE_ERROR',
+ CLEAR_ERROR = 'CLEAR_ERROR',
+}
+
+export const actions = {
+ updateEthUsdPrice: (price?: BigNumber) => createAction(ActionTypes.UPDATE_ETH_USD_PRICE, price),
+ updateSelectedAssetAmount: (amount?: BigNumber) => createAction(ActionTypes.UPDATE_SELECTED_ASSET_AMOUNT, amount),
+ updatebuyOrderState: (buyState: AsyncProcessState) =>
+ createAction(ActionTypes.UPDATE_SELECTED_ASSET_BUY_STATE, buyState),
+ updateLatestBuyQuote: (buyQuote?: BuyQuote) => createAction(ActionTypes.UPDATE_LATEST_BUY_QUOTE, buyQuote),
+ updateBuyQuoteStatePending: () => createAction(ActionTypes.UPDATE_BUY_QUOTE_STATE_PENDING),
+ updateBuyQuoteStateFailure: () => createAction(ActionTypes.UPDATE_BUY_QUOTE_STATE_FAILURE),
+ setError: (error?: any) => createAction(ActionTypes.SET_ERROR, error),
+ hideError: () => createAction(ActionTypes.HIDE_ERROR),
+ clearError: () => createAction(ActionTypes.CLEAR_ERROR),
+};
diff --git a/packages/instant/src/redux/async_data.ts b/packages/instant/src/redux/async_data.ts
new file mode 100644
index 000000000..348838307
--- /dev/null
+++ b/packages/instant/src/redux/async_data.ts
@@ -0,0 +1,22 @@
+import { BIG_NUMBER_ZERO } from '../constants';
+import { coinbaseApi } from '../util/coinbase_api';
+
+import { ActionTypes } from './actions';
+
+import { store } from './store';
+
+export const asyncData = {
+ fetchAndDispatchToStore: async () => {
+ let ethUsdPrice = BIG_NUMBER_ZERO;
+ try {
+ ethUsdPrice = await coinbaseApi.getEthUsdPrice();
+ } catch (e) {
+ // ignore
+ } finally {
+ store.dispatch({
+ type: ActionTypes.UPDATE_ETH_USD_PRICE,
+ data: ethUsdPrice,
+ });
+ }
+ },
+};
diff --git a/packages/instant/src/redux/reducer.ts b/packages/instant/src/redux/reducer.ts
index 5026895ae..54290483b 100644
--- a/packages/instant/src/redux/reducer.ts
+++ b/packages/instant/src/redux/reducer.ts
@@ -1,16 +1,37 @@
+import { BuyQuote } from '@0xproject/asset-buyer';
import { BigNumber } from '@0xproject/utils';
import * as _ from 'lodash';
-import { Action, ActionTypes } from '../types';
+import { zrxAssetData } from '../constants';
+import { AsyncProcessState } from '../types';
+import { Action, ActionTypes } from './actions';
+
+export enum LatestErrorDisplay {
+ Present,
+ Hidden,
+}
export interface State {
- ethUsdPrice?: string;
+ selectedAssetData?: string;
selectedAssetAmount?: BigNumber;
+ buyOrderState: AsyncProcessState;
+ ethUsdPrice?: BigNumber;
+ latestBuyQuote?: BuyQuote;
+ quoteState: AsyncProcessState;
+ latestError?: any;
+ latestErrorDisplay: LatestErrorDisplay;
}
export const INITIAL_STATE: State = {
- ethUsdPrice: undefined,
+ // TODO: Remove hardcoded zrxAssetData
+ selectedAssetData: zrxAssetData,
selectedAssetAmount: undefined,
+ buyOrderState: AsyncProcessState.NONE,
+ ethUsdPrice: undefined,
+ latestBuyQuote: undefined,
+ latestError: undefined,
+ latestErrorDisplay: LatestErrorDisplay.Hidden,
+ quoteState: AsyncProcessState.NONE,
};
export const reducer = (state: State = INITIAL_STATE, action: Action): State => {
@@ -25,6 +46,46 @@ export const reducer = (state: State = INITIAL_STATE, action: Action): State =>
...state,
selectedAssetAmount: action.data,
};
+ case ActionTypes.UPDATE_LATEST_BUY_QUOTE:
+ return {
+ ...state,
+ latestBuyQuote: action.data,
+ quoteState: AsyncProcessState.SUCCESS,
+ };
+ case ActionTypes.UPDATE_BUY_QUOTE_STATE_PENDING:
+ return {
+ ...state,
+ latestBuyQuote: undefined,
+ quoteState: AsyncProcessState.PENDING,
+ };
+ case ActionTypes.UPDATE_BUY_QUOTE_STATE_FAILURE:
+ return {
+ ...state,
+ latestBuyQuote: undefined,
+ quoteState: AsyncProcessState.FAILURE,
+ };
+ case ActionTypes.UPDATE_SELECTED_ASSET_BUY_STATE:
+ return {
+ ...state,
+ buyOrderState: action.data,
+ };
+ case ActionTypes.SET_ERROR:
+ return {
+ ...state,
+ latestError: action.data,
+ latestErrorDisplay: LatestErrorDisplay.Present,
+ };
+ case ActionTypes.HIDE_ERROR:
+ return {
+ ...state,
+ latestErrorDisplay: LatestErrorDisplay.Hidden,
+ };
+ case ActionTypes.CLEAR_ERROR:
+ return {
+ ...state,
+ latestError: undefined,
+ latestErrorDisplay: LatestErrorDisplay.Hidden,
+ };
default:
return state;
}
diff --git a/packages/instant/src/redux/store.ts b/packages/instant/src/redux/store.ts
index fcd19f9a8..b9ce9c0c1 100644
--- a/packages/instant/src/redux/store.ts
+++ b/packages/instant/src/redux/store.ts
@@ -1,6 +1,7 @@
import * as _ from 'lodash';
import { createStore, Store as ReduxStore } from 'redux';
+import { devToolsEnhancer } from 'redux-devtools-extension/developmentOnly';
import { reducer, State } from './reducer';
-export const store: ReduxStore<State> = createStore(reducer);
+export const store: ReduxStore<State> = createStore(reducer, devToolsEnhancer({}));
diff --git a/packages/instant/src/types.ts b/packages/instant/src/types.ts
index d150bd8ab..f0ffb893b 100644
--- a/packages/instant/src/types.ts
+++ b/packages/instant/src/types.ts
@@ -1,9 +1,33 @@
-export enum ActionTypes {
- UPDATE_ETH_USD_PRICE,
- UPDATE_SELECTED_ASSET_AMOUNT,
+import { AssetProxyId, ObjectMap } from '@0xproject/types';
+
+// Reusable
+export enum AsyncProcessState {
+ NONE = 'None',
+ PENDING = 'Pending',
+ SUCCESS = 'Success',
+ FAILURE = 'Failure',
+}
+
+export type FunctionType = (...args: any[]) => any;
+export type ActionCreatorsMapObject = ObjectMap<FunctionType>;
+export type ActionsUnion<A extends ActionCreatorsMapObject> = ReturnType<A[keyof A]>;
+
+export interface ERC20AssetMetaData {
+ assetProxyId: AssetProxyId.ERC20;
+ decimals: number;
+ primaryColor?: string;
+ symbol: string;
}
-export interface Action {
- type: ActionTypes;
- data?: any;
+export interface ERC721AssetMetaData {
+ assetProxyId: AssetProxyId.ERC721;
+ name: string;
+ primaryColor?: string;
+}
+
+export type AssetMetaData = ERC20AssetMetaData | ERC721AssetMetaData;
+
+export enum Network {
+ Kovan = 42,
+ Mainnet = 1,
}
diff --git a/packages/instant/src/util/asset_buyer.ts b/packages/instant/src/util/asset_buyer.ts
new file mode 100644
index 000000000..27d66d600
--- /dev/null
+++ b/packages/instant/src/util/asset_buyer.ts
@@ -0,0 +1,9 @@
+import { AssetBuyer } from '@0xproject/asset-buyer';
+
+import { sraApiUrl } from '../constants';
+
+import { getProvider } from './provider';
+
+const provider = getProvider();
+
+export const assetBuyer = AssetBuyer.getAssetBuyerForStandardRelayerAPIUrl(provider, sraApiUrl);
diff --git a/packages/instant/src/util/asset_data.ts b/packages/instant/src/util/asset_data.ts
new file mode 100644
index 000000000..f7c5b78cd
--- /dev/null
+++ b/packages/instant/src/util/asset_data.ts
@@ -0,0 +1,21 @@
+import * as _ from 'lodash';
+
+import { AssetProxyId } from '@0xproject/types';
+
+import { assetMetaData } from '../data/asset_meta_data';
+
+export const assetDataUtil = {
+ bestNameForAsset: (assetData: string | undefined, defaultString: string) => {
+ if (_.isUndefined(assetData)) {
+ return defaultString;
+ }
+ const metaData = assetMetaData[assetData];
+ if (_.isUndefined(metaData)) {
+ return defaultString;
+ }
+ if (metaData.assetProxyId === AssetProxyId.ERC20) {
+ return metaData.symbol.toUpperCase();
+ }
+ return defaultString;
+ },
+};
diff --git a/packages/instant/src/util/coinbase_api.ts b/packages/instant/src/util/coinbase_api.ts
new file mode 100644
index 000000000..94a5d3c80
--- /dev/null
+++ b/packages/instant/src/util/coinbase_api.ts
@@ -0,0 +1,10 @@
+import { BigNumber } from '@0xproject/utils';
+
+const baseEndpoint = 'https://api.coinbase.com/v2';
+export const coinbaseApi = {
+ getEthUsdPrice: async (): Promise<BigNumber> => {
+ const res = await fetch(`${baseEndpoint}/prices/ETH-USD/buy`);
+ const resJson = await res.json();
+ return new BigNumber(resJson.data.amount);
+ },
+};
diff --git a/packages/instant/src/util/error.ts b/packages/instant/src/util/error.ts
new file mode 100644
index 000000000..48cb131a9
--- /dev/null
+++ b/packages/instant/src/util/error.ts
@@ -0,0 +1,62 @@
+import { AssetBuyerError } from '@0xproject/asset-buyer';
+import { Dispatch } from 'redux';
+
+import { Action, actions } from '../redux/actions';
+import { assetDataUtil } from '../util/asset_data';
+
+class ErrorFlasher {
+ private _timeoutId?: number;
+ public flashNewError(dispatch: Dispatch<Action>, error: any, delayMs: number = 7000): void {
+ this._clearTimeout();
+
+ // dispatch new message
+ dispatch(actions.setError(error));
+
+ this._timeoutId = window.setTimeout(() => {
+ dispatch(actions.hideError());
+ }, delayMs);
+ }
+ public clearError(dispatch: Dispatch<Action>): void {
+ this._clearTimeout();
+ dispatch(actions.hideError());
+ }
+ private _clearTimeout(): void {
+ if (this._timeoutId) {
+ window.clearTimeout(this._timeoutId);
+ }
+ }
+}
+
+const humanReadableMessageForError = (error: Error, assetData?: string): string | undefined => {
+ const hasInsufficientLiquidity =
+ error.message === AssetBuyerError.InsufficientAssetLiquidity ||
+ error.message === AssetBuyerError.InsufficientZrxLiquidity;
+ if (hasInsufficientLiquidity) {
+ const assetName = assetDataUtil.bestNameForAsset(assetData, 'of this asset');
+ return `Not enough ${assetName} available`;
+ }
+
+ if (
+ error.message === AssetBuyerError.StandardRelayerApiError ||
+ error.message.startsWith(AssetBuyerError.AssetUnavailable)
+ ) {
+ const assetName = assetDataUtil.bestNameForAsset(assetData, 'This asset');
+ return `${assetName} is currently unavailable`;
+ }
+
+ return undefined;
+};
+
+export const errorUtil = {
+ errorFlasher: new ErrorFlasher(),
+ errorDescription: (error?: any, assetData?: string): { icon: string; message: string } => {
+ let bestMessage: string | undefined;
+ if (error instanceof Error) {
+ bestMessage = humanReadableMessageForError(error, assetData);
+ }
+ return {
+ icon: '😢',
+ message: bestMessage || 'Something went wrong...',
+ };
+ },
+};
diff --git a/packages/instant/src/util/format.ts b/packages/instant/src/util/format.ts
new file mode 100644
index 000000000..09eb880b2
--- /dev/null
+++ b/packages/instant/src/util/format.ts
@@ -0,0 +1,53 @@
+import { BigNumber } from '@0xproject/utils';
+import { Web3Wrapper } from '@0xproject/web3-wrapper';
+import * as _ from 'lodash';
+
+import { ethDecimals } from '../constants';
+
+export const format = {
+ ethBaseAmount: (
+ ethBaseAmount?: BigNumber,
+ decimalPlaces: number = 4,
+ defaultText: React.ReactNode = '0 ETH',
+ ): React.ReactNode => {
+ if (_.isUndefined(ethBaseAmount)) {
+ return defaultText;
+ }
+ const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseAmount, ethDecimals);
+ return format.ethUnitAmount(ethUnitAmount, decimalPlaces);
+ },
+ ethUnitAmount: (
+ ethUnitAmount?: BigNumber,
+ decimalPlaces: number = 4,
+ defaultText: React.ReactNode = '0 ETH',
+ ): React.ReactNode => {
+ if (_.isUndefined(ethUnitAmount)) {
+ return defaultText;
+ }
+ const roundedAmount = ethUnitAmount.round(decimalPlaces);
+ return `${roundedAmount} ETH`;
+ },
+ ethBaseAmountInUsd: (
+ ethBaseAmount?: BigNumber,
+ ethUsdPrice?: BigNumber,
+ decimalPlaces: number = 2,
+ defaultText: React.ReactNode = '$0.00',
+ ): React.ReactNode => {
+ if (_.isUndefined(ethBaseAmount) || _.isUndefined(ethUsdPrice)) {
+ return defaultText;
+ }
+ const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseAmount, ethDecimals);
+ return format.ethUnitAmountInUsd(ethUnitAmount, ethUsdPrice, decimalPlaces);
+ },
+ ethUnitAmountInUsd: (
+ ethUnitAmount?: BigNumber,
+ ethUsdPrice?: BigNumber,
+ decimalPlaces: number = 2,
+ defaultText: React.ReactNode = '$0.00',
+ ): React.ReactNode => {
+ if (_.isUndefined(ethUnitAmount) || _.isUndefined(ethUsdPrice)) {
+ return defaultText;
+ }
+ return `$${ethUnitAmount.mul(ethUsdPrice).toFixed(decimalPlaces)}`;
+ },
+};
diff --git a/packages/instant/src/util/provider.ts b/packages/instant/src/util/provider.ts
new file mode 100644
index 000000000..49705fd11
--- /dev/null
+++ b/packages/instant/src/util/provider.ts
@@ -0,0 +1,12 @@
+import { Provider } from 'ethereum-types';
+
+export const getProvider = (): Provider => {
+ const injectedWeb3 = (window as any).web3 || undefined;
+ try {
+ // Use MetaMask/Mist provider
+ return injectedWeb3.currentProvider;
+ } catch (err) {
+ // Throws when user doesn't have MetaMask/Mist running
+ throw new Error(`No injected web3 found: ${err}`);
+ }
+};
diff --git a/packages/instant/src/util/util.ts b/packages/instant/src/util/util.ts
new file mode 100644
index 000000000..232a86850
--- /dev/null
+++ b/packages/instant/src/util/util.ts
@@ -0,0 +1,5 @@
+import * as _ from 'lodash';
+
+export const util = {
+ boundNoop: _.noop.bind(_),
+};
diff --git a/packages/instant/src/util/web3_wrapper.ts b/packages/instant/src/util/web3_wrapper.ts
new file mode 100644
index 000000000..d7e43521f
--- /dev/null
+++ b/packages/instant/src/util/web3_wrapper.ts
@@ -0,0 +1,5 @@
+import { Web3Wrapper } from '@0xproject/web3-wrapper';
+
+import { getProvider } from './provider';
+
+export const web3Wrapper = new Web3Wrapper(getProvider());