Skip to content

Commit

Permalink
Logging and small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Mar 21, 2021
1 parent 08fdff4 commit c8745d7
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 29 deletions.
25 changes: 18 additions & 7 deletions app/src/account/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ export default class Account {
readonly trader = new TradeProcessor(this);
readonly storage = new Storage(this);

constructor(readonly options: AccountOptions) {}
constructor(readonly options: AccountOptions) {
this.logger.info(`The account was created, waiting for login...`);
}

login() {
this.logger.info('logging In');
const { client, options } = this;
const { username, password } = options.login;
client.logOn({
Expand All @@ -47,36 +50,44 @@ export default class Account {
machineName: 'steam-trader'
});
client.on('loggedOn', () => this.onLogin());
client.on('steamGuard', (_domain: any, callback: (code: string) => void) => callback(this.getAuthCode()));
}

logoff() {
this.logger.info(`Logging Off`);
this.client.logOff();
}

private onLogin() {
const { options, client, manager, getAuthCode, onWebSession, trader, setCurrency } = this;
this.logger.info('We logged in');
const { options, client, manager, onWebSession, trader } = this;
client.setPersona(1);
client.gamesPlayed(options.status.gameId);

client.on('steamGuard', (_domain: any, callback: (code: string) => void) => callback(getAuthCode()));
this.logger.debug('Started to listen!');
client.on('webSession', (_sessionId: number, cookies: string[]) => onWebSession(cookies));
client.on('wallet', (_hasWallet: boolean, currency: number) => setCurrency(currency));
client.on('wallet', (_hasWallet: boolean, currency: number) => this.setCurrency(currency));
manager.on('newOffer', (offer: Offer) => trader.begin(offer));
}

private onWebSession(cookies: string[]) {
this.logger.debug('Started web session, delivering the cookies.');
const { community, options, manager } = this;
manager.setCookies(cookies);
community.setCookies(cookies);
community.startConfirmationChecker(2000, options.login.identity);
}

private setCurrency(currency: number) {
this.options.status.currency = getCurrency(currency);
private setCurrency(c: number) {
const currency = getCurrency(c)
this.logger.debug(`The currency used is '${currency.name}'`);
this.options.status.currency = getCurrency(c);
}

private getAuthCode() {
const { sharedSecret } = this.options.login;
return SteamTotp.generateAuthCode(sharedSecret);
const auth = SteamTotp.generateAuthCode(sharedSecret);
this.logger.debug(`Requested steam guard auth code '${auth}'`);
return auth;
}
}
13 changes: 8 additions & 5 deletions app/src/account/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,26 @@ export default class Storage {
fs.mkdir(PATH, (err) => {} /* Folder already exists */);
}

async saveTransaction(context: OfferContext, accepted: boolean) {
fs.writeFileSync(this.getPath(context.offer.id), this.stringifyTransaction(context, accepted));
async saveTransaction(context: OfferContext, reason: string) {
const { id } = context.offer;
this.account.logger.debug(`Saving transaction '${id}'`);
fs.writeFileSync(this.getPath(id), this.stringifyTransaction(context, reason));
this.account.logger.debug(`Transaction '${id}' saved.`);
}

private getPath(id: string) {
return path.resolve(PATH, `${id}.json`);
}

private stringifyTransaction({ offer, profit }: OfferContext, accepted: boolean) {
private stringifyTransaction({ offer, profit }: OfferContext, reason: string) {
return JSON.stringify({
accepted,
account: this.account.options.login.username,
partner: offer.partner.getSteamID64(),
offerId: offer.id,
profit,
ourItems: mapItems(offer.itemsToGive),
theirItems: mapItems(offer.itemsToReceive)
theirItems: mapItems(offer.itemsToReceive),
reason
});
}
}
Expand Down
3 changes: 2 additions & 1 deletion app/src/trading/logic/calculatePrices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { NextFunction } from '../../util/middleware';
import { getAllItemsPrice } from '../../steam/market';
import { AccountOptions } from '../../account/account';
import { ItemPrice, OfferContext } from '../types';
import { Reason } from '../processor';

export default async function middleware(context: OfferContext, next: NextFunction) {
const { processor, offer } = context;

context.receiveItemsPrices = await getAllItemsPrice(offer.itemsToReceive);

if (context.receiveItemsPrices.some((item) => isTrash(item, processor.account.options))) {
processor.decline(context);
processor.decline(context, Reason.TRASH);
}

context.receivePrice = reducePrices(context.receiveItemsPrices);
Expand Down
7 changes: 4 additions & 3 deletions app/src/trading/logic/checkOverpay.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NextFunction } from '../../util/middleware';
import { Reason } from '../processor';
import { OfferContext } from '../types';

export default function middleware(context: OfferContext, next: NextFunction) {
Expand All @@ -8,13 +9,13 @@ export default function middleware(context: OfferContext, next: NextFunction) {
const { trading } = context.processor.account.options;

if (profit < 0) {
processor.decline(context);
processor.decline(context, Reason.OVERPAY);
return;
} else if (profit == 0) {
if (trading.tradeWith0Profit) {
processor.accept(context);
processor.accept(context, Reason.SAME_SIDES_TRUE);
} else {
processor.decline(context);
processor.decline(context, Reason.SAME_SIDES);
}
return;
}
Expand Down
5 changes: 3 additions & 2 deletions app/src/trading/logic/checkSides.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { NextFunction } from '../../util/middleware';
import { Reason } from '../processor';
import { OfferContext } from '../types';

export default function middleware(context: OfferContext, next: NextFunction) {
const { processor, offer } = context;

if (offer.itemsToReceive.length < 1) {
processor.decline(context);
processor.decline(context, Reason.OVERPAY);
return;
} else if (offer.itemsToGive.length < 1) {
processor.accept(context);
processor.accept(context, Reason.GIFT);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion app/src/trading/logic/glitched.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { NextFunction } from '../../util/middleware';
import { Reason } from '../processor';
import { OfferContext } from '../types';

export default function middleware(context: OfferContext, next: NextFunction) {
const { processor, offer } = context;

if (offer.isGlitched()) {
processor.decline(context);
processor.decline(context, Reason.GLITCHED);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion app/src/trading/logic/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import calculatePrices from './calculatePrices';
import checkOverpay from './checkOverpay';
import { Middleware } from '../../util/middleware';
import { OfferContext } from '../types';
import { Reason } from '../processor';

const logic: Middleware<OfferContext>[] = [
glitched,
Expand All @@ -15,7 +16,7 @@ const logic: Middleware<OfferContext>[] = [
calculatePrices,
checkOverpay,
// If not rejected, accept at the end.
(context: OfferContext) => context.processor.accept(context)
(context: OfferContext) => context.processor.accept(context, Reason.PROFIT)
];

export default logic;
3 changes: 2 additions & 1 deletion app/src/trading/logic/isOwner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NextFunction } from '../../util/middleware';
import { Reason } from '../processor';
import { OfferContext } from '../types';

export default function middleware(context: OfferContext, next: NextFunction) {
Expand All @@ -7,7 +8,7 @@ export default function middleware(context: OfferContext, next: NextFunction) {

// I transform partner.getSteamID64() to string because it was reading wrong. IDK why.
if (owners.includes(offer.partner.getSteamID64())) {
processor.accept(context);
processor.accept(context, Reason.OWNER);
return;
}

Expand Down
4 changes: 3 additions & 1 deletion app/src/trading/logic/unmarketable.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { NextFunction } from '../../util/middleware';
import { Reason } from '../processor';
import { OfferContext } from '../types';


export default function middleware(context: OfferContext, next: NextFunction) {
const { processor, offer } = context;

const unmarketable = offer.itemsToReceive.filter((item) => !item.marketable);
if (unmarketable.length > 0) {
processor.decline(context);
processor.decline(context, Reason.UNMARKETABLE);
}

return next();
Expand Down
37 changes: 30 additions & 7 deletions app/src/trading/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,44 @@ export default class TradeProcessor {
constructor(readonly account: Account) {}

async begin(offer: Offer) {
this.account.logger.info(`Received an new trade. The id is '${offer.id}'`);
await this.pipeline.execute(createContext(offer, this));
}

async decline(offer: OfferContext) {
async decline(offer: OfferContext, reason: Reason) {
const { logger } = this.account;
logger.info(`Declining trade '${offer.offer.id}'`, { reason });
await offer.offer.decline((err) => {
if (err) throw err;
if (err) {
logger.error(`Catch an error while trying to decline the trade '${offer.offer.id}'`, err);
return;
}
logger.info(`Declined trade '${offer.offer.id}'`);
});
}

async accept(offer: OfferContext) {
const { community, storage } = this.account;
community.checkConfirmations();
storage.saveTransaction(offer, true);
async accept(offer: OfferContext, reason: Reason) {
const { storage, logger } = this.account;
logger.info(`Accepting trade '${offer.offer.id}'`, { reason });
await offer.offer.accept((err) => {
if (err) throw err;
if (err) {
logger.error(`Catch an error while trying to accept the trade '${offer.offer.id}'`, err);
return;
}
logger.info(`Accepted trade '${offer.offer.id}'`);
storage.saveTransaction(offer, reason);
});
}
}

export enum Reason {
GLITCHED = 'The trade was glitched',
UNMARKETABLE = 'The trade contains unmarketable items',
OWNER = 'The trade partner is listed as an owner of this bot',
GIFT = 'The trade is a gift for us',
OVERPAY = 'We will lose money accepting this trade',
PROFIT = 'The trade is profitable',
SAME_SIDES = `This trade have both sides at the same price and the flag 'tradeWith0Profit' is false`,
TRASH = 'This trade has itens with an value lower than the trash limit',
SAME_SIDES_TRUE = "This trade have both sides at the same price but the flag 'tradeWith0Profit' is true"
}

0 comments on commit c8745d7

Please sign in to comment.