Merge pull request #3748 from danielyxie/api-wrap

MISC: API Wrapping blocked
This commit is contained in:
hydroflame 2022-05-24 20:19:52 -04:00 committed by GitHub
commit 467e307c05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 2200 additions and 2080 deletions

@ -9,15 +9,16 @@ import { Settings } from "../Settings/Settings";
import { CONSTANTS } from "../Constants"; import { CONSTANTS } from "../Constants";
type ExternalFunction = (...args: any[]) => any; type ExternalFunction = (...args: any[]) => any;
type ExternalAPI = { export type ExternalAPI = {
[string: string]: ExternalAPI | ExternalFunction; [string: string]: ExternalAPI | ExternalFunction;
}; };
type InternalFunction<F extends (...args: unknown[]) => unknown> = (ctx: NetscriptContext) => F; type InternalFunction<F extends (...args: unknown[]) => unknown> = (ctx: NetscriptContext) => F;
export type InternalAPI<API> = { export type InternalAPI<API> = {
[Property in keyof API]: API[Property] extends ExternalFunction [Property in keyof API]: API[Property] extends ExternalFunction
? InternalFunction<API[Property]> ? InternalFunction<API[Property]>
: API[Property] extends ExternalAPI : API[Property] extends object
? InternalAPI<API[Property]> ? InternalAPI<API[Property]>
: never; : never;
}; };
@ -42,9 +43,14 @@ type NetscriptHelpers = {
number: (funcName: string, argName: string, v: unknown) => number; number: (funcName: string, argName: string, v: unknown) => number;
city: (funcName: string, argName: string, v: unknown) => CityName; city: (funcName: string, argName: string, v: unknown) => CityName;
boolean: (v: unknown) => boolean; boolean: (v: unknown) => boolean;
getServer: (hostname: string, callingFnName: string) => BaseServer; getServer: (hostname: string, ctx: NetscriptContext) => BaseServer;
checkSingularityAccess: (func: string) => void; checkSingularityAccess: (func: string) => void;
hack: (hostname: any, manual: any, { threads: requestedThreads, stock }?: any) => Promise<number>; hack: (
ctx: NetscriptContext,
hostname: any,
manual: any,
{ threads: requestedThreads, stock }?: any,
) => Promise<number>;
getValidPort: (funcName: string, port: any) => IPort; getValidPort: (funcName: string, port: any) => IPort;
}; };
@ -87,7 +93,7 @@ function wrapFunction(
number: (argName: string, v: unknown) => helpers.number(functionPath, argName, v), number: (argName: string, v: unknown) => helpers.number(functionPath, argName, v),
city: (argName: string, v: unknown) => helpers.city(functionPath, argName, v), city: (argName: string, v: unknown) => helpers.city(functionPath, argName, v),
boolean: helpers.boolean, boolean: helpers.boolean,
getServer: (hostname: string) => helpers.getServer(hostname, functionPath), getServer: (hostname: string) => helpers.getServer(hostname, ctx),
checkSingularityAccess: () => helpers.checkSingularityAccess(functionName), checkSingularityAccess: () => helpers.checkSingularityAccess(functionName),
hack: helpers.hack, hack: helpers.hack,
getValidPort: (port: any) => helpers.getValidPort(functionPath, port), getValidPort: (port: any) => helpers.getValidPort(functionPath, port),

@ -1,6 +1,18 @@
import { IPlayer } from "src/PersonObjects/IPlayer"; import { IPlayer } from "src/PersonObjects/IPlayer";
import { IMap } from "../types"; import { IMap } from "../types";
import { NS as INS } from "../ScriptEditor/NetscriptDefinitions";
import { INetscriptExtra } from "../NetscriptFunctions/Extra";
type RamCostTree<API> = {
[Property in keyof API]: API[Property] extends () => void
? number | ((p: IPlayer) => void)
: API[Property] extends object
? RamCostTree<API[Property]>
: never;
};
// TODO remember to update RamCalculations.js and WorkerScript.js // TODO remember to update RamCalculations.js and WorkerScript.js
// RAM costs for Netscript functions // RAM costs for Netscript functions
@ -89,7 +101,7 @@ function SF4Cost(cost: number): (player: IPlayer) => number {
} }
// Hacknet API // Hacknet API
const hacknet: IMap<any> = { const hacknet = {
numNodes: 0, numNodes: 0,
purchaseNode: 0, purchaseNode: 0,
getPurchaseNodeCost: 0, getPurchaseNodeCost: 0,
@ -106,10 +118,15 @@ const hacknet: IMap<any> = {
hashCost: 0, hashCost: 0,
spendHashes: 0, spendHashes: 0,
maxNumNodes: 0, maxNumNodes: 0,
hashCapacity: 0,
getHashUpgrades: 0,
getHashUpgradeLevel: 0,
getStudyMult: 0,
getTrainingMult: 0,
}; };
// Stock API // Stock API
const stock: IMap<any> = { const stock = {
getSymbols: RamCostConstants.ScriptGetStockRamCost, getSymbols: RamCostConstants.ScriptGetStockRamCost,
getPrice: RamCostConstants.ScriptGetStockRamCost, getPrice: RamCostConstants.ScriptGetStockRamCost,
getAskPrice: RamCostConstants.ScriptGetStockRamCost, getAskPrice: RamCostConstants.ScriptGetStockRamCost,
@ -134,7 +151,7 @@ const stock: IMap<any> = {
}; };
// Singularity API // Singularity API
const singularity: IMap<any> = { const singularity = {
universityCourse: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost), universityCourse: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost),
gymWorkout: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost), gymWorkout: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost),
travelToCity: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost), travelToCity: SF4Cost(RamCostConstants.ScriptSingularityFn1RamCost),
@ -190,7 +207,7 @@ const singularity: IMap<any> = {
}; };
// Gang API // Gang API
const gang: IMap<any> = { const gang = {
createGang: RamCostConstants.ScriptGangApiBaseRamCost / 4, createGang: RamCostConstants.ScriptGangApiBaseRamCost / 4,
inGang: RamCostConstants.ScriptGangApiBaseRamCost / 4, inGang: RamCostConstants.ScriptGangApiBaseRamCost / 4,
getMemberNames: RamCostConstants.ScriptGangApiBaseRamCost / 4, getMemberNames: RamCostConstants.ScriptGangApiBaseRamCost / 4,
@ -215,7 +232,7 @@ const gang: IMap<any> = {
}; };
// Bladeburner API // Bladeburner API
const bladeburner: IMap<any> = { const bladeburner = {
getContractNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10, getContractNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getOperationNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10, getOperationNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
getBlackOpNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10, getBlackOpNames: RamCostConstants.ScriptBladeburnerApiBaseRamCost / 10,
@ -253,15 +270,13 @@ const bladeburner: IMap<any> = {
getBonusTime: 0, getBonusTime: 0,
}; };
const infiltration: IMap<any> = { const infiltration = {
calculateDifficulty: RamCostConstants.ScriptInfiltrationCalculateDifficulty, getPossibleLocations: RamCostConstants.ScriptInfiltrationGetLocations,
calculateRewards: RamCostConstants.ScriptInfiltrationCalculateRewards, getInfiltration: RamCostConstants.ScriptInfiltrationGetInfiltrations,
calculateGetLocations: RamCostConstants.ScriptInfiltrationGetLocations,
calculateGetInfiltrations: RamCostConstants.ScriptInfiltrationGetInfiltrations,
}; };
// Coding Contract API // Coding Contract API
const codingcontract: IMap<any> = { const codingcontract = {
attempt: RamCostConstants.ScriptCodingContractBaseRamCost, attempt: RamCostConstants.ScriptCodingContractBaseRamCost,
getContractType: RamCostConstants.ScriptCodingContractBaseRamCost / 2, getContractType: RamCostConstants.ScriptCodingContractBaseRamCost / 2,
getData: RamCostConstants.ScriptCodingContractBaseRamCost / 2, getData: RamCostConstants.ScriptCodingContractBaseRamCost / 2,
@ -270,7 +285,7 @@ const codingcontract: IMap<any> = {
}; };
// Duplicate Sleeve API // Duplicate Sleeve API
const sleeve: IMap<any> = { const sleeve = {
getNumSleeves: RamCostConstants.ScriptSleeveBaseRamCost, getNumSleeves: RamCostConstants.ScriptSleeveBaseRamCost,
setToShockRecovery: RamCostConstants.ScriptSleeveBaseRamCost, setToShockRecovery: RamCostConstants.ScriptSleeveBaseRamCost,
setToSynchronize: RamCostConstants.ScriptSleeveBaseRamCost, setToSynchronize: RamCostConstants.ScriptSleeveBaseRamCost,
@ -290,7 +305,7 @@ const sleeve: IMap<any> = {
}; };
// Stanek API // Stanek API
const stanek: IMap<any> = { const stanek = {
giftWidth: RamCostConstants.ScriptStanekWidth, giftWidth: RamCostConstants.ScriptStanekWidth,
giftHeight: RamCostConstants.ScriptStanekHeight, giftHeight: RamCostConstants.ScriptStanekHeight,
chargeFragment: RamCostConstants.ScriptStanekCharge, chargeFragment: RamCostConstants.ScriptStanekCharge,
@ -305,7 +320,7 @@ const stanek: IMap<any> = {
}; };
// UI API // UI API
const ui: IMap<any> = { const ui = {
getTheme: 0, getTheme: 0,
setTheme: 0, setTheme: 0,
resetTheme: 0, resetTheme: 0,
@ -313,17 +328,84 @@ const ui: IMap<any> = {
setStyles: 0, setStyles: 0,
resetStyles: 0, resetStyles: 0,
getGameInfo: 0, getGameInfo: 0,
clearTerminal: 0,
}; };
// Grafting API // Grafting API
const grafting: IMap<any> = { const grafting = {
getAugmentationGraftPrice: 3.75, getAugmentationGraftPrice: 3.75,
getAugmentationGraftTime: 3.75, getAugmentationGraftTime: 3.75,
getGraftableAugmentations: 5, getGraftableAugmentations: 5,
graftAugmentation: 7.5, graftAugmentation: 7.5,
}; };
export const RamCosts: IMap<any> = { const corporation = {
createCorporation: 0,
hasUnlockUpgrade: 0,
getUnlockUpgradeCost: 0,
getUpgradeLevel: 0,
getUpgradeLevelCost: 0,
getExpandIndustryCost: 0,
getExpandCityCost: 0,
getInvestmentOffer: 0,
acceptInvestmentOffer: 0,
goPublic: 0,
bribe: 0,
getCorporation: 0,
getDivision: 0,
expandIndustry: 0,
expandCity: 0,
unlockUpgrade: 0,
levelUpgrade: 0,
issueDividends: 0,
buyBackShares: 0,
sellShares: 0,
getBonusTime: 0,
sellMaterial: 0,
sellProduct: 0,
discontinueProduct: 0,
setSmartSupply: 0,
setSmartSupplyUseLeftovers: 0,
buyMaterial: 0,
bulkPurchase: 0,
getWarehouse: 0,
getProduct: 0,
getMaterial: 0,
setMaterialMarketTA1: 0,
setMaterialMarketTA2: 0,
setProductMarketTA1: 0,
setProductMarketTA2: 0,
exportMaterial: 0,
cancelExportMaterial: 0,
purchaseWarehouse: 0,
upgradeWarehouse: 0,
makeProduct: 0,
limitMaterialProduction: 0,
limitProductProduction: 0,
getPurchaseWarehouseCost: 0,
getUpgradeWarehouseCost: 0,
hasWarehouse: 0,
assignJob: 0,
hireEmployee: 0,
upgradeOfficeSize: 0,
throwParty: 0,
buyCoffee: 0,
hireAdVert: 0,
research: 0,
getOffice: 0,
getEmployee: 0,
getHireAdVertCost: 0,
getHireAdVertCount: 0,
getResearchCost: 0,
hasResearched: 0,
setAutoJobAssignment: 0,
getOfficeSizeUpgradeCost: 0,
};
const SourceRamCosts = {
args: undefined as unknown as never[], // special use case
enums: undefined as unknown as never,
corporation,
hacknet, hacknet,
stock, stock,
singularity, singularity,
@ -363,7 +445,6 @@ export const RamCosts: IMap<any> = {
enableLog: 0, enableLog: 0,
isLogEnabled: 0, isLogEnabled: 0,
getScriptLogs: 0, getScriptLogs: 0,
clearTerminal: RamCostConstants.ScriptClearTerminalCost,
nuke: RamCostConstants.ScriptPortProgramRamCost, nuke: RamCostConstants.ScriptPortProgramRamCost,
brutessh: RamCostConstants.ScriptPortProgramRamCost, brutessh: RamCostConstants.ScriptPortProgramRamCost,
ftpcrack: RamCostConstants.ScriptPortProgramRamCost, ftpcrack: RamCostConstants.ScriptPortProgramRamCost,
@ -382,7 +463,6 @@ export const RamCosts: IMap<any> = {
ps: RamCostConstants.ScriptScanRamCost, ps: RamCostConstants.ScriptScanRamCost,
getRecentScripts: RamCostConstants.ScriptRecentScriptsRamCost, getRecentScripts: RamCostConstants.ScriptRecentScriptsRamCost,
hasRootAccess: RamCostConstants.ScriptHasRootAccessRamCost, hasRootAccess: RamCostConstants.ScriptHasRootAccessRamCost,
getIp: RamCostConstants.ScriptGetHostnameRamCost,
getHostname: RamCostConstants.ScriptGetHostnameRamCost, getHostname: RamCostConstants.ScriptGetHostnameRamCost,
getHackingLevel: RamCostConstants.ScriptGetHackingLevelRamCost, getHackingLevel: RamCostConstants.ScriptGetHackingLevelRamCost,
getHackingMultipliers: RamCostConstants.ScriptGetMultipliersRamCost, getHackingMultipliers: RamCostConstants.ScriptGetMultipliersRamCost,
@ -439,12 +519,74 @@ export const RamCosts: IMap<any> = {
getOwnedSourceFiles: RamCostConstants.ScriptGetOwnedSourceFiles, getOwnedSourceFiles: RamCostConstants.ScriptGetOwnedSourceFiles,
tail: 0, tail: 0,
toast: 0, toast: 0,
closeTail: 0,
clearPort: 0,
openDevMenu: 0,
alert: 0,
flags: 0,
exploit: 0,
bypass: 0,
alterReality: 0,
rainbow: 0,
heart: { heart: {
// Easter egg function // Easter egg function
break: 0, break: 0,
}, },
formulas: {
reputation: {
calculateFavorToRep: 0,
calculateRepToFavor: 0,
repFromDonation: 0,
},
skills: {
calculateSkill: 0,
calculateExp: 0,
},
hacking: {
hackChance: 0,
hackExp: 0,
hackPercent: 0,
growPercent: 0,
hackTime: 0,
growTime: 0,
weakenTime: 0,
},
hacknetNodes: {
moneyGainRate: 0,
levelUpgradeCost: 0,
ramUpgradeCost: 0,
coreUpgradeCost: 0,
hacknetNodeCost: 0,
constants: 0,
},
hacknetServers: {
hashGainRate: 0,
levelUpgradeCost: 0,
ramUpgradeCost: 0,
coreUpgradeCost: 0,
cacheUpgradeCost: 0,
hashUpgradeCost: 0,
hacknetServerCost: 0,
constants: 0,
},
gang: {
wantedPenalty: 0,
respectGain: 0,
wantedLevelGain: 0,
moneyGain: 0,
ascensionPointsGain: 0,
ascensionMultiplier: 0,
},
},
}; };
export const RamCosts: IMap<any> = SourceRamCosts;
// This line in particular is there so typescript typechecks that we are not missing any static ram cost.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _typecheck: RamCostTree<INS & INetscriptExtra> = SourceRamCosts;
export function getRamCost(player: IPlayer, ...args: string[]): number { export function getRamCost(player: IPlayer, ...args: string[]): number {
if (args.length === 0) { if (args.length === 0) {
console.warn(`No arguments passed to getRamCost()`); console.warn(`No arguments passed to getRamCost()`);

@ -2,6 +2,7 @@ import { isString } from "./utils/helpers/isString";
import { GetServer } from "./Server/AllServers"; import { GetServer } from "./Server/AllServers";
import { ScriptDeath } from "./Netscript/ScriptDeath"; import { ScriptDeath } from "./Netscript/ScriptDeath";
import { WorkerScript } from "./Netscript/WorkerScript"; import { WorkerScript } from "./Netscript/WorkerScript";
import { NetscriptContext } from "./Netscript/APIWrapper";
export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> { export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> {
// Cancel any pre-existing netscriptDelay'ed function call // Cancel any pre-existing netscriptDelay'ed function call
@ -36,26 +37,22 @@ export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): s
return "|DELIMITER|" + server.hostname + "|DELIMITER|" + workerScript.name + "|DELIMITER|" + msg; return "|DELIMITER|" + server.hostname + "|DELIMITER|" + workerScript.name + "|DELIMITER|" + msg;
} }
export function resolveNetscriptRequestedThreads( export function resolveNetscriptRequestedThreads(ctx: NetscriptContext, requestedThreads: number): number {
workerScript: WorkerScript, const threads = ctx.workerScript.scriptRef.threads;
functionName: string,
requestedThreads: number,
): number {
const threads = workerScript.scriptRef.threads;
if (!requestedThreads) { if (!requestedThreads) {
return isNaN(threads) || threads < 1 ? 1 : threads; return isNaN(threads) || threads < 1 ? 1 : threads;
} }
const requestedThreadsAsInt = requestedThreads | 0; const requestedThreadsAsInt = requestedThreads | 0;
if (isNaN(requestedThreads) || requestedThreadsAsInt < 1) { if (isNaN(requestedThreads) || requestedThreadsAsInt < 1) {
throw makeRuntimeRejectMsg( throw makeRuntimeRejectMsg(
workerScript, ctx.workerScript,
`Invalid thread count passed to ${functionName}: ${requestedThreads}. Threads must be a positive number.`, `Invalid thread count passed to ${ctx.function}: ${requestedThreads}. Threads must be a positive number.`,
); );
} }
if (requestedThreadsAsInt > threads) { if (requestedThreadsAsInt > threads) {
throw makeRuntimeRejectMsg( throw makeRuntimeRejectMsg(
workerScript, ctx.workerScript,
`Too many threads requested by ${functionName}. Requested: ${requestedThreads}. Has: ${threads}.`, `Too many threads requested by ${ctx.function}. Requested: ${requestedThreads}. Has: ${threads}.`,
); );
} }
return requestedThreadsAsInt; return requestedThreadsAsInt;

File diff suppressed because it is too large Load Diff

@ -1,9 +1,8 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer"; import { IPlayer } from "../PersonObjects/IPlayer";
import { Exploit } from "../Exploits/Exploit"; import { Exploit } from "../Exploits/Exploit";
import * as bcrypt from "bcryptjs"; import * as bcrypt from "bcryptjs";
import { INetscriptHelper } from "./INetscriptHelper";
import { Apr1Events as devMenu } from "../ui/Apr1"; import { Apr1Events as devMenu } from "../ui/Apr1";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
export interface INetscriptExtra { export interface INetscriptExtra {
heart: { heart: {
@ -16,35 +15,37 @@ export interface INetscriptExtra {
rainbow(guess: string): void; rainbow(guess: string): void;
} }
export function NetscriptExtra(player: IPlayer, workerScript: WorkerScript, helper: INetscriptHelper): INetscriptExtra { export function NetscriptExtra(player: IPlayer): InternalAPI<INetscriptExtra> {
return { return {
heart: { heart: {
// Easter egg function // Easter egg function
break: function (): number { break: () => (): number => {
return player.karma; return player.karma;
}, },
}, },
openDevMenu: function (): void { openDevMenu: () => (): void => {
devMenu.emit(); devMenu.emit();
}, },
exploit: function (): void { exploit: () => (): void => {
player.giveExploit(Exploit.UndocumentedFunctionCall); player.giveExploit(Exploit.UndocumentedFunctionCall);
}, },
bypass: function (doc: unknown): void { bypass:
// reset both fields first (ctx: NetscriptContext) =>
const d = doc as any; (doc: unknown): void => {
d.completely_unused_field = undefined; // reset both fields first
const real_document: any = document; const d = doc as any;
real_document.completely_unused_field = undefined; d.completely_unused_field = undefined;
// set one to true and check that it affected the other. const real_document: any = document;
real_document.completely_unused_field = true; real_document.completely_unused_field = undefined;
if (d.completely_unused_field && workerScript.ramUsage === 1.6) { // set one to true and check that it affected the other.
player.giveExploit(Exploit.Bypass); real_document.completely_unused_field = true;
} if (d.completely_unused_field && ctx.workerScript.ramUsage === 1.6) {
d.completely_unused_field = undefined; player.giveExploit(Exploit.Bypass);
real_document.completely_unused_field = undefined; }
}, d.completely_unused_field = undefined;
alterReality: function (): void { real_document.completely_unused_field = undefined;
},
alterReality: () => (): void => {
// We need to trick webpack into not optimizing a variable that is guaranteed to be false (and doesn't use prototypes) // We need to trick webpack into not optimizing a variable that is guaranteed to be false (and doesn't use prototypes)
let x = false; let x = false;
const recur = function (depth: number): void { const recur = function (depth: number): void {
@ -59,20 +60,22 @@ export function NetscriptExtra(player: IPlayer, workerScript: WorkerScript, help
player.giveExploit(Exploit.RealityAlteration); player.giveExploit(Exploit.RealityAlteration);
} }
}, },
rainbow: function (guess: unknown): boolean { rainbow:
function tryGuess(): boolean { (ctx: NetscriptContext) =>
// eslint-disable-next-line no-sync (guess: unknown): boolean => {
const verified = bcrypt.compareSync( function tryGuess(): boolean {
helper.string("rainbow", "guess", guess), // eslint-disable-next-line no-sync
"$2a$10$aertxDEkgor8baVtQDZsLuMwwGYmkRM/ohcA6FjmmzIHQeTCsrCcO", const verified = bcrypt.compareSync(
); ctx.helper.string("guess", guess),
if (verified) { "$2a$10$aertxDEkgor8baVtQDZsLuMwwGYmkRM/ohcA6FjmmzIHQeTCsrCcO",
player.giveExploit(Exploit.INeedARainbow); );
return true; if (verified) {
player.giveExploit(Exploit.INeedARainbow);
return true;
}
return false;
} }
return false; return tryGuess();
} },
return tryGuess();
},
}; };
} }

@ -39,212 +39,267 @@ import {
} from "../Gang/formulas/formulas"; } from "../Gang/formulas/formulas";
import { favorToRep as calculateFavorToRep, repToFavor as calculateRepToFavor } from "../Faction/formulas/favor"; import { favorToRep as calculateFavorToRep, repToFavor as calculateRepToFavor } from "../Faction/formulas/favor";
import { repFromDonation } from "../Faction/formulas/donation"; import { repFromDonation } from "../Faction/formulas/donation";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
export function NetscriptFormulas(player: IPlayer, workerScript: WorkerScript, helper: INetscriptHelper): IFormulas { export function NetscriptFormulas(player: IPlayer, helper: INetscriptHelper): InternalAPI<IFormulas> {
const checkFormulasAccess = function (func: string): void { const checkFormulasAccess = function (ctx: NetscriptContext): void {
if (!player.hasProgram(Programs.Formulas.name)) { if (!player.hasProgram(Programs.Formulas.name)) {
throw helper.makeRuntimeErrorMsg(`formulas.${func}`, `Requires Formulas.exe to run.`); throw helper.makeRuntimeErrorMsg(`formulas.${ctx.function}`, `Requires Formulas.exe to run.`);
} }
}; };
return { return {
reputation: { reputation: {
calculateFavorToRep: function (_favor: unknown): number { calculateFavorToRep:
const favor = helper.number("calculateFavorToRep", "favor", _favor); (ctx: NetscriptContext) =>
checkFormulasAccess("reputation.calculateFavorToRep"); (_favor: unknown): number => {
return calculateFavorToRep(favor); const favor = ctx.helper.number("favor", _favor);
}, checkFormulasAccess(ctx);
calculateRepToFavor: function (_rep: unknown): number { return calculateFavorToRep(favor);
const rep = helper.number("calculateRepToFavor", "rep", _rep); },
checkFormulasAccess("reputation.calculateRepToFavor"); calculateRepToFavor:
return calculateRepToFavor(rep); (ctx: NetscriptContext) =>
}, (_rep: unknown): number => {
repFromDonation: function (_amount: unknown, player: any): number { const rep = ctx.helper.number("rep", _rep);
const amount = helper.number("repFromDonation", "amount", _amount); checkFormulasAccess(ctx);
checkFormulasAccess("reputation.repFromDonation"); return calculateRepToFavor(rep);
return repFromDonation(amount, player); },
}, repFromDonation:
(ctx: NetscriptContext) =>
(_amount: unknown, player: any): number => {
const amount = ctx.helper.number("amount", _amount);
checkFormulasAccess(ctx);
return repFromDonation(amount, player);
},
}, },
skills: { skills: {
calculateSkill: function (_exp: unknown, _mult: unknown = 1): number { calculateSkill:
const exp = helper.number("calculateSkill", "exp", _exp); (ctx: NetscriptContext) =>
const mult = helper.number("calculateSkill", "mult", _mult); (_exp: unknown, _mult: unknown = 1): number => {
checkFormulasAccess("skills.calculateSkill"); const exp = ctx.helper.number("exp", _exp);
return calculateSkill(exp, mult); const mult = ctx.helper.number("mult", _mult);
}, checkFormulasAccess(ctx);
calculateExp: function (_skill: unknown, _mult: unknown = 1): number { return calculateSkill(exp, mult);
const skill = helper.number("calculateExp", "skill", _skill); },
const mult = helper.number("calculateExp", "mult", _mult); calculateExp:
checkFormulasAccess("skills.calculateExp"); (ctx: NetscriptContext) =>
return calculateExp(skill, mult); (_skill: unknown, _mult: unknown = 1): number => {
}, const skill = ctx.helper.number("skill", _skill);
const mult = ctx.helper.number("mult", _mult);
checkFormulasAccess(ctx);
return calculateExp(skill, mult);
},
}, },
hacking: { hacking: {
hackChance: function (server: any, player: any): number { hackChance:
checkFormulasAccess("hacking.hackChance"); (ctx: NetscriptContext) =>
return calculateHackingChance(server, player); (server: any, player: any): number => {
}, checkFormulasAccess(ctx);
hackExp: function (server: any, player: any): number { return calculateHackingChance(server, player);
checkFormulasAccess("hacking.hackExp"); },
return calculateHackingExpGain(server, player); hackExp:
}, (ctx: NetscriptContext) =>
hackPercent: function (server: any, player: any): number { (server: any, player: any): number => {
checkFormulasAccess("hacking.hackPercent"); checkFormulasAccess(ctx);
return calculatePercentMoneyHacked(server, player); return calculateHackingExpGain(server, player);
}, },
growPercent: function (server: any, _threads: unknown, player: any, _cores: unknown = 1): number { hackPercent:
const threads = helper.number("growPercent", "threads", _threads); (ctx: NetscriptContext) =>
const cores = helper.number("growPercent", "cores", _cores); (server: any, player: any): number => {
checkFormulasAccess("hacking.growPercent"); checkFormulasAccess(ctx);
return calculateServerGrowth(server, threads, player, cores); return calculatePercentMoneyHacked(server, player);
}, },
hackTime: function (server: any, player: any): number { growPercent:
checkFormulasAccess("hacking.hackTime"); (ctx: NetscriptContext) =>
return calculateHackingTime(server, player) * 1000; (server: any, _threads: unknown, player: any, _cores: unknown = 1): number => {
}, const threads = ctx.helper.number("threads", _threads);
growTime: function (server: any, player: any): number { const cores = ctx.helper.number("cores", _cores);
checkFormulasAccess("hacking.growTime"); checkFormulasAccess(ctx);
return calculateGrowTime(server, player) * 1000; return calculateServerGrowth(server, threads, player, cores);
}, },
weakenTime: function (server: any, player: any): number { hackTime:
checkFormulasAccess("hacking.weakenTime"); (ctx: NetscriptContext) =>
return calculateWeakenTime(server, player) * 1000; (server: any, player: any): number => {
}, checkFormulasAccess(ctx);
return calculateHackingTime(server, player) * 1000;
},
growTime:
(ctx: NetscriptContext) =>
(server: any, player: any): number => {
checkFormulasAccess(ctx);
return calculateGrowTime(server, player) * 1000;
},
weakenTime:
(ctx: NetscriptContext) =>
(server: any, player: any): number => {
checkFormulasAccess(ctx);
return calculateWeakenTime(server, player) * 1000;
},
}, },
hacknetNodes: { hacknetNodes: {
moneyGainRate: function (_level: unknown, _ram: unknown, _cores: unknown, _mult: unknown = 1): number { moneyGainRate:
const level = helper.number("moneyGainRate", "level", _level); (ctx: NetscriptContext) =>
const ram = helper.number("moneyGainRate", "ram", _ram); (_level: unknown, _ram: unknown, _cores: unknown, _mult: unknown = 1): number => {
const cores = helper.number("moneyGainRate", "cores", _cores); const level = ctx.helper.number("level", _level);
const mult = helper.number("moneyGainRate", "mult", _mult); const ram = ctx.helper.number("ram", _ram);
checkFormulasAccess("hacknetNodes.moneyGainRate"); const cores = ctx.helper.number("cores", _cores);
return calculateMoneyGainRate(level, ram, cores, mult); const mult = ctx.helper.number("mult", _mult);
}, checkFormulasAccess(ctx);
levelUpgradeCost: function (_startingLevel: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number { return calculateMoneyGainRate(level, ram, cores, mult);
const startingLevel = helper.number("levelUpgradeCost", "startingLevel", _startingLevel); },
const extraLevels = helper.number("levelUpgradeCost", "extraLevels", _extraLevels); levelUpgradeCost:
const costMult = helper.number("levelUpgradeCost", "costMult", _costMult); (ctx: NetscriptContext) =>
checkFormulasAccess("hacknetNodes.levelUpgradeCost"); (_startingLevel: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number => {
return calculateLevelUpgradeCost(startingLevel, extraLevels, costMult); const startingLevel = ctx.helper.number("startingLevel", _startingLevel);
}, const extraLevels = ctx.helper.number("extraLevels", _extraLevels);
ramUpgradeCost: function (_startingRam: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number { const costMult = ctx.helper.number("costMult", _costMult);
const startingRam = helper.number("ramUpgradeCost", "startingRam", _startingRam); checkFormulasAccess(ctx);
const extraLevels = helper.number("ramUpgradeCost", "extraLevels", _extraLevels); return calculateLevelUpgradeCost(startingLevel, extraLevels, costMult);
const costMult = helper.number("ramUpgradeCost", "costMult", _costMult); },
checkFormulasAccess("hacknetNodes.ramUpgradeCost"); ramUpgradeCost:
return calculateRamUpgradeCost(startingRam, extraLevels, costMult); (ctx: NetscriptContext) =>
}, (_startingRam: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number => {
coreUpgradeCost: function (_startingCore: unknown, _extraCores: unknown = 1, _costMult: unknown = 1): number { const startingRam = ctx.helper.number("startingRam", _startingRam);
const startingCore = helper.number("coreUpgradeCost", "startingCore", _startingCore); const extraLevels = ctx.helper.number("extraLevels", _extraLevels);
const extraCores = helper.number("coreUpgradeCost", "extraCores", _extraCores); const costMult = ctx.helper.number("costMult", _costMult);
const costMult = helper.number("coreUpgradeCost", "costMult", _costMult); checkFormulasAccess(ctx);
checkFormulasAccess("hacknetNodes.coreUpgradeCost"); return calculateRamUpgradeCost(startingRam, extraLevels, costMult);
return calculateCoreUpgradeCost(startingCore, extraCores, costMult); },
}, coreUpgradeCost:
hacknetNodeCost: function (_n: unknown, _mult: unknown): number { (ctx: NetscriptContext) =>
const n = helper.number("hacknetNodeCost", "n", _n); (_startingCore: unknown, _extraCores: unknown = 1, _costMult: unknown = 1): number => {
const mult = helper.number("hacknetNodeCost", "mult", _mult); const startingCore = ctx.helper.number("startingCore", _startingCore);
checkFormulasAccess("hacknetNodes.hacknetNodeCost"); const extraCores = ctx.helper.number("extraCores", _extraCores);
return calculateNodeCost(n, mult); const costMult = ctx.helper.number("costMult", _costMult);
}, checkFormulasAccess(ctx);
constants: function (): any { return calculateCoreUpgradeCost(startingCore, extraCores, costMult);
checkFormulasAccess("hacknetNodes.constants"); },
hacknetNodeCost:
(ctx: NetscriptContext) =>
(_n: unknown, _mult: unknown): number => {
const n = ctx.helper.number("n", _n);
const mult = ctx.helper.number("mult", _mult);
checkFormulasAccess(ctx);
return calculateNodeCost(n, mult);
},
constants: (ctx: NetscriptContext) => (): any => {
checkFormulasAccess(ctx);
return Object.assign({}, HacknetNodeConstants); return Object.assign({}, HacknetNodeConstants);
}, },
}, },
hacknetServers: { hacknetServers: {
hashGainRate: function ( hashGainRate:
_level: unknown, (ctx: NetscriptContext) =>
_ramUsed: unknown, (_level: unknown, _ramUsed: unknown, _maxRam: unknown, _cores: unknown, _mult: unknown = 1): number => {
_maxRam: unknown, const level = ctx.helper.number("level", _level);
_cores: unknown, const ramUsed = ctx.helper.number("ramUsed", _ramUsed);
_mult: unknown = 1, const maxRam = ctx.helper.number("maxRam", _maxRam);
): number { const cores = ctx.helper.number("cores", _cores);
const level = helper.number("hashGainRate", "level", _level); const mult = ctx.helper.number("mult", _mult);
const ramUsed = helper.number("hashGainRate", "ramUsed", _ramUsed); checkFormulasAccess(ctx);
const maxRam = helper.number("hashGainRate", "maxRam", _maxRam); return HScalculateHashGainRate(level, ramUsed, maxRam, cores, mult);
const cores = helper.number("hashGainRate", "cores", _cores); },
const mult = helper.number("hashGainRate", "mult", _mult); levelUpgradeCost:
checkFormulasAccess("hacknetServers.hashGainRate"); (ctx: NetscriptContext) =>
return HScalculateHashGainRate(level, ramUsed, maxRam, cores, mult); (_startingLevel: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number => {
}, const startingLevel = ctx.helper.number("startingLevel", _startingLevel);
levelUpgradeCost: function (_startingLevel: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number { const extraLevels = ctx.helper.number("extraLevels", _extraLevels);
const startingLevel = helper.number("levelUpgradeCost", "startingLevel", _startingLevel); const costMult = ctx.helper.number("costMult", _costMult);
const extraLevels = helper.number("levelUpgradeCost", "extraLevels", _extraLevels); checkFormulasAccess(ctx);
const costMult = helper.number("levelUpgradeCost", "costMult", _costMult); return HScalculateLevelUpgradeCost(startingLevel, extraLevels, costMult);
checkFormulasAccess("hacknetServers.levelUpgradeCost"); },
return HScalculateLevelUpgradeCost(startingLevel, extraLevels, costMult); ramUpgradeCost:
}, (ctx: NetscriptContext) =>
ramUpgradeCost: function (_startingRam: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number { (_startingRam: unknown, _extraLevels: unknown = 1, _costMult: unknown = 1): number => {
const startingRam = helper.number("ramUpgradeCost", "startingRam", _startingRam); const startingRam = ctx.helper.number("startingRam", _startingRam);
const extraLevels = helper.number("ramUpgradeCost", "extraLevels", _extraLevels); const extraLevels = ctx.helper.number("extraLevels", _extraLevels);
const costMult = helper.number("ramUpgradeCost", "costMult", _costMult); const costMult = ctx.helper.number("costMult", _costMult);
checkFormulasAccess("hacknetServers.ramUpgradeCost"); checkFormulasAccess(ctx);
return HScalculateRamUpgradeCost(startingRam, extraLevels, costMult); return HScalculateRamUpgradeCost(startingRam, extraLevels, costMult);
}, },
coreUpgradeCost: function (_startingCore: unknown, _extraCores: unknown = 1, _costMult: unknown = 1): number { coreUpgradeCost:
const startingCore = helper.number("coreUpgradeCost", "startingCore", _startingCore); (ctx: NetscriptContext) =>
const extraCores = helper.number("coreUpgradeCost", "extraCores", _extraCores); (_startingCore: unknown, _extraCores: unknown = 1, _costMult: unknown = 1): number => {
const costMult = helper.number("coreUpgradeCost", "costMult", _costMult); const startingCore = ctx.helper.number("startingCore", _startingCore);
checkFormulasAccess("hacknetServers.coreUpgradeCost"); const extraCores = ctx.helper.number("extraCores", _extraCores);
return HScalculateCoreUpgradeCost(startingCore, extraCores, costMult); const costMult = ctx.helper.number("costMult", _costMult);
}, checkFormulasAccess(ctx);
cacheUpgradeCost: function (_startingCache: unknown, _extraCache: unknown = 1): number { return HScalculateCoreUpgradeCost(startingCore, extraCores, costMult);
const startingCache = helper.number("cacheUpgradeCost", "startingCache", _startingCache); },
const extraCache = helper.number("cacheUpgradeCost", "extraCache", _extraCache); cacheUpgradeCost:
checkFormulasAccess("hacknetServers.cacheUpgradeCost"); (ctx: NetscriptContext) =>
return HScalculateCacheUpgradeCost(startingCache, extraCache); (_startingCache: unknown, _extraCache: unknown = 1): number => {
}, const startingCache = ctx.helper.number("startingCache", _startingCache);
hashUpgradeCost: function (_upgName: unknown, _level: unknown): number { const extraCache = ctx.helper.number("extraCache", _extraCache);
const upgName = helper.string("hashUpgradeCost", "upgName", _upgName); checkFormulasAccess(ctx);
const level = helper.number("hashUpgradeCost", "level", _level); return HScalculateCacheUpgradeCost(startingCache, extraCache);
checkFormulasAccess("hacknetServers.hashUpgradeCost"); },
const upg = player.hashManager.getUpgrade(upgName); hashUpgradeCost:
if (!upg) { (ctx: NetscriptContext) =>
throw helper.makeRuntimeErrorMsg( (_upgName: unknown, _level: unknown): number => {
"formulas.hacknetServers.calculateHashUpgradeCost", const upgName = helper.string("hashUpgradeCost", "upgName", _upgName);
`Invalid Hash Upgrade: ${upgName}`, const level = ctx.helper.number("level", _level);
); checkFormulasAccess(ctx);
} const upg = player.hashManager.getUpgrade(upgName);
return upg.getCost(level); if (!upg) {
}, throw helper.makeRuntimeErrorMsg(
hacknetServerCost: function (_n: unknown, _mult: unknown = 1): number { "formulas.hacknetServers.calculateHashUpgradeCost",
const n = helper.number("hacknetServerCost", "n", _n); `Invalid Hash Upgrade: ${upgName}`,
const mult = helper.number("hacknetServerCost", "mult", _mult); );
checkFormulasAccess("hacknetServers.hacknetServerCost"); }
return HScalculateServerCost(n, mult); return upg.getCost(level);
}, },
constants: function (): any { hacknetServerCost:
checkFormulasAccess("hacknetServers.constants"); (ctx: NetscriptContext) =>
(_n: unknown, _mult: unknown = 1): number => {
const n = ctx.helper.number("n", _n);
const mult = ctx.helper.number("mult", _mult);
checkFormulasAccess(ctx);
return HScalculateServerCost(n, mult);
},
constants: (ctx: NetscriptContext) => (): any => {
checkFormulasAccess(ctx);
return Object.assign({}, HacknetServerConstants); return Object.assign({}, HacknetServerConstants);
}, },
}, },
gang: { gang: {
wantedPenalty(gang: any): number { wantedPenalty:
checkFormulasAccess("gang.wantedPenalty"); (ctx: NetscriptContext) =>
return calculateWantedPenalty(gang); (gang: any): number => {
}, checkFormulasAccess(ctx);
respectGain: function (gang: any, member: any, task: any): number { return calculateWantedPenalty(gang);
checkFormulasAccess("gang.respectGain"); },
return calculateRespectGain(gang, member, task); respectGain:
}, (ctx: NetscriptContext) =>
wantedLevelGain: function (gang: any, member: any, task: any): number { (gang: any, member: any, task: any): number => {
checkFormulasAccess("gang.wantedLevelGain"); checkFormulasAccess(ctx);
return calculateWantedLevelGain(gang, member, task); return calculateRespectGain(gang, member, task);
}, },
moneyGain: function (gang: any, member: any, task: any): number { wantedLevelGain:
checkFormulasAccess("gang.moneyGain"); (ctx: NetscriptContext) =>
return calculateMoneyGain(gang, member, task); (gang: any, member: any, task: any): number => {
}, checkFormulasAccess(ctx);
ascensionPointsGain: function (_exp: unknown): number { return calculateWantedLevelGain(gang, member, task);
const exp = helper.number("ascensionPointsGain", "exp", _exp); },
checkFormulasAccess("gang.ascensionPointsGain"); moneyGain:
return calculateAscensionPointsGain(exp); (ctx: NetscriptContext) =>
}, (gang: any, member: any, task: any): number => {
ascensionMultiplier: function (_points: unknown): number { checkFormulasAccess(ctx);
const points = helper.number("ascensionMultiplier", "points", _points); return calculateMoneyGain(gang, member, task);
checkFormulasAccess("gang.ascensionMultiplier"); },
return calculateAscensionMult(points); ascensionPointsGain:
}, (ctx: NetscriptContext) =>
(_exp: unknown): number => {
const exp = ctx.helper.number("exp", _exp);
checkFormulasAccess(ctx);
return calculateAscensionPointsGain(exp);
},
ascensionMultiplier:
(ctx: NetscriptContext) =>
(_points: unknown): number => {
const points = ctx.helper.number("points", _points);
checkFormulasAccess(ctx);
return calculateAscensionMult(points);
},
}, },
}; };
} }

@ -1,4 +1,6 @@
import { CityName } from "src/Locations/data/CityNames"; import { CityName } from "src/Locations/data/CityNames";
import { NetscriptContext } from "src/Netscript/APIWrapper";
import { IPort } from "src/NetscriptPort";
import { BaseServer } from "../Server/BaseServer"; import { BaseServer } from "../Server/BaseServer";
export interface INetscriptHelper { export interface INetscriptHelper {
@ -8,7 +10,8 @@ export interface INetscriptHelper {
number(funcName: string, argName: string, v: unknown): number; number(funcName: string, argName: string, v: unknown): number;
city(funcName: string, argName: string, v: unknown): CityName; city(funcName: string, argName: string, v: unknown): CityName;
boolean(v: unknown): boolean; boolean(v: unknown): boolean;
getServer(ip: any, fn: any): BaseServer; getServer(ip: any, ctx: NetscriptContext): BaseServer;
checkSingularityAccess(func: string): void; checkSingularityAccess(func: string): void;
hack(hostname: string, manual: boolean): Promise<number>; hack(ctx: NetscriptContext, hostname: string, manual: boolean): Promise<number>;
getValidPort(funcName: string, port: number): IPort;
} }