Skip to content

Commit

Permalink
First code version. Still need updates
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Mar 19, 2021
1 parent fe2d661 commit b4be692
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 36 deletions.
11 changes: 7 additions & 4 deletions app/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import config from '../../config.json';
import SteamUser from 'steam-user';
import SteamCommunity from 'steamcommunity';
import config from '../config.json';
import SteamTotp from 'steam-totp';
// @ts-ignore https://github.com/TypeStrong/ts-node#help-my-types-are-missing
import SteamCommunity from 'steamcommunity';
// @ts-ignore https://github.com/TypeStrong/ts-node#help-my-types-are-missing
import SteamUser from 'steam-user';
// @ts-ignore https://github.com/TypeStrong/ts-node#help-my-types-are-missing
import TradeOfferManager from 'steam-tradeoffer-manager';
import { info, Ad } from './logger';
import { Offer } from './trade/types';
Expand Down Expand Up @@ -35,7 +38,7 @@ client.on('loggedOn', () => {
info(`Logged into steam with username: '${username}'. Playing game id: '${statusGameId}'`);
});

client.on('webSession', (sessionId: number, cookies: string[]) => {
client.on('webSession', (_sessionId: number, cookies: string[]) => {
manager.setCookies(cookies);
community.setCookies(cookies);
community.startConfirmationChecker(2000, identitySecret);
Expand Down
12 changes: 6 additions & 6 deletions app/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,28 @@ import { enable } from 'colors';

enable();

export function info(...message: string[]) {
export function info(...message: any[]) {
printAll('INFO', 'green', ...message);
}

export function warn(...message: string[]) {
export function warn(...message: any[]) {
printAll('WARN', 'yellow', ...message);
}

export function error(...message: string[]) {
export function error(...message: any[]) {
printAll('ERROR', 'red', ...message);
}

export function log(...message: string[]) {
export function log(...message: any[]) {
printAll('#', undefined, ...message);
}

function printAll(prefix: string, color: string | undefined, ...message: string[]) {
function printAll(prefix: string, color: string | undefined, ...message: any[]) {
write(...message);
message.forEach((msg) => console.log(`[${prefix}]`.blue, color ? msg[color] : msg));
}

export function write(...message: string[]) {
export function write(...message: any[]) {
//TODO: write in the logs only
}

Expand Down
6 changes: 3 additions & 3 deletions app/src/trade/analyzer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { trading } from '../../../config.json';
import { trading } from '../../config.json';
import { Item, ItemPrice } from './types';

export function isTrash(item: ItemPrice): boolean {
Expand All @@ -13,6 +13,6 @@ export function containsUnmarketable(items: Item[], callback: (items: Item[]) =>
} else return false;
}

export function calculatePrice({ median_price, lowest_price }: ItemPrice): number {
return lowest_price > median_price ? lowest_price : median_price + lowest_price / 2;
export function calculatePrice({ median_price, lowest_price }: ItemPrice): number {
return !median_price || lowest_price > median_price ? lowest_price : median_price + lowest_price / 2;
}
15 changes: 9 additions & 6 deletions app/src/trade/market.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import axios from 'axios';
import { error, info } from '../logger';
import { ItemPrice, Item } from './types';
import { calculatePrice, isTrash } from './analyzer';

export async function getItemPrice({ appid, market_hash_name }: Item): Promise<ItemPrice> {
return new Promise<ItemPrice>(async (resolve, reject) => {
const params = { appid, currency: 1, market_hash_name };
try {
const data = await axios.get('http://steamcommunity.com/market/priceoverview', { params });
const { data } = await axios.get('http://steamcommunity.com/market/priceoverview', { params });
info('Received a response for the request on steamcommunity');
return resolve(parseData(data));
} catch (err) {
Expand All @@ -25,15 +24,19 @@ export async function getAllItemsPrice(items: Item[]) {
return prices;
}

function parseData({ success, lowest_price, volume, median_price }: any): ItemPrice {
function parseData({ success, lowest_price, median_price }: any): ItemPrice {
return {
success,
volume: Number(volume),
lowest_price: cleanPrice(lowest_price),
median_price: cleanPrice(median_price)
median_price: median_price ? cleanPrice(median_price) : undefined
};
}

function cleanPrice(price: string): number {
return Number(price.substring(1));
try {
return Number(price.substring(1));
} catch (err) {
console.log('erro', price);
return 0;
}
}
15 changes: 8 additions & 7 deletions app/src/trade/processor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { info, warn } from '../logger';
import config from '../../../config.json';
import config from '../../config.json';
import { getAllItemsPrice } from './market';
import { Offer, Community } from './types';
import { containsUnmarketable, isTrash, calculatePrice } from './analyzer';
Expand All @@ -21,9 +21,10 @@ export async function process(offer: Offer, community: Community): Promise<void>
return declineOffer(offer, Reason.GLITCHED);
}

if (ownerIds.includes(partner.getSteamID64())) {
// I transform partner.getSteamID64() to string because it was reading wrong. IDK why.
if (ownerIds.includes(`${partner.getSteamID64()}`)) {
info('Trade partner is owner');
return acceptOffer(offer);
return acceptOffer(community, offer);
}

info(`All our items are: ${itemsToGive.map((item) => item.name)}`);
Expand Down Expand Up @@ -53,15 +54,15 @@ export async function process(offer: Offer, community: Community): Promise<void>

const receivePrice = receiveItemsPrices.map(calculatePrice).reduce((a, b) => a + b);

const givePrice = (await getAllItemsPrice(itemsToGive)).map(calculatePrice).reduce((a, b) => a + b);
const givePrice = (await getAllItemsPrice(itemsToGive)).map(calculatePrice).reduce((a, b) => a + b, 0);

info(`Our price are: '$${givePrice}' and their price are: '$${receivePrice}'`);

if (isGift) {
info('Accepting gift');
return acceptOffer(offer, receivePrice);
return acceptOffer(community,offer, receivePrice);
} else {
if (givePrice >= receivePrice) {
if (givePrice > receivePrice) {
info('We are overpaying. Declining offer...');
return declineOffer(offer, Reason.NEGATIVE_PROFIT);
} else {
Expand All @@ -78,7 +79,7 @@ export async function process(offer: Offer, community: Community): Promise<void>
const profit = receivePrice - givePrice;

info(`Our profit is ${profit}. Accepting offer...`);
return acceptOffer(offer, profit);
return acceptOffer(community, offer, profit);
}
}
}
Expand Down
17 changes: 13 additions & 4 deletions app/src/trade/trader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Offer } from './types';
import { Offer, Community } from './types';
import { info, warn, error } from '../logger';
import {debug} from '../../config.json'

export enum Reason {
TRASH_LIMIT = 'Exists one or more itens with an value lower than the trash limit',
Expand All @@ -10,16 +11,24 @@ export enum Reason {
}

export async function declineOffer(offer: Offer, reason: Reason) {
if(debug) {
info('Trade declined');
return;
}
await offer.decline((err) => {
if (err) {
error('Was thrown an error while declining this offer.', err);
if (err) { error('Was thrown an error while declining this offer.', err);
return;
}
warn(`Declined the offer. Reason: '${reason}'`);
});
}

export async function acceptOffer(offer: Offer, profit?: number) {
export async function acceptOffer(community: Community, offer: Offer, profit?: number) {
if(debug) {
info('Trade accepted');
return;
}
community.checkConfirmations();
await offer.accept((err) => {
if (err) {
error('Was thrown an error while accepting this offer.', err);
Expand Down
11 changes: 6 additions & 5 deletions app/src/trade/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@ export interface Item {
export interface ItemPrice {
success: boolean;
lowest_price: number;
volume: number;
median_price: number;
median_price?: number;
}

export interface Offer {
isGlitched: () => boolean;
accept: (err: (err: any) => void) => void;
decline: (err: (err: any) => void) => void;
accept: (err?: (err: null | Error) => void) => void;
decline: (err?: (err: null | Error) => void) => void;
partner: Partner;
itemsToGive: Item[];
itemsToReceive: Item[];
message: string;
isOurOffer: boolean;
}

export interface Community {}
export interface Community {
checkConfirmations: (callback?: (err: null | Error) => void) => void;
}
2 changes: 1 addition & 1 deletion app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
"typeRoots": ["node_modules/@types", "app/@types"] /* List of folders to include type definitions from. */,
// "typeRoots": ["./node_modules/@types", "./src/@types"] /* List of folders to include type definitions from. */,
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
Expand Down

0 comments on commit b4be692

Please sign in to comment.