refactor stock for ctx instead of workerScript

This commit is contained in:
Snarling 2022-08-19 19:32:30 -04:00
parent 1b8993a3dc
commit 4001b4cbb0
3 changed files with 63 additions and 61 deletions

@ -163,7 +163,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
const shares = helpers.number(ctx, "shares", _shares); const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx); checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol); const stock = getStockFromSymbol(ctx, symbol);
const res = buyStock(stock, shares, ctx.workerScript, {}); const res = buyStock(stock, shares, ctx, {});
return res ? stock.getAskPrice() : 0; return res ? stock.getAskPrice() : 0;
}, },
sellStock: sellStock:
@ -173,7 +173,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
const shares = helpers.number(ctx, "shares", _shares); const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx); checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol); const stock = getStockFromSymbol(ctx, symbol);
const res = sellStock(stock, shares, ctx.workerScript, {}); const res = sellStock(stock, shares, ctx, {});
return res ? stock.getBidPrice() : 0; return res ? stock.getBidPrice() : 0;
}, },
@ -192,7 +192,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
} }
} }
const stock = getStockFromSymbol(ctx, symbol); const stock = getStockFromSymbol(ctx, symbol);
const res = shortStock(stock, shares, ctx.workerScript, {}); const res = shortStock(stock, shares, ctx, {});
return res ? stock.getBidPrice() : 0; return res ? stock.getBidPrice() : 0;
}, },
@ -211,7 +211,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
} }
} }
const stock = getStockFromSymbol(ctx, symbol); const stock = getStockFromSymbol(ctx, symbol);
const res = sellShort(stock, shares, ctx.workerScript, {}); const res = sellShort(stock, shares, ctx, {});
return res ? stock.getAskPrice() : 0; return res ? stock.getAskPrice() : 0;
}, },
@ -258,7 +258,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid position type: ${pos}`); throw helpers.makeRuntimeErrorMsg(ctx, `Invalid position type: ${pos}`);
} }
return placeOrder(stock, shares, price, orderType, orderPos, ctx.workerScript); return placeOrder(stock, shares, price, orderType, orderPos, ctx);
}, },
cancelOrder: cancelOrder:
(ctx: NetscriptContext) => (ctx: NetscriptContext) =>
@ -314,7 +314,7 @@ export function NetscriptStockMarket(): InternalAPI<TIX> {
type: orderType, type: orderType,
pos: orderPos, pos: orderPos,
}; };
return cancelOrder(params, ctx.workerScript); return cancelOrder(params, ctx);
}, },
getOrders: (ctx: NetscriptContext) => (): StockOrder => { getOrders: (ctx: NetscriptContext) => (): StockOrder => {
checkTixApiAccess(ctx); checkTixApiAccess(ctx);

@ -12,7 +12,6 @@ import {
import { PositionTypes } from "./data/PositionTypes"; import { PositionTypes } from "./data/PositionTypes";
import { CONSTANTS } from "../Constants"; import { CONSTANTS } from "../Constants";
import { WorkerScript } from "../Netscript/WorkerScript";
import { Player } from "../Player"; import { Player } from "../Player";
import { numeralWrapper } from "../ui/numeralFormat"; import { numeralWrapper } from "../ui/numeralFormat";
@ -21,6 +20,8 @@ import { Money } from "../ui/React/Money";
import { dialogBoxCreate } from "../ui/React/DialogBox"; import { dialogBoxCreate } from "../ui/React/DialogBox";
import * as React from "react"; import * as React from "react";
import { NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
/** /**
* Each function takes an optional config object as its last argument * Each function takes an optional config object as its last argument
@ -34,14 +35,14 @@ interface IOptions {
* Attempt to buy a stock in the long position * Attempt to buy a stock in the long position
* @param {Stock} stock - Stock to buy * @param {Stock} stock - Stock to buy
* @param {number} shares - Number of shares to buy * @param {number} shares - Number of shares to buy
* @param {WorkerScript} workerScript - If this is being called through Netscript * @param {NetscriptContext} ctx - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file * @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} - true if successful, false otherwise * @returns {boolean} - true if successful, false otherwise
*/ */
export function buyStock( export function buyStock(
stock: Stock, stock: Stock,
shares: number, shares: number,
workerScript: WorkerScript | null = null, ctx: NetscriptContext | null = null,
opts: IOptions = {}, opts: IOptions = {},
): boolean { ): boolean {
// Validate arguments // Validate arguments
@ -50,8 +51,8 @@ export function buyStock(
return false; return false;
} }
if (stock == null || isNaN(shares)) { if (stock == null || isNaN(shares)) {
if (workerScript) { if (ctx) {
workerScript.log("stock.buyStock", () => `Invalid arguments: stock='${stock}' shares='${shares}'`); helpers.log(ctx, () => `Invalid arguments: stock='${stock}' shares='${shares}'`);
} else if (opts.suppressDialog !== true) { } else if (opts.suppressDialog !== true) {
dialogBoxCreate("Failed to buy stock. This may be a bug, contact developer"); dialogBoxCreate("Failed to buy stock. This may be a bug, contact developer");
} }
@ -65,9 +66,9 @@ export function buyStock(
return false; return false;
} }
if (Player.money < totalPrice) { if (Player.money < totalPrice) {
if (workerScript) { if (ctx) {
workerScript.log( helpers.log(
"stock.buyStock", ctx,
() => () =>
`You do not have enough money to purchase this position. You need ${numeralWrapper.formatMoney(totalPrice)}.`, `You do not have enough money to purchase this position. You need ${numeralWrapper.formatMoney(totalPrice)}.`,
); );
@ -84,9 +85,9 @@ export function buyStock(
// Would this purchase exceed the maximum number of shares? // Would this purchase exceed the maximum number of shares?
if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) { if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) {
if (workerScript) { if (ctx) {
workerScript.log( helpers.log(
"stock.buyStock", ctx,
() => () =>
`Purchasing '${shares + stock.playerShares + stock.playerShortShares}' shares would exceed ${ `Purchasing '${shares + stock.playerShares + stock.playerShortShares}' shares would exceed ${
stock.symbol stock.symbol
@ -113,13 +114,13 @@ export function buyStock(
opts.rerenderFn(); opts.rerenderFn();
} }
if (workerScript) { if (ctx) {
const resultTxt = `Bought ${numeralWrapper.formatShares(shares)} shares of ${ const resultTxt = `Bought ${numeralWrapper.formatShares(shares)} shares of ${
stock.symbol stock.symbol
} for ${numeralWrapper.formatMoney(totalPrice)}. Paid ${numeralWrapper.formatMoney( } for ${numeralWrapper.formatMoney(totalPrice)}. Paid ${numeralWrapper.formatMoney(
CONSTANTS.StockMarketCommission, CONSTANTS.StockMarketCommission,
)} in commission fees.`; )} in commission fees.`;
workerScript.log("stock.buyStock", () => resultTxt); helpers.log(ctx, () => resultTxt);
} else if (opts.suppressDialog !== true) { } else if (opts.suppressDialog !== true) {
dialogBoxCreate( dialogBoxCreate(
<> <>
@ -136,20 +137,20 @@ export function buyStock(
* Attempt to sell a stock in the long position * Attempt to sell a stock in the long position
* @param {Stock} stock - Stock to sell * @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to sell * @param {number} shares - Number of shares to sell
* @param {WorkerScript} workerScript - If this is being called through Netscript * @param {NetscriptContext} ctx - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file * @param opts - Optional configuration for this function's behavior. See top of file
* returns {boolean} - true if successfully sells given number of shares OR MAX owned, false otherwise * returns {boolean} - true if successfully sells given number of shares OR MAX owned, false otherwise
*/ */
export function sellStock( export function sellStock(
stock: Stock, stock: Stock,
shares: number, shares: number,
workerScript: WorkerScript | null = null, ctx: NetscriptContext | null = null,
opts: IOptions = {}, opts: IOptions = {},
): boolean { ): boolean {
// Sanitize/Validate arguments // Sanitize/Validate arguments
if (stock == null || shares < 0 || isNaN(shares)) { if (stock == null || shares < 0 || isNaN(shares)) {
if (workerScript) { if (ctx) {
workerScript.log("stock.sellStock", () => `Invalid arguments: stock='${stock}' shares='${shares}'`); helpers.log(ctx, () => `Invalid arguments: stock='${stock}' shares='${shares}'`);
} else if (opts.suppressDialog !== true) { } else if (opts.suppressDialog !== true) {
dialogBoxCreate( dialogBoxCreate(
"Failed to sell stock. This is probably due to an invalid quantity. Otherwise, this may be a bug, contact developer", "Failed to sell stock. This is probably due to an invalid quantity. Otherwise, this may be a bug, contact developer",
@ -175,8 +176,8 @@ export function sellStock(
netProfit = 0; netProfit = 0;
} }
Player.gainMoney(gains, "stock"); Player.gainMoney(gains, "stock");
if (workerScript) { if (ctx) {
workerScript.scriptRef.onlineMoneyMade += netProfit; ctx.workerScript.scriptRef.onlineMoneyMade += netProfit;
Player.scriptProdSinceLastAug += netProfit; Player.scriptProdSinceLastAug += netProfit;
} }
@ -191,11 +192,11 @@ export function sellStock(
opts.rerenderFn(); opts.rerenderFn();
} }
if (workerScript) { if (ctx) {
const resultTxt = const resultTxt =
`Sold ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` + `Sold ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` +
`After commissions, you gained a total of ${numeralWrapper.formatMoney(gains)}.`; `After commissions, you gained a total of ${numeralWrapper.formatMoney(gains)}.`;
workerScript.log("stock.sellStock", () => resultTxt); helpers.log(ctx, () => resultTxt);
} else if (opts.suppressDialog !== true) { } else if (opts.suppressDialog !== true) {
dialogBoxCreate( dialogBoxCreate(
<> <>
@ -212,14 +213,14 @@ export function sellStock(
* Attempt to buy a stock in the short position * Attempt to buy a stock in the short position
* @param {Stock} stock - Stock to sell * @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to short * @param {number} shares - Number of shares to short
* @param {WorkerScript} workerScript - If this is being called through Netscript * @param {NetscriptContext} ctx - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file * @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} - true if successful, false otherwise * @returns {boolean} - true if successful, false otherwise
*/ */
export function shortStock( export function shortStock(
stock: Stock, stock: Stock,
shares: number, shares: number,
workerScript: WorkerScript | null = null, ctx: NetscriptContext | null = null,
opts: IOptions = {}, opts: IOptions = {},
): boolean { ): boolean {
// Validate arguments // Validate arguments
@ -228,8 +229,8 @@ export function shortStock(
return false; return false;
} }
if (stock == null || isNaN(shares)) { if (stock == null || isNaN(shares)) {
if (workerScript) { if (ctx) {
workerScript.log("stock.shortStock", () => `Invalid arguments: stock='${stock}' shares='${shares}'`); helpers.log(ctx, () => `Invalid arguments: stock='${stock}' shares='${shares}'`);
} else if (opts.suppressDialog !== true) { } else if (opts.suppressDialog !== true) {
dialogBoxCreate( dialogBoxCreate(
"Failed to initiate a short position in a stock. This is probably " + "Failed to initiate a short position in a stock. This is probably " +
@ -245,9 +246,9 @@ export function shortStock(
return false; return false;
} }
if (Player.money < totalPrice) { if (Player.money < totalPrice) {
if (workerScript) { if (ctx) {
workerScript.log( helpers.log(
"stock.shortStock", ctx,
() => () =>
"You do not have enough " + "You do not have enough " +
"money to purchase this short position. You need " + "money to purchase this short position. You need " +
@ -266,9 +267,9 @@ export function shortStock(
// Would this purchase exceed the maximum number of shares? // Would this purchase exceed the maximum number of shares?
if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) { if (shares + stock.playerShares + stock.playerShortShares > stock.maxShares) {
if (workerScript) { if (ctx) {
workerScript.log( helpers.log(
"stock.shortStock", ctx,
() => () =>
`This '${shares + stock.playerShares + stock.playerShortShares}' short shares would exceed ${ `This '${shares + stock.playerShares + stock.playerShortShares}' short shares would exceed ${
stock.symbol stock.symbol
@ -294,14 +295,14 @@ export function shortStock(
opts.rerenderFn(); opts.rerenderFn();
} }
if (workerScript) { if (ctx) {
const resultTxt = const resultTxt =
`Bought a short position of ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol} ` + `Bought a short position of ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol} ` +
`for ${numeralWrapper.formatMoney(totalPrice)}. Paid ${numeralWrapper.formatMoney( `for ${numeralWrapper.formatMoney(totalPrice)}. Paid ${numeralWrapper.formatMoney(
CONSTANTS.StockMarketCommission, CONSTANTS.StockMarketCommission,
)} ` + )} ` +
`in commission fees.`; `in commission fees.`;
workerScript.log("stock.shortStock", () => resultTxt); helpers.log(ctx, () => resultTxt);
} else if (!opts.suppressDialog) { } else if (!opts.suppressDialog) {
dialogBoxCreate( dialogBoxCreate(
<> <>
@ -318,19 +319,19 @@ export function shortStock(
* Attempt to sell a stock in the short position * Attempt to sell a stock in the short position
* @param {Stock} stock - Stock to sell * @param {Stock} stock - Stock to sell
* @param {number} shares - Number of shares to sell * @param {number} shares - Number of shares to sell
* @param {WorkerScript} workerScript - If this is being called through Netscript * @param {NetscriptContext} ctx - If this is being called through Netscript
* @param opts - Optional configuration for this function's behavior. See top of file * @param opts - Optional configuration for this function's behavior. See top of file
* @returns {boolean} true if successfully sells given amount OR max owned, false otherwise * @returns {boolean} true if successfully sells given amount OR max owned, false otherwise
*/ */
export function sellShort( export function sellShort(
stock: Stock, stock: Stock,
shares: number, shares: number,
workerScript: WorkerScript | null = null, ctx: NetscriptContext | null = null,
opts: IOptions = {}, opts: IOptions = {},
): boolean { ): boolean {
if (stock == null || isNaN(shares) || shares < 0) { if (stock == null || isNaN(shares) || shares < 0) {
if (workerScript) { if (ctx) {
workerScript.log("stock.sellShort", () => `Invalid arguments: stock='${stock}' shares='${shares}'`); helpers.log(ctx, () => `Invalid arguments: stock='${stock}' shares='${shares}'`);
} else if (!opts.suppressDialog) { } else if (!opts.suppressDialog) {
dialogBoxCreate( dialogBoxCreate(
"Failed to sell a short position in a stock. This is probably " + "Failed to sell a short position in a stock. This is probably " +
@ -351,9 +352,9 @@ export function sellShort(
const origCost = shares * stock.playerAvgShortPx; const origCost = shares * stock.playerAvgShortPx;
const totalGain = getSellTransactionGain(stock, shares, PositionTypes.Short); const totalGain = getSellTransactionGain(stock, shares, PositionTypes.Short);
if (totalGain == null || isNaN(totalGain) || origCost == null) { if (totalGain == null || isNaN(totalGain) || origCost == null) {
if (workerScript) { if (ctx) {
workerScript.log( helpers.log(
"stock.sellShort", ctx,
() => `Failed to sell short position in a stock. This is probably either due to invalid arguments, or a bug`, () => `Failed to sell short position in a stock. This is probably either due to invalid arguments, or a bug`,
); );
} else if (!opts.suppressDialog) { } else if (!opts.suppressDialog) {
@ -369,8 +370,8 @@ export function sellShort(
profit = 0; profit = 0;
} }
Player.gainMoney(totalGain, "stock"); Player.gainMoney(totalGain, "stock");
if (workerScript) { if (ctx) {
workerScript.scriptRef.onlineMoneyMade += profit; ctx.workerScript.scriptRef.onlineMoneyMade += profit;
Player.scriptProdSinceLastAug += profit; Player.scriptProdSinceLastAug += profit;
} }
@ -384,11 +385,11 @@ export function sellShort(
opts.rerenderFn(); opts.rerenderFn();
} }
if (workerScript) { if (ctx) {
const resultTxt = const resultTxt =
`Sold your short position of ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` + `Sold your short position of ${numeralWrapper.formatShares(shares)} shares of ${stock.symbol}. ` +
`After commissions, you gained a total of ${numeralWrapper.formatMoney(totalGain)}`; `After commissions, you gained a total of ${numeralWrapper.formatMoney(totalGain)}`;
workerScript.log("stock.sellShort", () => resultTxt); helpers.log(ctx, () => resultTxt);
} else if (!opts.suppressDialog) { } else if (!opts.suppressDialog) {
dialogBoxCreate( dialogBoxCreate(
<> <>

@ -10,7 +10,6 @@ import { PositionTypes } from "./data/PositionTypes";
import { StockSymbols } from "./data/StockSymbols"; import { StockSymbols } from "./data/StockSymbols";
import { CONSTANTS } from "../Constants"; import { CONSTANTS } from "../Constants";
import { WorkerScript } from "../Netscript/WorkerScript";
import { IMap } from "../types"; import { IMap } from "../types";
import { EventEmitter } from "../utils/EventEmitter"; import { EventEmitter } from "../utils/EventEmitter";
@ -18,6 +17,8 @@ import { numeralWrapper } from "../ui/numeralFormat";
import { dialogBoxCreate } from "../ui/React/DialogBox"; import { dialogBoxCreate } from "../ui/React/DialogBox";
import { Reviver } from "../utils/JSONReviver"; import { Reviver } from "../utils/JSONReviver";
import { NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export let StockMarket: IStockMarket = { export let StockMarket: IStockMarket = {
lastUpdate: 0, lastUpdate: 0,
@ -33,19 +34,19 @@ export function placeOrder(
price: number, price: number,
type: OrderTypes, type: OrderTypes,
position: PositionTypes, position: PositionTypes,
workerScript: WorkerScript | null = null, ctx: NetscriptContext | null = null,
): boolean { ): boolean {
if (!(stock instanceof Stock)) { if (!(stock instanceof Stock)) {
if (workerScript) { if (ctx) {
workerScript.log("stock.placeOrder", () => `Invalid stock: '${stock}'`); helpers.log(ctx, () => `Invalid stock: '${stock}'`);
} else { } else {
dialogBoxCreate(`ERROR: Invalid stock passed to placeOrder() function`); dialogBoxCreate(`ERROR: Invalid stock passed to placeOrder() function`);
} }
return false; return false;
} }
if (typeof shares !== "number" || typeof price !== "number") { if (typeof shares !== "number" || typeof price !== "number") {
if (workerScript) { if (ctx) {
workerScript.log("stock.placeOrder", () => `Invalid arguments: shares='${shares}' price='${price}'`); helpers.log(ctx, () => `Invalid arguments: shares='${shares}' price='${price}'`);
} else { } else {
dialogBoxCreate("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); dialogBoxCreate("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument");
} }
@ -85,7 +86,7 @@ export interface ICancelOrderParams {
stock?: Stock; stock?: Stock;
type?: OrderTypes; type?: OrderTypes;
} }
export function cancelOrder(params: ICancelOrderParams, workerScript: WorkerScript | null = null): boolean { export function cancelOrder(params: ICancelOrderParams, ctx: NetscriptContext | null = null): boolean {
if (StockMarket["Orders"] == null) { if (StockMarket["Orders"] == null) {
return false; return false;
} }
@ -120,14 +121,14 @@ export function cancelOrder(params: ICancelOrderParams, workerScript: WorkerScri
params.pos === order.pos params.pos === order.pos
) { ) {
stockOrders.splice(i, 1); stockOrders.splice(i, 1);
if (workerScript) { if (ctx) {
workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); helpers.log(ctx, ()=>"Successfully cancelled order: " + orderTxt);
} }
return true; return true;
} }
} }
if (workerScript) { if (ctx) {
workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); helpers.log(ctx, ()=>"Failed to cancel order: " + orderTxt);
} }
return false; return false;
} }