repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
avgust13/Account-Manager
|
src/renderer/containers/Validator/AddValidatorModal/AddValidatorModalFields.tsx
|
import React, {FC} from 'react';
import {useFormContext} from '@renderer/hooks';
import {FormInput, FormSelect} from '@renderer/components/FormComponents';
import {InputOption} from '@renderer/types';
const protocolOptions: InputOption[] = [{value: 'http'}, {value: 'https'}];
const AddValidatorModalFields: FC = () => {
const {errors, touched} = useFormContext();
const addressError = !!errors.form && !!touched.form;
return (
<>
{addressError ? <span className="AddValidatorModal__form-error">{errors.form}</span> : null}
<FormSelect focused label="Protocol" name="protocol" options={protocolOptions} required searchable={false} />
<FormInput label="IP Address" name="ipAddress" required />
<FormInput label="Port" name="port" type="number" />
<FormInput label="Nickname" name="nickname" />
</>
);
};
export default AddValidatorModalFields;
|
avgust13/Account-Manager
|
src/renderer/components/FormComponents/index.tsx
|
<reponame>avgust13/Account-Manager
import Form from './Form';
import FormButton, {FormButtonProps} from './FormButton';
import FormInput from './FormInput';
import FormRadioGroup from './FormRadioGroup';
import FormSelect from './FormSelect';
import FormSelectDetailed from './FormSelectDetailed';
import FormTextArea from './FormTextArea';
export {Form, FormButton, FormButtonProps, FormInput, FormRadioGroup, FormSelect, FormSelectDetailed, FormTextArea};
|
avgust13/Account-Manager
|
src/renderer/hooks/useEventListener.tsx
|
import {useEffect, useRef} from 'react';
type EventName = 'mousedown';
const useEventListener = (eventName: EventName, handler: (e: Event) => any, element: EventTarget = window): void => {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
}, [handler]);
useEffect(() => {
const eventListener = (e: Event) => handlerRef.current(e);
element.addEventListener(eventName, eventListener);
return () => {
element.removeEventListener(eventName, eventListener);
};
}, [element, eventName]);
};
export default useEventListener;
|
avgust13/Account-Manager
|
src/renderer/components/PageHeader/index.tsx
|
import React, {FC, ReactNode} from 'react';
import DropdownMenuButton, {DropdownMenuDirection, DropdownMenuOption} from '@renderer/components/DropdownMenuButton';
import './PageHeader.scss';
interface ComponentProps {
dropdownMenuOptions?: DropdownMenuOption[];
leftContent?: ReactNode;
rightContent?: ReactNode;
title: string;
}
const PageHeader: FC<ComponentProps> = ({dropdownMenuOptions, leftContent, rightContent, title}) => {
return (
<div className="PageHeader">
<div className="PageHeader__left-section">
<h1 className="PageHeader__title">{title}</h1>
{leftContent}
</div>
{(dropdownMenuOptions?.length || rightContent) && (
<div className="PageHeader__right-section">
{rightContent}
{dropdownMenuOptions?.length ? (
<DropdownMenuButton
className="PageHeader__DropdownMenuButton"
direction={DropdownMenuDirection.left}
options={dropdownMenuOptions}
/>
) : null}
</div>
)}
</div>
);
};
export default PageHeader;
|
avgust13/Account-Manager
|
src/renderer/components/FormElements/Radio/index.tsx
|
import React, {FC, useEffect, useRef} from 'react';
import clsx from 'clsx';
import Icon, {IconType} from '@renderer/components/Icon';
import {getCustomClassNames} from '@renderer/utils/components';
import './Radio.scss';
export interface BaseRadioProps {
checked: boolean;
className?: string;
disabled?: boolean;
error?: boolean;
focused?: boolean;
name?: string;
onClick?(e?: React.MouseEvent<HTMLDivElement, MouseEvent>): void;
onKeyDown?(e?: React.KeyboardEvent<HTMLDivElement>): void;
size?: number | string;
unfocusable?: boolean;
value: string;
}
const Radio: FC<BaseRadioProps> = ({
checked,
className,
disabled = false,
error = false,
focused = false,
name,
onClick,
onKeyDown,
size,
unfocusable = false,
value,
}) => {
const radioRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (focused) {
radioRef.current?.focus();
}
}, [focused, radioRef]);
return (
<>
<Icon
className={clsx('Radio', className, {
'Radio--checked': checked,
'Radio--error': error,
...getCustomClassNames(className, '--checked', checked),
...getCustomClassNames(className, '--error', error),
})}
disabled={disabled}
icon={checked ? IconType.radioboxMarked : IconType.radioboxBlank}
onClick={onClick}
onKeyDown={onKeyDown}
ref={radioRef}
size={size}
unfocusable={unfocusable}
/>
<input
className="Radio__input"
checked={checked}
disabled={disabled}
id={name || value}
name={name || value}
readOnly
type="radio"
value={value}
/>
</>
);
};
export default Radio;
|
avgust13/Account-Manager
|
src/renderer/store/banks/bankConfirmationBlocks.ts
|
import {createSlice} from '@reduxjs/toolkit';
import {BANK_CONFIRMATION_BLOCKS} from '@renderer/constants';
import {BankConfirmationBlock, DictWithPaginatedResultsAndError} from '@renderer/types';
import {setPaginatedResultErrorReducer, setPaginatedResultReducer, unsetDataReducer} from '@renderer/utils/store';
const bankConfirmationBlocks = createSlice({
initialState: {} as DictWithPaginatedResultsAndError<BankConfirmationBlock>,
name: BANK_CONFIRMATION_BLOCKS,
reducers: {
setBankConfirmationBlocks: setPaginatedResultReducer<BankConfirmationBlock>(),
setBankConfirmationBlocksError: setPaginatedResultErrorReducer(),
unsetBankConfirmationBlocks: unsetDataReducer(),
},
});
export const {
setBankConfirmationBlocks,
setBankConfirmationBlocksError,
unsetBankConfirmationBlocks,
} = bankConfirmationBlocks.actions;
export default bankConfirmationBlocks;
|
avgust13/Account-Manager
|
src/renderer/containers/Bank/RemoveBankModal/index.tsx
|
import React, {FC} from 'react';
import {useDispatch} from 'react-redux';
import Modal from '@renderer/components/Modal';
import {unsetManagedBank} from '@renderer/store/app';
import {AppDispatch, ManagedNode} from '@renderer/types';
interface ComponentProps {
bank: ManagedNode;
close(): void;
}
const RemoveBankModal: FC<ComponentProps> = ({bank, close}) => {
const dispatch = useDispatch<AppDispatch>();
const handleSubmit = async (): Promise<void> => {
dispatch(unsetManagedBank(bank));
close();
};
return (
<Modal className="RemoveBankModal" close={close} header="Remove Bank" onSubmit={handleSubmit} submitButton="Yes">
Are you sure you want to remove this bank?
</Modal>
);
};
export default RemoveBankModal;
|
avgust13/Account-Manager
|
src/renderer/containers/Notifications/index.tsx
|
import React, {FC, ReactNode, useEffect, useMemo, useRef, useState} from 'react';
import {createPortal} from 'react-dom';
import {useSelector} from 'react-redux';
import {NavLink, useLocation} from 'react-router-dom';
import clsx from 'clsx';
import formatDistanceToNow from 'date-fns/formatDistanceToNow';
import reverse from 'lodash/reverse';
import sortBy from 'lodash/sortBy';
import Icon, {IconType} from '@renderer/components/Icon';
import {useBooleanState} from '@renderer/hooks';
import {getManagedAccounts, getManagedFriends, getNotifications} from '@renderer/selectors';
import {NotificationType} from '@renderer/types';
import NotificationsMenu from './NotificationsMenu';
import './Notifications.scss';
const dropdownRoot = document.getElementById('dropdown-root')!;
const Notifications: FC = () => {
const {pathname} = useLocation();
const [lastReadTime, setLastReadTime] = useState<number>(new Date().getTime());
const [open, toggleOpen, , closeMenu] = useBooleanState(false);
const iconRef = useRef<HTMLDivElement>(null);
const managedAccounts = useSelector(getManagedAccounts);
const managedFriends = useSelector(getManagedFriends);
const notifications = useSelector(getNotifications);
const managedAccountNumbersString = useMemo(
() =>
Object.values(managedAccounts)
.map(({account_number}) => account_number)
.sort()
.join('-'),
[managedAccounts],
);
const managedAccountNumbers = useMemo(() => managedAccountNumbersString.split('-'), [managedAccountNumbersString]);
const unreadNotificationsLength = useMemo(
() => notifications.filter(({notificationTime}) => lastReadTime < notificationTime).length,
[lastReadTime, notifications],
);
useEffect(() => {
closeMenu();
}, [pathname, closeMenu]);
const getAccountNickname = (accountNumber: string): string => {
const managedAccount = managedAccounts[accountNumber];
if (managedAccount) {
return managedAccount.nickname
? truncate(managedAccount.nickname, 16)
: truncate(managedAccount.account_number, 8);
}
const managedFriend = managedFriends[accountNumber];
if (managedFriend) {
return managedFriend.nickname ? truncate(managedFriend.nickname, 16) : truncate(managedFriend.account_number, 8);
}
return truncate(accountNumber, 16);
};
const handleBellClick = (): void => {
if (open) {
updateLastReadTime();
closeMenu();
} else {
toggleOpen();
}
};
const handleMenuClose = (): void => {
updateLastReadTime();
closeMenu();
};
const renderNotifications = (): ReactNode[] => {
let confirmationBlockNotifications = notifications.filter(
({notificationType}) => notificationType === NotificationType.confirmationBlockNotification,
);
confirmationBlockNotifications = sortBy(confirmationBlockNotifications, ['notificationTime']);
confirmationBlockNotifications = reverse(confirmationBlockNotifications);
return confirmationBlockNotifications.map(({notificationTime, payload}) => {
const {
message: {
block: {
account_number: senderAccountNumber,
message: {txs},
},
},
} = payload;
return txs
.filter(({recipient}) => managedAccountNumbers.includes(recipient))
.map(({amount, recipient}) => {
const read = lastReadTime > notificationTime;
return (
<div className="Notifications__notification" key={recipient}>
<Icon
className={clsx('Notifications__Icon', {
'Notifications__Icon--read': read,
})}
icon={IconType.checkboxBlankCircle}
size={8}
/>
<div className="Notifications__right">
<div className="Notifications__description">
<div>
<NavLink className="Notifications__NavLink" to={`/account/${senderAccountNumber}/overview`}>
{getAccountNickname(senderAccountNumber)}
</NavLink>{' '}
paid you{' '}
<NavLink className="Notifications__NavLink" to={`/account/${recipient}/overview`}>
({getAccountNickname(recipient)})
</NavLink>
</div>
<div
className={clsx('Notifications__time', {
'Notifications__time--read': read,
})}
>
{formatDistanceToNow(notificationTime, {includeSeconds: true})} ago
</div>
</div>
<div className="Notifications__amount">+ {amount}</div>
</div>
</div>
);
});
});
};
const renderUnreadNotificationsDot = (): ReactNode => {
return unreadNotificationsLength ? (
<span className="Notifications__unread-notifications-dot" onClick={handleBellClick} />
) : null;
};
const truncate = (str: string, size: number): string => {
return str.length <= size ? str : `${str.slice(0, size)}...`;
};
const updateLastReadTime = (): void => {
const time = new Date().getTime();
setLastReadTime(time);
};
return (
<>
<div className="Notifications__Icon-container">
<Icon
className={clsx('Notifications', {'Notifications--active': open})}
icon={IconType.bell}
onClick={handleBellClick}
ref={iconRef}
/>
{renderUnreadNotificationsDot()}
</div>
{open &&
createPortal(
<NotificationsMenu
handleMenuClose={handleMenuClose}
iconRef={iconRef}
menuOpen={open}
notifications={renderNotifications()}
unreadNotificationsLength={unreadNotificationsLength}
updateLastReadTime={updateLastReadTime}
/>,
dropdownRoot,
)}
</>
);
};
export default Notifications;
|
avgust13/Account-Manager
|
src/renderer/utils/blocks.ts
|
import axios from 'axios';
import {BankConfig, Dict, ManagedAccount, Tx, ValidatorConfig} from '@renderer/types';
import {formatAddress} from '@renderer/utils/address';
import {generateBlock, getKeyPairFromSigningKeyHex} from '@renderer/utils/signing';
import {getBankTxFee, getPrimaryValidatorTxFee} from '@renderer/utils/transactions';
const createBlock = async (
activePrimaryValidator: ValidatorConfig,
managedAccounts: Dict<ManagedAccount>,
recipientAccountNumber: string,
senderAccountNumber: string,
txs: Tx[],
): Promise<string> => {
const {signing_key: signingKeyHex} = managedAccounts[senderAccountNumber];
const {publicKeyHex, signingKey} = getKeyPairFromSigningKeyHex(signingKeyHex);
const balanceLock = await fetchAccountBalanceLock(senderAccountNumber, activePrimaryValidator);
return generateBlock(balanceLock, publicKeyHex, signingKey, txs);
};
const fetchAccountBalanceLock = async (
accountNumber: string,
activePrimaryValidator: ValidatorConfig,
): Promise<string> => {
const {ip_address: ipAddress, port, protocol} = activePrimaryValidator;
const address = formatAddress(ipAddress, port, protocol);
const {
data: {balance_lock: balanceLock},
} = await axios.get(`${address}/accounts/${accountNumber}/balance_lock`);
return balanceLock;
};
export const sendBlock = async (
activeBank: BankConfig,
activePrimaryValidator: ValidatorConfig,
managedAccounts: Dict<ManagedAccount>,
points: number,
recipientAccountNumber: string,
senderAccountNumber: string,
): Promise<void> => {
const recipientIsActiveBank = recipientAccountNumber === activeBank.account_number;
const recipientIsActivePrimaryValidator = recipientAccountNumber === activePrimaryValidator.account_number;
const bankTxFee = getBankTxFee(activeBank, senderAccountNumber);
const primaryValidatorTxFee = getPrimaryValidatorTxFee(activePrimaryValidator, senderAccountNumber);
let txs: Tx[] = [
{
amount:
points +
(recipientIsActiveBank ? bankTxFee : 0) +
(recipientIsActivePrimaryValidator ? primaryValidatorTxFee : 0),
recipient: recipientAccountNumber,
},
];
if (!recipientIsActiveBank) {
txs.push({
amount: bankTxFee,
recipient: activeBank.account_number,
});
}
if (!recipientIsActivePrimaryValidator) {
txs.push({
amount: primaryValidatorTxFee,
recipient: activePrimaryValidator.account_number,
});
}
txs = txs.filter((tx) => !!tx.amount);
const {ip_address: ipAddress, port, protocol} = activeBank;
const address = formatAddress(ipAddress, port, protocol);
const block = await createBlock(
activePrimaryValidator,
managedAccounts,
recipientAccountNumber,
senderAccountNumber,
txs,
);
await axios.post(`${address}/blocks`, block, {
headers: {
'Content-Type': 'application/json',
},
});
};
|
avgust13/Account-Manager
|
src/renderer/containers/LeftMenu/LeftSubmenuItem/index.tsx
|
<filename>src/renderer/containers/LeftMenu/LeftSubmenuItem/index.tsx
import React, {FC, ReactNode} from 'react';
import {NavLink, RouteComponentProps, withRouter} from 'react-router-dom';
import './LeftSubmenuItem.scss';
export interface LeftSubmenuItemProps extends RouteComponentProps {
baseUrl: string;
key: string;
label: ReactNode;
to: string;
}
const LeftSubmenuItem: FC<LeftSubmenuItemProps> = ({baseUrl, key, label, location, to}) => {
const getIsActive = (): boolean => location.pathname.includes(baseUrl);
return (
<NavLink
activeClassName="LeftSubmenuItem--active"
className="LeftSubmenuItem"
isActive={getIsActive}
key={key}
to={to}
>
<div className="LeftSubmenuItem__label">{label}</div>
</NavLink>
);
};
export default withRouter(LeftSubmenuItem);
|
avgust13/Account-Manager
|
src/renderer/components/Logo/index.tsx
|
<gh_stars>100-1000
import React, {FC, memo} from 'react';
import clsx from 'clsx';
import TnbLogo from '@renderer/assets/logo.png';
interface ComponentProps {
className?: string;
size?: number;
}
const Logo: FC<ComponentProps> = ({className, size = 24}) => {
return (
<img
alt="thenewboston logo"
className={clsx('Logo', className)}
src={TnbLogo}
style={{height: size, width: size}}
/>
);
};
export default memo(Logo);
|
avgust13/Account-Manager
|
src/renderer/containers/Friend/EditFriendNicknameModal/index.tsx
|
<gh_stars>1-10
import React, {FC} from 'react';
import {useDispatch} from 'react-redux';
import Modal from '@renderer/components/Modal';
import {FormInput} from '@renderer/components/FormComponents';
import {setManagedFriend} from '@renderer/store/app';
import {AppDispatch, ManagedFriend} from '@renderer/types';
interface ComponentProps {
close(): void;
managedFriend: ManagedFriend;
}
const EditFriendNicknameModal: FC<ComponentProps> = ({close, managedFriend}) => {
const dispatch = useDispatch<AppDispatch>();
const initialValues = {
nickname: managedFriend.nickname,
};
type FormValues = typeof initialValues;
const handleSubmit = ({nickname}: FormValues): void => {
dispatch(
setManagedFriend({
account_number: managedFriend.account_number,
nickname,
}),
);
close();
};
return (
<Modal
cancelButton="Cancel"
close={close}
header="Edit Friend Nickname"
initialValues={initialValues}
onSubmit={handleSubmit}
submitButton="Save"
>
<FormInput focused label="Friend Nickname" name="nickname" />
</Modal>
);
};
export default EditFriendNicknameModal;
|
avgust13/Account-Manager
|
src/renderer/containers/LeftMenu/LeftSubmenuItemStatus/index.tsx
|
import React, {FC, ReactNode} from 'react';
import {NavLink, RouteComponentProps, withRouter} from 'react-router-dom';
import clsx from 'clsx';
import Icon, {IconType} from '@renderer/components/Icon';
import './LeftSubmenuItemStatus.scss';
export interface LeftSubmenuItemStatusProps extends RouteComponentProps {
badge: 'active-bank' | 'primary-validator' | null;
baseUrl: string;
key: string;
label: ReactNode;
status: 'offline' | 'online';
to: string;
}
const LeftSubmenuItemStatus: FC<LeftSubmenuItemStatusProps> = ({badge, baseUrl, key, label, location, status, to}) => {
const getIsActive = (): boolean => location.pathname.includes(baseUrl);
const renderBadge = (): ReactNode => {
if (!badge) return null;
return (
<div
className={clsx('LeftSubmenuItemStatus__badge', {
'LeftSubmenuItemStatus__badge--active-bank': badge === 'active-bank',
'LeftSubmenuItemStatus__badge--primary-validator': badge === 'primary-validator',
})}
>
{badge === 'active-bank' ? 'Active' : 'Primary'}
</div>
);
};
const renderStatusIcon = (): ReactNode => {
return {
offline: (
<Icon
className="LeftSubmenuItemStatus__Icon LeftSubmenuItemStatus__Icon--offline"
icon={IconType.checkboxBlankCircleOutline}
size={8}
/>
),
online: (
<Icon
className="LeftSubmenuItemStatus__Icon LeftSubmenuItemStatus__Icon--online"
icon={IconType.checkboxBlankCircle}
size={8}
/>
),
}[status];
};
return (
<NavLink
activeClassName="LeftSubmenuItemStatus--active"
className="LeftSubmenuItemStatus"
isActive={getIsActive}
key={key}
to={to}
>
{renderStatusIcon()}
<div
className={clsx('LeftSubmenuItemStatus__label', {
'LeftSubmenuItemStatus__label--with-badge': badge,
})}
>
{label}
</div>
{renderBadge()}
</NavLink>
);
};
export default withRouter(LeftSubmenuItemStatus);
|
avgust13/Account-Manager
|
src/renderer/components/DropdownMenuButton/index.tsx
|
import React, {CSSProperties, FC, KeyboardEvent, ReactNode, useEffect, useRef, useState} from 'react';
import {createPortal} from 'react-dom';
import clsx from 'clsx';
import noop from 'lodash/noop';
import Icon, {IconType} from '@renderer/components/Icon';
import {useBooleanState, useEventListener} from '@renderer/hooks';
import {GenericVoidFunction} from '@renderer/types';
import {getCustomClassNames} from '@renderer/utils/components';
import './DropdownMenuButton.scss';
export enum DropdownMenuDirection {
left,
right,
}
export interface DropdownMenuOption {
disabled?: boolean;
label: ReactNode;
onClick: GenericVoidFunction;
}
interface ComponentProps {
className?: string;
direction?: DropdownMenuDirection;
options: DropdownMenuOption[];
}
const dropdownRoot = document.getElementById('dropdown-root')!;
const DropdownMenuButton: FC<ComponentProps> = ({className, direction = DropdownMenuDirection.right, options}) => {
const iconRef = useRef<HTMLDivElement>(null);
const optionsRef = useRef<HTMLDivElement[]>([]);
const [open, toggleOpen, , closeMenu] = useBooleanState(false);
const [dropdownPositionStyle, setDropdownPositionStyle] = useState<CSSProperties | undefined>(undefined);
useEffect(() => {
if (open) {
optionsRef.current[0]?.focus();
}
}, [open, optionsRef]);
const handleClick = (e: any): void => {
if (!dropdownRoot.contains(e.target) && !iconRef.current?.contains(e.target)) {
closeMenu();
}
};
useEventListener('mousedown', handleClick, document);
const handleOpenDropdown = (): void => {
if (iconRef.current) {
const {bottom, left, width} = iconRef.current.getBoundingClientRect();
if (direction === DropdownMenuDirection.left) {
setDropdownPositionStyle({right: window.innerWidth - left - width / 2, top: bottom + 3});
} else if (direction === DropdownMenuDirection.right) {
setDropdownPositionStyle({left: left + width / 2, top: bottom + 3});
}
toggleOpen();
}
};
const handleOptionClick = (optionOnClick: GenericVoidFunction) => async (): Promise<void> => {
await optionOnClick();
closeMenu();
};
const handleOptionKeyDown = (optionOnClick: GenericVoidFunction, index: number) => async (
e: KeyboardEvent<HTMLDivElement>,
): Promise<void> => {
if (index !== options.length - 1 && e.key === 'ArrowDown') {
optionsRef.current[index + 1]?.focus();
return;
}
if (index !== 0 && e.key === 'ArrowUp') {
optionsRef.current[index - 1]?.focus();
return;
}
if (e.key === 'Enter') {
await optionOnClick();
closeMenu();
}
};
return (
<>
<Icon
className={clsx('DropdownMenuButton', className, {
'DropdownMenuButton--active': open,
...getCustomClassNames(className, '--active', open),
})}
icon={IconType.dotsVertical}
onClick={handleOpenDropdown}
ref={iconRef}
/>
{open &&
createPortal(
<div
className={clsx('DropdownMenuButton__menu', {...getCustomClassNames(className, '__menu', true)})}
style={dropdownPositionStyle}
>
{options.map(({disabled = false, label, onClick: optionOnClick}, index) => {
return (
<div
className={clsx('DropdownMenuButton__option', {
'DropdownMenuButton__option--disabled': disabled,
...getCustomClassNames(className, '__option--disabled', disabled),
})}
key={JSON.stringify(label)}
onKeyDown={disabled ? noop : handleOptionKeyDown(optionOnClick, index)}
onClick={disabled ? noop : handleOptionClick(optionOnClick)}
ref={(el) => {
if (el) {
optionsRef.current[index] = el;
}
}}
role="button"
tabIndex={0}
>
{label}
</div>
);
})}
</div>,
dropdownRoot,
)}
</>
);
};
export default DropdownMenuButton;
|
avgust13/Account-Manager
|
src/renderer/store/localStore.ts
|
import ElectronStore from 'electron-store';
const localStore = new ElectronStore();
export default localStore;
|
avgust13/Account-Manager
|
src/renderer/dispatchers/app/index.ts
|
import {
clearManagedAccounts,
clearManagedBanks,
clearManagedFriends,
clearManagedValidators,
setManagedBank,
setManagedValidator,
unsetActiveBank,
unsetActivePrimaryValidator,
} from '@renderer/store/app';
import {AddressData, AppDispatch} from '@renderer/types';
import {formatAddressFromNode} from '@renderer/utils/address';
import {fetchBankConfig} from '../banks';
import {fetchValidatorConfig} from '../validators';
export const clearLocalState = () => (dispatch: AppDispatch) => {
dispatch(clearManagedAccounts());
dispatch(clearManagedBanks());
dispatch(clearManagedFriends());
dispatch(clearManagedValidators());
};
export const connect = (bankAddressData: AddressData) => async (dispatch: AppDispatch) => {
const address = formatAddressFromNode(bankAddressData);
const bankConfig = await dispatch(fetchBankConfig(address));
if (bankConfig.error) {
return {
address: bankConfig.address,
error: bankConfig.error,
};
}
if (!bankConfig.data) {
throw new Error('No BankConfig data');
}
const {primary_validator: primaryValidator} = bankConfig.data;
const primaryValidatorAddress = formatAddressFromNode(primaryValidator);
const validatorConfig = await dispatch(fetchValidatorConfig(primaryValidatorAddress));
if (validatorConfig.error) {
return {
address: validatorConfig.error,
error: validatorConfig.error,
};
}
if (!validatorConfig.data) {
throw new Error('No ValidatorConfig data');
}
return {
address,
bankConfig: bankConfig.data,
validatorConfig: validatorConfig.data,
};
};
export const connectAndStoreLocalData = (bankAddressData: AddressData, bankNickname: string) => async (
dispatch: AppDispatch,
) => {
const connectResponse = await dispatch(connect(bankAddressData));
if (connectResponse?.error) {
return connectResponse;
}
const {bankConfig, validatorConfig} = connectResponse;
if (!bankConfig) {
return {
address: connectResponse.address,
error: 'No BankConfig Data',
};
}
if (!validatorConfig) {
return {
address: connectResponse.address,
error: 'No ValidatorConfig Data',
};
}
const activeBankData = {
ip_address: bankConfig.ip_address,
is_default: true,
nickname: bankNickname,
nid_signing_key: '',
node_identifier: bankConfig.node_identifier,
port: bankConfig.port,
protocol: bankConfig.protocol,
};
dispatch(unsetActiveBank());
dispatch(setManagedBank(activeBankData));
const activePrimaryValidatorData = {
ip_address: validatorConfig.ip_address,
is_default: true,
nickname: '',
nid_signing_key: '',
node_identifier: validatorConfig.node_identifier,
port: validatorConfig.port,
protocol: validatorConfig.protocol,
};
dispatch(unsetActivePrimaryValidator());
dispatch(setManagedValidator(activePrimaryValidatorData));
return connectResponse;
};
|
avgust13/Account-Manager
|
src/renderer/containers/Validator/RemoveValidatorModal/index.tsx
|
import React, {FC} from 'react';
import {useDispatch} from 'react-redux';
import Modal from '@renderer/components/Modal';
import {unsetManagedValidator} from '@renderer/store/app';
import {AppDispatch, ManagedNode} from '@renderer/types';
interface ComponentProps {
close(): void;
validator: ManagedNode;
}
const RemoveValidatorModal: FC<ComponentProps> = ({close, validator}) => {
const dispatch = useDispatch<AppDispatch>();
const handleSubmit = async (): Promise<void> => {
dispatch(unsetManagedValidator(validator));
close();
};
return (
<Modal
className="RemoveValidatorModal"
close={close}
header="Remove Validator"
onSubmit={handleSubmit}
submitButton="Yes"
>
Are you sure you want to remove this validator?
</Modal>
);
};
export default RemoveValidatorModal;
|
avgust13/Account-Manager
|
src/renderer/types/generic.ts
|
<reponame>avgust13/Account-Manager
type GenericFunctionConstructor<T> = (...args: any[]) => T;
export type GenericFunction = GenericFunctionConstructor<any>;
export type GenericVoidFunction = GenericFunctionConstructor<void | Promise<void>>;
|
avgust13/Account-Manager
|
src/renderer/containers/Friend/FriendOverview/index.tsx
|
import React, {FC, useEffect, useState} from 'react';
import {useSelector} from 'react-redux';
import {useParams} from 'react-router-dom';
import axios from 'axios';
import {TileAccountBalance, TileAccountNumber} from '@renderer/components/Tiles';
import {getActivePrimaryValidatorConfig} from '@renderer/selectors';
import {formatAddress} from '@renderer/utils/address';
import './FriendOverview.scss';
const FriendOverview: FC = () => {
const {accountNumber} = useParams();
const [balance, setBalance] = useState<number | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const activePrimaryValidator = useSelector(getActivePrimaryValidatorConfig);
useEffect(() => {
if (!activePrimaryValidator) return;
const fetchData = async (): Promise<void> => {
const {ip_address: ipAddress, port, protocol} = activePrimaryValidator;
const address = formatAddress(ipAddress, port, protocol);
setLoading(true);
const {data} = await axios.get(`${address}/accounts/${accountNumber}/balance`);
setBalance(data.balance);
setLoading(false);
};
fetchData();
}, [accountNumber, activePrimaryValidator]);
return (
<div className="FriendOverview">
<TileAccountBalance balance={balance || 0} loading={loading} type="friend" />
<TileAccountNumber accountNumber={accountNumber} type="friend" />
</div>
);
};
export default FriendOverview;
|
avgust13/Account-Manager
|
src/renderer/containers/Validator/ValidatorAccounts/index.tsx
|
<filename>src/renderer/containers/Validator/ValidatorAccounts/index.tsx
import React, {FC, useMemo} from 'react';
import AccountLink from '@renderer/components/AccountLink';
import PageTable, {PageTableData, PageTableItems} from '@renderer/components/PageTable';
import Pagination from '@renderer/components/Pagination';
import {VALIDATOR_ACCOUNTS} from '@renderer/constants';
import {useAddress, usePaginatedNetworkDataFetcher} from '@renderer/hooks';
import {ValidatorAccount} from '@renderer/types';
enum TableKeys {
accountNumber,
balance,
balanceLock,
}
const ValidatorAccounts: FC = () => {
const address = useAddress();
const {count, currentPage, loading, results: validatorAccounts, setPage, totalPages} = usePaginatedNetworkDataFetcher<
ValidatorAccount
>(VALIDATOR_ACCOUNTS, address);
const validatorAccountsTableData = useMemo<PageTableData[]>(
() =>
validatorAccounts.map((account) => ({
key: account.id,
[TableKeys.accountNumber]: <AccountLink accountNumber={account.account_number} />,
[TableKeys.balanceLock]: account.balance_lock,
[TableKeys.balance]: account.balance,
})) || [],
[validatorAccounts],
);
const pageTableItems = useMemo<PageTableItems>(
() => ({
data: validatorAccountsTableData,
headers: {
[TableKeys.accountNumber]: 'Account Number',
[TableKeys.balanceLock]: 'Balance Lock',
[TableKeys.balance]: 'Balance',
},
orderedKeys: [TableKeys.accountNumber, TableKeys.balance, TableKeys.balanceLock],
}),
[validatorAccountsTableData],
);
return (
<div className="ValidatorAccounts">
<PageTable count={count} currentPage={currentPage} items={pageTableItems} loading={loading} />
<Pagination currentPage={currentPage} setPage={setPage} totalPages={totalPages} />
</div>
);
};
export default ValidatorAccounts;
|
avgust13/Account-Manager
|
src/renderer/store/notifications/index.ts
|
<filename>src/renderer/store/notifications/index.ts
import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {NOTIFICATIONS} from '@renderer/constants';
import {Notification, NotificationType} from '@renderer/types';
const notifications = createSlice({
initialState: [] as Notification[],
name: NOTIFICATIONS,
reducers: {
setConfirmationBlockNotification: (state, {payload}: PayloadAction<Notification>) => {
const blockIdentifiers = Object.values(state)
.filter(({notificationType}) => notificationType === NotificationType.confirmationBlockNotification)
.map((notification) => notification.payload.message.block_identifier);
if (blockIdentifiers.includes(payload.payload.message.block_identifier)) return;
state.push(payload);
},
},
});
export const {setConfirmationBlockNotification} = notifications.actions;
export default notifications;
|
avgust13/Account-Manager
|
src/renderer/utils/api.ts
|
<reponame>avgust13/Account-Manager<filename>src/renderer/utils/api.ts
import axios from 'axios';
import {AppDispatch, PaginatedQueryParams, PaginatedResults} from '@renderer/types';
import {formatQueryParams} from '@renderer/utils/address';
import {SetError, SetResults} from '@renderer/utils/store';
export async function fetchPaginatedResults<T>(
address: string,
urlParam: string,
queryParams: PaginatedQueryParams,
dispatch: AppDispatch,
setResults: SetResults<T>,
setError: SetError,
) {
try {
const {data} = await axios.get<PaginatedResults<T>>(`${address}/${urlParam}${formatQueryParams(queryParams)}`);
dispatch(setResults({address, ...data}));
return data.results;
} catch (error) {
if (!error.response) {
throw error;
}
dispatch(setError({address, error: error.response.data}));
}
}
|
avgust13/Account-Manager
|
src/renderer/components/Tiles/TileAccountBalance/index.tsx
|
import React, {FC, memo, useMemo} from 'react';
import clsx from 'clsx';
import {getCustomClassNames} from '@renderer/utils/components';
import Tile from '../Tile';
import './TileAccountBalance.scss';
interface ComponentProps {
balance: number;
className?: string;
loading: boolean;
type: 'account' | 'friend';
}
const TileAccountBalance: FC<ComponentProps> = ({balance, className, loading, type}) => {
const title = useMemo(() => {
const prefix = type === 'account' ? 'My' : "Friend's";
return `${prefix} Account Balance`;
}, [type]);
const balanceStr = useMemo(() => {
if (loading) return '-';
return balance.toLocaleString();
}, [balance, loading]);
return (
<Tile className={clsx('TileAccountBalance', className)}>
<>
<div className={clsx('TileAccountBalance__title', {...getCustomClassNames(className, '__title', true)})}>
{title}
</div>
<div className={clsx('TileAccountBalance__amount', {...getCustomClassNames(className, '__amount', true)})}>
{balanceStr}
</div>
</>
</Tile>
);
};
export default memo(TileAccountBalance);
|
avgust13/Account-Manager
|
src/renderer/components/Icon/index.tsx
|
/* eslint-disable react/jsx-props-no-spreading */
import React, {forwardRef, ReactNode, useCallback, useMemo} from 'react';
import clsx from 'clsx';
import AlertIcon from 'mdi-react/AlertIcon';
import AlertCircleOutlineIcon from 'mdi-react/AlertCircleOutlineIcon';
import ArrowLeftIcon from 'mdi-react/ArrowLeftIcon';
import ArrowRightIcon from 'mdi-react/ArrowRightIcon';
import BellIcon from 'mdi-react/BellIcon';
import CheckboxBlankCircleIcon from 'mdi-react/CheckboxBlankCircleIcon';
import CheckboxBlankCircleOutlineIcon from 'mdi-react/CheckboxBlankCircleOutlineIcon';
import ChevronLeftIcon from 'mdi-react/ChevronLeftIcon';
import ChevronRightIcon from 'mdi-react/ChevronRightIcon';
import CloseIcon from 'mdi-react/CloseIcon';
import ContentCopyIcon from 'mdi-react/ContentCopyIcon';
import DotsVerticalIcon from 'mdi-react/DotsVerticalIcon';
import LanConnectIcon from 'mdi-react/LanConnectIcon';
import LanDisconnectIcon from 'mdi-react/LanDisconnectIcon';
import LoadingIcon from 'mdi-react/LoadingIcon';
import PencilIcon from 'mdi-react/PencilIcon';
import PowerIcon from 'mdi-react/PowerIcon';
import PlayIcon from 'mdi-react/PlayIcon';
import PlusIcon from 'mdi-react/PlusIcon';
import RadioboxBlankIcon from 'mdi-react/RadioboxBlankIcon';
import RadioboxMarkedIcon from 'mdi-react/RadioboxMarkedIcon';
import RefreshIcon from 'mdi-react/RefreshIcon';
import SyncIcon from 'mdi-react/SyncIcon';
import ThumbsUpIcon from 'mdi-react/ThumbsUpIcon';
import {getCustomClassNames} from '@renderer/utils/components';
import TnbIcon from './TnbIcon';
import './Icon.scss';
// These names are camelCased versions of the names found in https://materialdesignicons.com/
export enum IconType {
alert,
alertCircleOutline,
arrowLeft,
arrowRight,
bell,
checkboxBlankCircle,
checkboxBlankCircleOutline,
chevronLeft,
chevronRight,
close,
contentCopy,
dotsVertical,
lanConnect,
lanDisconnect,
loading,
pencil,
play,
plus,
power,
radioboxBlank,
radioboxMarked,
refresh,
sync,
thumbsUp,
tnb,
}
interface ComponentProps {
className?: string;
disabled?: boolean;
icon: IconType;
onClick?(e?: React.MouseEvent<HTMLDivElement, MouseEvent>): void;
onKeyDown?(e?: React.KeyboardEvent<HTMLDivElement>): void;
size?: number | string;
unfocusable?: boolean;
}
const Icon = forwardRef<HTMLDivElement, ComponentProps>(
({className, disabled = false, icon, onClick, onKeyDown, size = 24, unfocusable = false}, ref) => {
const iconProps = useMemo(
() => ({
size,
}),
[size],
);
const getTabIndex = () => {
if (unfocusable) return undefined;
return onClick ? 0 : undefined;
};
const handleClick = (e?: React.MouseEvent<HTMLDivElement, MouseEvent>): void => {
if (disabled || !onClick) return;
onClick(e);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>): void => {
if (!onClick) return;
if (e.key === 'Enter' && !disabled) {
handleClick();
}
onKeyDown?.(e);
};
const renderIcon = useCallback((): ReactNode => {
switch (icon) {
case IconType.alert:
return <AlertIcon {...iconProps} />;
case IconType.alertCircleOutline:
return <AlertCircleOutlineIcon {...iconProps} />;
case IconType.arrowLeft:
return <ArrowLeftIcon {...iconProps} />;
case IconType.arrowRight:
return <ArrowRightIcon {...iconProps} />;
case IconType.bell:
return <BellIcon {...iconProps} />;
case IconType.checkboxBlankCircle:
return <CheckboxBlankCircleIcon {...iconProps} />;
case IconType.checkboxBlankCircleOutline:
return <CheckboxBlankCircleOutlineIcon {...iconProps} />;
case IconType.chevronLeft:
return <ChevronLeftIcon {...iconProps} />;
case IconType.chevronRight:
return <ChevronRightIcon {...iconProps} />;
case IconType.close:
return <CloseIcon {...iconProps} />;
case IconType.contentCopy:
return <ContentCopyIcon {...iconProps} />;
case IconType.dotsVertical:
return <DotsVerticalIcon {...iconProps} />;
case IconType.lanConnect:
return <LanConnectIcon {...iconProps} />;
case IconType.lanDisconnect:
return <LanDisconnectIcon {...iconProps} />;
case IconType.loading:
return <LoadingIcon {...iconProps} />;
case IconType.pencil:
return <PencilIcon {...iconProps} />;
case IconType.play:
return <PlayIcon {...iconProps} />;
case IconType.plus:
return <PlusIcon {...iconProps} />;
case IconType.power:
return <PowerIcon {...iconProps} />;
case IconType.radioboxBlank:
return <RadioboxBlankIcon {...iconProps} />;
case IconType.radioboxMarked:
return <RadioboxMarkedIcon {...iconProps} />;
case IconType.refresh:
return <RefreshIcon {...iconProps} />;
case IconType.sync:
return <SyncIcon {...iconProps} />;
case IconType.thumbsUp:
return <ThumbsUpIcon {...iconProps} />;
case IconType.tnb:
return <TnbIcon {...iconProps} />;
default:
return null;
}
}, [icon, iconProps]);
return (
<div
className={clsx('Icon', className, {
'Icon--button': !!onClick,
'Icon--disabled': disabled,
...getCustomClassNames(className, '--disabled', disabled),
})}
ref={ref}
onClick={handleClick}
onKeyDown={handleKeyDown}
tabIndex={getTabIndex()}
>
{renderIcon()}
</div>
);
},
);
export default Icon;
|
avgust13/Account-Manager
|
src/renderer/components/PageLayout/index.tsx
|
import React, {FC, ReactNode} from 'react';
import clsx from 'clsx';
import {getCustomClassNames} from '@renderer/utils/components';
import './PageLayout.scss';
interface ComponentProps {
className?: string;
content: ReactNode;
top: ReactNode;
}
const PageLayout: FC<ComponentProps> = ({className, content, top}) => {
return (
<div className={clsx('PageLayout', className)}>
<div className={clsx('PageLayout__header', {...getCustomClassNames(className, '__header', true)})}>{top}</div>
<hr className={clsx('PageLayout__divider', {...getCustomClassNames(className, '__divider', true)})} />
<div className={clsx('PageLayout__content', {...getCustomClassNames(className, '__content', true)})}>
{content}
</div>
</div>
);
};
export default PageLayout;
|
avgust13/Account-Manager
|
src/renderer/components/FormElements/Select/index.tsx
|
/* eslint-disable react/jsx-props-no-spreading */
import React, {FC, ReactNode, useMemo} from 'react';
import ReactSelect, {ActionMeta, FocusEventHandler, FormatOptionLabelMeta} from 'react-select';
import ReactSelectCreatable from 'react-select/creatable';
import {ValueType} from 'react-select/src/types';
import clsx from 'clsx';
import {InputOption} from '@renderer/types';
import {getCustomClassNames} from '@renderer/utils/components';
import './Select.scss';
export interface BaseSelectProps {
className?: string;
clearable?: boolean;
creatable?: boolean;
disabled?: boolean;
error?: boolean;
focused?: boolean;
name?: string;
onBlur?: FocusEventHandler;
onChange?(value: ValueType<InputOption>, actionMeta?: ActionMeta<InputOption>): void;
options: InputOption[];
placeholder?: string;
searchable?: boolean;
value?: InputOption | null;
}
interface ComponentProps extends BaseSelectProps {
filterOption?(option: InputOption, rawInput: string): boolean;
formatOptionLabel?(option: InputOption, labelMeta: FormatOptionLabelMeta<InputOption>): ReactNode;
}
const Select: FC<ComponentProps> = ({
className,
clearable = false,
creatable = false,
disabled = false,
error = false,
filterOption,
focused = false,
formatOptionLabel,
searchable = true,
name,
onBlur,
onChange,
options,
placeholder = 'Select',
value,
}) => {
const formattedOptions = useMemo(
() =>
options.map(({disabled: optionDisabled, label, value: optionValue}) => ({
isDisabled: optionDisabled,
label,
value: optionValue,
})),
[options],
);
const getOptionLabel = ({label, value: valueParam}: InputOption): string => label || valueParam;
const getSharedSelectProps = () => {
return {
autoFocus: focused,
className: clsx('Select', className, {
'Select--error': error,
...getCustomClassNames(className, '--error', error),
}),
classNamePrefix: 'Select',
filterOption,
formatOptionLabel,
getOptionLabel,
isClearable: clearable,
isDisabled: disabled,
isSearchable: searchable,
menuPortalTarget: document.getElementById('dropdown-root'),
name,
onBlur,
onChange,
onKeyDown: handleKeyDown,
options: formattedOptions,
placeholder,
value,
};
};
const handleKeyDown = (e: any) => {
if (!e.target.value && e.key === 'Backspace') {
onChange?.(null);
}
};
return creatable ? (
<ReactSelectCreatable formatCreateLabel={() => undefined} {...getSharedSelectProps()} />
) : (
<ReactSelect {...getSharedSelectProps()} />
);
};
export default Select;
|
avgust13/Account-Manager
|
src/renderer/utils/dates.ts
|
<reponame>avgust13/Account-Manager
import format from 'date-fns/format';
import parseISO from 'date-fns/parseISO';
export const formatDate = (dateStr: string) =>
dateStr.length ? format(parseISO(dateStr), 'yyyy-MM-dd hh:mm:ss a') : '';
|
avgust13/Account-Manager
|
src/renderer/components/PaginationSummary/index.tsx
|
import React, {FC, memo} from 'react';
import clsx from 'clsx';
import {PAGINATED_RESULTS_LIMIT} from '@renderer/config';
import './PaginationSummary.scss';
interface ComponentProps {
className?: string;
count: number;
currentPage: number;
}
const PaginationSummary: FC<ComponentProps> = ({className, count, currentPage}) => {
const firstRow = Math.min((currentPage - 1) * PAGINATED_RESULTS_LIMIT + 1, count);
const lastRow = Math.min(currentPage * PAGINATED_RESULTS_LIMIT, count);
const summary = `${firstRow}-${lastRow} of ${count}`;
return <div className={clsx('PaginationSummary', className)}>{summary}</div>;
};
export default memo(PaginationSummary);
|
avgust13/Account-Manager
|
src/renderer/utils/signing.ts
|
import {sign, SignKeyPair} from 'tweetnacl';
import orderBy from 'lodash/orderBy';
import {Tx} from '@renderer/types';
export const generateBlock = (
balanceLock: string,
publicKeyHex: string,
signingKey: Uint8Array,
transactions: Tx[],
) => {
const message = {
balance_key: balanceLock,
txs: orderBy(transactions, ['recipient']),
};
const strMessage: string = JSON.stringify(message);
const block = {
account_number: publicKeyHex,
message,
signature: generateSignature(strMessage, signingKey),
};
return JSON.stringify(block);
};
export const generateSignature = (message: string, signingKey: Uint8Array) => {
const encoder = new TextEncoder();
const encodedData = encoder.encode(message);
const signatureArray = sign(encodedData, signingKey);
const signature = Buffer.from(signatureArray).toString('hex');
return signature.substring(0, 128);
};
export const generateSignedMessage = (message: object, publicKeyHex: string, signingKey: Uint8Array) => {
const strMessage = JSON.stringify(message);
const signedMessage = {
message,
node_identifier: publicKeyHex,
signature: generateSignature(strMessage, signingKey),
};
return JSON.stringify(signedMessage);
};
export const getKeyPairDetails = (keyPair: SignKeyPair) => {
const {publicKey, secretKey: signingKey} = keyPair;
const publicKeyHex = Buffer.from(publicKey).toString('hex');
const signingKeyHex = Buffer.from(signingKey).toString('hex');
return {
publicKey,
publicKeyHex,
signingKey,
signingKeyHex: signingKeyHex.replace(publicKeyHex, ''),
};
};
export const getKeyPairFromSigningKeyHex = (signingKeyHex: string) => {
const keyPair = sign.keyPair.fromSeed(Buffer.from(signingKeyHex, 'hex'));
return getKeyPairDetails(keyPair);
};
|
avgust13/Account-Manager
|
src/renderer/components/Tiles/index.tsx
|
<gh_stars>0
import Tile from './Tile';
import TileAccountBalance from './TileAccountBalance';
import TileAccountNumber from './TileAccountNumber';
import TileSigningKey from './TileSigningKey';
export {Tile, TileAccountBalance, TileAccountNumber, TileSigningKey};
|
avgust13/Account-Manager
|
src/renderer/hooks/useNavigationalHistory.tsx
|
<filename>src/renderer/hooks/useNavigationalHistory.tsx
import {useCallback, useState} from 'react';
import {useHistory, useLocation} from 'react-router-dom';
const locationKeys: string[] = [];
const useNavigationalHistory = () => {
const history = useHistory();
const location = useLocation();
const [backEnabled, setBackEnabled] = useState(false);
const [forwardEnabled, setForwardEnabled] = useState(false);
history.listen(({key}) => {
if (key === undefined) return;
// User visiting a new location
if (!locationKeys.includes(key)) {
locationKeys.push(key);
if (locationKeys.length > 1) {
setBackEnabled(true);
}
setForwardEnabled(false);
return;
}
// User re-visiting first location in history
if (key === locationKeys[0]) {
setBackEnabled(false);
return;
}
// User came back to last location after navigating through earlier history
if (key === locationKeys[locationKeys.length - 1]) {
setForwardEnabled(false);
return;
}
// User is navigating through history (but not at first or last)
setBackEnabled(true);
setForwardEnabled(true);
});
const back = useCallback<() => void>(() => {
if (backEnabled) {
history.goBack();
(document.activeElement as any)?.blur();
}
}, [backEnabled, history]);
const forward = useCallback<() => void>(() => {
if (forwardEnabled) {
history.goForward();
(document.activeElement as any)?.blur();
}
}, [forwardEnabled, history]);
const reload = useCallback(() => {
const currentLocation = location.pathname;
history.replace('/reload');
setTimeout(() => {
history.replace(currentLocation);
(document.activeElement as any)?.blur();
});
}, [history, location]);
return {
back,
backEnabled,
forward,
forwardEnabled,
reload,
};
};
export default useNavigationalHistory;
|
avgust13/Account-Manager
|
src/renderer/containers/PurchaseConfirmationServicesModal/PurchaseConfirmationServicesModalFields/index.tsx
|
<filename>src/renderer/containers/PurchaseConfirmationServicesModal/PurchaseConfirmationServicesModalFields/index.tsx
import React, {FC, useMemo} from 'react';
import {useSelector} from 'react-redux';
import {FormInput, FormSelectDetailed} from '@renderer/components/FormComponents';
import RequiredAsterisk from '@renderer/components/RequiredAsterisk';
import {useFormContext} from '@renderer/hooks';
import {
getActiveBankConfig,
getActivePrimaryValidatorConfig,
getBankConfigs,
getManagedAccounts,
getManagedBanks,
} from '@renderer/selectors';
import {BaseValidator, InputOption} from '@renderer/types';
import {getBankTxFee, getPrimaryValidatorTxFee} from '@renderer/utils/transactions';
import './PurchaseConfirmationServicesModalFields.scss';
export interface FormValues {
amount: string;
bankAddress: string;
}
interface ComponentProps {
submitting: boolean;
validator: BaseValidator;
}
const PurchaseConfirmationServicesModalFields: FC<ComponentProps> = ({submitting, validator}) => {
const {values} = useFormContext<FormValues>();
const activeBankConfig = useSelector(getActiveBankConfig)!;
const activePrimaryValidatorConfig = useSelector(getActivePrimaryValidatorConfig)!;
const bankConfigs = useSelector(getBankConfigs);
const managedAccounts = useSelector(getManagedAccounts);
const managedBanks = useSelector(getManagedBanks);
const getBanksAccountNumberFromAddress = (bankAddress: string) => {
const {
data: {account_number: accountNumber},
} = bankConfigs[bankAddress];
return accountNumber;
};
const getFromOptions = useMemo<InputOption[]>(
() =>
Object.entries(managedBanks).map(([key, managedBank]) => ({
label: managedBank.nickname,
value: key,
})),
[managedBanks],
);
const renderActiveBankFee = (): string => {
if (!values?.bankAddress) return activeBankConfig.default_transaction_fee.toLocaleString();
return getBankTxFee(activeBankConfig, getBanksAccountNumberFromAddress(values.bankAddress)).toLocaleString() || '-';
};
const renderBanksAccountBalance = (): string => {
const {bankAddress} = values;
if (!bankAddress) return '-';
const accountNumber = getBanksAccountNumberFromAddress(bankAddress);
const managedAccount = managedAccounts[accountNumber];
return managedAccount?.balance?.toLocaleString() || '0';
};
const renderDays = (): string => {
const {daily_confirmation_rate: dailyRate} = validator;
const {amount} = values;
if (!amount || !dailyRate) return '-';
const days = (parseInt(amount, 10) / dailyRate).toFixed(2);
return `${days} days`;
};
const renderTotal = (): string => {
const {amount, bankAddress} = values;
if (!amount || !bankAddress) return '-';
const accountNumber = getBanksAccountNumberFromAddress(bankAddress);
const bankTxFee = getBankTxFee(activeBankConfig, accountNumber);
const validatorTxFee = getPrimaryValidatorTxFee(activePrimaryValidatorConfig, accountNumber);
return (parseInt(amount, 10) + bankTxFee + validatorTxFee).toLocaleString();
};
return (
<>
<FormSelectDetailed
disabled={submitting}
focused
label="From: Managed Bank"
name="bankAddress"
options={getFromOptions}
required
/>
<div className="PurchaseConfirmationServicesModalFields__label">To: Validator</div>
<div className="PurchaseConfirmationServicesModalFields__validator-nid">
<div>{validator.node_identifier.slice(0, 32)}</div>
<div>{validator.node_identifier.slice(32)}</div>
</div>
<table className="PurchaseConfirmationServicesModalFields__table">
<tbody>
<tr>
<td>Account Balance</td>
<td>
<span className="PurchaseConfirmationServicesModalFields__account-balance">
{renderBanksAccountBalance()}
</span>
</td>
</tr>
<tr>
<td>
Amount
<RequiredAsterisk />
</td>
<td>
<FormInput disabled={submitting} hideErrorBlock name="amount" placeholder="0" type="number" />
</td>
</tr>
<tr>
<td>Daily Rate</td>
<td>{validator.daily_confirmation_rate}</td>
</tr>
<tr>
<td>Time</td>
<td>
<b>{renderDays()}</b>
</td>
</tr>
<tr className="PurchaseConfirmationServicesModalFields__bank-fee-tr">
<td>Active Bank Fee</td>
<td>{renderActiveBankFee()}</td>
</tr>
<tr>
<td>Primary Validator Fee</td>
<td>{getPrimaryValidatorTxFee(activePrimaryValidatorConfig, values?.bankAddress) || '-'}</td>
</tr>
<tr>
<td>Total Tx Cost</td>
<td>
<b>{renderTotal()}</b>
</td>
</tr>
</tbody>
</table>
</>
);
};
export default PurchaseConfirmationServicesModalFields;
|
avgust13/Account-Manager
|
src/renderer/store/validators/validatorValidators.ts
|
import {createSlice} from '@reduxjs/toolkit';
import {VALIDATOR_VALIDATORS} from '@renderer/constants';
import {BaseValidator, DictWithPaginatedResultsAndError} from '@renderer/types';
import {setPaginatedResultErrorReducer, setPaginatedResultReducer, unsetDataReducer} from '@renderer/utils/store';
const validatorValidators = createSlice({
initialState: {} as DictWithPaginatedResultsAndError<BaseValidator>,
name: VALIDATOR_VALIDATORS,
reducers: {
setValidatorValidators: setPaginatedResultReducer<BaseValidator>(),
setValidatorValidatorsError: setPaginatedResultErrorReducer(),
unsetValidatorValidators: unsetDataReducer(),
},
});
export const {
setValidatorValidators,
setValidatorValidatorsError,
unsetValidatorValidators,
} = validatorValidators.actions;
export default validatorValidators;
|
avgust13/Account-Manager
|
src/renderer/containers/LeftMenu/LeftSubmenu/index.tsx
|
<gh_stars>1-10
import React, {FC, ReactNode} from 'react';
import ArrowToggle from '@renderer/components/ArrowToggle';
import Icon, {IconType} from '@renderer/components/Icon';
import {useBooleanState} from '@renderer/hooks';
import './LeftSubmenu.scss';
interface ComponentProps {
leftIcon?: ReactNode;
menuItems: ReactNode[];
rightOnClick?(): void;
rightText?: string;
title: string;
}
const LeftSubmenu: FC<ComponentProps> = ({leftIcon, menuItems, rightOnClick, rightText, title}) => {
const [expanded, toggleExpanded] = useBooleanState(true);
const renderHeaderContent = (): ReactNode => {
return (
<>
<div className="LeftSubmenu__left-items">
{leftIcon || <ArrowToggle expanded={expanded} onClick={toggleExpanded} />}
<span className="LeftSubmenu__title">{title}</span>
</div>
{rightOnClick ? renderRightSection() : null}
</>
);
};
const renderRightSection = (): ReactNode => {
if (!rightOnClick) return null;
if (rightText) {
return (
<span className="LeftSubmenu__right" onClick={rightOnClick}>
{rightText}
</span>
);
}
return <Icon className="LeftSubmenu__add-icon" icon={IconType.plus} onClick={rightOnClick} size={20} />;
};
return (
<div className="LeftSubmenu">
<div className="LeftSubmenu__header">{renderHeaderContent()}</div>
{expanded && menuItems}
</div>
);
};
export default LeftSubmenu;
|
avgust13/Account-Manager
|
src/renderer/selectors/utils.ts
|
<reponame>avgust13/Account-Manager<filename>src/renderer/selectors/utils.ts
import {RootState} from '@renderer/types';
export const getNthArg = (n: number) => (state: RootState, ...args: any[]) => args[n - 1];
|
avgust13/Account-Manager
|
src/renderer/containers/Friend/FriendTransactions/index.tsx
|
<gh_stars>0
import React, {FC, useMemo} from 'react';
import {useSelector} from 'react-redux';
import {useParams} from 'react-router-dom';
import AccountLink from '@renderer/components/AccountLink';
import PageTable, {PageTableData, PageTableItems} from '@renderer/components/PageTable';
import Pagination from '@renderer/components/Pagination';
import {BANK_BANK_TRANSACTIONS} from '@renderer/constants';
import {usePaginatedNetworkDataFetcher} from '@renderer/hooks';
import {getActiveBankConfig} from '@renderer/selectors';
import {BankTransaction} from '@renderer/types';
import {formatAddressFromNode} from '@renderer/utils/address';
import {formatDate} from '@renderer/utils/dates';
enum TableKeys {
senderAccountNumber,
recipientAccountNumber,
amount,
balanceKey,
signature,
dateCreated,
}
const FriendTransactions: FC = () => {
const {accountNumber} = useParams();
const activeBank = useSelector(getActiveBankConfig)!;
const activeBankAddress = formatAddressFromNode(activeBank);
const {count, currentPage, loading, results: bankTransactions, setPage, totalPages} = usePaginatedNetworkDataFetcher<
BankTransaction
>(BANK_BANK_TRANSACTIONS, activeBankAddress, {account_number: accountNumber});
const bankTransactionsTableData = useMemo<PageTableData[]>(
() =>
bankTransactions.map((bankTransaction) => ({
key: bankTransaction.id,
[TableKeys.amount]: bankTransaction.amount,
[TableKeys.balanceKey]: bankTransaction.block.balance_key,
[TableKeys.dateCreated]: formatDate(bankTransaction.block.created_date),
[TableKeys.recipientAccountNumber]: <AccountLink accountNumber={bankTransaction.recipient} />,
[TableKeys.senderAccountNumber]: <AccountLink accountNumber={bankTransaction.block.sender} />,
[TableKeys.signature]: bankTransaction.block.signature,
})) || [],
[bankTransactions],
);
const pageTableItems = useMemo<PageTableItems>(
() => ({
data: bankTransactionsTableData,
headers: {
[TableKeys.amount]: 'Amount',
[TableKeys.balanceKey]: 'Balance Key',
[TableKeys.dateCreated]: 'Date Created',
[TableKeys.recipientAccountNumber]: 'Recipient',
[TableKeys.senderAccountNumber]: 'Sender',
[TableKeys.signature]: 'Signature',
},
orderedKeys: [
TableKeys.senderAccountNumber,
TableKeys.recipientAccountNumber,
TableKeys.amount,
TableKeys.balanceKey,
TableKeys.signature,
TableKeys.dateCreated,
],
}),
[bankTransactionsTableData],
);
return (
<div className="FriendTransactions">
<PageTable count={count} currentPage={currentPage} items={pageTableItems} loading={loading} />
<Pagination currentPage={currentPage} setPage={setPage} totalPages={totalPages} />
</div>
);
};
export default FriendTransactions;
|
avgust13/Account-Manager
|
src/renderer/store/validators/validatorAccounts.ts
|
<gh_stars>1-10
import {createSlice} from '@reduxjs/toolkit';
import {VALIDATOR_ACCOUNTS} from '@renderer/constants';
import {DictWithPaginatedResultsAndError, ValidatorAccount} from '@renderer/types';
import {setPaginatedResultErrorReducer, setPaginatedResultReducer, unsetDataReducer} from '@renderer/utils/store';
const validatorAccounts = createSlice({
initialState: {} as DictWithPaginatedResultsAndError<ValidatorAccount>,
name: VALIDATOR_ACCOUNTS,
reducers: {
setValidatorAccounts: setPaginatedResultReducer<ValidatorAccount>(),
setValidatorAccountsError: setPaginatedResultErrorReducer(),
unsetValidatorAccounts: unsetDataReducer(),
},
});
export const {setValidatorAccounts, setValidatorAccountsError, unsetValidatorAccounts} = validatorAccounts.actions;
export default validatorAccounts;
|
FakeBarenziah/runtheworld
|
src/boilerplate/scenes/mainScene.ts
|
<filename>src/boilerplate/scenes/mainScene.ts
import Guy from "../sprites/Guy";
import Stringer from "./Stringer"
/** Boilerplate credits!
* @author Digitsensitive <<EMAIL>>
* @copyright 2018 - 2019 digitsensitive
* @license Digitsensitive
*/
interface keysObj {
jump: any,
right:any,
left: any,
big: any,
small: any
}
export class MainScene extends Phaser.Scene {
private keys: keysObj
private guy: Guy
private groundLayers: Array<Phaser.Tilemaps.StaticTilemapLayer>
private zoom: number
private world: number
public physics: any
public input: any
public cameras: any
public make: any
public load: any
public cache: any
public add: any
public anims:any
private terrainTypes:Array<string>
private currentWorld: number
private layer1:Phaser.Tilemaps.StaticTilemapLayer
private layer2:Phaser.Tilemaps.StaticTilemapLayer
private layer3:Phaser.Tilemaps.StaticTilemapLayer
private layer4:Phaser.Tilemaps.StaticTilemapLayer
private layer5:Phaser.Tilemaps.StaticTilemapLayer
private layer6:Phaser.Tilemaps.StaticTilemapLayer
private layer7:Phaser.Tilemaps.StaticTilemapLayer
constructor() {
super({
key: "MainScene"
});
this.zoom = 1.0
this.world = 2
this.currentWorld = 0
this.terrainTypes = ["Desert", "Castle", "Town", "Mountain"]
}
preload(): void {
// Pull in all of our tilesets and backgrounds
/* Load your new tilesets here! */
this.load.image('Desert', "./src/boilerplate/assets/Desert.png")
this.load.image("Castle", "./src/boilerplate/assets/Castle.png")
this.load.image("Town", "./src/boilerplate/assets/Town.png")
this.load.image("Mountain", "./src/boilerplate/assets/Mountain.png")
this.load.image("BackgroundPallette", "./src/boilerplate/assets/BackgroundPallete.png")
this.load.tilemapTiledJSON("bg1", "./src/boilerplate/assets/bg1.json")
this.load.tilemapTiledJSON("bg2", "./src/boilerplate/assets/bg2.json")
this.load.tilemapTiledJSON("bg3", "./src/boilerplate/assets/bg3.json")
this.load.tilemapTiledJSON("bg4", "./src/boilerplate/assets/bg4.json")
//Load up the image for our guy
this.load.multiatlas('RoboGuy', "./src/boilerplate/assets/RoboSprites.json", "./src/boilerplate/assets");
// console.log(this.cache)
}
create(): void {
var bgMap1 = this.make.tilemap({key:"bg1"})
var bgMap2 = this.make.tilemap({key:"bg2"})
var bgMap3 = this.make.tilemap({key:"bg2"})
var bgMap4 = this.make.tilemap({key:"bg3"})
var bgMap5 = this.make.tilemap({key:"bg3"})
var bgMap6 = this.make.tilemap({key:"bg4"})
var bgMap7 = this.make.tilemap({key:"bg4"})
var backgroundTileset1 = bgMap1.addTilesetImage("BackgroundPallette")
var backgroundTileset2 = bgMap2.addTilesetImage("BackgroundPallette")
var backgroundTileset3 = bgMap3.addTilesetImage("BackgroundPallette")
var backgroundTileset4 = bgMap4.addTilesetImage("BackgroundPallette")
var backgroundTileset5 = bgMap2.addTilesetImage("BackgroundPallette")
var backgroundTileset6 = bgMap3.addTilesetImage("BackgroundPallette")
var backgroundTileset7 = bgMap4.addTilesetImage("BackgroundPallette")
this.layer1 = bgMap1.createStaticLayer("Tile Layer 1", backgroundTileset1, 75, 0)
this.layer2 = bgMap2.createStaticLayer("Tile Layer 1", backgroundTileset2, 75, 0)
this.layer3 = bgMap3.createStaticLayer("Tile Layer 1", backgroundTileset3, -75, 0)
this.layer4 = bgMap4.createStaticLayer("Tile Layer 1", backgroundTileset4, 75, 0)
this.layer5 = bgMap5.createStaticLayer("Tile Layer 1", backgroundTileset5, -75, 0)
this.layer6 = bgMap6.createStaticLayer("Tile Layer 1", backgroundTileset6, 75, 0)
this.layer7 = bgMap7.createStaticLayer("Tile Layer 1", backgroundTileset7, -75, 0)
///Generate two random chunks
var terrain1 = this.terrainTypes[Math.floor(Math.random()*this.terrainTypes.length)]
this.cache.tilemap.entries.entries.map1 = {"format":1,"data":Stringer(terrain1)}
var terrain2 = this.terrainTypes[Math.floor(Math.random()*this.terrainTypes.length)]
this.cache.tilemap.entries.entries.map2 = {"format":1,"data":Stringer(terrain2)}
//Generates Layers for w1 and w2
var map1 = this.make.tilemap({key: 'map1'})
var map2 = this.make.tilemap({key: 'map2'})
var groundTile1 = map1.addTilesetImage(terrain1)
var groundTile2 = map2.addTilesetImage(terrain2)
this.groundLayers = [map1.createStaticLayer('Tile Layer 1', groundTile1, 0, 0)];
this.groundLayers.push(map2.createStaticLayer('Tile Layer 1', groundTile2, 150*32, 0))
// Sets up a Phaser world that's two chunks wide and one chunk high
//we'll be using mostly c1 for the player and c2 holds the next world
this.physics.world.bounds.width = 300*32;
this.physics.world.bounds.height = 100*32;
// Input map that enumerates and exposes player input options
this.keys = {
jump: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE),
right: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D),
left: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A),
big: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W),
small: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S)
}
// Makes our guy and adds him to the scene
this.guy = new Guy({
scene:this,
key:"RoboGuy",
x:75*32,
y:10*32
})
var walkFrames = this.anims.generateFrameNames("RoboGuy", {start:1, end:5, prefix:"RoboGuysplit-", suffix:".png"})
this.anims.create({
key:"walk",
frames:walkFrames,
frameRate:20
})
var standFrames = this.anims.generateFrameNames("RoboGuy", {start:0, end:0, prefix:"RoboGuysplit-", suffix:".png"})
this.anims.create({
key:"stand",
frames:standFrames,
frameRate:20
})
this.guy.anims.play("walk", this.guy)
//handle collision setup for layers and our guy
map1.setCollisionByProperty({"Collides":true}, true, true)
map2.setCollisionByProperty({"Collides":true}, true, true)
this.guy.body.collideWorldBounds=true;
this.guy.body.setBounce(.2)
//Critical for consistent collisions!
this.physics.add.collider(this.guy,this.groundLayers[0])
this.physics.add.collider(this.guy,this.groundLayers[1])
}
update(time, delta):void {
//use those colliders!
this.groundLayers.forEach(layer => {
this.physics.collide(this.guy, layer)})
//control zoom level and update game state based on zoom
let input = {
big: this.keys.big.isDown,
small: this.keys.small.isDown,
left: this.keys.left.isDown,
right: this.keys.right.isDown
};
//This if statement chooses the animation to play based on whether the player is walking or not
if(input.left || input.right){
this.guy.anims.play("walk", this.guy)
} else this.guy.anims.play("stand", this.guy)
if(input.big && this.zoom < 5){
this.zoom += .05
}
if(input.small && this.zoom > .15){
this.zoom -= .05
}
if(input.left&&!this.guy.body.blocked.left){
this.layer1.x -= 3
this.layer2.x -= 3/2
this.layer3.x -= 3/2
this.layer4.x -= 3/4
this.layer5.x -= 3/4
this.layer6.x -= 3/8
this.layer7.x -= 3/8
}
if(input.right&&!this.guy.body.blocked.right){
this.layer1.x += 3
this.layer2.x += 3/2
this.layer3.x += 3/2
this.layer4.x += 3/4
this.layer5.x += 3/4
this.layer6.x += 3/8
this.layer7.x += 3/8
}
this.cameras.main.zoom = 1/this.zoom
this.guy.setScale(this.zoom*2)
this.cameras.main.startFollow(this.guy,false,0,0,this.zoom,100*this.zoom)
//load in a new chunk if we're far enough along
if(this.guy.x > 240*32){
this.currentWorld++
this.groundLayers.forEach(layer => {
layer.x-=150*32
})
this.guy.x -= 150*32
this.layer1.x -=150*32
this.layer2.x -=150*32
this.layer3.x -=150*32
this.layer4.x -=150*32
if(this.currentWorld===this.world-1){
this.loadNewMap(false)}
}
if(this.guy.x < 50*32){
this.groundLayers.forEach(layer => {
layer.x+=150*32
})
this.guy.x += 150*32
this.layer1.x +=150*32
this.layer2.x +=150*32
this.layer3.x +=150*32
this.layer4.x +=150*32
if(this.currentWorld===0){
this.loadNewMap(true)
}else{this.currentWorld--}
}
this.guy.update(this.keys, time, delta, this.zoom)
}
loadNewMap(left:boolean): void {
var nextTerrain = this.terrainTypes[Math.floor(Math.random()*this.terrainTypes.length)]
this.cache.tilemap.entries.entries[`map${this.world}`] = {"format":1,"data":Stringer(nextTerrain)}
var nextMap = this.make.tilemap({key: `map${this.world}`})
if(left){
var groundTile1 = nextMap.addTilesetImage(nextTerrain)
this.groundLayers.unshift(nextMap.createStaticLayer('Tile Layer 1', groundTile1, 0, 0));
//make sure collision data is up to date
nextMap.setCollisionByProperty({"Collides":true}, true, true)
this.physics.add.collider(this.guy,this.groundLayers[0])
} else{
var groundTile2 = nextMap.addTilesetImage(nextTerrain)
this.groundLayers.push(nextMap.createStaticLayer('Tile Layer 1', groundTile2, 150*32, 0));
//make sure collision data is up to date
nextMap.setCollisionByProperty({"Collides":true}, true, true)
this.physics.add.collider(this.guy,this.groundLayers[this.world-1])
}
this.world++
}
}
|
FakeBarenziah/runtheworld
|
src/boilerplate/scenes/MapMaker.ts
|
const MapMaker= (type:string):Array<number> =>{
const outArray = [];
const colsArray = [];
// This function returns the outArray,
// which is a flat array containing all
// of the values to assign tiles to a
// world. Phaser makes the maps from arrays
// of values to assign corresponding tiles
// from a tileset. It builds the maps
// row-by-row, but we want to generate
// them column-by-column! No big deal,
// we just need to reorder the elements
// before returning it.
// The colsArray will have a number
// of arrays in it equal to the width of
// the world (here it is 150 tiles), and
// each array will have a number of elements
// equal to the height of the world (100)
// MapMaker accepts a string which assigns the type
function levelCheck(aVal:number):boolean{
return aVal>0
// Helper function to check when
// tiles in the previous column
// start to have non-zero values.
};
// Initialize the height of the first
// column to something that gives us
// some headroom
let level:number = 80;
// Variables for making the castle
// towers that need to be outside the
// scope of the for loop
let castle_towerflag:boolean = false
let castle_towerEnd:number
let castle_towerHeight:number
// Make 150 columns
for (let i=0; i < 150; i++){
// Initialize a level offset to
// manipulate the index of each
// column to start adding blocks
let levelOffset:number
if(level>=90){
// If the level of collision
// tiles has fallen to near
// the bottom, raise it by 2
levelOffset = -2
} else if (level<=10){
// Or if it has risen to be near the
// top, lower it
levelOffset = 2
}
// If we are making the last 20 columns
// and are above or below the level the
// next one is going to start at, we
// need to start moving towards 80.
// Castle types have their own logic
// for changing level that obviates this.
else if (i>130&&type!=="Castle"){
if(type==="Mountain"){
// Mountain terrain can increment
// and decrement by 2
if(level>81){
levelOffset=-2
} else if(level<80){
levelOffset=2
} else{
levelOffset = 0
}
} else {
// Other terrain types offset
// by one at a time
if(level>80){
levelOffset=-1
} else if(level<80){
levelOffset=1
} else{
levelOffset = 0
}
}
// If we are not preparing the level
// for meeting the next world or
// correcting extreme elevations, we
// can apply the normal rules for
// procedurally generating height
} else if(type==="Castle"){
// Castles are generally flat, so have
// a levelOffset of zero...
levelOffset = 0
// ...unless we're making walls.
// The walls rise by 40 tiles for
// 5 tiles, and then fall by 40
// tiles, 5 tiles from the edge
// of the castle zone.
if(i===5||i===140){
levelOffset = -40
} else if(i===10||i===145){
levelOffset = 40
} else {
// If we are within the walls of a Castle area,
// we can make towers. First, it checks if we
// are already making a tower, and if not,
// it makes one 6% of the time.
if(!castle_towerflag && i > 20 && i < 130){
var towerChance = Math.random()
if(towerChance<0.06 && level===80){
castle_towerHeight = Math.floor(Math.random()*20)+10
// When a tower is to be built, its height is
// randomly determined between 10 and 29, and
// this value is assigned to the variable in
// the outer scope.
levelOffset=-castle_towerHeight
// The level offset is changed to reflect the
// determined height, and the Castle type doesn't
// change it otherwise.
castle_towerEnd = i+Math.ceil(Math.random()*6)+2
// The tower's width is defined by randomly
// determining its endpoint 3 to 8 columns
// from its start.
castle_towerflag = true
// Flags a tower as being built so another
// one doesn't get built on top of it.
}
}
if(i===castle_towerEnd){
// When we get to the index that is to be the
// end of the tower, we lower the column height
// by the same amount it was raised earlier and
// reset the build tower flag.
levelOffset=castle_towerHeight
castle_towerflag = false
}
}
} else if (type==="Mountain") {
levelOffset = Math.floor((Math.random()*5)-2);
} else {
// All other terrain can vary by one tile per column
levelOffset = Math.floor((Math.random()*3)-1);
}
const column:number[] = [];
const newLevel:number = level + levelOffset
for(let j=0; j<100; j++){
// This for loop makes each column
if(j < newLevel){
// Pushes zeroes into the column until
// the index reaches the level we have
// decided to start adding tiles.
column.push(0)
}
else if(j === newLevel){
// When we reach the level determined by the
// outer loop, we push a random value to
// correspond with a tile from the 18
// surface-design tiles in the tileset
column.push(Math.floor((Math.random()*18)+10))
}
else if(j > newLevel){
// Beyond that, we push a random value to
// correspond with one of the 9 below-surface
// design tiles.
column.push(Math.floor((Math.random()*9)+1))
}
}
// Push that full column into the colsArray
colsArray.push(column)
// Reassign the level to be the first index
// of the column we just made that is not a zero
// so that the next column can refernce the height
// of the one before it.
level = colsArray[colsArray.length-1].findIndex(levelCheck)
}
// Move the first item in each column array into the main
// array until colsArray is full of emptry arrays.
while(colsArray[0].length){
colsArray.forEach(each => outArray.push(each.shift()))
}
return outArray
}
export default MapMaker
|
FakeBarenziah/runtheworld
|
src/boilerplate/sprites/Guy.ts
|
<filename>src/boilerplate/sprites/Guy.ts
export default class Guy extends Phaser.GameObjects.Sprite{
private acceleration:number
public body: any
public type: string
public x: number
public flipX: boolean
public setScale: any
public anims:any
constructor(config: any) {
super(config.scene, config.x, config.y, config.key)
config.scene.physics.world.enable(this);
config.scene.add.existing(this);
this.acceleration = 100;
this.body.maxVelocity.x = 600;
this.body.maxVelocity.y = 700;
this.body.checkCollision.up = false;
this.type = 'guy';
}
update(keys, time, delta, zoom: number){
//input map from parent's keys for semantics
let input = {
left: keys.left.isDown,
right:keys.right.isDown,
jump:keys.jump.isDown
};
//control logic
if (input.left) {
this.run(-this.acceleration*Math.max(1, zoom*2));
this.flipX = true;
}
else if (input.right) {
this.run(this.acceleration*Math.max(1, zoom*2));
this.flipX = false;
}
else {
this.run(0)
}
if (input.jump) {
this.jump(zoom*2);
}
}
run(vel: number) {
this.body.setVelocityX(vel);
}
jump(zoom: number) {
this.body.setVelocityY(-450*Math.sqrt(zoom))
}
}
|
SetProtocol/set-protocol-viewers
|
utils/helpers/protocolViewerHelper.ts
|
<gh_stars>1-10
import { BigNumber } from 'bignumber.js';
import { Address } from 'set-protocol-utils';
import Web3 from 'web3';
import {
CTokenViewerContract,
ERC20ViewerContract,
ManagerViewerContract,
OracleViewerContract,
ProtocolViewerContract,
RebalancingSetTokenViewerContract,
SocialTradingManagerMockContract,
TradingPoolViewerContract,
TrendingManagerMockContract,
} from '../contracts';
import { getContractInstance, txnFrom } from '../web3Helper';
import {
ONE_DAY_IN_SECONDS,
DEFAULT_GAS,
} from '../constants';
import { RebalancingSetTokenV3FactoryContract, TWAPLiquidatorContract } from 'set-protocol-contracts';
const RebalancingSetTokenV3Factory =
require(
'set-protocol-contracts/dist/artifacts/ts/RebalancingSetTokenV3Factory'
).RebalancingSetTokenV3Factory;
const TWAPLiquidator =
require(
'set-protocol-contracts/dist/artifacts/ts/TWAPLiquidator'
).TWAPLiquidator;
const FactoryUtilsLibrary =
require('set-protocol-contracts/dist/artifacts/ts/FactoryUtilsLibrary').FactoryUtilsLibrary;
const Bytes32Library =
require('set-protocol-contracts/dist/artifacts/ts/Bytes32Library').Bytes32Library;
const CTokenViewer = artifacts.require('CTokenViewer');
const ERC20Viewer = artifacts.require('ERC20Viewer');
const ManagerViewer = artifacts.require('ManagerViewer');
const OracleViewer = artifacts.require('OracleViewer');
const ProtocolViewer = artifacts.require('ProtocolViewer');
const RebalancingSetTokenViewer = artifacts.require('RebalancingSetTokenViewer');
const SocialTradingManagerMock = artifacts.require('SocialTradingManagerMock');
const TradingPoolViewer = artifacts.require('TradingPoolViewer');
const TrendingManagerMock = artifacts.require('TrendingManagerMock');
const contract = require('truffle-contract');
export class ProtocolViewerHelper {
private _contractOwnerAddress: Address;
constructor(contractOwnerAddress: Address) {
this._contractOwnerAddress = contractOwnerAddress;
}
/* ============ Deployment ============ */
public async deployCTokenViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<CTokenViewerContract> {
const
cTokenViewer = await CTokenViewer.new(
txnFrom(from)
);
return new CTokenViewerContract(
getContractInstance(cTokenViewer),
txnFrom(from),
);
}
public async deployERC20ViewerContract(
from: Address = this._contractOwnerAddress
): Promise<ERC20ViewerContract> {
const erc20ViewerContract = await ERC20Viewer.new(txnFrom(from));
return new ERC20ViewerContract(
getContractInstance(erc20ViewerContract),
txnFrom(from),
);
}
public async deployManagerViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<ManagerViewerContract> {
const
managerViewer = await ManagerViewer.new(
txnFrom(from)
);
return new ManagerViewerContract(
getContractInstance(managerViewer),
txnFrom(from),
);
}
public async deployOracleViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<OracleViewerContract> {
const
oracleViewer = await OracleViewer.new(
txnFrom(from)
);
return new OracleViewerContract(
getContractInstance(oracleViewer),
txnFrom(from),
);
}
public async deployProtocolViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<ProtocolViewerContract> {
const protocolViewerContract = await ProtocolViewer.new(txnFrom(from));
return new ProtocolViewerContract(
getContractInstance(protocolViewerContract),
txnFrom(from),
);
}
public async deployRebalancingSetTokenViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<RebalancingSetTokenViewerContract> {
const rebalancingSetTokenViewer = await RebalancingSetTokenViewer.new(txnFrom(from));
return new RebalancingSetTokenViewerContract(
getContractInstance(rebalancingSetTokenViewer),
txnFrom(from),
);
}
public async deployTradingPoolViewerAsync(
from: Address = this._contractOwnerAddress
): Promise<TradingPoolViewerContract> {
const
tradingPoolViewer = await TradingPoolViewer.new(
txnFrom(from)
);
return new TradingPoolViewerContract(
getContractInstance(tradingPoolViewer),
txnFrom(from),
);
}
public async deploySocialTradingManagerMockAsync(
from: Address = this._contractOwnerAddress
): Promise<SocialTradingManagerMockContract> {
const
socialManager = await SocialTradingManagerMock.new(
txnFrom(from)
);
return new SocialTradingManagerMockContract(
getContractInstance(socialManager),
txnFrom(from),
);
}
public async deployTrendingManagerMockAsync(
crossoverTimestamp: BigNumber,
from: Address = this._contractOwnerAddress
): Promise<TrendingManagerMockContract> {
const trendingManagerMock = await TrendingManagerMock.new(
crossoverTimestamp,
txnFrom(from)
);
return new TrendingManagerMockContract(
getContractInstance(trendingManagerMock),
txnFrom(from),
);
}
public async deployRebalancingSetTokenV3FactoryAsync(
coreAddress: Address,
componentWhitelistAddress: Address,
liquidatorWhitelistAddress: Address,
feeCalculatorWhitelistAddress: Address,
minimumRebalanceInterval: BigNumber = ONE_DAY_IN_SECONDS,
minimumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS,
maximumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS.mul(30),
minimumNaturalUnit: BigNumber = new BigNumber(10),
maximumNaturalUnit: BigNumber = new BigNumber(10 ** 14),
from: Address = this._contractOwnerAddress
): Promise<RebalancingSetTokenV3FactoryContract> {
const truffleBytes32LibraryContract = this.setDefaultTruffleContract(web3, Bytes32Library);
const deployedBytes32LibraryContract = await truffleBytes32LibraryContract.new();
const truffleFactoryUtilsLibContract = this.setDefaultTruffleContract(web3, FactoryUtilsLibrary);
const deployedFactoryUtilsLibContract = await truffleFactoryUtilsLibContract.new();
const truffleTokenFactory = this.setDefaultTruffleContract(web3, RebalancingSetTokenV3Factory);
await truffleTokenFactory.link(
'Bytes32Library',
deployedBytes32LibraryContract.address
);
await truffleTokenFactory.link(
'FactoryUtilsLibrary',
deployedFactoryUtilsLibContract.address
);
const deployedTokenFactory = await truffleTokenFactory.new(
coreAddress,
componentWhitelistAddress,
liquidatorWhitelistAddress,
feeCalculatorWhitelistAddress,
minimumRebalanceInterval,
minimumFailRebalancePeriod,
maximumFailRebalancePeriod,
minimumNaturalUnit,
maximumNaturalUnit,
{ from },
);
return await RebalancingSetTokenV3FactoryContract.at(
deployedTokenFactory.address,
web3,
{ from, gas: DEFAULT_GAS },
);
}
public async deployTWAPLiquidatorAsync(
core: Address,
oracleWhiteList: Address,
auctionPeriod: BigNumber,
rangeStart: BigNumber,
rangeEnd: BigNumber,
assetPairHashes: string[],
assetPairBounds: {}[],
name: string,
from: Address = this._contractOwnerAddress
): Promise<TWAPLiquidatorContract> {
const assetPairBoundsStr = [];
for (let i = 0; i < assetPairBounds.length; i++) {
assetPairBoundsStr.push(assetPairBounds[i]);
}
const truffleLiquidator = this.setDefaultTruffleContract(web3, TWAPLiquidator);
const twapLiquidator = await truffleLiquidator.new(
core,
oracleWhiteList,
auctionPeriod,
rangeStart,
rangeEnd,
assetPairHashes,
assetPairBoundsStr,
name,
txnFrom(from)
);
return new TWAPLiquidatorContract(
getContractInstance(twapLiquidator),
txnFrom(from)
);
}
private setDefaultTruffleContract(web3: Web3, contractInstance: any): any {
const TX_DEFAULTS = {
from: this._contractOwnerAddress,
gasPrice: 6000000000,
gas: 6712390,
};
const truffleContract = contract(contractInstance);
truffleContract.setProvider(web3.currentProvider);
truffleContract.setNetwork(50);
truffleContract.defaults(TX_DEFAULTS);
return truffleContract;
}
}
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/lib/managerViewer.spec.ts
|
require('module-alias/register');
import * as chai from 'chai';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
ManagerViewerContract,
TrendingManagerMockContract
} from '@utils/contracts';
import {
Blockchain,
} from 'set-protocol-contracts';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
BigNumberSetup.configure();
ChaiSetup.configure();
const blockchain = new Blockchain(web3);
const { expect } = chai;
contract('ManagerViewer', accounts => {
const [
deployerAccount,
] = accounts;
let trendingManagerMock1: TrendingManagerMockContract;
let trendingManagerMock2: TrendingManagerMockContract;
let crossoverTimestamp1: BigNumber;
let crossoverTimestamp2: BigNumber;
const protocolViewerHelper = new ProtocolViewerHelper(deployerAccount);
let managerViewer: ManagerViewerContract;
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
crossoverTimestamp1 = new BigNumber(14800000000);
crossoverTimestamp2 = new BigNumber(11800000000);
trendingManagerMock1 = await protocolViewerHelper.deployTrendingManagerMockAsync(
crossoverTimestamp1
);
trendingManagerMock2 = await protocolViewerHelper.deployTrendingManagerMockAsync(
crossoverTimestamp2
);
managerViewer = await protocolViewerHelper.deployManagerViewerAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#batchFetchMACOV2CrossoverTimestamp', async () => {
let subjectManagerAddresses: Address[];
beforeEach(async () => {
subjectManagerAddresses = [trendingManagerMock1.address, trendingManagerMock2.address];
});
async function subject(): Promise<BigNumber[]> {
return managerViewer.batchFetchMACOV2CrossoverTimestamp.callAsync(
subjectManagerAddresses,
);
}
it('fetches the lastCrossoverConfirmationTimestamp of the MACO Managers', async () => {
const actualCrossoverArray = await subject();
const expectedEntryFeeArray = [crossoverTimestamp1, crossoverTimestamp2];
expect(JSON.stringify(actualCrossoverArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
describe('#batchFetchAssetPairCrossoverTimestamp', async () => {
let subjectManagerAddresses: Address[];
beforeEach(async () => {
subjectManagerAddresses = [trendingManagerMock1.address, trendingManagerMock2.address];
});
async function subject(): Promise<BigNumber[]> {
return managerViewer.batchFetchAssetPairCrossoverTimestamp.callAsync(
subjectManagerAddresses,
);
}
it('fetches the recentInitialProposeTimestamp of the Asset Pair Managers', async () => {
const actualCrossoverArray = await subject();
const expectedEntryFeeArray = [crossoverTimestamp1, crossoverTimestamp2];
expect(JSON.stringify(actualCrossoverArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
});
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/lib/tradingPoolViewer.spec.ts
|
require('module-alias/register');
import * as _ from 'lodash';
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
UpdatableOracleMockContract
} from 'set-protocol-oracles';
import {
CoreMockContract,
FixedFeeCalculatorContract,
LinearAuctionLiquidatorContract,
OracleWhiteListContract,
PerformanceFeeCalculatorContract,
SetTokenContract,
RebalancingSetTokenV2Contract,
RebalancingSetTokenV2FactoryContract,
RebalancingSetTokenV3Contract,
RebalancingSetTokenV3FactoryContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
TWAPLiquidatorContract,
VaultContract,
WhiteListContract,
} from 'set-protocol-contracts';
import {
SocialTradingManagerMockContract,
TradingPoolViewerContract,
} from '@utils/contracts';
import { ether, gWei } from '@utils/units';
import {
DEFAULT_REBALANCING_NATURAL_UNIT,
DEFAULT_UNIT_SHARES,
ONE_DAY_IN_SECONDS,
ONE_YEAR_IN_SECONDS,
ZERO,
} from '@utils/constants';
import { getWeb3 } from '@utils/web3Helper';
import {
Blockchain,
CoreHelper,
ERC20Helper,
FeeCalculatorHelper,
LiquidatorHelper,
RebalancingSetV2Helper,
RebalancingSetV3Helper,
ValuationHelper,
} from 'set-protocol-contracts';
import {
OracleHelper,
} from 'set-protocol-oracles';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
const CoreMock =
require('set-protocol-contracts/dist/artifacts/ts/CoreMock').CoreMock;
BigNumberSetup.configure();
ChaiSetup.configure();
const web3 = getWeb3();
const { expect } = chai;
const blockchain = new Blockchain(web3);
contract('TradingPoolViewer', accounts => {
const [
deployerAccount,
feeRecipient,
trader,
allocator,
trader2,
] = accounts;
let rebalancingSetToken: RebalancingSetTokenV2Contract;
let coreMock: CoreMockContract;
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let setTokenFactory: SetTokenFactoryContract;
let rebalancingFactory: RebalancingSetTokenV2FactoryContract;
let rebalancingSetTokenV3Factory: RebalancingSetTokenV3FactoryContract;
let rebalancingComponentWhiteList: WhiteListContract;
let liquidatorWhitelist: WhiteListContract;
let liquidator: LinearAuctionLiquidatorContract;
let twapLiquidator: TWAPLiquidatorContract;
let fixedFeeCalculator: FixedFeeCalculatorContract;
let feeCalculatorWhitelist: WhiteListContract;
let name: string;
let auctionPeriod: BigNumber;
let rangeStart: BigNumber;
let rangeEnd: BigNumber;
let oracleWhiteList: OracleWhiteListContract;
let component1: StandardTokenMockContract;
let component2: StandardTokenMockContract;
let component1Price: BigNumber;
let component2Price: BigNumber;
let set1: SetTokenContract;
let set2: SetTokenContract;
let set1Components: Address[];
let set1Units: BigNumber[];
let set1NaturalUnit: BigNumber;
let set2Components: Address[];
let set2Units: BigNumber[];
let set2NaturalUnit: BigNumber;
let component1Oracle: UpdatableOracleMockContract;
let component2Oracle: UpdatableOracleMockContract;
let poolViewer: TradingPoolViewerContract;
const coreHelper = new CoreHelper(deployerAccount, deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const feeCalculatorHelper = new FeeCalculatorHelper(deployerAccount);
const oracleHelper = new OracleHelper(deployerAccount);
const rebalancingHelper = new RebalancingSetV2Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const rebalancingSetV3Helper = new RebalancingSetV3Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper);
const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper);
const viewerHelper = new ProtocolViewerHelper(deployerAccount);
before(async () => {
ABIDecoder.addABI(CoreMock.abi);
});
after(async () => {
ABIDecoder.removeABI(CoreMock.abi);
});
beforeEach(async () => {
blockchain.saveSnapshotAsync();
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault);
setTokenFactory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address);
rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync();
liquidatorWhitelist = await coreHelper.deployWhiteListAsync();
feeCalculatorWhitelist = await coreHelper.deployWhiteListAsync();
await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, setTokenFactory);
component1 = await erc20Helper.deployTokenAsync(deployerAccount);
component2 = await erc20Helper.deployTokenAsync(deployerAccount);
await coreHelper.addTokensToWhiteList(
[component1.address, component2.address],
rebalancingComponentWhiteList,
);
await erc20Helper.approveTransfersAsync(
[component1, component2],
transferProxy.address
);
set1Components = [component1.address, component2.address];
set1Units = [gWei(1), gWei(1)];
set1NaturalUnit = gWei(1);
set1 = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
set1Components,
set1Units,
set1NaturalUnit,
);
set2Components = [component1.address, component2.address];
set2Units = [gWei(2), gWei(3)];
set2NaturalUnit = gWei(2);
set2 = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
set2Components,
set2Units,
set2NaturalUnit,
);
component1Price = ether(1);
component2Price = ether(2);
component1Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component1Price);
component2Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component2Price);
oracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[component1.address, component2.address],
[component1Oracle.address, component2Oracle.address],
);
auctionPeriod = ONE_DAY_IN_SECONDS;
rangeStart = new BigNumber(10); // 10% above fair value
rangeEnd = new BigNumber(10); // 10% below fair value
name = 'liquidator';
liquidator = await liquidatorHelper.deployLinearAuctionLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
name,
);
await coreHelper.addAddressToWhiteList(liquidator.address, liquidatorWhitelist);
const assetPairHashes = [
liquidatorHelper.generateAssetPairHashes(component1.address, component2.address),
];
const assetPairBounds = [
{min: ether(10 ** 4).toString(), max: ether(10 ** 6).toString()},
];
twapLiquidator = await viewerHelper.deployTWAPLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
assetPairHashes,
assetPairBounds,
name,
);
await coreHelper.addAddressToWhiteList(twapLiquidator.address, liquidatorWhitelist);
fixedFeeCalculator = await feeCalculatorHelper.deployFixedFeeCalculatorAsync();
await coreHelper.addAddressToWhiteList(fixedFeeCalculator.address, feeCalculatorWhitelist);
poolViewer = await viewerHelper.deployTradingPoolViewerAsync();
});
afterEach(async () => {
blockchain.revertAsync();
});
describe('#fetchNewTradingPoolDetails', async () => {
let subjectTradingPool: Address;
let currentSetToken: SetTokenContract;
let currentAllocation: BigNumber;
let lastRebalanceTimestamp: BigNumber;
let setManager: SocialTradingManagerMockContract;
let newFee: BigNumber;
let feeUpdateTimestamp: BigNumber;
beforeEach(async () => {
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
currentSetToken = set1;
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = timestamp;
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
newFee = ether(.02);
await setManager.updateFee.sendTransactionAsync(
rebalancingSetToken.address,
newFee
);
const block = await web3.eth.getBlock('latest');
feeUpdateTimestamp = new BigNumber(block.timestamp);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return poolViewer.fetchNewTradingPoolDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(currentAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(newFee);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(feeUpdateTimestamp);
});
it('fetches the correct RebalancingSetTokenV2/TradingPool data', async () => {
const [ , rbSetData, ] = await subject();
expect(rbSetData.manager).to.equal(setManager.address);
expect(rbSetData.feeRecipient).to.equal(feeRecipient);
expect(rbSetData.currentSet).to.equal(currentSetToken.address);
expect(rbSetData.liquidator).to.equal(liquidator.address);
expect(rbSetData.name).to.equal('Rebalancing Set Token');
expect(rbSetData.symbol).to.equal('RBSET');
expect(rbSetData.unitShares).to.be.bignumber.equal(DEFAULT_UNIT_SHARES);
expect(rbSetData.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(rbSetData.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(rbSetData.entryFee).to.be.bignumber.equal(ZERO);
expect(rbSetData.rebalanceFee).to.be.bignumber.equal(ZERO);
expect(rbSetData.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set1Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set1Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set1NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#fetchNewTradingPoolV2Details', async () => {
let subjectTradingPool: Address;
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let collateralSetComponents: Address[];
let collateralSetUnits: BigNumber[];
let collateralSetNaturalUnit: BigNumber;
let firstSetUnits: BigNumber;
let setManager: SocialTradingManagerMockContract;
let lastRebalanceTimestamp: BigNumber;
let currentAllocation: BigNumber;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
beforeEach(async () => {
rebalancingSetTokenV3Factory = await viewerHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingSetTokenV3Factory);
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = timestamp;
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
setManager.address,
liquidator.address,
feeRecipient,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return poolViewer.fetchNewTradingPoolV2Details.callAsync(
subjectTradingPool
);
}
it('fetches the correct RebalancingSetTokenV3/TradingPool data', async () => {
const [ , tradingPoolInfo, , , ] = await subject();
expect(tradingPoolInfo.manager).to.equal(setManager.address);
expect(tradingPoolInfo.feeRecipient).to.equal(feeRecipient);
expect(tradingPoolInfo.currentSet).to.equal(collateralSet.address);
expect(tradingPoolInfo.liquidator).to.equal(liquidator.address);
expect(tradingPoolInfo.name).to.equal('Rebalancing Set Token');
expect(tradingPoolInfo.symbol).to.equal('RBSET');
expect(tradingPoolInfo.unitShares).to.be.bignumber.equal(firstSetUnits);
expect(tradingPoolInfo.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(tradingPoolInfo.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(tradingPoolInfo.entryFee).to.be.bignumber.equal(ZERO);
expect(tradingPoolInfo.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(tradingPoolInfo.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , , , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(currentAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV3/Performance Fee data', async () => {
const [ , , performanceFeeState, , ] = await subject();
const [
profitFeePeriod,
highWatermarkResetPeriod,
profitFeePercentage,
streamingFeePercentage,
highWatermark,
lastProfitFeeTimestamp,
lastStreamingFeeTimestamp,
] = performanceFeeState;
const expectedFeeStates: any = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
expect(profitFeePeriod).to.equal(expectedFeeStates.profitFeePeriod);
expect(highWatermarkResetPeriod).to.equal(expectedFeeStates.highWatermarkResetPeriod);
expect(profitFeePercentage).to.equal(expectedFeeStates.profitFeePercentage);
expect(streamingFeePercentage).to.equal(expectedFeeStates.streamingFeePercentage);
expect(highWatermark).to.equal(expectedFeeStates.highWatermark);
expect(lastProfitFeeTimestamp).to.equal(expectedFeeStates.lastProfitFeeTimestamp);
expect(lastStreamingFeeTimestamp).to.equal(expectedFeeStates.lastStreamingFeeTimestamp);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , , collateralSetData, ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralSetComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(collateralSetUnits));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(collateralSetNaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct PerformanceFeeCalculator address', async () => {
const [ , , , , performanceFeeCalculatorAddress ] = await subject();
expect(performanceFeeCalculatorAddress).to.equal(ethPerformanceFeeCalculator.address);
});
});
describe('#fetchTradingPoolRebalanceDetails', async () => {
let subjectTradingPool: Address;
let setManager: SocialTradingManagerMockContract;
let newAllocation: BigNumber;
let nextSet: SetTokenContract;
beforeEach(async () => {
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
const currentSetToken = set1;
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
const currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = '0x';
nextSet = set2;
newAllocation = ether(.4);
await setManager.rebalance.sendTransactionAsync(
rebalancingSetToken.address,
nextSet.address,
newAllocation,
liquidatorData
);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return poolViewer.fetchTradingPoolRebalanceDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(newAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV2/TradingPool data', async () => {
const [ , rbSetData, ] = await subject();
const auctionPriceParams = await rebalancingSetToken.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetToken.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetToken.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(liquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#fetchTradingPoolTWAPRebalanceDetails', async () => {
let subjectTradingPool: Address;
let setManager: SocialTradingManagerMockContract;
let newAllocation: BigNumber;
let nextSet: SetTokenContract;
beforeEach(async () => {
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
const currentSetToken = set1;
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
rebalancingSetToken = await rebalancingSetV3Helper.createDefaultRebalancingSetTokenV3Async(
coreMock,
rebalancingFactory.address,
setManager.address,
twapLiquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
);
const currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(
ether(10 ** 6),
ONE_DAY_IN_SECONDS,
);
nextSet = set2;
newAllocation = ether(.4);
await setManager.rebalance.sendTransactionAsync(
rebalancingSetToken.address,
nextSet.address,
newAllocation,
liquidatorData
);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return poolViewer.fetchTradingPoolTWAPRebalanceDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(newAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV2/TradingPool data', async () => {
const [ , rbSetData, ] = await subject();
const auctionPriceParams = await rebalancingSetToken.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetToken.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetToken.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(twapLiquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#batchFetchTradingPoolOperator', async () => {
let subjectTradingPools: Address[];
let rebalancingSetToken2: RebalancingSetTokenV2Contract;
beforeEach(async () => {
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
const setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
set1.address,
failPeriod,
lastRebalanceTimestamp,
);
rebalancingSetToken2 = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address, // Set as other address
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
set1.address,
failPeriod,
lastRebalanceTimestamp,
);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader, // Set to first trader
allocator,
ether(.3)
);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken2.address,
trader2, // Set to second trader
allocator,
ether(.6)
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
});
async function subject(): Promise<any> {
return poolViewer.batchFetchTradingPoolOperator.callAsync(
subjectTradingPools
);
}
it('fetches the correct operators array', async () => {
const actualOperatorsArray = await subject();
const expectedOperatorsArray = [trader, trader2];
expect(JSON.stringify(actualOperatorsArray)).to.equal(JSON.stringify(expectedOperatorsArray));
});
});
describe('#batchFetchTradingPoolEntryFees', async () => {
let subjectTradingPools: Address[];
let rebalancingSetToken2: RebalancingSetTokenV2Contract;
let entryFee1: BigNumber;
let entryFee2: BigNumber;
beforeEach(async () => {
rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
const setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
entryFee1 = ether(.02);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
set1.address,
failPeriod,
lastRebalanceTimestamp,
entryFee1
);
entryFee2 = ether(.03);
rebalancingSetToken2 = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactory.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
set1.address,
failPeriod,
lastRebalanceTimestamp,
entryFee2
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
});
async function subject(): Promise<any> {
return poolViewer.batchFetchTradingPoolEntryFees.callAsync(
subjectTradingPools
);
}
it('fetches the correct entryFee array', async () => {
const actualEntryFeeArray = await subject();
const expectedEntryFeeArray = [entryFee1, entryFee2];
expect(JSON.stringify(actualEntryFeeArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
describe('#batchFetchTradingPoolRebalanceFees', async () => {
let subjectTradingPools: Address[];
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let usdPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let rebalancingSetToken2: RebalancingSetTokenV3Contract;
let subjectIncreaseChainTime: BigNumber;
beforeEach(async () => {
rebalancingSetTokenV3Factory = await viewerHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingSetTokenV3Factory);
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
const collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
const collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
feeRecipient,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
usdPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
usdOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(usdPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const secondNaturalUnit = new BigNumber(10 ** 8);
const secondSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const secondSetUnits = new BigNumber(100).mul(secondNaturalUnit).mul(10 ** 18).div(secondSetValue).round(0, 3);
const secondSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
usdPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
rebalancingSetToken2 = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[secondSetUnits],
secondNaturalUnit,
secondSetCallData
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
subjectIncreaseChainTime = ONE_YEAR_IN_SECONDS;
});
async function subject(): Promise<any> {
await blockchain.increaseTimeAsync(subjectIncreaseChainTime);
await blockchain.mineBlockAsync();
return poolViewer.batchFetchTradingPoolRebalanceFees.callAsync(
subjectTradingPools
);
}
it('fetches the correct fee accumulation array', async () => {
const feeState1 = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
const feeState2 = await usdPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken2.address);
const actualFeeArray = await subject();
const lastBlock = await web3.eth.getBlock('latest');
const rebalancingSetValue1 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken,
ethOracleWhiteList,
);
const rebalancingSetValue2 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken2,
usdOracleWhiteList,
);
const expectedFee1 = await feeCalculatorHelper.calculateAccruedFeesAsync(
feeState1,
rebalancingSetValue1,
new BigNumber(lastBlock.timestamp)
);
const expectedFee2 = await feeCalculatorHelper.calculateAccruedFeesAsync(
feeState2,
rebalancingSetValue2,
new BigNumber(lastBlock.timestamp)
);
const expectedFeeArray = [expectedFee1, expectedFee2];
expect(JSON.stringify(actualFeeArray)).to.equal(JSON.stringify(expectedFeeArray));
});
});
describe('#batchFetchTradingPoolAccumulation', async () => {
let subjectTradingPools: Address[];
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let usdPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let rebalancingSetToken2: RebalancingSetTokenV3Contract;
let subjectIncreaseChainTime: BigNumber;
beforeEach(async () => {
rebalancingSetTokenV3Factory = await viewerHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingSetTokenV3Factory);
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
const collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
const collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
feeRecipient,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
usdPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
usdOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(usdPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const secondNaturalUnit = new BigNumber(10 ** 8);
const secondSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const secondSetUnits = new BigNumber(100).mul(secondNaturalUnit).mul(10 ** 18).div(secondSetValue).round(0, 3);
const secondSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
usdPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
rebalancingSetToken2 = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[secondSetUnits],
secondNaturalUnit,
secondSetCallData
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
subjectIncreaseChainTime = ONE_YEAR_IN_SECONDS;
});
async function subject(): Promise<any> {
await blockchain.increaseTimeAsync(subjectIncreaseChainTime);
await blockchain.mineBlockAsync();
return poolViewer.batchFetchTradingPoolAccumulation.callAsync(
subjectTradingPools
);
}
it('fetches the correct profit/streaming fee accumulation array', async () => {
const feeState1: any = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
const feeState2: any = await usdPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken2.address);
const [
actualStreamingFeeArray,
actualProfitFeeArray,
] = await subject();
const lastBlock = await web3.eth.getBlock('latest');
const rebalancingSetValue1 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken,
ethOracleWhiteList,
);
const rebalancingSetValue2 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken2,
usdOracleWhiteList,
);
const expectedStreamingFee1 = await feeCalculatorHelper.calculateAccruedStreamingFee(
feeState1.streamingFeePercentage,
new BigNumber(lastBlock.timestamp).sub(feeState1.lastStreamingFeeTimestamp)
);
const expectedStreamingFee2 = await feeCalculatorHelper.calculateAccruedStreamingFee(
feeState2.streamingFeePercentage,
new BigNumber(lastBlock.timestamp).sub(feeState2.lastStreamingFeeTimestamp)
);
const expectedProfitFee1 = await feeCalculatorHelper.calculateAccruedProfitFeeAsync(
feeState1,
rebalancingSetValue1,
new BigNumber(lastBlock.timestamp)
);
const expectedProfitFee2 = await feeCalculatorHelper.calculateAccruedProfitFeeAsync(
feeState2,
rebalancingSetValue2,
new BigNumber(lastBlock.timestamp)
);
const expectedStreamingFeeArray = [expectedStreamingFee1, expectedStreamingFee2];
const expectedProfitFeeArray = [expectedProfitFee1, expectedProfitFee2];
expect(JSON.stringify(actualStreamingFeeArray)).to.equal(JSON.stringify(expectedStreamingFeeArray));
expect(JSON.stringify(actualProfitFeeArray)).to.equal(JSON.stringify(expectedProfitFeeArray));
});
});
describe('#batchFetchTradingPoolFeeState', async () => {
let subjectTradingPools: Address[];
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let usdPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let secondRebalancingSetToken: RebalancingSetTokenV3Contract;
beforeEach(async () => {
rebalancingSetTokenV3Factory = await viewerHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingSetTokenV3Factory);
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
const collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
const collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
setTokenFactory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = new BigNumber(10 ** 8);
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
usdPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
usdOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(usdPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const secondNaturalUnit = new BigNumber(10 ** 8);
const secondSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const secondSetUnits = new BigNumber(100).mul(secondNaturalUnit).mul(10 ** 18).div(secondSetValue).round(0, 3);
const secondSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
usdPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
secondRebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[collateralSet.address],
[secondSetUnits],
secondNaturalUnit,
secondSetCallData
);
subjectTradingPools = [rebalancingSetToken.address, secondRebalancingSetToken.address];
});
async function subject(): Promise<any> {
return poolViewer.batchFetchTradingPoolFeeState.callAsync(
subjectTradingPools
);
}
it('fetches the correct rebalanceFee array', async () => {
const tradingPoolFeeStates = await subject();
const firstFeeState: any = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
const secondFeeState: any = await usdPerformanceFeeCalculator.feeState.callAsync(
secondRebalancingSetToken.address
);
const expectedFeeStateInfo = _.map([firstFeeState, secondFeeState], feeStates =>
[
feeStates.profitFeePeriod,
feeStates.highWatermarkResetPeriod,
feeStates.profitFeePercentage,
feeStates.streamingFeePercentage,
feeStates.highWatermark,
feeStates.lastProfitFeeTimestamp,
feeStates.lastStreamingFeeTimestamp,
]
);
expect(JSON.stringify(tradingPoolFeeStates)).to.equal(JSON.stringify(expectedFeeStateInfo));
});
});
});
|
SetProtocol/set-protocol-viewers
|
artifacts/index.ts
|
<gh_stars>1-10
export { CTokenViewer } from './ts/CTokenViewer';
export { ERC20Viewer } from './ts/ERC20Viewer';
export { ProtocolViewer } from './ts/ProtocolViewer';
export { RebalancingSetTokenViewer } from './ts/RebalancingSetTokenViewer';
export { TradingPoolViewer } from './ts/TradingPoolViewer';
export {
BaseContract,
CTokenViewerContract,
ERC20ViewerContract,
ProtocolViewerContract,
RebalancingSetTokenViewerContract,
TradingPoolViewerContract
} from '../utils/contracts';
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/protocolViewer.spec.ts
|
require('module-alias/register');
import * as _ from 'lodash';
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import * as setProtocolUtils from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import { Address } from 'set-protocol-utils';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
UpdatableOracleMockContract
} from 'set-protocol-oracles';
import {
ConstantAuctionPriceCurveContract,
CoreMockContract,
FixedFeeCalculatorContract,
LinearAuctionLiquidatorContract,
OracleWhiteListContract,
PerformanceFeeCalculatorContract,
RebalancingSetTokenContract,
RebalancingSetTokenV2Contract,
RebalancingSetTokenV3Contract,
RebalancingSetTokenFactoryContract,
RebalancingSetTokenV2FactoryContract,
RebalancingSetTokenV3FactoryContract,
SetTokenContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
TWAPLiquidatorContract,
VaultContract,
WhiteListContract,
} from 'set-protocol-contracts';
import {
ProtocolViewerContract,
SocialTradingManagerMockContract,
TrendingManagerMockContract
} from '@utils/contracts';
import { ether, gWei } from '@utils/units';
import {
ONE_DAY_IN_SECONDS,
ONE_YEAR_IN_SECONDS,
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
DEFAULT_REBALANCING_NATURAL_UNIT,
DEFAULT_UNIT_SHARES,
ZERO,
} from '@utils/constants';
import {
Blockchain,
CompoundHelper,
CoreHelper,
ERC20Helper,
FeeCalculatorHelper,
LiquidatorHelper,
RebalancingHelper,
RebalancingSetV2Helper,
RebalancingSetV3Helper,
ValuationHelper,
} from 'set-protocol-contracts';
import {
OracleHelper,
} from 'set-protocol-oracles';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
const CoreMock =
require('set-protocol-contracts/dist/artifacts/ts/CoreMock').CoreMock;
BigNumberSetup.configure();
ChaiSetup.configure();
const { SetProtocolUtils: SetUtils } = setProtocolUtils;
const blockchain = new Blockchain(web3);
const { expect } = chai;
const { NULL_ADDRESS } = SetUtils.CONSTANTS;
contract('ProtocolViewer', accounts => {
const [
deployerAccount,
managerAccount,
ownerAccount,
feeRecipient,
trader,
allocator,
trader2,
] = accounts;
const coreHelper = new CoreHelper(deployerAccount, deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const protocolViewerHelper = new ProtocolViewerHelper(deployerAccount);
const rebalancingHelper = new RebalancingHelper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const oracleHelper = new OracleHelper(deployerAccount);
const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper);
const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper);
const feeCalculatorHelper = new FeeCalculatorHelper(deployerAccount);
const viewerHelper = new ProtocolViewerHelper(deployerAccount);
const compoundHelper = new CompoundHelper(deployerAccount);
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let coreMock: CoreMockContract;
let factory: SetTokenFactoryContract;
let rebalancingComponentWhiteList: WhiteListContract;
let rebalancingFactoryV1: RebalancingSetTokenFactoryContract;
let constantAuctionPriceCurve: ConstantAuctionPriceCurveContract;
let protocolViewer: ProtocolViewerContract;
before(async () => {
ABIDecoder.addABI(CoreMock.abi);
});
after(async () => {
ABIDecoder.removeABI(CoreMock.abi);
});
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault);
factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address);
rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync();
rebalancingFactoryV1 = await coreHelper.deployRebalancingSetTokenFactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
);
constantAuctionPriceCurve = await rebalancingHelper.deployConstantAuctionPriceCurveAsync(
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
);
await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactoryV1);
await rebalancingHelper.addPriceLibraryAsync(coreMock, constantAuctionPriceCurve);
protocolViewer = await protocolViewerHelper.deployProtocolViewerAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#batchFetchSupplies', async () => {
let subjectTokenAddresses: Address[];
let token: StandardTokenMockContract;
beforeEach(async () => {
token = await erc20Helper.deployTokenAsync(ownerAccount);
subjectTokenAddresses = [token.address];
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchSupplies.callAsync(
subjectTokenAddresses,
);
}
it('fetches the supplies of the token addresses', async () => {
const supplies: BigNumber[] = await subject();
const suppliesJSON = JSON.stringify(supplies);
const expectedSupplies = await erc20Helper.getTokenSupplies([token]);
const expectedSuppliesJSON = JSON.stringify(expectedSupplies);
expect(suppliesJSON).to.equal(expectedSuppliesJSON);
});
});
describe('#batchFetchBalancesOf', async () => {
let subjectTokenAddresses: Address[];
let subjectTokenOwner: Address;
let token: StandardTokenMockContract;
beforeEach(async () => {
token = await erc20Helper.deployTokenAsync(ownerAccount);
subjectTokenAddresses = [token.address];
subjectTokenOwner = deployerAccount;
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchBalancesOf.callAsync(
subjectTokenAddresses,
subjectTokenOwner,
);
}
it('fetches the balances of the token addresses', async () => {
const balances: BigNumber[] = await subject();
const balancesJSON = JSON.stringify(balances);
const expectedSupplies = await erc20Helper.getTokenBalances([token], subjectTokenOwner);
const expectedSuppliesJSON = JSON.stringify(expectedSupplies);
expect(balancesJSON).to.equal(expectedSuppliesJSON);
});
});
describe('#fetchRebalanceProposalStateAsync', async () => {
let subjectRebalancingSetAddress: Address;
let rebalancingSetToken: RebalancingSetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
const currentSetToken = setTokens[0];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactoryV1.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetTokenQuantityToIssue = ether(8);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
subjectRebalancingSetAddress = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return protocolViewer.fetchRebalanceProposalStateAsync.callAsync(
subjectRebalancingSetAddress,
);
}
it('fetches the RebalancingSetToken\'s current proposal\'s parameters', async () => {
const rebalanceProposalState: any[] = await subject();
const rebalancingSetState = rebalanceProposalState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
const [nextSetAddress, auctionLibraryAddress] = rebalanceProposalState[1];
expect(nextSetAddress).to.equal(NULL_ADDRESS);
expect(auctionLibraryAddress).to.equal(NULL_ADDRESS);
const [
proposalStartTime,
auctionTimeToPivot,
auctionStartPrice,
auctionPivotPrice,
] = rebalanceProposalState[2];
expect(proposalStartTime).to.be.bignumber.equal(ZERO);
expect(auctionTimeToPivot).to.be.bignumber.equal(ZERO);
expect(auctionStartPrice).to.be.bignumber.equal(ZERO);
expect(auctionPivotPrice).to.be.bignumber.equal(ZERO);
});
});
describe('#fetchRebalanceAuctionStateAsync', async () => {
let subjectRebalancingSetAddress: Address;
let rebalancingSetToken: RebalancingSetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
const currentSetToken = setTokens[0];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactoryV1.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetTokenQuantityToIssue = ether(8);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
subjectRebalancingSetAddress = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return protocolViewer.fetchRebalanceAuctionStateAsync.callAsync(
subjectRebalancingSetAddress,
);
}
it('fetches the RebalancingSetToken\'s current auction\'s parameters', async () => {
const rebalanceAuctionState: any[] = await subject();
const rebalancingSetState = rebalanceAuctionState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
const [
startingCurrentSetAmount,
auctionStartTime,
minimumBid,
remainingCurrentSets,
] = rebalanceAuctionState[1];
expect(startingCurrentSetAmount).to.be.bignumber.equal(ZERO);
expect(auctionStartTime).to.be.bignumber.equal(ZERO);
expect(minimumBid).to.be.bignumber.equal(ZERO);
expect(remainingCurrentSets).to.be.bignumber.equal(ZERO);
});
});
describe('#batchFetchUnitSharesAsync', async () => {
let subjectRebalancingSetAddresses: Address[];
let rebalancingSetToken: RebalancingSetTokenContract;
let setTokenOne: SetTokenContract;
let setTokenTwo: SetTokenContract;
let defaultRebalancingSetToken: RebalancingSetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
setTokenOne = setTokens[0];
setTokenTwo = setTokens[1];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactoryV1.address,
managerAccount,
setTokenOne.address,
ONE_DAY_IN_SECONDS
);
defaultRebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactoryV1.address,
managerAccount,
setTokenTwo.address,
ONE_DAY_IN_SECONDS
);
subjectRebalancingSetAddresses = [rebalancingSetToken.address, defaultRebalancingSetToken.address];
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchUnitSharesAsync.callAsync(
subjectRebalancingSetAddresses,
);
}
it('fetches the RebalancingSetTokens\' unitShares', async () => {
const rebalanceUnitShares: BigNumber[] = await subject();
const firstUnitShares = rebalanceUnitShares[0];
const firstExpectedUnitShares = await rebalancingSetToken.unitShares.callAsync();
expect(firstUnitShares).to.be.bignumber.equal(firstExpectedUnitShares);
const secondUnitShares = rebalanceUnitShares[1];
const secondExpectedUnitShares = await defaultRebalancingSetToken.unitShares.callAsync();
expect(secondUnitShares).to.be.bignumber.equal(secondExpectedUnitShares);
});
});
describe('RebalancingSetTokenV2/V3 Tests', async () => {
let rebalancingSetToken: RebalancingSetTokenV2Contract;
let rebalancingSetTokenV3: RebalancingSetTokenV3Contract;
let rebalancingFactoryV2: RebalancingSetTokenV2FactoryContract;
let rebalancingFactoryV3: RebalancingSetTokenV3FactoryContract;
let liquidatorWhitelist: WhiteListContract;
let liquidator: LinearAuctionLiquidatorContract;
let twapLiquidator: TWAPLiquidatorContract;
let fixedFeeCalculator: FixedFeeCalculatorContract;
let feeCalculatorWhitelist: WhiteListContract;
let name: string;
let auctionPeriod: BigNumber;
let rangeStart: BigNumber;
let rangeEnd: BigNumber;
let oracleWhiteList: OracleWhiteListContract;
let component1: StandardTokenMockContract;
let component2: StandardTokenMockContract;
let component1Price: BigNumber;
let component2Price: BigNumber;
let set1: SetTokenContract;
let set2: SetTokenContract;
let set1Components: Address[];
let set1Units: BigNumber[];
let set1NaturalUnit: BigNumber;
let set2Components: Address[];
let set2Units: BigNumber[];
let set2NaturalUnit: BigNumber;
let component1Oracle: UpdatableOracleMockContract;
let component2Oracle: UpdatableOracleMockContract;
const rebalancingHelper = new RebalancingSetV2Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const rebalancingSetV3Helper = new RebalancingSetV3Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
let currentSetToken: SetTokenContract;
let nextSet: SetTokenContract;
let currentAllocation: BigNumber;
let newAllocation: BigNumber;
let lastRebalanceTimestamp: BigNumber;
let entryFee: BigNumber;
let rebalanceFee: BigNumber;
let setManager: SocialTradingManagerMockContract;
beforeEach(async () => {
liquidatorWhitelist = await coreHelper.deployWhiteListAsync();
feeCalculatorWhitelist = await coreHelper.deployWhiteListAsync();
rebalancingFactoryV2 = await coreHelper.deployRebalancingSetTokenV2FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactoryV2);
rebalancingFactoryV3 = await coreHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactoryV3);
component1 = await erc20Helper.deployTokenAsync(deployerAccount);
component2 = await erc20Helper.deployTokenAsync(deployerAccount);
await coreHelper.addTokensToWhiteList(
[component1.address, component2.address],
rebalancingComponentWhiteList,
);
await erc20Helper.approveTransfersAsync(
[component1, component2],
transferProxy.address
);
set1Components = [component1.address, component2.address];
set1Units = [gWei(1), gWei(1)];
set1NaturalUnit = gWei(1);
set1 = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
set1Components,
set1Units,
set1NaturalUnit,
);
set2Components = [component1.address, component2.address];
set2Units = [gWei(2), gWei(3)];
set2NaturalUnit = gWei(2);
set2 = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
set2Components,
set2Units,
set2NaturalUnit,
);
component1Price = ether(1);
component2Price = ether(2);
component1Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component1Price);
component2Oracle = await oracleHelper.deployUpdatableOracleMockAsync(component2Price);
oracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[component1.address, component2.address],
[component1Oracle.address, component2Oracle.address],
);
auctionPeriod = ONE_DAY_IN_SECONDS;
rangeStart = new BigNumber(10); // 10% above fair value
rangeEnd = new BigNumber(10); // 10% below fair value
name = 'liquidator';
liquidator = await liquidatorHelper.deployLinearAuctionLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
name,
);
await coreHelper.addAddressToWhiteList(liquidator.address, liquidatorWhitelist);
const assetPairHashes = [
liquidatorHelper.generateAssetPairHashes(component1.address, component2.address),
];
const assetPairBounds = [
{min: ether(10 ** 4).toString(), max: ether(10 ** 6).toString()},
];
twapLiquidator = await viewerHelper.deployTWAPLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
assetPairHashes,
assetPairBounds,
name,
);
await coreHelper.addAddressToWhiteList(twapLiquidator.address, liquidatorWhitelist);
fixedFeeCalculator = await feeCalculatorHelper.deployFixedFeeCalculatorAsync();
await coreHelper.addAddressToWhiteList(fixedFeeCalculator.address, feeCalculatorWhitelist);
currentSetToken = set1;
nextSet = set2;
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = new BigNumber(timestamp);
entryFee = ether(.02);
rebalanceFee = ether(.002);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactoryV2.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
lastRebalanceTimestamp,
entryFee,
rebalanceFee
);
rebalancingSetTokenV3 = await rebalancingSetV3Helper.createDefaultRebalancingSetTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
deployerAccount,
twapLiquidator.address,
feeRecipient,
fixedFeeCalculator.address,
currentSetToken.address,
failPeriod,
new BigNumber(lastRebalanceTimestamp),
);
currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
});
describe('#fetchNewTradingPoolDetails', async () => {
let subjectTradingPool: Address;
let newFee: BigNumber;
let feeUpdateTimestamp: BigNumber;
beforeEach(async () => {
newFee = ether(.04);
await setManager.updateFee.sendTransactionAsync(
rebalancingSetToken.address,
newFee
);
const { timestamp } = await web3.eth.getBlock('latest');
feeUpdateTimestamp = new BigNumber(timestamp);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return protocolViewer.fetchNewTradingPoolDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(currentAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(newFee);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(feeUpdateTimestamp);
});
it('fetches the correct TradingPool data', async () => {
const [ , rbSetData, ] = await subject();
expect(rbSetData.manager).to.equal(setManager.address);
expect(rbSetData.feeRecipient).to.equal(feeRecipient);
expect(rbSetData.currentSet).to.equal(currentSetToken.address);
expect(rbSetData.name).to.equal('Rebalancing Set Token');
expect(rbSetData.symbol).to.equal('RBSET');
expect(rbSetData.unitShares).to.be.bignumber.equal(DEFAULT_UNIT_SHARES);
expect(rbSetData.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(rbSetData.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(rbSetData.entryFee).to.be.bignumber.equal(entryFee);
expect(rbSetData.rebalanceFee).to.be.bignumber.equal(rebalanceFee);
expect(rbSetData.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set1Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set1Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set1NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#fetchNewTradingPoolV2Details and fetchNewRebalancingSetDetails', async () => {
let subjectTradingPool: Address;
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let collateralSetComponents: Address[];
let collateralSetUnits: BigNumber[];
let collateralSetNaturalUnit: BigNumber;
let firstSetUnits: BigNumber;
let currentAllocation: BigNumber;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
beforeEach(async () => {
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
setManager = await viewerHelper.deploySocialTradingManagerMockAsync();
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = new BigNumber(timestamp);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
setManager.address,
liquidator.address,
feeRecipient,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
currentAllocation = ether(.6);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader,
allocator,
currentAllocation
);
subjectTradingPool = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return protocolViewer.fetchNewTradingPoolV2Details.callAsync(
subjectTradingPool
);
}
async function subjectRBSet(): Promise<any> {
return protocolViewer.fetchNewRebalancingSetDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct RebalancingSetTokenV3/TradingPool data', async () => {
const [ , tradingPoolInfo, , , ] = await subject();
expect(tradingPoolInfo.manager).to.equal(setManager.address);
expect(tradingPoolInfo.feeRecipient).to.equal(feeRecipient);
expect(tradingPoolInfo.currentSet).to.equal(collateralSet.address);
expect(tradingPoolInfo.liquidator).to.equal(liquidator.address);
expect(tradingPoolInfo.name).to.equal('Rebalancing Set Token');
expect(tradingPoolInfo.symbol).to.equal('RBSET');
expect(tradingPoolInfo.unitShares).to.be.bignumber.equal(firstSetUnits);
expect(tradingPoolInfo.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(tradingPoolInfo.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(tradingPoolInfo.entryFee).to.be.bignumber.equal(ZERO);
expect(tradingPoolInfo.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(tradingPoolInfo.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , , , ] = await subject();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(currentAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV3/Performance Fee data', async () => {
const [ , , performanceFeeState, , ] = await subject();
const [
profitFeePeriod,
highWatermarkResetPeriod,
profitFeePercentage,
streamingFeePercentage,
highWatermark,
lastProfitFeeTimestamp,
lastStreamingFeeTimestamp,
] = performanceFeeState;
const expectedFeeStates: any =
await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
expect(profitFeePeriod).to.equal(expectedFeeStates.profitFeePeriod);
expect(highWatermarkResetPeriod).to.equal(expectedFeeStates.highWatermarkResetPeriod);
expect(profitFeePercentage).to.equal(expectedFeeStates.profitFeePercentage);
expect(streamingFeePercentage).to.equal(expectedFeeStates.streamingFeePercentage);
expect(highWatermark).to.equal(expectedFeeStates.highWatermark);
expect(lastProfitFeeTimestamp).to.equal(expectedFeeStates.lastProfitFeeTimestamp);
expect(lastStreamingFeeTimestamp).to.equal(expectedFeeStates.lastStreamingFeeTimestamp);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , , collateralSetData, ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralSetComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(collateralSetUnits));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(collateralSetNaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct PerformanceFeeCalculator address', async () => {
const [ , , , , performanceFeeCalculatorAddress ] = await subject();
expect(performanceFeeCalculatorAddress).to.equal(ethPerformanceFeeCalculator.address);
});
it('fetches the correct RebalancingSetTokenV3 data', async () => {
const [ tradingPoolInfo, , , ] = await subjectRBSet();
expect(tradingPoolInfo.manager).to.equal(setManager.address);
expect(tradingPoolInfo.feeRecipient).to.equal(feeRecipient);
expect(tradingPoolInfo.currentSet).to.equal(collateralSet.address);
expect(tradingPoolInfo.liquidator).to.equal(liquidator.address);
expect(tradingPoolInfo.name).to.equal('Rebalancing Set Token');
expect(tradingPoolInfo.symbol).to.equal('RBSET');
expect(tradingPoolInfo.unitShares).to.be.bignumber.equal(firstSetUnits);
expect(tradingPoolInfo.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(tradingPoolInfo.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(tradingPoolInfo.entryFee).to.be.bignumber.equal(ZERO);
expect(tradingPoolInfo.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(tradingPoolInfo.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV3/Performance Fee data', async () => {
const [ , performanceFeeState, , ] = await subjectRBSet();
const [
profitFeePeriod,
highWatermarkResetPeriod,
profitFeePercentage,
streamingFeePercentage,
highWatermark,
lastProfitFeeTimestamp,
lastStreamingFeeTimestamp,
] = performanceFeeState;
const expectedFeeStates: any =
await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
expect(profitFeePeriod).to.equal(expectedFeeStates.profitFeePeriod);
expect(highWatermarkResetPeriod).to.equal(expectedFeeStates.highWatermarkResetPeriod);
expect(profitFeePercentage).to.equal(expectedFeeStates.profitFeePercentage);
expect(streamingFeePercentage).to.equal(expectedFeeStates.streamingFeePercentage);
expect(highWatermark).to.equal(expectedFeeStates.highWatermark);
expect(lastProfitFeeTimestamp).to.equal(expectedFeeStates.lastProfitFeeTimestamp);
expect(lastStreamingFeeTimestamp).to.equal(expectedFeeStates.lastStreamingFeeTimestamp);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData, ] = await subjectRBSet();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralSetComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(collateralSetUnits));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(collateralSetNaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct PerformanceFeeCalculator address', async () => {
const [ , , , performanceFeeCalculatorAddress ] = await subjectRBSet();
expect(performanceFeeCalculatorAddress).to.equal(ethPerformanceFeeCalculator.address);
});
});
describe('#fetchTradingPoolRebalanceDetails and fetchRBSetRebalanceDetails', async () => {
let subjectTradingPool: Address;
beforeEach(async () => {
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = '0x';
nextSet = set2;
newAllocation = ether(.4);
await setManager.rebalance.sendTransactionAsync(
rebalancingSetToken.address,
nextSet.address,
newAllocation,
liquidatorData
);
subjectTradingPool = rebalancingSetToken.address;
});
async function subjectSocialTrading(): Promise<any> {
return protocolViewer.fetchTradingPoolRebalanceDetails.callAsync(
subjectTradingPool
);
}
async function subjectRBSet(): Promise<any> {
return protocolViewer.fetchRBSetRebalanceDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subjectSocialTrading();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(newAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct TradingPool data', async () => {
const [ , rbSetData, ] = await subjectSocialTrading();
const auctionPriceParams = await rebalancingSetToken.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetToken.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetToken.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(liquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subjectSocialTrading();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct RebalancingSetTokenV2 data', async () => {
const [ rbSetData, ] = await subjectRBSet();
const auctionPriceParams = await rebalancingSetToken.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetToken.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetToken.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(liquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , collateralSetData ] = await subjectRBSet();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#fetchTradingPoolTWAPRebalanceDetails and fetchRBSetTWAPRebalanceDetails', async () => {
let subjectTradingPool: Address;
beforeEach(async () => {
const currentAllocation = ether(.6);
await rebalancingSetTokenV3.setManager.sendTransactionAsync(setManager.address);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetTokenV3.address,
trader,
allocator,
currentAllocation
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetTokenV3
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetTokenV3.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(
ether(10 ** 6),
ONE_DAY_IN_SECONDS,
);
nextSet = set2;
newAllocation = ether(.4);
await setManager.rebalance.sendTransactionAsync(
rebalancingSetTokenV3.address,
nextSet.address,
newAllocation,
liquidatorData
);
subjectTradingPool = rebalancingSetTokenV3.address;
});
async function subjectSocialTrading(): Promise<any> {
return protocolViewer.fetchTradingPoolTWAPRebalanceDetails.callAsync(
subjectTradingPool
);
}
async function subjectRBSet(): Promise<any> {
return protocolViewer.fetchRBSetTWAPRebalanceDetails.callAsync(
subjectTradingPool
);
}
it('fetches the correct poolInfo data', async () => {
const [ poolInfo, , ] = await subjectSocialTrading();
expect(poolInfo.trader).to.equal(trader);
expect(poolInfo.allocator).to.equal(allocator);
expect(poolInfo.currentAllocation).to.be.bignumber.equal(newAllocation);
expect(poolInfo.newEntryFee).to.be.bignumber.equal(ZERO);
expect(poolInfo.feeUpdateTimestamp).to.be.bignumber.equal(ZERO);
});
it('fetches the correct TradingPool data', async () => {
const [ , rbSetData, ] = await subjectSocialTrading();
const auctionPriceParams = await rebalancingSetTokenV3.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetTokenV3.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetTokenV3.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(twapLiquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData ] = await subjectSocialTrading();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct RebalancingSetToken data', async () => {
const [ rbSetData, ] = await subjectRBSet();
const auctionPriceParams = await rebalancingSetTokenV3.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetTokenV3.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetTokenV3.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(twapLiquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , collateralSetData ] = await subjectRBSet();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(set2Components));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('Trading Pool V1 Batch Fetches', async () => {
let rebalancingSetToken2: RebalancingSetTokenV2Contract;
let rebalanceFee2: BigNumber;
let entryFee2: BigNumber;
beforeEach(async () => {
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = timestamp;
entryFee2 = ether(.03);
rebalanceFee2 = ether(.003);
rebalancingSetToken2 = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async(
coreMock,
rebalancingFactoryV2.address,
setManager.address,
liquidator.address,
feeRecipient,
fixedFeeCalculator.address,
set1.address,
failPeriod,
new BigNumber(lastRebalanceTimestamp),
entryFee2,
rebalanceFee2
);
});
describe('#batchFetchTradingPoolEntryFees', async () => {
let subjectTradingPools: Address[];
beforeEach(async () => {
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
});
async function subject(): Promise<any> {
return protocolViewer.batchFetchTradingPoolEntryFees.callAsync(
subjectTradingPools
);
}
it('fetches the correct entryFee array', async () => {
const actualEntryFeeArray = await subject();
const expectedEntryFeeArray = [entryFee, entryFee2];
expect(JSON.stringify(actualEntryFeeArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
describe('#batchFetchTradingPoolRebalanceFees', async () => {
let subjectTradingPools: Address[];
beforeEach(async () => {
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
});
async function subject(): Promise<any> {
return protocolViewer.batchFetchTradingPoolRebalanceFees.callAsync(
subjectTradingPools
);
}
it('fetches the correct rebalanceFee array', async () => {
const actualEntryRebalanceArray = await subject();
const expectedEntryRebalanceArray = [rebalanceFee, rebalanceFee2];
expect(JSON.stringify(actualEntryRebalanceArray)).to.equal(JSON.stringify(expectedEntryRebalanceArray));
});
});
describe('#batchFetchTradingPoolOperator', async () => {
let subjectTradingPools: Address[];
beforeEach(async () => {
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken.address,
trader, // Set to first trader
allocator,
ether(.3)
);
await setManager.updateRecord.sendTransactionAsync(
rebalancingSetToken2.address,
trader2, // Set to second trader
allocator,
ether(.6)
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
});
async function subject(): Promise<any> {
return protocolViewer.batchFetchTradingPoolOperator.callAsync(
subjectTradingPools
);
}
it('fetches the correct operators array', async () => {
const actualOperatorsArray = await subject();
const expectedOperatorsArray = [trader, trader2];
expect(JSON.stringify(actualOperatorsArray)).to.equal(JSON.stringify(expectedOperatorsArray));
});
});
});
describe('#batchFetchTradingPoolAccumulation', async () => {
let subjectTradingPools: Address[];
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let usdPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let rebalancingSetToken2: RebalancingSetTokenV3Contract;
let subjectIncreaseChainTime: BigNumber;
beforeEach(async () => {
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
const collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
const collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
const lastRebalanceTimestamp = new BigNumber(timestamp);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
feeRecipient,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
usdPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
usdOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(usdPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const secondNaturalUnit = new BigNumber(10 ** 8);
const secondSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const secondSetUnits = new BigNumber(100)
.mul(secondNaturalUnit)
.mul(10 ** 18)
.div(secondSetValue)
.round(0, 3);
const secondSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
usdPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
rebalancingSetToken2 = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
[collateralSet.address],
[secondSetUnits],
secondNaturalUnit,
secondSetCallData
);
subjectTradingPools = [rebalancingSetToken.address, rebalancingSetToken2.address];
subjectIncreaseChainTime = ONE_YEAR_IN_SECONDS;
});
async function subject(): Promise<any> {
await blockchain.increaseTimeAsync(subjectIncreaseChainTime);
await blockchain.mineBlockAsync();
return protocolViewer.batchFetchTradingPoolAccumulation.callAsync(
subjectTradingPools
);
}
it('fetches the correct profit/streaming fee accumulation array', async () => {
const feeState1: any = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
const feeState2: any = await usdPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken2.address);
const [
actualStreamingFeeArray,
actualProfitFeeArray,
] = await subject();
const lastBlock = await web3.eth.getBlock('latest');
const rebalancingSetValue1 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken,
ethOracleWhiteList,
);
const rebalancingSetValue2 = await valuationHelper.calculateRebalancingSetTokenValueAsync(
rebalancingSetToken2,
usdOracleWhiteList,
);
const expectedStreamingFee1 = await feeCalculatorHelper.calculateAccruedStreamingFee(
feeState1.streamingFeePercentage,
new BigNumber(lastBlock.timestamp).sub(feeState1.lastStreamingFeeTimestamp)
);
const expectedStreamingFee2 = await feeCalculatorHelper.calculateAccruedStreamingFee(
feeState2.streamingFeePercentage,
new BigNumber(lastBlock.timestamp).sub(feeState2.lastStreamingFeeTimestamp)
);
const expectedProfitFee1 = await feeCalculatorHelper.calculateAccruedProfitFeeAsync(
feeState1,
rebalancingSetValue1,
new BigNumber(lastBlock.timestamp)
);
const expectedProfitFee2 = await feeCalculatorHelper.calculateAccruedProfitFeeAsync(
feeState2,
rebalancingSetValue2,
new BigNumber(lastBlock.timestamp)
);
const expectedStreamingFeeArray = [expectedStreamingFee1, expectedStreamingFee2];
const expectedProfitFeeArray = [expectedProfitFee1, expectedProfitFee2];
expect(JSON.stringify(actualStreamingFeeArray)).to.equal(JSON.stringify(expectedStreamingFeeArray));
expect(JSON.stringify(actualProfitFeeArray)).to.equal(JSON.stringify(expectedProfitFeeArray));
});
});
describe('#batchFetchTradingPoolFeeState', async () => {
let subjectTradingPools: Address[];
let ethOracleWhiteList: OracleWhiteListContract;
let usdOracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let collateralSet: SetTokenContract;
let usdWrappedETHOracle: UpdatableOracleMockContract;
let usdWrappedBTCOracle: UpdatableOracleMockContract;
let usdUSDCOracle: UpdatableOracleMockContract;
let usdDaiOracle: UpdatableOracleMockContract;
let ethWrappedETHOracle: UpdatableOracleMockContract;
let ethWrappedBTCOracle: UpdatableOracleMockContract;
let ethUSDCOracle: UpdatableOracleMockContract;
let ethDaiOracle: UpdatableOracleMockContract;
let ethPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let usdPerformanceFeeCalculator: PerformanceFeeCalculatorContract;
let secondRebalancingSetToken: RebalancingSetTokenV3Contract;
beforeEach(async () => {
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
usdWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
usdWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
usdDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
usdOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[usdWrappedETHOracle.address, usdWrappedBTCOracle.address, usdUSDCOracle.address, usdDaiOracle.address],
);
ethWrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedETHPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethWrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
wrappedBTCPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethUSDCOracle = await oracleHelper.deployUpdatableOracleMockAsync(
usdcPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethDaiOracle = await oracleHelper.deployUpdatableOracleMockAsync(
daiPrice.mul(ether(1)).div(wrappedETHPrice).round(0, 3)
);
ethOracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[ethWrappedETHOracle.address, ethWrappedBTCOracle.address, ethUSDCOracle.address, ethDaiOracle.address],
);
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
ethPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
ethOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(ethPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const collateralSetComponents = [wrappedETH.address, wrappedBTC.address];
const collateralSetUnits = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
const collateralSetNaturalUnit = new BigNumber(10 ** 12);
collateralSet = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
collateralSetComponents,
collateralSetUnits,
collateralSetNaturalUnit,
);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = new BigNumber(10 ** 8);
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
ethPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
rebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
[collateralSet.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
usdPerformanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
usdOracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
await coreHelper.addAddressToWhiteList(usdPerformanceFeeCalculator.address, feeCalculatorWhitelist);
const secondNaturalUnit = new BigNumber(10 ** 8);
const secondSetValue = await valuationHelper.calculateSetTokenValueAsync(collateralSet, usdOracleWhiteList);
const secondSetUnits = new BigNumber(100)
.mul(secondNaturalUnit)
.mul(10 ** 18)
.div(secondSetValue)
.round(0, 3);
const secondSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
deployerAccount,
liquidator.address,
deployerAccount,
usdPerformanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
ONE_DAY_IN_SECONDS.mul(2),
ZERO,
ZERO,
calculatorData
);
secondRebalancingSetToken = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingFactoryV3.address,
[collateralSet.address],
[secondSetUnits],
secondNaturalUnit,
secondSetCallData
);
subjectTradingPools = [rebalancingSetToken.address, secondRebalancingSetToken.address];
});
async function subject(): Promise<any> {
return protocolViewer.batchFetchTradingPoolFeeState.callAsync(
subjectTradingPools
);
}
it('fetches the correct rebalanceFee array', async () => {
const tradingPoolFeeStates = await subject();
const firstFeeState: any = await ethPerformanceFeeCalculator.feeState.callAsync(rebalancingSetToken.address);
const secondFeeState: any = await usdPerformanceFeeCalculator.feeState.callAsync(
secondRebalancingSetToken.address
);
const expectedFeeStateInfo = _.map([firstFeeState, secondFeeState], feeStates =>
[
feeStates.profitFeePeriod,
feeStates.highWatermarkResetPeriod,
feeStates.profitFeePercentage,
feeStates.streamingFeePercentage,
feeStates.highWatermark,
feeStates.lastProfitFeeTimestamp,
feeStates.lastStreamingFeeTimestamp,
]
);
expect(JSON.stringify(tradingPoolFeeStates)).to.equal(JSON.stringify(expectedFeeStateInfo));
});
});
});
describe('#batchFetchOraclePrices', async () => {
let wrappedETHOracle: UpdatableOracleMockContract;
let wrappedBTCOracle: UpdatableOracleMockContract;
let usdcOracle: UpdatableOracleMockContract;
let daiOracle: UpdatableOracleMockContract;
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
let subjectOracleAddresses: Address[];
beforeEach(async () => {
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
wrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
wrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdcOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
daiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
subjectOracleAddresses = [
wrappedETHOracle.address,
wrappedBTCOracle.address,
usdcOracle.address,
daiOracle.address,
];
});
async function subject(): Promise<any> {
return protocolViewer.batchFetchOraclePrices.callAsync(
subjectOracleAddresses,
);
}
it('fetches oracle prices', async () => {
const oraclePrices = await subject();
const expectedOraclePrices = [wrappedETHPrice, wrappedBTCPrice, usdcPrice, daiPrice];
expect(JSON.stringify(oraclePrices)).to.equal(JSON.stringify(expectedOraclePrices));
});
});
describe('#batchFetchExchangeRateStored', async () => {
let cUSDCAddress: Address;
let cDAIAddress: Address;
let subjectTokenAddresses: Address[];
beforeEach(async () => {
// Set up Compound USDC token
const usdcInstance = await erc20Helper.deployTokenAsync(
deployerAccount,
6,
);
cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, deployerAccount);
await compoundHelper.enableCToken(cUSDCAddress);
// Set the Borrow Rate
await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999'));
// Set up Compound DAI token
const daiInstance = await erc20Helper.deployTokenAsync(
deployerAccount,
18,
);
cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, deployerAccount);
await compoundHelper.enableCToken(cDAIAddress);
// Set the Borrow Rate
await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165'));
subjectTokenAddresses = [cUSDCAddress, cDAIAddress];
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchExchangeRateStored.callAsync(
subjectTokenAddresses,
);
}
it('fetches the exchangeRates of the token addresses', async () => {
const exchangeRates: BigNumber[] = await subject();
const exchangeRatesJSON = JSON.stringify(exchangeRates);
const expectedExchangeRates: BigNumber[] = [];
for (let i = 0; i < subjectTokenAddresses.length; i++) {
const expectedExchangeRate = await compoundHelper.getExchangeRate(subjectTokenAddresses[i]);
expectedExchangeRates.push(expectedExchangeRate);
}
const expectedExchangeRatesJSON = JSON.stringify(expectedExchangeRates);
expect(exchangeRatesJSON).to.equal(expectedExchangeRatesJSON);
});
});
describe('Manager Viewer Tests', async () => {
let trendingManagerMock1: TrendingManagerMockContract;
let trendingManagerMock2: TrendingManagerMockContract;
let crossoverTimestamp1: BigNumber;
let crossoverTimestamp2: BigNumber;
beforeEach(async () => {
crossoverTimestamp1 = new BigNumber(14800000000);
crossoverTimestamp2 = new BigNumber(11800000000);
trendingManagerMock1 = await protocolViewerHelper.deployTrendingManagerMockAsync(
crossoverTimestamp1
);
trendingManagerMock2 = await protocolViewerHelper.deployTrendingManagerMockAsync(
crossoverTimestamp2
);
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#batchFetchMACOV2CrossoverTimestamp', async () => {
let subjectManagerAddresses: Address[];
beforeEach(async () => {
subjectManagerAddresses = [trendingManagerMock1.address, trendingManagerMock2.address];
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchMACOV2CrossoverTimestamp.callAsync(
subjectManagerAddresses,
);
}
it('fetches the lastCrossoverConfirmationTimestamp of the MACO Managers', async () => {
const actualCrossoverArray = await subject();
const expectedEntryFeeArray = [crossoverTimestamp1, crossoverTimestamp2];
expect(JSON.stringify(actualCrossoverArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
describe('#batchFetchAssetPairCrossoverTimestamp', async () => {
let subjectManagerAddresses: Address[];
beforeEach(async () => {
subjectManagerAddresses = [trendingManagerMock1.address, trendingManagerMock2.address];
});
async function subject(): Promise<BigNumber[]> {
return protocolViewer.batchFetchAssetPairCrossoverTimestamp.callAsync(
subjectManagerAddresses,
);
}
it('fetches the recentInitialProposeTimestamp of the Asset Pair Managers', async () => {
const actualCrossoverArray = await subject();
const expectedEntryFeeArray = [crossoverTimestamp1, crossoverTimestamp2];
expect(JSON.stringify(actualCrossoverArray)).to.equal(JSON.stringify(expectedEntryFeeArray));
});
});
});
});
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/lib/rebalancingSetTokenViewer.spec.ts
|
<gh_stars>1-10
require('module-alias/register');
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import * as setProtocolUtils from 'set-protocol-utils';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
ConstantAuctionPriceCurveContract,
CoreMockContract,
LinearAuctionLiquidatorContract,
OracleWhiteListContract,
PerformanceFeeCalculatorContract,
RebalancingSetTokenContract,
RebalancingSetTokenFactoryContract,
RebalancingSetTokenV3Contract,
RebalancingSetTokenV3FactoryContract,
SetTokenContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
TWAPLiquidatorContract,
VaultContract,
WhiteListContract,
} from 'set-protocol-contracts';
import {
UpdatableOracleMockContract,
} from 'set-protocol-oracles';
import {
RebalancingSetTokenViewerContract,
} from '@utils/contracts';
import { ether } from '@utils/units';
import {
ONE_DAY_IN_SECONDS,
ONE_YEAR_IN_SECONDS,
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
DEFAULT_REBALANCE_TIME_TO_PIVOT,
DEFAULT_REBALANCE_START_PRICE,
DEFAULT_REBALANCING_NATURAL_UNIT,
ZERO,
ONE_HOUR_IN_SECONDS,
} from '@utils/constants';
import { expectRevertError } from '@utils/tokenAssertions';
import {
Blockchain,
CoreHelper,
ERC20Helper,
FeeCalculatorHelper,
LiquidatorHelper,
RebalancingHelper,
RebalancingSetV3Helper,
ValuationHelper,
} from 'set-protocol-contracts';
import {
OracleHelper
} from 'set-protocol-oracles';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
const CoreMock =
require('set-protocol-contracts/dist/artifacts/ts/CoreMock').CoreMock;
BigNumberSetup.configure();
ChaiSetup.configure();
const { SetProtocolUtils: SetUtils } = setProtocolUtils;
const blockchain = new Blockchain(web3);
const { expect } = chai;
const { NULL_ADDRESS } = SetUtils.CONSTANTS;
contract('RebalancingSetTokenViewer', accounts => {
const [
deployerAccount,
managerAccount,
ownerAccount,
] = accounts;
let coreMock: CoreMockContract;
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let factory: SetTokenFactoryContract;
let rebalancingComponentWhiteList: WhiteListContract;
let rebalancingFactory: RebalancingSetTokenFactoryContract;
let constantAuctionPriceCurve: ConstantAuctionPriceCurveContract;
const coreHelper = new CoreHelper(deployerAccount, deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const feeCalculatorHelper = new FeeCalculatorHelper(deployerAccount);
const oracleHelper = new OracleHelper(deployerAccount);
const rebalancingHelper = new RebalancingHelper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const rebalancingSetV3Helper = new RebalancingSetV3Helper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper);
const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper);
const viewerHelper = new ProtocolViewerHelper(deployerAccount);
let rebalancingSetTokenViewer: RebalancingSetTokenViewerContract;
before(async () => {
ABIDecoder.addABI(CoreMock.abi);
});
after(async () => {
ABIDecoder.removeABI(CoreMock.abi);
});
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault);
factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address);
rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync();
rebalancingFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
);
constantAuctionPriceCurve = await rebalancingHelper.deployConstantAuctionPriceCurveAsync(
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
);
await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
await rebalancingHelper.addPriceLibraryAsync(coreMock, constantAuctionPriceCurve);
rebalancingSetTokenViewer = await viewerHelper.deployRebalancingSetTokenViewerAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#fetchRebalanceProposalStateAsync', async () => {
let subjectRebalancingSetAddress: Address;
let rebalancingSetToken: RebalancingSetTokenContract;
let nextSetToken: SetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
const currentSetToken = setTokens[0];
nextSetToken = setTokens[1];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetTokenQuantityToIssue = ether(8);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
subjectRebalancingSetAddress = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.fetchRebalanceProposalStateAsync.callAsync(
subjectRebalancingSetAddress,
);
}
it('fetches the RebalancingSetToken\'s current proposal\'s parameters', async () => {
const rebalanceProposalState: any[] = await subject();
const rebalancingSetState = rebalanceProposalState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
const [nextSetAddress, auctionLibraryAddress] = rebalanceProposalState[1];
expect(nextSetAddress).to.equal(NULL_ADDRESS);
expect(auctionLibraryAddress).to.equal(NULL_ADDRESS);
const [
proposalStartTime,
auctionTimeToPivot,
auctionStartPrice,
auctionPivotPrice,
] = rebalanceProposalState[2];
expect(proposalStartTime).to.be.bignumber.equal(ZERO);
expect(auctionTimeToPivot).to.be.bignumber.equal(ZERO);
expect(auctionStartPrice).to.be.bignumber.equal(ZERO);
expect(auctionPivotPrice).to.be.bignumber.equal(ZERO);
});
describe('when the token address is not for a RebalancingSetToken contract', async () => {
beforeEach(async () => {
subjectRebalancingSetAddress = ownerAccount;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the rebalancing set is in propose state', async () => {
beforeEach(async () => {
await rebalancingHelper.defaultTransitionToProposeAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
});
it('should revert', async () => {
const rebalanceProposalState: any[] = await subject();
const rebalancingSetState = rebalanceProposalState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.PROPOSAL);
const [nextSetAddress, auctionLibraryAddress] = rebalanceProposalState[1];
expect(nextSetAddress).to.equal(nextSetToken.address);
expect(auctionLibraryAddress).to.equal(constantAuctionPriceCurve.address);
const [
proposalStartTime,
auctionTimeToPivot,
auctionStartPrice,
auctionPivotPrice,
] = rebalanceProposalState[2];
expect(auctionTimeToPivot).to.be.bignumber.equal(DEFAULT_REBALANCE_TIME_TO_PIVOT);
expect(auctionStartPrice).to.be.bignumber.equal(DEFAULT_REBALANCE_START_PRICE);
expect(auctionPivotPrice).to.be.bignumber.equal(DEFAULT_AUCTION_PRICE_NUMERATOR);
const expectedProposalStartTime = await rebalancingSetToken.proposalStartTime.callAsync();
expect(proposalStartTime).to.be.bignumber.equal(expectedProposalStartTime);
});
});
});
describe('#fetchRebalanceAuctionStateAsync', async () => {
let subjectRebalancingSetAddress: Address;
let rebalancingSetToken: RebalancingSetTokenContract;
let currentSetToken: SetTokenContract;
let nextSetToken: SetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
currentSetToken = setTokens[0];
nextSetToken = setTokens[1];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetTokenQuantityToIssue = ether(8);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
subjectRebalancingSetAddress = rebalancingSetToken.address;
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.fetchRebalanceAuctionStateAsync.callAsync(
subjectRebalancingSetAddress,
);
}
it('fetches the RebalancingSetToken\'s current auction\'s parameters', async () => {
const rebalanceAuctionState: any[] = await subject();
const rebalancingSetState = rebalanceAuctionState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
const [
startingCurrentSetAmount,
auctionStartTime,
minimumBid,
remainingCurrentSets,
] = rebalanceAuctionState[1];
expect(startingCurrentSetAmount).to.be.bignumber.equal(ZERO);
expect(auctionStartTime).to.be.bignumber.equal(ZERO);
expect(minimumBid).to.be.bignumber.equal(ZERO);
expect(remainingCurrentSets).to.be.bignumber.equal(ZERO);
});
describe('when the token address is not for a RebalancingSetToken contract', async () => {
beforeEach(async () => {
subjectRebalancingSetAddress = ownerAccount;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the rebalancing set is in propose state', async () => {
beforeEach(async () => {
await rebalancingHelper.defaultTransitionToProposeAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
});
it('fetches the RebalancingSetToken\'s current auction\'s parameters', async () => {
const rebalanceAuctionState: any[] = await subject();
const rebalancingSetState = rebalanceAuctionState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.PROPOSAL);
const [
startingCurrentSetAmount,
auctionStartTime,
minimumBid,
remainingCurrentSets,
] = rebalanceAuctionState[1];
expect(startingCurrentSetAmount).to.be.bignumber.equal(ZERO);
expect(auctionStartTime).to.be.bignumber.equal(ZERO);
expect(minimumBid).to.be.bignumber.equal(ZERO);
expect(remainingCurrentSets).to.be.bignumber.equal(ZERO);
});
});
describe('when the rebalancing set is in rebalance state', async () => {
beforeEach(async () => {
await rebalancingHelper.defaultTransitionToRebalanceAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
});
it('fetches the RebalancingSetToken\'s current auction\'s parameters', async () => {
const rebalanceAuctionState: any[] = await subject();
const rebalancingSetState = rebalanceAuctionState[0];
expect(rebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.REBALANCE);
const [
startingCurrentSetAmount,
auctionStartTime,
minimumBid,
] = rebalanceAuctionState[1];
const expectedStartingCurrentSetAmount = await rebalancingSetToken.startingCurrentSetAmount.callAsync();
expect(startingCurrentSetAmount).to.be.bignumber.equal(expectedStartingCurrentSetAmount);
const [expectedAuctionStartTime] = await rebalancingSetToken.getAuctionPriceParameters.callAsync();
expect(auctionStartTime).to.be.bignumber.equal(expectedAuctionStartTime);
const [
expectedMinimumBid,
expectedRemainingCurrentSets,
] = await rebalancingSetToken.getBiddingParameters.callAsync();
expect(minimumBid).to.be.bignumber.equal(expectedMinimumBid);
expect(expectedRemainingCurrentSets).to.be.bignumber.equal(expectedRemainingCurrentSets);
});
});
});
describe('RebalancingSetTokenV2/V3', async () => {
let rebalancingSetTokenV3Factory: RebalancingSetTokenV3FactoryContract;
let rebalancingSetTokenV3: RebalancingSetTokenV3Contract;
let oracleWhiteList: OracleWhiteListContract;
let wrappedETH: StandardTokenMockContract;
let wrappedBTC: StandardTokenMockContract;
let usdc: StandardTokenMockContract;
let dai: StandardTokenMockContract;
let set1: SetTokenContract;
let set2: SetTokenContract;
let collateralComponents: Address[];
let set1Units: BigNumber[];
let set1NaturalUnit: BigNumber;
let set2Units: BigNumber[];
let set2NaturalUnit: BigNumber;
let firstSetUnits: BigNumber;
let lastRebalanceTimestamp: BigNumber;
let wrappedETHOracle: UpdatableOracleMockContract;
let wrappedBTCOracle: UpdatableOracleMockContract;
let usdcOracle: UpdatableOracleMockContract;
let daiOracle: UpdatableOracleMockContract;
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
let liquidatorWhitelist: WhiteListContract;
let feeCalculatorWhitelist: WhiteListContract;
let performanceFeeCalculator: PerformanceFeeCalculatorContract;
let liquidator: LinearAuctionLiquidatorContract;
let twapLiquidator: TWAPLiquidatorContract;
beforeEach(async () => {
// Oracles
wrappedETH = await erc20Helper.deployTokenAsync(deployerAccount, 18);
await rebalancingComponentWhiteList.addAddress.sendTransactionAsync(wrappedETH.address);
wrappedBTC = await erc20Helper.deployTokenAsync(deployerAccount, 8);
await rebalancingComponentWhiteList.addAddress.sendTransactionAsync(wrappedBTC.address);
usdc = await erc20Helper.deployTokenAsync(deployerAccount, 6);
await rebalancingComponentWhiteList.addAddress.sendTransactionAsync(usdc.address);
dai = await erc20Helper.deployTokenAsync(deployerAccount, 18);
await rebalancingComponentWhiteList.addAddress.sendTransactionAsync(dai.address);
await erc20Helper.approveTransfersAsync([wrappedBTC, wrappedETH, dai, usdc], transferProxy.address);
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
wrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
wrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdcOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
daiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
oracleWhiteList = await coreHelper.deployOracleWhiteListAsync(
[wrappedETH.address, wrappedBTC.address, usdc.address, dai.address],
[wrappedETHOracle.address, wrappedBTCOracle.address, usdcOracle.address, daiOracle.address],
);
// Liquidators
const auctionPeriod = ONE_DAY_IN_SECONDS;
const rangeStart = new BigNumber(1); // 1% above fair value
const rangeEnd = new BigNumber(23); // 23% below fair value
liquidator = await liquidatorHelper.deployLinearAuctionLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
'LinearLiquidator',
);
const assetPairHashes = [
liquidatorHelper.generateAssetPairHashes(wrappedETH.address, wrappedBTC.address),
];
const assetPairBounds = [
{min: ether(10 ** 4).toString(), max: ether(10 ** 6).toString()},
];
twapLiquidator = await viewerHelper.deployTWAPLiquidatorAsync(
coreMock.address,
oracleWhiteList.address,
auctionPeriod,
rangeStart,
rangeEnd,
assetPairHashes,
assetPairBounds,
'TWAPLiquidator',
);
liquidatorWhitelist = await coreHelper.deployWhiteListAsync([liquidator.address, twapLiquidator.address]);
// Fee Calculators
const maxProfitFeePercentage = ether(.5);
const maxStreamingFeePercentage = ether(.1);
performanceFeeCalculator = await feeCalculatorHelper.deployPerformanceFeeCalculatorAsync(
coreMock.address,
oracleWhiteList.address,
maxProfitFeePercentage,
maxStreamingFeePercentage
);
feeCalculatorWhitelist = await coreHelper.deployWhiteListAsync([performanceFeeCalculator.address]);
// RebalancingSetTokenV3Factory
rebalancingSetTokenV3Factory = await viewerHelper.deployRebalancingSetTokenV3FactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
liquidatorWhitelist.address,
feeCalculatorWhitelist.address,
);
await coreHelper.addFactoryAsync(coreMock, rebalancingSetTokenV3Factory);
// Collateral Sets
collateralComponents = [wrappedETH.address, wrappedBTC.address];
set1Units = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(100)];
set1NaturalUnit = new BigNumber(10 ** 12);
set1 = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
collateralComponents,
set1Units,
set1NaturalUnit,
);
set2Units = [wrappedBTCPrice.div(wrappedETHPrice).mul(10 ** 12), new BigNumber(300)];
set2NaturalUnit = new BigNumber(10 ** 12);
set2 = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
collateralComponents,
set2Units,
set2NaturalUnit,
);
// Deploy RebalancingSetTokenV3
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = new BigNumber(timestamp).sub(ONE_DAY_IN_SECONDS);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(set1, oracleWhiteList);
firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
managerAccount,
twapLiquidator.address,
managerAccount,
performanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
rebalancingSetTokenV3 = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[set1.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
});
describe('#fetchNewRebalancingSetDetails', async () => {
let subjectRebalancingSet: Address;
beforeEach(async () => {
subjectRebalancingSet = rebalancingSetTokenV3.address;
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.fetchNewRebalancingSetDetails.callAsync(
subjectRebalancingSet
);
}
it('fetches the correct RebalancingSetTokenV3/TradingPool data', async () => {
const [ tradingPoolInfo, , , ] = await subject();
expect(tradingPoolInfo.manager).to.equal(managerAccount);
expect(tradingPoolInfo.feeRecipient).to.equal(managerAccount);
expect(tradingPoolInfo.currentSet).to.equal(set1.address);
expect(tradingPoolInfo.liquidator).to.equal(twapLiquidator.address);
expect(tradingPoolInfo.name).to.equal('Rebalancing Set Token');
expect(tradingPoolInfo.symbol).to.equal('RBSET');
expect(tradingPoolInfo.unitShares).to.be.bignumber.equal(firstSetUnits);
expect(tradingPoolInfo.naturalUnit).to.be.bignumber.equal(DEFAULT_REBALANCING_NATURAL_UNIT);
expect(tradingPoolInfo.rebalanceInterval).to.be.bignumber.equal(ONE_DAY_IN_SECONDS);
expect(tradingPoolInfo.entryFee).to.be.bignumber.equal(ZERO);
expect(tradingPoolInfo.lastRebalanceTimestamp).to.be.bignumber.equal(lastRebalanceTimestamp);
expect(tradingPoolInfo.rebalanceState).to.be.bignumber.equal(ZERO);
});
it('fetches the correct RebalancingSetTokenV3/Performance Fee data', async () => {
const [ , performanceFeeState, , ] = await subject();
const [
profitFeePeriod,
highWatermarkResetPeriod,
profitFeePercentage,
streamingFeePercentage,
highWatermark,
lastProfitFeeTimestamp,
lastStreamingFeeTimestamp,
] = performanceFeeState;
const expectedFeeStates: any = await performanceFeeCalculator.feeState.callAsync(rebalancingSetTokenV3.address);
expect(profitFeePeriod).to.equal(expectedFeeStates.profitFeePeriod);
expect(highWatermarkResetPeriod).to.equal(expectedFeeStates.highWatermarkResetPeriod);
expect(profitFeePercentage).to.equal(expectedFeeStates.profitFeePercentage);
expect(streamingFeePercentage).to.equal(expectedFeeStates.streamingFeePercentage);
expect(highWatermark).to.equal(expectedFeeStates.highWatermark);
expect(lastProfitFeeTimestamp).to.equal(expectedFeeStates.lastProfitFeeTimestamp);
expect(lastStreamingFeeTimestamp).to.equal(expectedFeeStates.lastStreamingFeeTimestamp);
});
it('fetches the correct CollateralSet data', async () => {
const [ , , collateralSetData, ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set1Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set1NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
it('fetches the correct PerformanceFeeCalculator address', async () => {
const [ , , , performanceFeeCalculatorAddress ] = await subject();
expect(performanceFeeCalculatorAddress).to.equal(performanceFeeCalculator.address);
});
});
describe('#fetchRBSetTWAPRebalanceDetails', async () => {
let subjectRebalancingSet: Address;
let currentSetToken: SetTokenContract;
let nextSet: SetTokenContract;
beforeEach(async () => {
currentSetToken = set1;
nextSet = set2;
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetTokenV3.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(
ether(10 ** 5),
ONE_HOUR_IN_SECONDS,
);
await rebalancingSetTokenV3.startRebalance.sendTransactionAsync(
nextSet.address,
liquidatorData,
{ from: managerAccount }
);
subjectRebalancingSet = rebalancingSetTokenV3.address;
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.fetchRBSetTWAPRebalanceDetails.callAsync(
subjectRebalancingSet
);
}
it('fetches the correct RebalancingSetTokenV2/TradingPool data', async () => {
const [ rbSetData, ] = await subject();
const auctionPriceParams = await rebalancingSetTokenV3.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetTokenV3.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetTokenV3.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(twapLiquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('#fetchRBSetRebalanceDetails', async () => {
let subjectRebalancingSet: Address;
let currentSetToken: SetTokenContract;
let nextSet: SetTokenContract;
beforeEach(async () => {
currentSetToken = set1;
nextSet = set2;
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
currentSetToken.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetTokenV3.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(
ether(10 ** 5),
ONE_HOUR_IN_SECONDS,
);
await rebalancingSetTokenV3.setLiquidator.sendTransactionAsync(liquidator.address, { from: managerAccount });
await rebalancingSetTokenV3.startRebalance.sendTransactionAsync(
nextSet.address,
liquidatorData,
{ from: managerAccount }
);
subjectRebalancingSet = rebalancingSetTokenV3.address;
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.fetchRBSetRebalanceDetails.callAsync(
subjectRebalancingSet
);
}
it('fetches the correct RebalancingSetTokenV2/TradingPool data', async () => {
const [ rbSetData, ] = await subject();
const auctionPriceParams = await rebalancingSetTokenV3.getAuctionPriceParameters.callAsync();
const startingCurrentSets = await rebalancingSetTokenV3.startingCurrentSetAmount.callAsync();
const biddingParams = await rebalancingSetTokenV3.getBiddingParameters.callAsync();
expect(rbSetData.rebalanceStartTime).to.be.bignumber.equal(auctionPriceParams[0]);
expect(rbSetData.timeToPivot).to.be.bignumber.equal(auctionPriceParams[1]);
expect(rbSetData.startPrice).to.be.bignumber.equal(auctionPriceParams[2]);
expect(rbSetData.endPrice).to.be.bignumber.equal(auctionPriceParams[3]);
expect(rbSetData.startingCurrentSets).to.be.bignumber.equal(startingCurrentSets);
expect(rbSetData.remainingCurrentSets).to.be.bignumber.equal(biddingParams[1]);
expect(rbSetData.minimumBid).to.be.bignumber.equal(biddingParams[0]);
expect(rbSetData.rebalanceState).to.be.bignumber.equal(new BigNumber(2));
expect(rbSetData.nextSet).to.equal(nextSet.address);
expect(rbSetData.liquidator).to.equal(liquidator.address);
});
it('fetches the correct CollateralSet data', async () => {
const [ , collateralSetData ] = await subject();
expect(JSON.stringify(collateralSetData.components)).to.equal(JSON.stringify(collateralComponents));
expect(JSON.stringify(collateralSetData.units)).to.equal(JSON.stringify(set2Units));
expect(collateralSetData.naturalUnit).to.be.bignumber.equal(set2NaturalUnit);
expect(collateralSetData.name).to.equal('Set Token');
expect(collateralSetData.symbol).to.equal('SET');
});
});
describe('Batch Fetching Functions', async () => {
let otherRebalancingSetV3: RebalancingSetTokenV3Contract;
beforeEach(async () => {
const failPeriod = ONE_DAY_IN_SECONDS;
const { timestamp } = await web3.eth.getBlock('latest');
lastRebalanceTimestamp = new BigNumber(timestamp).sub(ONE_DAY_IN_SECONDS);
const calculatorData = feeCalculatorHelper.generatePerformanceFeeCallDataBuffer(
ONE_DAY_IN_SECONDS.mul(30),
ONE_YEAR_IN_SECONDS,
ether(.2),
ether(.02)
);
const firstNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT;
const firstSetValue = await valuationHelper.calculateSetTokenValueAsync(set1, oracleWhiteList);
firstSetUnits = new BigNumber(100).mul(firstNaturalUnit).mul(10 ** 18).div(firstSetValue).round(0, 3);
const firstSetCallData = rebalancingSetV3Helper.generateRebalancingSetTokenV3CallData(
managerAccount,
liquidator.address,
managerAccount,
performanceFeeCalculator.address,
ONE_DAY_IN_SECONDS,
failPeriod,
lastRebalanceTimestamp,
ZERO,
calculatorData
);
otherRebalancingSetV3 = await rebalancingSetV3Helper.createRebalancingTokenV3Async(
coreMock,
rebalancingSetTokenV3Factory.address,
[set2.address],
[firstSetUnits],
firstNaturalUnit,
firstSetCallData
);
});
describe('#batchFetchLiquidator', async () => {
let subjectRebalancingSets: Address[];
beforeEach(async () => {
subjectRebalancingSets = [rebalancingSetTokenV3.address, otherRebalancingSetV3.address];
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.batchFetchLiquidator.callAsync(
subjectRebalancingSets
);
}
it('fetches the correct liquidator array', async () => {
const liquidators = await subject();
const expectedLiquidators = [twapLiquidator.address, liquidator.address];
expect(JSON.stringify(liquidators)).to.equal(JSON.stringify(expectedLiquidators));
});
});
describe('#batchFetchStateAndCollateral', async () => {
let subjectRebalancingSets: Address[];
beforeEach(async () => {
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(
set1.address,
ether(8),
{from: deployerAccount}
);
await erc20Helper.approveTransfersAsync([set1], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetQuantityToIssue = ether(7);
await coreMock.issue.sendTransactionAsync(rebalancingSetTokenV3.address, rebalancingSetQuantityToIssue);
await blockchain.increaseTimeAsync(ONE_DAY_IN_SECONDS);
const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(
ether(10 ** 5),
ONE_HOUR_IN_SECONDS,
);
await rebalancingSetTokenV3.startRebalance.sendTransactionAsync(
set2.address,
liquidatorData,
{ from: managerAccount }
);
subjectRebalancingSets = [rebalancingSetTokenV3.address, otherRebalancingSetV3.address];
});
async function subject(): Promise<any> {
return rebalancingSetTokenViewer.batchFetchStateAndCollateral.callAsync(
subjectRebalancingSets
);
}
it('fetches the correct liquidator array', async () => {
const statuses: any[] = await subject();
expect(statuses[0].collateralSet).to.equal(set1.address);
expect(statuses[1].collateralSet).to.equal(set2.address);
expect(statuses[0].state).to.be.bignumber.equal(new BigNumber(2));
expect(statuses[1].state).to.be.bignumber.equal(ZERO);
});
});
});
});
describe('#batchFetchRebalanceStateAsync', async () => {
let subjectRebalancingSetAddresses: Address[];
let rebalancingSetToken: RebalancingSetTokenContract;
let currentSetToken: SetTokenContract;
let nextSetToken: SetTokenContract;
let defaultRebalancingSetToken: RebalancingSetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
currentSetToken = setTokens[0];
nextSetToken = setTokens[1];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
// Issue currentSetToken
await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount});
await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address);
// Use issued currentSetToken to issue rebalancingSetToken
const rebalancingSetTokenQuantityToIssue = ether(8);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
// Transition original rebalancing set to proposal
await rebalancingHelper.defaultTransitionToProposeAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
nextSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
defaultRebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
currentSetToken.address,
ONE_DAY_IN_SECONDS
);
subjectRebalancingSetAddresses = [rebalancingSetToken.address, defaultRebalancingSetToken.address];
});
async function subject(): Promise<BigNumber[]> {
return rebalancingSetTokenViewer.batchFetchRebalanceStateAsync.callAsync(
subjectRebalancingSetAddresses,
);
}
it('fetches the RebalancingSetTokens\' states', async () => {
const rebalanceAuctionStates: BigNumber[] = await subject();
const firstRebalancingSetState = rebalanceAuctionStates[0];
expect(firstRebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.PROPOSAL);
const secondRebalancingSetState = rebalanceAuctionStates[1];
expect(secondRebalancingSetState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT);
});
});
describe('#batchFetchUnitSharesAsync', async () => {
let subjectRebalancingSetAddresses: Address[];
let rebalancingSetToken: RebalancingSetTokenContract;
let setTokenOne: SetTokenContract;
let setTokenTwo: SetTokenContract;
let defaultRebalancingSetToken: RebalancingSetTokenContract;
beforeEach(async () => {
const naturalUnits = [ether(.001), ether(.0001)];
const setTokens = await rebalancingHelper.createSetTokensAsync(
coreMock,
factory.address,
transferProxy.address,
2,
naturalUnits
);
setTokenOne = setTokens[0];
setTokenTwo = setTokens[1];
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
setTokenOne.address,
ONE_DAY_IN_SECONDS
);
defaultRebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
setTokenTwo.address,
ONE_DAY_IN_SECONDS
);
subjectRebalancingSetAddresses = [rebalancingSetToken.address, defaultRebalancingSetToken.address];
});
async function subject(): Promise<BigNumber[]> {
return rebalancingSetTokenViewer.batchFetchUnitSharesAsync.callAsync(
subjectRebalancingSetAddresses,
);
}
it('fetches the RebalancingSetTokens\' unitShares', async () => {
const rebalanceUnitShares: BigNumber[] = await subject();
const firstUnitShares = rebalanceUnitShares[0];
const firstExpectedUnitShares = await rebalancingSetToken.unitShares.callAsync();
expect(firstUnitShares).to.be.bignumber.equal(firstExpectedUnitShares);
const secondUnitShares = rebalanceUnitShares[1];
const secondExpectedUnitShares = await defaultRebalancingSetToken.unitShares.callAsync();
expect(secondUnitShares).to.be.bignumber.equal(secondExpectedUnitShares);
});
});
});
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/lib/oracleViewer.spec.ts
|
<gh_stars>1-10
require('module-alias/register');
import * as chai from 'chai';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
OracleViewerContract,
} from '@utils/contracts';
import {
Blockchain
} from 'set-protocol-contracts';
import {
OracleHelper,
UpdatableOracleMockContract
} from 'set-protocol-oracles';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
import { ether } from '@utils/units';
BigNumberSetup.configure();
ChaiSetup.configure();
const { expect } = chai;
const blockchain = new Blockchain(web3);
contract('OracleViewer', accounts => {
const [
deployerAccount,
] = accounts;
let wrappedETHOracle: UpdatableOracleMockContract;
let wrappedBTCOracle: UpdatableOracleMockContract;
let usdcOracle: UpdatableOracleMockContract;
let daiOracle: UpdatableOracleMockContract;
let wrappedETHPrice: BigNumber;
let wrappedBTCPrice: BigNumber;
let usdcPrice: BigNumber;
let daiPrice: BigNumber;
const oracleHelper = new OracleHelper(deployerAccount);
const protocolViewerHelper = new ProtocolViewerHelper(deployerAccount);
let oracleViewer: OracleViewerContract;
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
wrappedETHPrice = ether(128);
wrappedBTCPrice = ether(7500);
usdcPrice = ether(1);
daiPrice = ether(1);
wrappedETHOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedETHPrice);
wrappedBTCOracle = await oracleHelper.deployUpdatableOracleMockAsync(wrappedBTCPrice);
usdcOracle = await oracleHelper.deployUpdatableOracleMockAsync(usdcPrice);
daiOracle = await oracleHelper.deployUpdatableOracleMockAsync(daiPrice);
oracleViewer = await protocolViewerHelper.deployOracleViewerAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#batchFetchOraclePrices', async () => {
let subjectOracleAddresses: Address[];
beforeEach(async () => {
subjectOracleAddresses = [
wrappedETHOracle.address,
wrappedBTCOracle.address,
usdcOracle.address,
daiOracle.address,
];
});
async function subject(): Promise<any> {
return oracleViewer.batchFetchOraclePrices.callAsync(
subjectOracleAddresses,
);
}
it('fetches oracle prices', async () => {
const oraclePrices = await subject();
const expectedOraclePrices = [wrappedETHPrice, wrappedBTCPrice, usdcPrice, daiPrice];
expect(JSON.stringify(oraclePrices)).to.equal(JSON.stringify(expectedOraclePrices));
});
});
});
|
SetProtocol/set-protocol-viewers
|
utils/contracts.ts
|
export { BaseContract } from '../types/base_contract';
export { CTokenViewerContract } from '../types/generated/c_token_viewer';
export { ERC20ViewerContract } from '../types/generated/erc20_viewer';
export { ManagerViewerContract } from '../types/generated/manager_viewer';
export { OracleViewerContract } from '../types/generated/oracle_viewer';
export { ProtocolViewerContract } from '../types/generated/protocol_viewer';
export { RebalancingSetTokenViewerContract } from '../types/generated/rebalancing_set_token_viewer';
export { SocialTradingManagerMockContract } from '../types/generated/social_trading_manager_mock';
export { TradingPoolViewerContract } from '../types/generated/trading_pool_viewer';
export { TrendingManagerMockContract } from '../types/generated/trending_manager_mock';
|
SetProtocol/set-protocol-viewers
|
test/contracts/viewer/lib/cTokenViewer.spec.ts
|
<reponame>SetProtocol/set-protocol-viewers
require('module-alias/register');
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import { Address } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
CTokenViewerContract,
} from '@utils/contracts';
import { expectRevertError } from '@utils/tokenAssertions';
import {
Blockchain,
CompoundHelper,
ERC20Helper,
} from 'set-protocol-contracts';
import { ProtocolViewerHelper } from '@utils/helpers/protocolViewerHelper';
const CoreMock =
require('set-protocol-contracts/dist/artifacts/ts/CoreMock').CoreMock;
BigNumberSetup.configure();
ChaiSetup.configure();
const blockchain = new Blockchain(web3);
const { expect } = chai;
contract('CTokenViewer', accounts => {
const [
deployerAccount,
managerAccount,
] = accounts;
let cUSDCAddress: Address;
let cDAIAddress: Address;
const compoundHelper = new CompoundHelper(deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const protocolViewerHelper = new ProtocolViewerHelper(deployerAccount);
let cTokenViewer: CTokenViewerContract;
before(async () => {
ABIDecoder.addABI(CoreMock.abi);
});
after(async () => {
ABIDecoder.removeABI(CoreMock.abi);
});
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
// Set up Compound USDC token
const usdcInstance = await erc20Helper.deployTokenAsync(
deployerAccount,
6,
);
cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, deployerAccount);
await compoundHelper.enableCToken(cUSDCAddress);
// Set the Borrow Rate
await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999'));
// Set up Compound DAI token
const daiInstance = await erc20Helper.deployTokenAsync(
deployerAccount,
18,
);
cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, deployerAccount);
await compoundHelper.enableCToken(cDAIAddress);
// Set the Borrow Rate
await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165'));
cTokenViewer = await protocolViewerHelper.deployCTokenViewerAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#batchFetchExchangeRateStored', async () => {
let subjectTokenAddresses: Address[];
beforeEach(async () => {
subjectTokenAddresses = [cUSDCAddress, cDAIAddress];
});
async function subject(): Promise<BigNumber[]> {
return cTokenViewer.batchFetchExchangeRateStored.callAsync(
subjectTokenAddresses,
);
}
it('fetches the exchangeRates of the token addresses', async () => {
const exchangeRates: BigNumber[] = await subject();
const exchangeRatesJSON = JSON.stringify(exchangeRates);
const expectedExchangeRates: BigNumber[] = [];
for (let i = 0; i < subjectTokenAddresses.length; i++) {
const expectedExchangeRate = await compoundHelper.getExchangeRate(subjectTokenAddresses[i]);
expectedExchangeRates.push(expectedExchangeRate);
}
const expectedExchangeRatesJSON = JSON.stringify(expectedExchangeRates);
expect(exchangeRatesJSON).to.equal(expectedExchangeRatesJSON);
});
describe('when the token addresses includes a non cToken contract', async () => {
beforeEach(async () => {
subjectTokenAddresses = [managerAccount];
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
});
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/agent-manager/agent-manager-container.component.ts
|
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { ApplicationListDataService } from 'app/core/components/application-list/application-list-data.service';
import { AgentManagerDataService } from './agent-manager-data.service';
@Component({
selector: 'pp-agent-manager-container',
templateUrl: './agent-manager-container.component.html',
styleUrls: ['./agent-manager-container.component.css']
})
export class AgentManagerContainerComponent implements OnInit, OnDestroy {
private unsubscribe: Subject<void> = new Subject();
applicationFilter = '';
showLoading = false;
applicationList: IApplication[];
agentList: {
[key: string]: any;
} = {};
canRemoveInactiveAgent = false;
constructor(
private applicationListDataService: ApplicationListDataService,
private agentManagerDataService: AgentManagerDataService
) {}
ngOnInit() {
this.applicationListDataService.getApplicationList().pipe(
takeUntil(this.unsubscribe)
).subscribe((applicationList: IApplication[]) => {
this.applicationList = applicationList;
});
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
getAgentList(application: IApplication): string[] {
return this.agentList[application.applicationName];
}
onLoadAgentList(applicationName: string): void {
this.agentManagerDataService.getAgentList(applicationName).subscribe((agentList: any) => {
const agentInfoList: any[] = [];
Object.keys(agentList).forEach((key: string) => {
agentList[key].forEach((agent: IAgent) => {
agentInfoList.push({
applicationName: agent.applicationName,
agentId: agent.agentId
});
});
});
this.agentList[applicationName] = agentInfoList;
});
}
onRemoveAgent([applicationName, agentId]: [string, string]): void {
this.agentManagerDataService.removeAgentId(applicationName, agentId).subscribe((result: string) => {
if (result === 'OK') {
const appInfo = this.agentList[applicationName];
const index = appInfo.findIndex((app: any) => {
return app.agentId === agentId;
});
appInfo.splice(index, 1);
}
});
}
onRemoveInactiveAgents(): void {
if (this.canRemoveInactiveAgent === false) {
return;
}
this.showLoading = true;
}
hasFilterStr(appName: string): boolean {
const filter = this.applicationFilter.trim();
if (filter === '') {
return true;
}
if (appName.indexOf(filter) === -1) {
return false;
} else {
return true;
}
}
onChangeCanRemoveInactiveAgent($event: any): void {
this.canRemoveInactiveAgent = $event.checked;
console.log( this.canRemoveInactiveAgent );
}
}
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/agent-admin-chart/agent-admin-chart-container.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { StoreHelperService } from 'app/shared/services';
@Component({
selector: 'pp-agent-admin-chart-container',
templateUrl: './agent-admin-chart-container.component.html',
styleUrls: ['./agent-admin-chart-container.component.css']
})
export class AgentAdminChartContainerComponent implements OnInit {
private unsubscribe: Subject<void> = new Subject();
showLoading = true;
agentCount = 0;
chartData: {
jvmVersion: {
[key: string]: number
},
agentVersion: {
[key: string]: number
}
} = {
jvmVersion: {},
agentVersion: {}
};
constructor(
private storeHelperService: StoreHelperService
) {}
ngOnInit() {
this.storeHelperService.getAgentList<IAgentList>(this.unsubscribe).subscribe((agentList: IAgentList) => {
this.extractChartData(agentList);
this.showLoading = false;
});
}
private extractChartData(agentList: IAgentList): void {
this.chartData = {
jvmVersion: {},
agentVersion: {}
};
let count = 0;
Object.keys(agentList).forEach((key: string) => {
const agents = agentList[key];
agents.forEach((agent: IAgent) => {
count++;
if (agent.agentVersion) {
this.chartData.agentVersion[agent.agentVersion] = (this.chartData.agentVersion[agent.agentVersion] || 0) + 1;
}
if (agent.jvmInfo && agent.jvmInfo.jvmVersion) {
this.chartData.jvmVersion[agent.jvmInfo.jvmVersion] = (this.chartData.jvmVersion[agent.jvmInfo.jvmVersion] || 0) + 1;
} else {
this.chartData.jvmVersion['UNKNOWN'] = (this.chartData.jvmVersion['UNKNOWN'] || 0) + 1;
}
});
});
this.agentCount = count;
}
}
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/application-list/application-list-for-header-container.component.ts
|
<gh_stars>0
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, ChangeDetectorRef, ChangeDetectionStrategy, OnDestroy, Renderer2 } from '@angular/core';
import { Subject, combineLatest, fromEvent, of } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, takeUntil, pluck, delay } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import {
StoreHelperService,
WebAppSettingDataService,
UrlRouteManagerService,
NewUrlStateNotificationService,
AnalyticsService,
TRACKED_EVENT_LIST
} from 'app/shared/services';
import { UrlPathId } from 'app/shared/models';
import { ApplicationListDataService } from './application-list-data.service';
import { FOCUS_TYPE } from './application-list-for-header.component';
@Component({
selector: 'pp-application-list-for-header-container',
templateUrl: './application-list-for-header-container.component.html',
styleUrls: ['./application-list-for-header-container.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ApplicationListForHeaderContainerComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('inputQuery') inputQuery: ElementRef;
private unsubscribe: Subject<null> = new Subject();
private maxIndex: number;
private minLength = 3;
private filterStr = '';
private initApplication: IApplication;
private applicationList: IApplication[];
private favoriteApplicationList: IApplication[];
i18nText: { [key: string]: string } = {
FAVORITE_LIST_TITLE: '',
APPLICATION_LIST_TITLE: '',
INPUT_APPLICATION_NAME: '',
SELECTED_APPLICATION_NAME: '',
EMPTY_LIST: ''
};
showTitle = true;
selectedApplication: IApplication;
focusType: FOCUS_TYPE = FOCUS_TYPE.KEYBOARD;
focusIndex = -1;
hiddenComponent = true;
filteredApplicationList: IApplication[] = [];
filteredFavoriteApplicationList: IApplication[] = [];
funcImagePath: Function;
showLoading = false;
constructor(
private changeDetector: ChangeDetectorRef,
private storeHelperService: StoreHelperService,
private webAppSettingDataService: WebAppSettingDataService,
private applicationListDataService: ApplicationListDataService,
private newUrlStateNotificationService: NewUrlStateNotificationService,
private urlRouteManagerService: UrlRouteManagerService,
private translateService: TranslateService,
private analyticsService: AnalyticsService,
private renderer: Renderer2
) {}
ngOnInit() {
this.initI18nText();
this.funcImagePath = this.webAppSettingDataService.getIconPathMakeFunc();
this.newUrlStateNotificationService.onUrlStateChange$.pipe(
takeUntil(this.unsubscribe)
).subscribe((urlService: NewUrlStateNotificationService) => {
if (urlService.hasValue(UrlPathId.APPLICATION)) {
this.initApplication = urlService.getPathValue(UrlPathId.APPLICATION);
this.selectApplication(this.initApplication);
this.hiddenComponent = true;
} else {
this.hiddenComponent = false;
this.selectedApplication = null;
this.changeDetector.detectChanges();
}
});
this.connectStore();
}
ngAfterViewInit() {
this.setFocusToInput();
this.bindUserInputEvent();
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
private connectStore(): void {
combineLatest(
this.storeHelperService.getApplicationList(this.unsubscribe),
this.storeHelperService.getFavoriteApplicationList(this.unsubscribe)
).pipe(
takeUntil(this.unsubscribe)
).subscribe((responseData: any[]) => {
this.refreshList(responseData[0], responseData[1]);
this.showLoading = true;
this.changeDetector.detectChanges();
});
}
private bindUserInputEvent(): void {
fromEvent(this.inputQuery.nativeElement, 'keyup').pipe(
debounceTime(300),
distinctUntilChanged(),
filter((event: KeyboardEvent) => {
return !this.isArrowKey(event.keyCode);
}),
pluck('target', 'value'),
filter((value: string) => {
return this.isLengthValid(value.trim().length);
})
).subscribe((value: string) => {
this.applyQuery(value);
});
}
private initI18nText(): void {
combineLatest(
this.translateService.get('MAIN.INPUT_APP_NAME_PLACE_HOLDER'),
this.translateService.get('MAIN.APP_LIST'),
this.translateService.get('MAIN.FAVORITE_APP_LIST'),
this.translateService.get('MAIN.SELECT_YOUR_APP'),
this.translateService.get('CONFIGURATION.GENERAL.EMPTY')
).subscribe((i18n: string[]) => {
this.i18nText.INPUT_APPLICATION_NAME = i18n[0];
this.i18nText.APPLICATION_LIST_TITLE = i18n[1];
this.i18nText.FAVORITE_LIST_TITLE = i18n[2];
this.i18nText.SELECTED_APPLICATION_NAME = i18n[3];
this.i18nText.EMPTY_LIST = i18n[4];
});
}
private refreshList(applicationList: IApplication[], favoriteList: IApplication[]): void {
this.applicationList = applicationList;
this.favoriteApplicationList = favoriteList;
this.filteredApplicationList = this.filterList(this.applicationList);
this.filteredFavoriteApplicationList = this.filterList(this.favoriteApplicationList);
this.maxIndex = this.filteredApplicationList.length + this.filteredFavoriteApplicationList.length;
}
private selectApplication(application: IApplication): void {
if (application) {
this.selectedApplication = application;
this.changeDetector.detectChanges();
}
}
private filterList(appList: IApplication[]): IApplication[] {
if (this.filterStr === '') {
return appList;
} else {
return appList.filter((application: IApplication) => {
return new RegExp(this.filterStr, 'i').test(application.getApplicationName());
});
}
}
private setFocusToInput(): void {
of(1).pipe(delay(0)).subscribe((v: number) => {
this.inputQuery.nativeElement.select();
});
}
private applyQuery(query: string): void {
this.filterStr = query;
this.filteredFavoriteApplicationList = this.filterList(this.favoriteApplicationList);
this.filteredApplicationList = this.filterList(this.applicationList);
this.maxIndex = this.filteredApplicationList.length + this.filteredFavoriteApplicationList.length;
this.focusIndex = -1;
this.changeDetector.detectChanges();
}
getSelectedApplicationIcon(): string {
return this.funcImagePath(this.selectedApplication.getServiceType());
}
getSelectedApplicationName(): string {
if (this.selectedApplication) {
return this.selectedApplication.getApplicationName();
} else {
return this.i18nText.SELECTED_APPLICATION_NAME;
}
}
toggleApplicationList(): void {
this.hiddenComponent = !this.hiddenComponent;
if (this.hiddenComponent === false) {
this.setFocusToInput();
}
}
onClose(): void {
this.hiddenComponent = true;
}
onSelectApplication(selectedApplication: IApplication): void {
this.hiddenComponent = true;
if (!selectedApplication.equals(this.selectedApplication)) {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.SELECT_APPLICATION);
this.urlRouteManagerService.changeApplication(selectedApplication.getUrlStr());
this.selectApplication(selectedApplication);
}
}
onFocused(index: number): void {
this.focusIndex = index;
this.focusType = FOCUS_TYPE.MOUSE;
this.changeDetector.detectChanges();
}
onKeyDown(keyCode: number): void {
if (!this.hiddenComponent) {
switch (keyCode) {
case 27: // ESC
this.renderer.setProperty(this.inputQuery.nativeElement, 'value', '');
this.applyQuery('');
this.hiddenComponent = true;
this.changeDetector.detectChanges();
break;
case 13: // Enter
if (this.focusIndex !== -1) {
const favoriteLen = this.filteredFavoriteApplicationList.length;
if (favoriteLen === 0 || this.focusIndex > favoriteLen) {
this.onSelectApplication(this.filteredApplicationList[this.focusIndex - favoriteLen]);
} else {
this.onSelectApplication(this.filteredFavoriteApplicationList[this.focusIndex]);
}
this.changeDetector.detectChanges();
}
break;
case 38: // ArrowUp
if (this.focusIndex - 1 >= 0) {
this.focusIndex -= 1;
this.focusType = FOCUS_TYPE.KEYBOARD;
this.changeDetector.detectChanges();
}
break;
case 40: // ArrowDown
if (this.focusIndex + 1 < this.maxIndex) {
this.focusIndex += 1;
this.focusType = FOCUS_TYPE.KEYBOARD;
this.changeDetector.detectChanges();
}
break;
}
}
}
onReload(): void {
this.analyticsService.trackEvent(TRACKED_EVENT_LIST.CLICK_RELOAD_APPLICATION_LIST_BUTTON);
this.showLoading = false;
this.refreshList([], []);
this.applicationListDataService.getApplicationList().subscribe((applicationList: IApplication[]) => {
this.showLoading = true;
this.changeDetector.detectChanges();
});
}
private isArrowKey(key: number): boolean {
return key >= 37 && key <= 40;
}
private isLengthValid(length: number): boolean {
return length === 0 || length >= this.minLength;
}
}
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/agent-stat-contents/agent-stat-contents-container.component.ts
|
<filename>web/src/main/webapp/v2/src/app/core/components/agent-stat-contents/agent-stat-contents-container.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { StoreHelperService } from 'app/shared/services';
import { Actions } from 'app/shared/store';
import { AgentListDataService } from './agent-list-data.service';
@Component({
selector: 'pp-agent-stat-contents-container',
templateUrl: './agent-stat-contents-container.component.html',
styleUrls: ['./agent-stat-contents-container.component.css']
})
export class AgentStatContentsContainerComponent implements OnInit, OnDestroy {
private unsubscribe: Subject<void> = new Subject();
constructor(
private storeHelperService: StoreHelperService,
private agentListDataService: AgentListDataService
) {}
ngOnInit() {
this.agentListDataService.retrieve().pipe(
takeUntil(this.unsubscribe)
).subscribe((agentList: { [key: string]: IAgent[] }) => {
this.storeHelperService.dispatch(new Actions.UpdateAdminAgentList(agentList));
});
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/agent-management-contents/agent-management-contents-container.component.ts
|
<reponame>xiaoshao/pinpoint
import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { StoreHelperService } from 'app/shared/services';
import { Actions } from 'app/shared/store';
import { ApplicationListDataService } from 'app/core/components/application-list/application-list-data.service';
@Component({
selector: 'pp-agent-management-contents-container',
templateUrl: './agent-management-contents-container.component.html',
styleUrls: ['./agent-management-contents-container.component.css']
})
export class AgentManagementContentsContainerComponent implements OnInit {
private unsubscribe: Subject<void> = new Subject();
constructor(
private storeHelperService: StoreHelperService,
private applicationListDataService: ApplicationListDataService
) {
}
ngOnInit() {
this.applicationListDataService.getApplicationList().pipe(
takeUntil(this.unsubscribe)
).subscribe((applicationList: IApplication[]) => {
this.storeHelperService.dispatch(new Actions.UpdateApplicationList(applicationList));
});
}
}
|
xiaoshao/pinpoint
|
web/src/main/webapp/v2/src/app/core/components/user-group/user-group-container.component.ts
|
<reponame>xiaoshao/pinpoint
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, combineLatest } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { WebAppSettingDataService, TranslateReplaceService } from 'app/shared/services';
import { UserGroupInteractionService } from './user-group-interaction.service';
import { UserGroupDataService, IUserGroup, IUserGroupCreated, IUserGroupDeleted } from './user-group-data.service';
@Component({
selector: 'pp-user-group-container',
templateUrl: './user-group-container.component.html',
styleUrls: ['./user-group-container.component.css']
})
export class UserGroupContainerComponent implements OnInit, OnDestroy {
private unsubscribe: Subject<null> = new Subject();
private searchQuery = '';
i18nText: { [key: string]: string } = {
NAME_LABEL: '',
USER_GROUP_NAME_REQUIRED: '',
USER_GROUP_NAME_MIN_LENGTH: '',
USER_GROUP_SERACH_MIN_LENGTH: ''
};
USER_GROUP_NAME_MIN_LENGTH = 3;
SEARCH_MIN_LENGTH = 2;
searchUseEnter = false;
userGroupList: IUserGroup[] = [];
useDisable = true;
showLoading = true;
showCreate = false;
message = '';
selectedUserGroupId = '';
constructor(
private webAppSettingDataService: WebAppSettingDataService,
private userGroupDataService: UserGroupDataService,
private translateService: TranslateService,
private translateReplaceService: TranslateReplaceService,
private userGroupInteractionService: UserGroupInteractionService
) {}
ngOnInit() {
this.getI18NText();
this.webAppSettingDataService.getUserId().subscribe((userId: string = '') => {
this.getUserGroupList(userId === '' ? null : {
userId: userId
});
});
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
private getI18NText(): void {
combineLatest(
this.translateService.get('COMMON.MIN_LENGTH'),
this.translateService.get('COMMON.REQUIRED'),
this.translateService.get('CONFIGURATION.COMMON.NAME')
).subscribe((i18n: string[]) => {
this.i18nText.USER_GROUP_NAME_MIN_LENGTH = this.translateReplaceService.replace(i18n[0], this.USER_GROUP_NAME_MIN_LENGTH);
this.i18nText.USER_GROUP_SEARCH_MIN_LENGTH = this.translateReplaceService.replace(i18n[0], this.SEARCH_MIN_LENGTH);
this.i18nText.USER_GROUP_NAME_REQUIRED = this.translateReplaceService.replace(i18n[1], i18n[2]);
this.i18nText.NAME_LABEL = i18n[2];
});
}
private getUserGroupList(param: any): void {
this.userGroupDataService.retrieve(param).subscribe((userGroupData: IUserGroup[]) => {
this.userGroupList = userGroupData;
this.hideProcessing();
}, (error: string) => {
this.hideProcessing();
this.message = error;
});
}
private makeUserGroupQuery(userId: string): any {
return this.searchQuery === '' ? {
userId: userId
} : {
userGroupId: this.searchQuery
};
}
onRemoveUserGroup(id: string): void {
this.showProcessing();
this.webAppSettingDataService.getUserId().subscribe((userId: string = '') => {
this.userGroupDataService.remove(id, userId).subscribe((response: IUserGroupDeleted) => {
if (response.result === 'SUCCESS') {
this.userGroupInteractionService.setSelectedUserGroup('');
this.getUserGroupList(this.makeUserGroupQuery(userId));
} else {
this.hideProcessing();
}
}, (error: string) => {
this.hideProcessing();
this.message = error;
});
});
}
onCreateUserGroup(newUserGroupName: string): void {
this.showProcessing();
this.webAppSettingDataService.getUserId().subscribe((userId: string = '') => {
this.userGroupDataService.create(newUserGroupName, userId).subscribe((userGroupData: IUserGroupCreated) => {
this.userGroupList.push({
id: newUserGroupName,
number: userGroupData.number
});
this.hideProcessing();
}, (error: string) => {
this.hideProcessing();
this.message = error;
});
});
}
onCloseCreateUserPopup(): void {
this.showCreate = false;
}
onShowCreateUserPopup(): void {
this.showCreate = true;
}
hasMessage(): boolean {
return this.message !== '';
}
onSelectUserGroup(userGroupId: string): void {
this.selectedUserGroupId = userGroupId;
this.userGroupInteractionService.setSelectedUserGroup(userGroupId);
}
onCloseMessage(): void {
this.message = '';
}
onSearch(query: string): void {
this.searchQuery = query;
this.webAppSettingDataService.getUserId().subscribe((userId: string = '') => {
this.getUserGroupList(this.makeUserGroupQuery(userId));
});
}
private showProcessing(): void {
this.useDisable = true;
this.showLoading = true;
}
private hideProcessing(): void {
this.useDisable = false;
this.showLoading = false;
}
}
|
sr-johnny/gameplay
|
src/routes/app.routes.tsx
|
<filename>src/routes/app.routes.tsx<gh_stars>0
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { NavigationContainer } from '@react-navigation/native';
import { theme } from '../global/styles/theme';
import { Home } from '../screens/Home';
import { AppointmentDetails } from '../screens/AppointmentDetails';
import { AppointmentCreate } from '../screens/AppointmentCreate';
const Stack = createNativeStackNavigator();
export function AppRoutes(){
return(
<NavigationContainer>
<Stack.Navigator
initialRouteName="SignIn"
screenOptions={{
headerShown: false,
contentStyle: { backgroundColor: theme.colors.secondary100 }
}}>
<Stack.Screen
name="Home"
component={Home}
/>
<Stack.Screen
name="AppointmentDetails"
component={AppointmentDetails}
/>
<Stack.Screen
name="AppointmentCreate"
component={AppointmentCreate}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
|
tiholic/mean.ti
|
ng/app/app.component.ts
|
<reponame>tiholic/mean.ti<gh_stars>0
/**
* Created by rohit on 7/9/16.
*/
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'ng/app/app.component.html', //All router links to be added inside this template
styleUrls: ['ng/app/app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
}
|
tiholic/mean.ti
|
ng/app/hero-detail/hero-detail.component.ts
|
<filename>ng/app/hero-detail/hero-detail.component.ts
/**
* Created by rohit on 7/9/16.
*/
import {Component, Input, OnInit} from "@angular/core";
import {ActivatedRoute, Params} from "@angular/router";
import {Hero} from "../hero";
import {HeroService} from "../heroes/heroes.service";
@Component({
selector: 'my-hero-detail',
templateUrl: 'ng/app/hero-detail/hero-detail.component.html',
})
export class HeroDetailComponent implements OnInit{
@Input()
hero: Hero;
errorMessage: string;
constructor(
private heroService: HeroService,
private route: ActivatedRoute
){
}
ngOnInit(): void {
this.route.params.forEach((params:Params) => {
let _id:string = params['id'];
this.heroService.getHero(_id).
subscribe(
hero => this.hero = hero,
error => this.errorMessage = <any>error
);
});
}
goBack(): void{
window.history.back();
}
save(): void{
this.heroService.update(this.hero)
.then(this.goBack)
}
}
|
tiholic/mean.ti
|
ng/app/app.module.ts
|
<reponame>tiholic/mean.ti
/**
* Created by rohit on 12/9/16.
*/
import './rxjs-extensions';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import {DashboardComponent} from "./dashboard/dashboard.component";
import {HeroDetailComponent} from "./hero-detail/hero-detail.component";
import {HeroesComponent} from "./heroes/heroes.component";
import {ChatComponent} from "./chat/chat.component";
import {HeroSearchComponent} from "./hero-search/hero-search.component";
import {HeroService} from "./heroes/heroes.service";
// Imports for loading & configuring the in-memory web api
// import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
// import { InMemoryDataService } from './in-memory-data.service';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
routing
// InMemoryWebApiModule.forRoot(InMemoryDataService)
],
declarations: [
AppComponent,
DashboardComponent,
HeroDetailComponent,
HeroesComponent,
ChatComponent,
HeroSearchComponent
],
providers: [
HeroService,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
|
tiholic/mean.ti
|
ng/app/heroes/heroes.service.ts
|
<filename>ng/app/heroes/heroes.service.ts
/**
* Created by rohit on 7/9/16.
*/
import { Injectable } from "@angular/core";
import 'rxjs/add/operator/toPromise';
import { Headers, Http, Response, RequestOptions } from "@angular/http";
import { Hero } from "../hero";
import { Observable } from 'rxjs/Observable'
@Injectable()
export class HeroService {
private heroesUrl = '/api/heroes';
private headers = new Headers({
'Content-Type': 'application/json'
});
constructor(private http: Http){ }
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
getHero(id: string): Observable<Hero> {
return this.getHeroes()
.map(heroes => heroes.find(hero => hero._id === id))
.catch(this.handleError);
}
update(hero:Hero):Promise<Hero>{
const url = `${this.heroesUrl}/${hero._id}`;
return this.http.put(url, JSON.stringify(hero), {headers: this.headers})
.toPromise()
.then(() => hero)
.catch(this.handleError)
}
create(name: String, strength: String, is_flying: boolean):Observable<Hero>{
let body = JSON.stringify({name, strength, is_flying});
const url = `${this.heroesUrl}`;
let options = new RequestOptions({ headers: this.headers });
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError)
}
del(id:String):Promise<Hero>{
let url = `${this.heroesUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError)
}
private extractData(res: Response){
let body = res.json();
return body.data || {};
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
|
tiholic/mean.ti
|
ng/app/app.routing.ts
|
<gh_stars>0
/**
* Created by rohit on 7/9/16.
*/
import {Routes, RouterModule} from "@angular/router";
import {ModuleWithProviders} from "@angular/core";
import {HeroesComponent} from "./heroes/heroes.component";
import {HeroDetailComponent} from "./hero-detail/hero-detail.component";
import {DashboardComponent} from "./dashboard/dashboard.component";
import {ChatComponent} from "./chat/chat.component"
const appRoutes : Routes = [
{
path: 'heroes',
component: HeroesComponent
},
{
path: 'heroes/:id',
component: HeroDetailComponent
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'chat',
component: ChatComponent
},
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
|
tiholic/mean.ti
|
ng/app/dashboard/dashboard.component.ts
|
<reponame>tiholic/mean.ti<filename>ng/app/dashboard/dashboard.component.ts
/**
* Created by rohit on 7/9/16.
*/
import {Component, OnInit} from "@angular/core";
import {Router} from "@angular/router";
import {Hero} from "../hero";
import {HeroService} from "../heroes/heroes.service";
@Component({
selector: 'my-dashboard',
templateUrl: 'ng/app/dashboard/dashboard.component.html',
styleUrls: ['ng/app/dashboard/dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
errorMessage: string;
constructor(
private heroService: HeroService,
private router: Router
){}
ngOnInit(): void {
this.heroService.getHeroes().
subscribe(
heroes => this.heroes = heroes.slice(0,4),
error => this.errorMessage = error
);
}
gotoDetail( hero:Hero ): void{
let link = ['/heroes', hero._id];
this.router.navigate(link);
}
}
|
tiholic/mean.ti
|
ng/app/chat/chat.component.ts
|
/**
* Created by rohit on 13/9/16.
*/
import {Component, OnInit, OnDestroy} from "@angular/core";
import * as io from "socket.io-client";
class message{
id: number = new Date().getTime();
message: string;
delivered: boolean;
}
@Component({
selector: 'chat',
templateUrl: '/ng/app/chat/chat.component.html',
styleUrls: ['ng/app/chat/chat.component.css']
})
export class ChatComponent implements OnInit, OnDestroy{
messages: message[];
to: string;
socket;
constructor(){ }
ngOnInit(){
this.socket = io();
this.messages = [
{id: new Date().getTime(), message:"Hello!", delivered: true},
{id: new Date().getTime(), message:"World!", delivered: false},
];
this.socket.on('delivered', id => {
var message = this.messages.filter(msg => msg.id==id)[0];
this.messages[this.messages.indexOf(message)].delivered = true;
});
this.socket.on('chat message', msg => this.messages.push(msg));
this.socket.on('new user', newSocketId => {
this.messages.push({id:0,message:newSocketId, delivered:false});
this.to = newSocketId;
});
}
ngOnDestroy(){
this.socket.disconnect();
}
send(message: string): void{
var msg = { id: new Date().getTime(), message: message, delivered: false };
this.messages.push(msg);
msg['to'] = this.to;
this.socket.emit('chat message', msg);
}
}
|
tiholic/mean.ti
|
ng/app/hero.ts
|
<reponame>tiholic/mean.ti<gh_stars>0
/**
* Created by rohit on 7/9/16.
*/
export class Hero {
_id: string;
name: string;
strength: string;
is_flying: boolean;
}
|
PabloSzx/graphql_what_why
|
api/type-graphql/resolvers/Species.ts
|
<filename>api/type-graphql/resolvers/Species.ts
import { FieldResolver, Resolver, Root } from "type-graphql";
import { SpeciesData } from "../../data";
import { Species } from "../entities/Species";
@Resolver(() => Species)
export class SpeciesResolver {
@FieldResolver()
lifespan(@Root() { name }: Pick<Species, "name">) {
const lifespan = SpeciesData.find(value => value.name === name)?.lifespan;
if (!lifespan) throw new Error("Lifespan could not be found for " + name);
return lifespan;
}
@FieldResolver()
origin(@Root() { name }: Pick<Species, "name">) {
const origin = SpeciesData.find(value => value.name === name)?.origin;
if (!origin) throw new Error("Origin could not be found for " + name);
return { name: origin };
}
}
|
PabloSzx/graphql_what_why
|
api/rest/routes/planets/index.ts
|
<filename>api/rest/routes/planets/index.ts
import { Router } from "express";
import { PlanetsData } from "../../../data";
export const PlanetsRouter = Router();
PlanetsRouter.get("/planetData", (req, res) => {
const { name } = req.query;
if (name === undefined) {
return res.status(400).send("Invalid name");
}
return res.send(PlanetsData.find(value => value.name === name));
});
PlanetsRouter.get("/planetsList", (req, res) => {
const { planets } = req.query;
const planetsList: string[] = planets?.split(",") ?? [];
return res.send(PlanetsData.filter(({ name }) => planetsList.includes(name)));
});
|
PabloSzx/graphql_what_why
|
api/rest/routes/species/index.ts
|
import { Router } from "express";
import { SpeciesData } from "../../../data";
export const SpeciesRouter = Router();
SpeciesRouter.get("/speciesData", (req, res) => {
const { name } = req.query;
if (name === undefined) {
return res.status(400).send("Invalid name");
}
res.send(SpeciesData.find(value => value.name === name));
});
|
PabloSzx/graphql_what_why
|
api/type-graphql/index.ts
|
import "reflect-metadata";
import { ApolloServer } from "apollo-server";
import path from "path";
import { buildSchemaSync } from "type-graphql";
import * as resolvers from "./resolvers";
const apolloServer = new ApolloServer({
schema: buildSchemaSync({
resolvers: [...(Object.values(resolvers) as Function[])],
emitSchemaFile: path.resolve(__dirname, "./schema.gql"),
}),
cors: true,
});
const port = 3003;
apolloServer.listen({ port }, () => {
console.log(`🚀 TypeGraphQL API Server ready at\
http://localhost:${port}`);
});
|
PabloSzx/graphql_what_why
|
api/rest/index.ts
|
import cors from "cors";
import express from "express";
import { CharactersRouter } from "./routes/characters";
import { PlanetsRouter } from "./routes/planets";
import { SpeciesRouter } from "./routes/species";
const app = express();
app.use(cors());
app.use("/species", SpeciesRouter);
app.use("/characters", CharactersRouter);
app.use("/planets", PlanetsRouter);
const port = 3002;
app.listen({ port }, () => {
console.log(`🚀 Rest API Server ready at http://localhost:${port}`);
});
|
PabloSzx/graphql_what_why
|
src/pages/code_first.tsx
|
import { NextPage } from "next";
import { withUrqlClient } from "next-urql";
import { useQuery } from "urql";
import { HERO_QUERY, IHeroData } from "../graphql/queries";
import omitDeep from "../utils/omitDeep";
const CodeFirst: NextPage = () => {
const [{ data, fetching }] = useQuery<IHeroData>({
query: HERO_QUERY,
});
return (
<div>
{fetching || !data
? "Loading..."
: JSON.stringify(omitDeep(data, ["__typename"]), null, 2)}
</div>
);
};
export default withUrqlClient({ url: "http://localhost:3003" })(CodeFirst);
|
PabloSzx/graphql_what_why
|
src/pages/index.tsx
|
import Link from "next/link";
export default () => {
return (
<div>
<p>
<Link href="/schema_first" passHref>
<a>GraphQL Schema First</a>
</Link>
</p>
<p>
<Link href="/rest" passHref>
<a>REST API</a>
</Link>
</p>
<p>
<Link href="/code_first" passHref>
<a>GraphQL Code First</a>
</Link>
</p>
</div>
);
};
|
PabloSzx/graphql_what_why
|
api/type-graphql/entities/Character.ts
|
import { Field, ObjectType } from "type-graphql";
import { Planet } from "./Planet";
import { Species } from "./Species";
@ObjectType()
export class Character {
@Field()
name: string;
@Field(() => [Character])
friends: Character[];
@Field(() => Planet, { nullable: true })
homeWorld?: Planet;
@Field(() => Species)
species: Species;
}
|
PabloSzx/graphql_what_why
|
src/pages/_app.tsx
|
<filename>src/pages/_app.tsx
import { NextPage } from "next";
import { AppProps } from "next/app";
import Link from "next/link";
import { useRouter } from "next/router";
const App: NextPage<AppProps> = ({ Component, pageProps }) => {
const { pathname } = useRouter();
return (
<>
{pathname !== "/" && (
<nav>
<Link href="/" passHref>
<a>Go back</a>
</Link>
<br />
<br />
</nav>
)}
<Component {...pageProps} />
</>
);
};
export default App;
|
PabloSzx/graphql_what_why
|
api/type-graphql/resolvers/Character.ts
|
<reponame>PabloSzx/graphql_what_why<gh_stars>0
import { sample } from "lodash";
import { FieldResolver, Query, Resolver, Root } from "type-graphql";
import { CharactersData } from "../../data";
import { Character } from "../entities/Character";
@Resolver(() => Character)
export class CharacterResolver {
@Query(() => Character)
hero() {
const chosenHero = sample(CharactersData);
if (chosenHero) {
return {
name: chosenHero.name,
friends: chosenHero.friends.map(name => ({ name })),
homeWorld: chosenHero.homeWorld
? { name: chosenHero.homeWorld }
: undefined,
species: { name: chosenHero.species },
};
}
return null;
}
@FieldResolver()
friends(@Root() { name, friends }: Pick<Character, "name" | "friends">) {
if (friends) {
return friends;
}
return (
CharactersData.find(value => value.name === name)?.friends.map(name => ({
name,
})) ?? []
);
}
@FieldResolver()
homeWorld(
@Root() { name, homeWorld }: Pick<Character, "name" | "homeWorld">,
) {
if (homeWorld) {
return homeWorld;
}
const homeWorldName = CharactersData.find(value => value.name === name)
?.homeWorld;
if (homeWorldName) {
return {
name: homeWorldName,
};
}
return null;
}
@FieldResolver()
species(@Root() { name, species }: Pick<Character, "name" | "species">) {
if (species) {
return species;
}
const speciesName = CharactersData.find(value => value.name === name)
?.species;
if (!speciesName) throw new Error("Species could not be found for " + name);
return {
name: speciesName,
};
}
}
|
PabloSzx/graphql_what_why
|
api/rest/routes/characters/index.ts
|
<reponame>PabloSzx/graphql_what_why<filename>api/rest/routes/characters/index.ts
import { Router } from "express";
import { sample } from "lodash";
import { CharactersData } from "../../../data";
export const CharactersRouter = Router();
CharactersRouter.get("/hero", (_req, res) => {
return res.send(sample(CharactersData));
});
CharactersRouter.get("/friends", (req, res) => {
const { friends } = req.query;
const friendsList: string[] = friends?.split(",") ?? [];
res.send(CharactersData.filter(({ name }) => friendsList.includes(name)));
});
CharactersRouter.get("/characterData", (req, res) => {
const { name } = req.query;
if (name === undefined) {
return res.status(400).send("Invalid name");
}
res.send(CharactersData.find(value => value.name === name));
});
|
PabloSzx/graphql_what_why
|
api/graphql/index.ts
|
<gh_stars>0
import { ApolloServer, gql } from "apollo-server";
import { sample } from "lodash";
import { CharactersData, PlanetsData, SpeciesData } from "../data";
const typeDefs = gql`
type Query {
hero: Character
}
type Character {
name: String!
friends: [Character!]!
homeWorld: Planet
species: Species!
}
type Planet {
name: String!
climate: String!
neighbors: [Planet!]!
}
type Species {
name: String!
lifespan: Int!
origin: Planet!
}
`;
const resolvers = {
Character: {
homeWorld: ({ name }: { name: string }) => {
const homeWorldName = CharactersData.find(value => value.name === name)
?.homeWorld;
if (homeWorldName) {
return {
name: homeWorldName,
};
}
return null;
},
species: ({ name }: { name: string }) => {
const speciesName = CharactersData.find(value => value.name === name)
?.species;
if (!speciesName)
throw new Error("Species could not be found for " + name);
return {
name: speciesName,
};
},
friends: ({ name }: { name: string }) => {
return (
CharactersData.find(
value => value.name === name,
)?.friends.map(name => ({ name })) ?? []
);
},
},
Planet: {
climate: ({ name }: { name: string }) => {
const climate = PlanetsData.find(value => value.name === name)?.climate;
if (!climate) throw new Error("Climate could not be found for " + name);
return climate;
},
neighbors: ({ name }: { name: string }) => {
return (
PlanetsData.find(value => value.name === name)?.neighbors.map(name => {
return { name };
}) ?? []
);
},
},
Species: {
lifespan: ({ name }: { name: string }) => {
const lifespan = SpeciesData.find(value => value.name === name)?.lifespan;
if (lifespan === undefined)
throw new Error("Lifespan could not be found for " + name);
return lifespan;
},
origin: ({ name }: { name: string }) => {
const origin = SpeciesData.find(value => value.name === name)?.origin;
if (origin === undefined)
throw new Error("Origin could not be found for " + name);
return { name: origin };
},
},
Query: {
hero: () => {
const chosenHero = sample(CharactersData);
if (chosenHero) {
return {
name: chosenHero.name,
};
}
return null;
},
},
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
cors: true,
});
const port = 3001;
apolloServer.listen({ port }, () => {
console.log(`🚀 GraphQL API Server ready at\
http://localhost:${port}`);
});
|
PabloSzx/graphql_what_why
|
api/data/index.ts
|
export const CharactersData: {
name: string;
friends: string[];
homeWorld?: string;
species: string;
}[] = [
{
name: "A",
friends: ["B", "D"],
homeWorld: "Planet A",
species: "Species A",
},
{
name: "B",
friends: ["A"],
homeWorld: "Planet A",
species: "Species B",
},
{
name: "C",
friends: [],
species: "Species B",
},
{
name: "D",
friends: ["A"],
homeWorld: "Planet B",
species: "Species A",
},
];
export const PlanetsData = [
{
name: "Planet A",
climate: "Tropical",
neighbors: ["Planet B"],
},
{
name: "Planet B",
climate: "Polar Chill",
neighbors: ["Planet A"],
},
{
name: "Planet C",
climate: "Arid",
neighbors: [],
},
];
export const SpeciesData = [
{
name: "Species A",
lifespan: 100,
origin: "Planet A",
},
{
name: "Species B",
lifespan: 80,
origin: "Planet C",
},
];
|
PabloSzx/graphql_what_why
|
api/type-graphql/resolvers/index.ts
|
export * from "./Character";
export * from "./Planet";
export * from "./Species";
|
PabloSzx/graphql_what_why
|
src/utils/omitDeep.ts
|
const omitDeep = (
input: Record<string, any>,
excludes: string[],
): Record<string, any> => {
return Object.entries(input).reduce<Record<string, any>>(
(nextInput, [key, value]) => {
const shouldExclude = excludes.includes(key);
if (shouldExclude) return nextInput;
if (Array.isArray(value)) {
const arrValue = value;
const nextValue = arrValue.map(arrItem => {
if (typeof arrItem === "object") {
return omitDeep(arrItem, excludes);
}
return arrItem;
});
nextInput[key] = nextValue;
return nextInput;
} else if (typeof value === "object") {
nextInput[key] = omitDeep(value, excludes);
return nextInput;
}
nextInput[key] = value;
return nextInput;
},
{},
);
};
export default omitDeep;
|
PabloSzx/graphql_what_why
|
api/type-graphql/resolvers/Planet.ts
|
import { FieldResolver, Resolver, Root } from "type-graphql";
import { PlanetsData } from "../../data";
import { Planet } from "../entities/Planet";
@Resolver(() => Planet)
export class PlanetResolver {
@FieldResolver()
climate(@Root() { name }: Pick<Planet, "name">) {
const climate = PlanetsData.find(value => value.name === name)?.climate;
if (!climate) throw new Error("Climate could not be found for " + name);
return climate;
}
@FieldResolver()
neighbors(@Root() { name }: Pick<Planet, "name">) {
return (
PlanetsData.find(value => value.name === name)?.neighbors.map(name => ({
name,
})) ?? []
);
}
}
|
PabloSzx/graphql_what_why
|
src/pages/rest.tsx
|
import useAxios from "axios-hooks";
import { NextPage } from "next";
import { CharactersData, PlanetsData, SpeciesData } from "../../api/data";
const REST: NextPage = () => {
const [{ data: dataHero, loading, error }] = useAxios<
typeof CharactersData[number]
>("http://localhost:3002/characters/hero");
const [{ data: dataSpecies }] = useAxios<typeof SpeciesData[number]>({
url: "http://localhost:3002/species/speciesData",
params: {
name: dataHero?.species ?? "",
},
});
const [{ data: dataSpeciesOrigin }] = useAxios<typeof PlanetsData[number]>({
url: "http://localhost:3002/planets/planetData",
params: {
name: dataSpecies?.origin ?? "",
},
});
const [{ data: dataSpeciesOriginNeighbors }] = useAxios<typeof PlanetsData>({
url: "http://localhost:3002/planets/planetsList",
params: {
planets: dataSpeciesOrigin?.neighbors?.join(",") ?? "",
},
});
const [{ data: dataHeroHomeWorld }] = useAxios<typeof PlanetsData[number]>({
url: "http://localhost:3002/planets/planetData",
params: {
name: dataHero?.homeWorld ?? "",
},
});
const [{ data: dataFriends }] = useAxios<typeof CharactersData>({
url: "http://localhost:3002/characters/friends",
params: {
friends: dataHero?.friends.join(","),
},
});
if (error) {
return <div>{JSON.stringify(error, null, 2)}</div>;
}
return (
<div>
{loading
? "Loading..."
: JSON.stringify(
{
hero: {
name: dataHero.name,
friends: dataFriends
? dataFriends.map(({ name, friends }) => ({
name,
friends: friends.map(name => ({ name })),
}))
: "Loading...",
species: dataSpecies
? {
name: dataSpecies.name,
lifespan: dataSpecies.lifespan,
origin: dataSpeciesOrigin
? {
name: dataSpeciesOrigin.name,
neighbors: dataSpeciesOriginNeighbors
? dataSpeciesOriginNeighbors.map(
({ name, climate }) => ({ name, climate }),
)
: "Loading...",
}
: "Loading...",
}
: "Loading...",
homeWorld: dataHeroHomeWorld
? {
name: dataHeroHomeWorld.name,
neighbors: dataHeroHomeWorld.neighbors.map(name => ({
name,
})),
climate: dataHeroHomeWorld.climate,
}
: "Loading...",
},
},
null,
2,
)}
</div>
);
};
export default REST;
|
PabloSzx/graphql_what_why
|
src/graphql/queries.ts
|
import gql from "graphql-tag";
export interface IHeroData {
hero?: {
name: string;
friends: { name: string; friends: { name: string }[] }[];
species: {
name: string;
lifespan: number;
origin: { name: string; neighbors: { name: string; climate: string }[] };
};
homeWorld?: {
name: string;
neighbors: { name: string }[];
climate: string;
};
};
}
export const HERO_QUERY = gql`
query {
hero {
name
friends {
name
friends {
name
}
}
species {
name
lifespan
origin {
name
neighbors {
name
climate
}
}
}
homeWorld {
name
neighbors {
name
}
climate
}
}
}
`;
|
PabloSzx/graphql_what_why
|
api/type-graphql/entities/Planet.ts
|
<filename>api/type-graphql/entities/Planet.ts
import { Field, ObjectType } from "type-graphql";
@ObjectType()
export class Planet {
@Field()
name: string;
@Field()
climate: string;
@Field(() => [Planet])
neighbors: Planet[];
}
|
dancrumb/node-jwks-rsa
|
tests/ts-definitions.tests.ts
|
import * as jwksRsaType from '../index';
import {expect} from 'chai';
import expressjwt6 from "express-jwt";
import { expressjwt as expressjwt7, GetVerificationKey } from "express-jwt-v7";
const { jwksEndpoint } = require('../tests/mocks/jwks');
const { publicKey } = require('../tests/mocks/keys');
const { x5cSingle } = require('../tests/keys.js');
const jwksRsa: typeof jwksRsaType = require('../src');
describe('typescript definition', () => {
const jwksHost = 'http://localhost';
describe('hapiJwt2KeyAsync', () => {
it('should return a secret provider function', async () => {
jwksEndpoint(jwksHost, [ { pub: publicKey, kid: '123' } ])
const secretProvider = jwksRsa.hapiJwt2KeyAsync({
jwksUri: `${jwksHost}/.well-known/jwks.json`
});
const { key } = await secretProvider({
header: {
'alg': 'RS256',
'kid': '123'
}
});
expect(key).to.contain('-----BEGIN PUBLIC KEY');
});
});
it('getKeysInterceptor', async () => {
const client = new jwksRsa.JwksClient({
jwksUri: `${jwksHost}/.well-known/jwks.json`,
getKeysInterceptor: () => Promise.resolve(x5cSingle.keys)
});
const key = await client.getSigningKey('<KEY>');
expect(key.kid).to.equal('<KEY>');
});
it('Types-Only Validation with express-jwt', () => {
expressjwt6({
algorithms: ["RS256"],
secret: jwksRsa.expressJwtSecret({
cache: true,
jwksUri: `https://my-authz-server/.well-known/jwks.json`
})
});
expressjwt7({
algorithms: ['RS256'],
secret: jwksRsa.expressJwtSecret({
cache: true,
jwksUri: `https://my-authz-server/.well-known/jwks.json`
}) as GetVerificationKey
});
})
});
|
plumier/examples
|
01-project-layout/file-layout-classic/src/controller/users-controller.ts
|
<reponame>plumier/examples
import { route } from "plumier"
import { User } from "../entity/users-entity"
export class UsersController {
// POST /users
@route.post("")
save(data: User) {
return {}
}
// GET /users
@route.get("")
list(limit: number, offset: number) {
return {}
}
// GET /users/:id
@route.get(":id")
get(id: string) {
return {}
}
// PUT /users/:id
@route.put(":id")
replace(id: string) {
return {}
}
// PATCH /users/:id
@route.patch(":id")
modify(id: string) {
return {}
}
// DELETE /users/:id
@route.delete(":id")
delete(id: string) {
return {}
}
}
|
plumier/examples
|
04-first-class-entity/first-class-entity-mongoose/src/controller/users-entity.ts
|
<reponame>plumier/examples
import model, { collection } from "@plumier/mongoose"
import { entity, genericController } from "plumier"
import { Email } from "./emails-entity"
// create generic controller
// it will generated into /users
@genericController()
@collection()
export class User {
@collection.id()
id: string
@collection.property()
name: string
// create generic controller from one-to-many relation
// it will generated into /users/:pid/emails
// note that the inverse property (user) need to specify,
// so Plumier understand that the user property of Email entity should be filled with :pid parameter
@genericController()
@collection.ref(x => [Email], "user")
emails: Email[]
// mark property as delete column,
// DELETE /users/:id will not delete the record permanently
@entity.deleteColumn()
@collection.property({ default: false })
deleted: boolean
}
|
plumier/examples
|
05-security/basic-security/src/policy/main-policy.ts
|
import { authPolicy } from "@plumier/core";
/**
* Here we define "name" for the authorization logic
* next we use those names to secure action to restrict access to some user
* using @authorize.route() decorator
*
* Important to note that, when user attach bearer JWT token on request, the user claim is accessible
* via ctx.user
*/
authPolicy()
// Admin policy is when user claim role is Admin
.register("Admin", ctx => ctx.user?.role === "Admin")
.register("SuperAdmin", ctx => ctx.user?.role === "SuperAdmin")
.register("User", ctx => ctx.user?.role === "User")
|
plumier/examples
|
02-controller/routing/src/controller/02-root-controller.ts
|
import { route } from "@plumier/core";
/**
* Root Route
*
* Used to rename controller name
*
* Generated into:
* GET /root/one/index
*/
@route.root("root/one")
export class RootOneController {
@route.get()
index() {
return {}
}
}
/**
* Root Route With Paramter
*
* Accept route parameter (start with :), backing parameter must be specified on all actions
*
* Generated into:
* GET /root/:id/one
* GET /root/:id/two/:tid
*/
@route.root("root/:id")
export class RootTwoController {
@route.get()
one(id: string) {
return {}
}
@route.get("two/:tid")
two(id: string, tid: string) {
return {}
}
}
/**
* Multiple root
*
* Multiple root can be specified and all actions generated accordingly based on each root
*
* Generated into:
* GET /api/v1/root/:id/one
* GET /api/v1/root/:id/two/:tid
* GET /api/v2/root/:id/one
* GET /api/v2/root/:id/two/:tid
*/
@route.root("api/v1/root/:id")
@route.root("api/v2/root/:id")
export class RootThreeController {
@route.get()
one(id: string) {
return {}
}
@route.get("two/:tid")
two(id: string, tid: string) {
return {}
}
}
/**
* Absolute Root Route
*
* Path start with slash (/) means absolute
* All preceding path (for example rootPath from configuration) will be ignored
*
* Generated into:
* GET /root/one/index
*/
@route.root("/root/four")
export class RootFourController {
@route.get()
index() {
return {}
}
}
|
plumier/examples
|
05-security/entity-policy/src/entity/emails-entity.ts
|
import { genericController } from "@plumier/generic-controller"
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm"
import { User } from "./users-entity"
@Entity()
export class Email {
@PrimaryGeneratedColumn()
id: number
@Column()
email: string
@Column()
description:string
@Column()
primary:boolean
@ManyToOne(x => User)
user:User
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/orders/order-entity.ts
|
<filename>08-complete-example/marketplace-api/src/api/orders/order-entity.ts
import { api, authorize, genericController, meta, val } from "plumier"
import { Column, CreateDateColumn, Entity, ManyToOne, OneToMany } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { OrderItem } from "../orders-items/order-item-entity"
import { ShippingAddress } from "../shipping-addresses/shipping-addresses-entity"
import { Shop } from "../shops/shops-entity"
import { User } from "../users/users-entity"
@Entity()
export class Order extends EntityBase {
@authorize.readonly()
@CreateDateColumn()
date: Date
@Column({ default: "ReceivedBySeller" })
@val.enums(["Issue", "ReceivedBySeller", "Prepared", "Sent", "ReceivedByBuyer"])
state: "Issue" | "ReceivedBySeller" | "Prepared" | "Sent" | "ReceivedByBuyer"
@authorize.readonly()
@ManyToOne(x => Shop)
shop: Shop
@authorize.readonly()
@ManyToOne(x => User)
user: User
@authorize.readonly()
@ManyToOne(x => ShippingAddress)
address: ShippingAddress
@genericController(c => {
c.accessors()
.transformer(OrderItemDto, (x: OrderItem) => ({ ...x, subTotal: x.quantity * x.price }))
.authorize("ResourceOwner", "ShopOwner", "ShopStaff")
c.mutators().ignore()
})
@api.tag("User Order Management")
@api.tag("Shop Order Management")
@authorize.readonly()
@OneToMany(x => OrderItem, x => x.order)
items: OrderItem[]
}
class OrderItemDto extends OrderItem {
@meta.property()
subTotal: number
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/users-shpping-addresses.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createUser, ignore } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Users Shipping Addresses", () => {
it("Should able to add multiple shipping addresses", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
await supertest(app.callback())
.post(`/api/users/${user.id}/shipping-addresses`)
.send({
address: "Br. Guntur Kemenuh Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/users/${user.id}/shipping-addresses`)
.send({
address: "Br. Kemuning Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/users/${user.id}/shipping-addresses`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(body[0]).toMatchSnapshot(ignore)
expect(body[1]).toMatchSnapshot(ignore)
})
it("Should able to deleted only by owner", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const otherUser = await createUser(app, { email: "<EMAIL>" })
const { body: added } = await supertest(app.callback())
.post(`/api/users/${user.id}/shipping-addresses`)
.send({
address: "Br. Guntur Kemenuh Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.delete(`/api/users/${user.id}/shipping-addresses/${added.id}`)
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(403)
await supertest(app.callback())
.delete(`/api/users/${user.id}/shipping-addresses/${added.id}`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/orders-items/order-item-entity.ts
|
import { Column, Entity, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { Product } from "../products/products-entity"
import { Order } from "../orders/order-entity"
import { authorize } from "plumier"
import { Shop } from "../shops/shops-entity"
@Entity()
export class OrderItem extends EntityBase {
@authorize.readonly()
@ManyToOne(x => Order)
order:Order
@authorize.readonly()
@ManyToOne(x => Product)
product:Product
@authorize.readonly()
@ManyToOne(x => Shop)
shop:Shop
@authorize.readonly()
@Column()
price: number
@authorize.readonly()
@Column()
quantity:number
}
|
plumier/examples
|
07-serve-static-and-file-upload/serve-static/src/index.ts
|
<filename>07-serve-static-and-file-upload/serve-static/src/index.ts
import { ServeStaticFacility } from "@plumier/serve-static"
import { join } from "path"
import Plumier, { response, route, WebApiFacility } from "plumier"
export class HomeController {
@route.get("/")
index() {
// use response.file to serve single file from action
return response.file(join(__dirname, "./www/index.html"))
}
}
new Plumier()
.set(new WebApiFacility())
// serve the static files (by default under www) directory
.set(new ServeStaticFacility())
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shops/shops-policy.ts
|
<filename>08-complete-example/marketplace-api/src/api/shops/shops-policy.ts
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { ShopUser } from "../shops-users/shops-users-entity"
import { Shop } from "./shops-entity"
entityPolicy(Shop)
.register("ShopOwner", async ({ user }, id) => {
const shopUser = await getRepository(ShopUser).findOne({ where: { user: user?.userId, shop: id, deleted: false }, cache: true })
return shopUser?.role === "ShopOwner"
})
.register("ShopStaff", async ({ user }, id) => {
const shopUser = await getRepository(ShopUser).findOne({ where: { user: user?.userId, shop: id, deleted: false }, cache: true })
return shopUser?.role === "ShopStaff"
})
|
plumier/examples
|
08-complete-example/marketplace-api/test/shop-orders.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createCart, ignore } from "./_helper"
const oIgnore = { ...ignore, date: expect.any(String), user: { ...ignore }, address: { ...ignore } }
afterEach(async () => {
await closeConnection()
})
describe("Shop Orders", () => {
it("Should able to list orders", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
expect(orders[0]).toMatchSnapshot(oIgnore)
})
it("Should accessible by owner", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.owner.token}`)
.expect(200)
})
it("Should not accessible by non shop user", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra, ali] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${ali.owner.token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/auth/auth-entity.ts
|
<reponame>plumier/examples<gh_stars>1-10
import {noop} from "@plumier/reflect"
export class Tokens {
@noop()
token: string
@noop()
refreshToken: string
}
|
plumier/examples
|
06-swagger/swagger/src/controller/users-entity.ts
|
import { entity, genericController } from "plumier"
import { Column, Entity, PrimaryGeneratedColumn, OneToMany } from "typeorm"
/**
* First class entity has its own generic controller
* which will provide the metadata for OAS3,
* Mostly no further configuration needed
*/
@genericController()
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column()
email: string
@entity.deleteColumn()
@Column({ default: false })
deleted: boolean
}
|
plumier/examples
|
05-security/entity-policy/src/entity/users-entity.ts
|
<gh_stars>1-10
import { authorize, entity, genericController } from "plumier"
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm"
import { Email } from "./emails-entity"
@genericController(c => {
// everyone can register
c.post().authorize("Public")
// only the owner can modify/delete the data
c.methods("Put", "Patch", "Delete").authorize("Owner")
// everyone can see list of user and user by ID
// Authenticated is built-in policy to allow only login user
c.accessors().authorize("Authenticated")
})
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
/**
* DOB only can be seen and set by the owner of the data.
* We already restrict User entity only can be modify/delete by the owner
* so the write protection on this property is not necessary
*
* We also add access to SuperAdmin to get rid of the Query Parser warning
*/
@authorize.read("Owner", "SuperAdmin")
@Column()
dob: Date
/**
* Authorize all routes /users/:pid/emails only accessible by Owner
*/
@genericController(c => c.all().authorize("Owner"))
@OneToMany(x => Email, x => x.user)
emails: Email
@entity.deleteColumn()
@Column({ default: false })
deleted: boolean
}
|
plumier/examples
|
03-data-access/data-access-typeorm/src/controller/users-controller.ts
|
<reponame>plumier/examples
import { route } from "@plumier/core";
import { User } from "../entity/users-entity";
import { getRepository } from "typeorm"
export class UsersController {
@route.post("")
save(data: User) {
// create repository or query builder like usual
const repo = getRepository(User)
return repo.save(data)
}
}
|
plumier/examples
|
07-serve-static-and-file-upload/file-upload-local/src/controller/file-controller.ts
|
<gh_stars>1-10
import { FormFile, meta, route, val } from "plumier"
import { join } from "path"
export class FileController {
/**
* Create upload handler POST /file/upload
* receive multipart form with <input type="file" name="file"/>
* which maximum uploaded file is 3MB
*/
@route.post()
async upload(@val.file("3MB") file: FormFile) {
// copy the uploaded file from temp directory into files directory
return file.copy(join(__dirname, "../files"))
}
/**
* Create upload handler for multiple file upload POST /file/multiple
* receive multipart form with <input type="file" name="file" multiple/>
* which maximum of each uploaded file is 3MB
*/
@route.post()
async multiple(@val.file("3MB") @meta.type([FormFile]) file: FormFile[]) {
// copy the uploaded files from temp directory into files directory
return Promise.all(file.map(f => f.copy(join(__dirname, "../files"))))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.