How to use workerScript method in wpt

Best JavaScript code snippet using wpt

NetscriptFunctions.js

Source:NetscriptFunctions.js Github

copy

Full Screen

1var sprintf = require('sprintf-js').sprintf,2 vsprintf = require('sprintf-js').vsprintf3import {updateActiveScriptsItems} from "./ActiveScriptsUI";4import {Augmentations, Augmentation,5 augmentationExists, installAugmentations,6 AugmentationNames} from "./Augmentations";7import {BitNodeMultipliers} from "./BitNode";8import {determineCrimeSuccess, findCrime} from "./Crimes";9import {Bladeburner} from "./Bladeburner";10import {Companies, Company, CompanyPosition,11 CompanyPositions, companyExists} from "./Company";12import {CONSTANTS} from "./Constants";13import {Programs} from "./CreateProgram";14import {DarkWebItems} from "./DarkWeb";15import {Engine} from "./engine";16import {AllGangs} from "./Gang";17import {Factions, Faction, joinFaction,18 factionExists, purchaseAugmentation} from "./Faction";19import {getCostOfNextHacknetNode, purchaseHacknet} from "./HacknetNode";20import {Locations} from "./Location";21import {Message, Messages} from "./Message";22import {inMission} from "./Missions";23import {Player} from "./Player";24import {Script, findRunningScript, RunningScript,25 isScriptFilename} from "./Script";26import {Server, getServer, AddToAllServers,27 AllServers, processSingleServerGrowth,28 GetServerByHostname} from "./Server";29import {Settings} from "./Settings";30import {SpecialServerIps} from "./SpecialServerIps";31import {StockMarket, StockSymbols, SymbolToStockMap, initStockSymbols,32 initStockMarket, initSymbolToStockMap, stockMarketCycle, buyStock,33 sellStock, updateStockPrices, displayStockMarketContent,34 updateStockTicker, updateStockPlayerPosition,35 Stock, shortStock, sellShort, OrderTypes,36 PositionTypes, placeOrder, cancelOrder} from "./StockMarket";37import {post} from "./Terminal";38import {TextFile, getTextFile, createTextFile} from "./TextFile";39import {unknownBladeburnerActionErrorMessage,40 unknownBladeburnerExceptionMessage,41 checkBladeburnerAccess} from "./NetscriptBladeburner.js";42import {WorkerScript, workerScripts,43 killWorkerScript, NetscriptPorts} from "./NetscriptWorker";44import {makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript,45 scriptCalculateHackingChance, scriptCalculateHackingTime,46 scriptCalculateExpGain, scriptCalculatePercentMoneyHacked,47 scriptCalculateGrowTime, scriptCalculateWeakenTime} from "./NetscriptEvaluator";48import {NetscriptPort} from "./NetscriptPort";49import Decimal from "decimal.js";50import {dialogBoxCreate} from "../utils/DialogBox";51import {isPowerOfTwo} from "../utils/helpers/isPowerOfTwo";52import {arrayToString} from "../utils/helpers/arrayToString";53import {createRandomIp} from "../utils/IPAddress";54import {formatNumber, isHTML} from "../utils/StringHelperFunctions";55import {isString} from "../utils/helpers/isString";56import {yesNoBoxClose, yesNoBoxGetYesButton,57 yesNoBoxGetNoButton, yesNoBoxCreate,58 yesNoBoxOpen} from "../utils/YesNoBox";59var hasCorporationSF = false, //Source-File 360 hasSingularitySF = false, //Source-File 461 hasAISF = false, //Source-File 562 hasBladeburnerSF = false, //Source-File 663 hasBladeburner2079SF = false, //Source-File 764 hasWallStreetSF = false, //Source-File 865 hasBn11SF = false; //Source-File 1166var singularitySFLvl=1, wallStreetSFLvl=1;67var possibleLogs = {68 ALL: true,69 scan: true,70 hack: true,71 sleep: true,72 disableLog: true,73 enableLog: true,74 grow: true,75 weaken: true,76 nuke: true,77 brutessh: true,78 ftpcrack: true,79 relaysmtp: true,80 httpworm: true,81 sqlinject: true,82 run:true,83 exec:true,84 spawn: true,85 kill: true,86 killall: true,87 scp: true,88 getHackingLevel: true,89 getServerMoneyAvailable: true,90 getServerSecurityLevel: true,91 getServerBaseSecurityLevel: true,92 getServerMinSecurityLevel: true,93 getServerRequiredHackingLevel: true,94 getServerMaxMoney: true,95 getServerGrowth: true,96 getServerNumPortsRequired: true,97 getServerRam: true,98 buyStock: true,99 sellStock: true,100 purchaseServer: true,101 deleteServer: true,102 universityCourse: true,103 gymWorkout: true,104 travelToCity: true,105 purchaseTor: true,106 purchaseProgram: true,107 stopAction: true,108 upgradeHomeRam: true,109 workForCompany: true,110 applyToCompany: true,111 joinFaction: true,112 workForFaction: true,113 createProgram: true,114 commitCrime: true,115 shortStock: true,116 sellShort: true,117 startAction: true,118 upgradeSkill: true,119 setTeamSize: true,120 joinBladeburnerFaction: true,121}122//Used to check and set flags for every Source File, despite the name of the function123function initSingularitySFFlags() {124 for (var i = 0; i < Player.sourceFiles.length; ++i) {125 if (Player.sourceFiles[i].n === 3) {hasCorporationSF = true;}126 if (Player.sourceFiles[i].n === 4) {127 hasSingularitySF = true;128 singularitySFLvl = Player.sourceFiles[i].lvl;129 }130 if (Player.sourceFiles[i].n === 5) {hasAISF = true;}131 if (Player.sourceFiles[i].n === 6) {hasBladeburnerSF = true;}132 if (Player.sourceFiles[i].n === 7) {hasBladeburner2079SF = true;}133 if (Player.sourceFiles[i].n === 8) {134 hasWallStreetSF = true;135 wallStreetSFLvl = Player.sourceFiles[i].lvl;136 }137 if (Player.sourceFiles[i].n === 11) {hasBn11SF = true;}138 }139}140function NetscriptFunctions(workerScript) {141 var updateDynamicRam = function(fnName, ramCost) {142 if (workerScript.dynamicLoadedFns[fnName]) {return;}143 workerScript.dynamicLoadedFns[fnName] = true;144 workerScript.dynamicRamUsage += ramCost;145 if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) {146 throw makeRuntimeRejectMsg(workerScript,147 "Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName +148 ". This is probably because you somehow circumvented the static RAM " +149 "calculation.<br><br>Please don't do that :(<br><br>" +150 "Dynamic RAM Usage: " + workerScript.dynamicRamUsage + "<br>" +151 "Static RAM Usage: " + workerScript.ramUsage);152 }153 };154 var updateStaticRam = function(fnName, ramCost) {155 if (workerScript.loadedFns[fnName]) {156 return 0;157 } else {158 workerScript.loadedFns[fnName] = true;159 return ramCost;160 }161 };162 //Utility function to get Hacknet Node object163 var getHacknetNode = function(i) {164 if (isNaN(i)) {165 throw makeRuntimeRejectMsg(workerScript, "Invalid index specified for Hacknet Node: " + i);166 }167 if (i < 0 || i >= Player.hacknetNodes.length) {168 throw makeRuntimeRejectMsg(workerScript, "Index specified for Hacknet Node is out-of-bounds: " + i);169 }170 return Player.hacknetNodes[i];171 };172 /**173 * @param {number} ram The amount of server RAM to calculate cost of.174 * @exception {Error} If the value passed in is not numeric, out of range, or too large of a value.175 * @returns {number} The cost of 176 */177 const getPurchaseServerRamCostGuard = (ram) => {178 const guardedRam = Math.round(ram);179 if (isNaN(guardedRam) || !isPowerOfTwo(guardedRam)) {180 throw Error("failed due to invalid ram argument. Must be numeric and a power of 2");181 }182 if (guardedRam > CONSTANTS.PurchasedServerMaxRam) {183 throw Error("failed because specified RAM was too high. Maximum RAM on a purchased server is " + CONSTANTS.PurchasedServerMaxRam + "GB");184 }185 return guardedRam * CONSTANTS.BaseCostFor1GBOfRamServer;186 };187 return {188 hacknet : {189 numNodes : function() {190 return Player.hacknetNodes.length;191 },192 purchaseNode : function() {193 return purchaseHacknet();194 },195 getPurchaseNodeCost : function() {196 return getCostOfNextHacknetNode();197 },198 getNodeStats : function(i) {199 var node = getHacknetNode(i);200 return {201 name: node.name,202 level: node.level,203 ram: node.ram,204 cores: node.cores,205 production: node.moneyGainRatePerSecond,206 timeOnline: node.onlineTimeSeconds,207 totalProduction: node.totalMoneyGenerated,208 };209 },210 upgradeLevel : function(i, n) {211 var node = getHacknetNode(i);212 return node.purchaseLevelUpgrade(n);213 },214 upgradeRam : function(i, n) {215 var node = getHacknetNode(i);216 return node.purchaseRamUpgrade(n);217 },218 upgradeCore : function(i, n) {219 var node = getHacknetNode(i);220 return node.purchaseCoreUpgrade(n);221 },222 getLevelUpgradeCost : function(i, n) {223 var node = getHacknetNode(i);224 return node.calculateLevelUpgradeCost(n);225 },226 getRamUpgradeCost : function(i, n) {227 var node = getHacknetNode(i);228 return node.calculateRamUpgradeCost(n);229 },230 getCoreUpgradeCost : function(i, n) {231 var node = getHacknetNode(i);232 return node.calculateCoreUpgradeCost(n);233 }234 },235 sprintf : sprintf,236 vsprintf: vsprintf,237 scan : function(ip=workerScript.serverIp, hostnames=true){238 if (workerScript.checkingRam) {239 return updateStaticRam("scan", CONSTANTS.ScriptScanRamCost);240 }241 updateDynamicRam("scan", CONSTANTS.ScriptScanRamCost);242 var server = getServer(ip);243 if (server == null) {244 throw makeRuntimeRejectMsg(workerScript, 'Invalid IP or hostname passed into scan() command');245 }246 var out = [];247 for (var i = 0; i < server.serversOnNetwork.length; i++) {248 var entry;249 if (hostnames) {250 entry = server.getServerOnNetwork(i).hostname;251 } else {252 entry = server.getServerOnNetwork(i).ip;253 }254 if (entry == null) {255 continue;256 }257 out.push(entry);258 }259 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) {260 workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname);261 }262 return out;263 },264 hack : function(ip){265 if (workerScript.checkingRam) {266 return updateStaticRam("hack", CONSTANTS.ScriptHackRamCost);267 }268 updateDynamicRam("hack", CONSTANTS.ScriptHackRamCost);269 if (ip === undefined) {270 throw makeRuntimeRejectMsg(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument");271 }272 var threads = workerScript.scriptRef.threads;273 if (isNaN(threads) || threads < 1) {threads = 1;}274 var server = getServer(ip);275 if (server == null) {276 workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");277 throw makeRuntimeRejectMsg(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");278 }279 //Calculate the hacking time280 var hackingTime = scriptCalculateHackingTime(server); //This is in seconds281 //No root access or skill level too low282 if (server.hasAdminRights == false) {283 workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access");284 throw makeRuntimeRejectMsg(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access");285 }286 if (server.requiredHackingSkill > Player.hacking_skill) {287 workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");288 throw makeRuntimeRejectMsg(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");289 }290 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {291 workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")");292 }293 return netscriptDelay(hackingTime* 1000, workerScript).then(function() {294 if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}295 var hackChance = scriptCalculateHackingChance(server);296 var rand = Math.random();297 var expGainedOnSuccess = scriptCalculateExpGain(server) * threads;298 var expGainedOnFailure = (expGainedOnSuccess / 4);299 if (rand < hackChance) { //Success!300 const percentHacked = scriptCalculatePercentMoneyHacked(server);301 let maxThreadNeeded = Math.ceil(1/percentHacked*(server.moneyAvailable/server.moneyMax));302 if (isNaN(maxThreadNeeded)) {303 //Server has a 'max money' of 0 (probably).304 //We'll set this to an arbitrarily large value305 maxThreadNeeded = 1e6;306 }307 let moneyGained = Math.floor(server.moneyAvailable * percentHacked) * threads;308 //Over-the-top safety checks309 if (moneyGained <= 0) {310 moneyGained = 0;311 expGainedOnSuccess = expGainedOnFailure;312 }313 if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;}314 server.moneyAvailable -= moneyGained;315 if (server.moneyAvailable < 0) {server.moneyAvailable = 0;}316 Player.gainMoney(moneyGained);317 workerScript.scriptRef.onlineMoneyMade += moneyGained;318 Player.scriptProdSinceLastAug += moneyGained;319 workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);320 Player.gainHackingExp(expGainedOnSuccess);321 workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;322 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {323 workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + formatNumber(moneyGained, 2) + " and " + formatNumber(expGainedOnSuccess, 4) + " exp (t=" + threads + ")");324 }325 server.fortify(CONSTANTS.ServerFortifyAmount * Math.min(threads, maxThreadNeeded));326 return Promise.resolve(moneyGained);327 } else {328 //Player only gains 25% exp for failure?329 Player.gainHackingExp(expGainedOnFailure);330 workerScript.scriptRef.onlineExpGained += expGainedOnFailure;331 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {332 workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + formatNumber(expGainedOnFailure, 4) + " exp (t=" + threads + ")");333 }334 return Promise.resolve(0);335 }336 });337 },338 sleep : function(time){339 if (workerScript.checkingRam) {return 0;}340 if (time === undefined) {341 throw makeRuntimeRejectMsg(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument");342 }343 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) {344 workerScript.scriptRef.log("Sleeping for " + time + " milliseconds");345 }346 return netscriptDelay(time, workerScript).then(function() {347 return Promise.resolve(true);348 });349 },350 grow : function(ip){351 if (workerScript.checkingRam) {352 return updateStaticRam("grow", CONSTANTS.ScriptGrowRamCost);353 }354 updateDynamicRam("grow", CONSTANTS.ScriptGrowRamCost);355 var threads = workerScript.scriptRef.threads;356 if (isNaN(threads) || threads < 1) {threads = 1;}357 if (ip === undefined) {358 throw makeRuntimeRejectMsg(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument");359 }360 var server = getServer(ip);361 if (server == null) {362 workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip);363 throw makeRuntimeRejectMsg(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip);364 }365 //No root access or skill level too low366 if (server.hasAdminRights == false) {367 workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access");368 throw makeRuntimeRejectMsg(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access");369 }370 var growTime = scriptCalculateGrowTime(server);371 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {372 workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + formatNumber(growTime/1000, 3) + " seconds (t=" + threads + ")");373 }374 return netscriptDelay(growTime, workerScript).then(function() {375 if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}376 const moneyBefore = server.moneyAvailable;377 server.moneyAvailable += (1 * threads); //It can be grown even if it has no money378 var growthPercentage = processSingleServerGrowth(server, 450 * threads);379 const moneyAfter = server.moneyAvailable;380 workerScript.scriptRef.recordGrow(server.ip, threads);381 var expGain = scriptCalculateExpGain(server) * threads;382 if (growthPercentage == 1) {383 expGain = 0;384 }385 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {386 workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " +387 formatNumber((moneyAfter/moneyBefore)*100 - 100, 6) + "%. Gained " +388 formatNumber(expGain, 4) + " hacking exp (t=" + threads +")");389 }390 workerScript.scriptRef.onlineExpGained += expGain;391 Player.gainHackingExp(expGain);392 return Promise.resolve(moneyAfter/moneyBefore);393 });394 },395 weaken : function(ip){396 if (workerScript.checkingRam) {397 return updateStaticRam("weaken", CONSTANTS.ScriptWeakenRamCost);398 }399 updateDynamicRam("weaken", CONSTANTS.ScriptWeakenRamCost);400 var threads = workerScript.scriptRef.threads;401 if (isNaN(threads) || threads < 1) {threads = 1;}402 if (ip === undefined) {403 throw makeRuntimeRejectMsg(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument");404 }405 var server = getServer(ip);406 if (server == null) {407 workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip);408 throw makeRuntimeRejectMsg(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip);409 }410 //No root access or skill level too low411 if (server.hasAdminRights == false) {412 workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access");413 throw makeRuntimeRejectMsg(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access");414 }415 var weakenTime = scriptCalculateWeakenTime(server);416 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {417 workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " +418 formatNumber(weakenTime/1000, 3) + " seconds (t=" + threads + ")");419 }420 return netscriptDelay(weakenTime, workerScript).then(function() {421 if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}422 server.weaken(CONSTANTS.ServerWeakenAmount * threads);423 workerScript.scriptRef.recordWeaken(server.ip, threads);424 var expGain = scriptCalculateExpGain(server) * threads;425 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {426 workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty +427 ". Gained " + formatNumber(expGain, 4) + " hacking exp (t=" + threads + ")");428 }429 workerScript.scriptRef.onlineExpGained += expGain;430 Player.gainHackingExp(expGain);431 return Promise.resolve(CONSTANTS.ServerWeakenAmount * threads);432 });433 },434 print : function(args){435 if (workerScript.checkingRam) {return 0;}436 if (args === undefined) {437 throw makeRuntimeRejectMsg(workerScript, "print() call has incorrect number of arguments. Takes 1 argument");438 }439 workerScript.scriptRef.log(args.toString());440 },441 tprint : function(args) {442 if (workerScript.checkingRam) {return 0;}443 if (args === undefined || args == null) {444 throw makeRuntimeRejectMsg(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument");445 }446 var x = args.toString();447 if (isHTML(x)) {448 Player.takeDamage(1);449 dialogBoxCreate("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims: <br><br>" +450 "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!<br><br>" +451 "(You lost 1 HP)");452 return;453 }454 post(workerScript.scriptRef.filename + ": " + args.toString());455 },456 clearLog : function() {457 if (workerScript.checkingRam) {return 0;}458 workerScript.scriptRef.clearLog();459 },460 disableLog : function(fn) {461 if (workerScript.checkingRam) {return 0;}462 if(possibleLogs[fn]===undefined) {463 throw makeRuntimeRejectMsg(workerScript, "Invalid argument to disableLog: "+fn);464 }465 workerScript.disableLogs[fn] = true;466 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) {467 workerScript.scriptRef.log("Disabled logging for " + fn);468 }469 },470 enableLog : function(fn) {471 if (workerScript.checkingRam) {return 0;}472 if(possibleLogs[fn]===undefined) {473 throw makeRuntimeRejectMsg(workerScript, "Invalid argument to enableLog: "+fn);474 }475 delete workerScript.disableLogs[fn];476 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) {477 workerScript.scriptRef.log("Enabled logging for " + fn);478 }479 },480 nuke : function(ip){481 if (workerScript.checkingRam) {482 return updateStaticRam("nuke", CONSTANTS.ScriptPortProgramRamCost);483 }484 updateDynamicRam("nuke", CONSTANTS.ScriptPortProgramRamCost);485 if (ip === undefined) {486 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");487 }488 var server = getServer(ip);489 if (server == null) {490 workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip);491 throw makeRuntimeRejectMsg(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip);492 }493 if (!Player.hasProgram(Programs.NukeProgram.name)) {494 throw makeRuntimeRejectMsg(workerScript, "You do not have the NUKE.exe virus!");495 }496 if (server.openPortCount < server.numOpenPortsRequired) {497 throw makeRuntimeRejectMsg(workerScript, "Not enough ports opened to use NUKE.exe virus");498 }499 if (server.hasAdminRights) {500 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {501 workerScript.scriptRef.log("Already have root access to " + server.hostname);502 }503 } else {504 server.hasAdminRights = true;505 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) {506 workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access");507 }508 }509 return true;510 },511 brutessh : function(ip){512 if (workerScript.checkingRam) {513 return updateStaticRam("brutessh", CONSTANTS.ScriptPortProgramRamCost);514 }515 updateDynamicRam("brutessh", CONSTANTS.ScriptPortProgramRamCost);516 if (ip === undefined) {517 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");518 }519 var server = getServer(ip);520 if (server == null) {521 workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);522 throw makeRuntimeRejectMsg(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);523 }524 if (!Player.hasProgram(Programs.BruteSSHProgram.name)) {525 workerScript.scriptRef.log("You do not have the BruteSSH.exe program!");526 throw makeRuntimeRejectMsg(workerScript, "You do not have the BruteSSH.exe program!");527 }528 if (!server.sshPortOpen) {529 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {530 workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)");531 }532 server.sshPortOpen = true;533 ++server.openPortCount;534 } else {535 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) {536 workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname);537 }538 }539 return true;540 },541 ftpcrack : function(ip){542 if (workerScript.checkingRam) {543 return updateStaticRam("ftpcrack", CONSTANTS.ScriptPortProgramRamCost);544 }545 updateDynamicRam("ftpcrack", CONSTANTS.ScriptPortProgramRamCost);546 if (ip === undefined) {547 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");548 }549 var server = getServer(ip);550 if (server == null) {551 workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);552 throw makeRuntimeRejectMsg(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);553 }554 if (!Player.hasProgram(Programs.FTPCrackProgram.name)) {555 throw makeRuntimeRejectMsg(workerScript, "You do not have the FTPCrack.exe program!");556 }557 if (!server.ftpPortOpen) {558 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {559 workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)");560 }561 server.ftpPortOpen = true;562 ++server.openPortCount;563 } else {564 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) {565 workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname);566 }567 }568 return true;569 },570 relaysmtp : function(ip){571 if (workerScript.checkingRam) {572 return updateStaticRam("relaysmtp", CONSTANTS.ScriptPortProgramRamCost);573 }574 updateDynamicRam("relaysmtp", CONSTANTS.ScriptPortProgramRamCost);575 if (ip === undefined) {576 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");577 }578 var server = getServer(ip);579 if (server == null) {580 workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);581 throw makeRuntimeRejectMsg(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);582 }583 if (!Player.hasProgram(Programs.RelaySMTPProgram.name)) {584 throw makeRuntimeRejectMsg(workerScript, "You do not have the relaySMTP.exe program!");585 }586 if (!server.smtpPortOpen) {587 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {588 workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)");589 }590 server.smtpPortOpen = true;591 ++server.openPortCount;592 } else {593 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) {594 workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname);595 }596 }597 return true;598 },599 httpworm : function(ip){600 if (workerScript.checkingRam) {601 return updateStaticRam("httpworm", CONSTANTS.ScriptPortProgramRamCost);602 }603 updateDynamicRam("httpworm", CONSTANTS.ScriptPortProgramRamCost);604 if (ip === undefined) {605 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");606 }607 var server = getServer(ip);608 if (server == null) {609 workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);610 throw makeRuntimeRejectMsg(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);611 }612 if (!Player.hasProgram(Programs.HTTPWormProgram.name)) {613 throw makeRuntimeRejectMsg(workerScript, "You do not have the HTTPWorm.exe program!");614 }615 if (!server.httpPortOpen) {616 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {617 workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)");618 }619 server.httpPortOpen = true;620 ++server.openPortCount;621 } else {622 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) {623 workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname);624 }625 }626 return true;627 },628 sqlinject : function(ip){629 if (workerScript.checkingRam) {630 return updateStaticRam("sqlinject", CONSTANTS.ScriptPortProgramRamCost);631 }632 updateDynamicRam("sqlinject", CONSTANTS.ScriptPortProgramRamCost);633 if (ip === undefined) {634 throw makeRuntimeRejectMsg(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");635 }636 var server = getServer(ip);637 if (server == null) {638 workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);639 throw makeRuntimeRejectMsg(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);640 }641 if (!Player.hasProgram(Programs.SQLInjectProgram.name)) {642 throw makeRuntimeRejectMsg(workerScript, "You do not have the SQLInject.exe program!");643 }644 if (!server.sqlPortOpen) {645 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {646 workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)");647 }648 server.sqlPortOpen = true;649 ++server.openPortCount;650 } else {651 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) {652 workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname);653 }654 }655 return true;656 },657 run : function(scriptname,threads = 1){658 if (workerScript.checkingRam) {659 return updateStaticRam("run", CONSTANTS.ScriptRunRamCost);660 }661 updateDynamicRam("run", CONSTANTS.ScriptRunRamCost);662 if (scriptname === undefined) {663 throw makeRuntimeRejectMsg(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)");664 }665 if (isNaN(threads) || threads < 1) {666 throw makeRuntimeRejectMsg(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0");667 }668 var argsForNewScript = [];669 for (var i = 2; i < arguments.length; ++i) {670 argsForNewScript.push(arguments[i]);671 }672 var scriptServer = getServer(workerScript.serverIp);673 if (scriptServer == null) {674 throw makeRuntimeRejectMsg(workerScript, "Could not find server. This is a bug in the game. Report to game dev");675 }676 return runScriptFromScript(scriptServer, scriptname, argsForNewScript, workerScript, threads);677 },678 exec : function(scriptname,ip,threads = 1) {679 if (workerScript.checkingRam) {680 return updateStaticRam("exec", CONSTANTS.ScriptExecRamCost);681 }682 updateDynamicRam("exec", CONSTANTS.ScriptExecRamCost);683 if (scriptname === undefined || ip === undefined) {684 throw makeRuntimeRejectMsg(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)");685 }686 if (isNaN(threads) || threads < 1) {687 throw makeRuntimeRejectMsg(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0");688 }689 var argsForNewScript = [];690 for (var i = 3; i < arguments.length; ++i) {691 argsForNewScript.push(arguments[i]);692 }693 var server = getServer(ip);694 if (server == null) {695 throw makeRuntimeRejectMsg(workerScript, "Invalid hostname/ip passed into exec() command: " + ip);696 }697 return runScriptFromScript(server, scriptname, argsForNewScript, workerScript, threads);698 },699 spawn : function(scriptname, threads) {700 if (workerScript.checkingRam) {701 return updateStaticRam("spawn", CONSTANTS.ScriptSpawnRamCost);702 }703 updateDynamicRam("spawn", CONSTANTS.ScriptSpawnRamCost);704 if (scriptname == null || threads == null) {705 throw makeRuntimeRejectMsg(workerScript, "Invalid scriptname or numThreads argument passed to spawn()");706 }707 setTimeout(()=>{708 if (scriptname === undefined) {709 throw makeRuntimeRejectMsg(workerScript, "spawn() call has incorrect number of arguments. Usage: spawn(scriptname, numThreads, [arg1], [arg2]...)");710 }711 if (isNaN(threads) || threads < 1) {712 throw makeRuntimeRejectMsg(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0");713 }714 var argsForNewScript = [];715 for (var i = 2; i < arguments.length; ++i) {716 argsForNewScript.push(arguments[i]);717 }718 var scriptServer = getServer(workerScript.serverIp);719 if (scriptServer == null) {720 throw makeRuntimeRejectMsg(workerScript, "Could not find server. This is a bug in the game. Report to game dev");721 }722 return runScriptFromScript(scriptServer, scriptname, argsForNewScript, workerScript, threads);723 }, 20000);724 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) {725 workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds");726 }727 NetscriptFunctions(workerScript).exit();728 },729 kill : function(filename,ip) {730 if (workerScript.checkingRam) {731 return updateStaticRam("kill", CONSTANTS.ScriptKillRamCost);732 }733 updateDynamicRam("kill", CONSTANTS.ScriptKillRamCost);734 if (filename === undefined || ip === undefined) {735 throw makeRuntimeRejectMsg(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)");736 }737 var server = getServer(ip);738 if (server == null) {739 workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip);740 throw makeRuntimeRejectMsg(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip);741 }742 var argsForKillTarget = [];743 for (var i = 2; i < arguments.length; ++i) {744 argsForKillTarget.push(arguments[i]);745 }746 var runningScriptObj = findRunningScript(filename, argsForKillTarget, server);747 if (runningScriptObj == null) {748 workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + arrayToString(argsForKillTarget));749 return false;750 }751 var res = killWorkerScript(runningScriptObj, server.ip);752 if (res) {753 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {754 workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + arrayToString(argsForKillTarget) + ". May take up to a few minutes for the scripts to die...");755 }756 return true;757 } else {758 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) {759 workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + arrayToString(argsForKillTarget));760 }761 return false;762 }763 },764 killall : function(ip=workerScript.serverIp){765 if (workerScript.checkingRam) {766 return updateStaticRam("killall", CONSTANTS.ScriptKillRamCost);767 }768 updateDynamicRam("killall", CONSTANTS.ScriptKillRamCost);769 if (ip === undefined) {770 throw makeRuntimeRejectMsg(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument");771 }772 var server = getServer(ip);773 if (server == null) {774 workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip);775 throw makeRuntimeRejectMsg(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip);776 }777 var scriptsRunning = (server.runningScripts.length > 0);778 for (var i = server.runningScripts.length-1; i >= 0; --i) {779 killWorkerScript(server.runningScripts[i], server.ip);780 }781 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) {782 workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die");783 }784 return scriptsRunning;785 },786 exit : function() {787 if (workerScript.checkingRam) {return 0;}788 var server = getServer(workerScript.serverIp);789 if (server == null) {790 throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev");791 }792 if (killWorkerScript(workerScript.scriptRef, server.ip)) {793 workerScript.scriptRef.log("Exiting...");794 } else {795 workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer");796 }797 },798 scp : function(scriptname, ip1, ip2) {799 if (workerScript.checkingRam) {800 return updateStaticRam("scp", CONSTANTS.ScriptScpRamCost);801 }802 updateDynamicRam("scp", CONSTANTS.ScriptScpRamCost);803 if (arguments.length !== 2 && arguments.length !== 3) {804 throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");805 }806 if (scriptname && scriptname.constructor === Array) {807 //Recursively call scp on all elements of array808 var res = false;809 scriptname.forEach(function(script) {810 if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) {811 res = true;812 };813 });814 return res;815 }816 if (!scriptname.endsWith(".lit") && !isScriptFilename(scriptname) &&817 !scriptname.endsWith("txt")) {818 throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() does not work with this file type. It only works for .script, .lit, and .txt files");819 }820 var destServer, currServ;821 if (arguments.length === 3) { //scriptname, source, destination822 if (scriptname === undefined || ip1 === undefined || ip2 === undefined) {823 throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");824 }825 destServer = getServer(ip2);826 if (destServer == null) {827 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip);828 }829 currServ = getServer(ip1);830 if (currServ == null) {831 throw makeRuntimeRejectMsg(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");832 }833 } else if (arguments.length === 2) { //scriptname, destination834 if (scriptname === undefined || ip1 === undefined) {835 throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");836 }837 destServer = getServer(ip1);838 if (destServer == null) {839 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip);840 }841 currServ = getServer(workerScript.serverIp);842 if (currServ == null) {843 throw makeRuntimeRejectMsg(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");844 }845 }846 //Scp for lit files847 if (scriptname.endsWith(".lit")) {848 var found = false;849 for (var i = 0; i < currServ.messages.length; ++i) {850 if (!(currServ.messages[i] instanceof Message) && currServ.messages[i] == scriptname) {851 found = true;852 break;853 }854 }855 if (!found) {856 workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");857 return false;858 }859 for (var i = 0; i < destServer.messages.length; ++i) {860 if (destServer.messages[i] === scriptname) {861 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {862 workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);863 }864 return true; //Already exists865 }866 }867 destServer.messages.push(scriptname);868 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {869 workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);870 }871 return true;872 }873 //Scp for text files874 if (scriptname.endsWith(".txt")) {875 var found = false, txtFile;876 for (var i = 0; i < currServ.textFiles.length; ++i) {877 if (currServ.textFiles[i].fn === scriptname) {878 found = true;879 txtFile = currServ.textFiles[i];880 break;881 }882 }883 if (!found) {884 workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");885 return false;886 }887 for (var i = 0; i < destServer.textFiles.length; ++i) {888 if (destServer.textFiles[i].fn === scriptname) {889 //Overwrite890 destServer.textFiles[i].text = txtFile.text;891 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {892 workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);893 }894 return true;895 }896 }897 var newFile = new TextFile(txtFile.fn, txtFile.text);898 destServer.textFiles.push(newFile);899 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {900 workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);901 }902 return true;903 }904 //Scp for script files905 var sourceScript = null;906 for (var i = 0; i < currServ.scripts.length; ++i) {907 if (scriptname == currServ.scripts[i].filename) {908 sourceScript = currServ.scripts[i];909 break;910 }911 }912 if (sourceScript == null) {913 workerScript.scriptRef.log(scriptname + " does not exist. scp() failed");914 return false;915 }916 //Overwrite script if it already exists917 for (var i = 0; i < destServer.scripts.length; ++i) {918 if (scriptname == destServer.scripts[i].filename) {919 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {920 workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten.");921 workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname);922 }923 var oldScript = destServer.scripts[i];924 oldScript.code = sourceScript.code;925 oldScript.ramUsage = sourceScript.ramUsage;926 oldScript.module = "";927 return true;928 }929 }930 //Create new script if it does not already exist931 var newScript = new Script();932 newScript.filename = scriptname;933 newScript.code = sourceScript.code;934 newScript.ramUsage = sourceScript.ramUsage;935 newScript.server = destServer.ip;936 destServer.scripts.push(newScript);937 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {938 workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);939 }940 return true;941 },942 ls : function(ip, grep) {943 if (workerScript.checkingRam) {944 return updateStaticRam("ls", CONSTANTS.ScriptScanRamCost);945 }946 updateDynamicRam("ls", CONSTANTS.ScriptScanRamCost);947 if (ip === undefined) {948 throw makeRuntimeRejectMsg(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])");949 }950 var server = getServer(ip);951 if (server == null) {952 workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip);953 throw makeRuntimeRejectMsg(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip);954 }955 //Get the grep filter, if one exists956 var filter = false;957 if (arguments.length >= 2) {958 filter = grep.toString();959 }960 var allFiles = [];961 for (var i = 0; i < server.programs.length; i++) {962 if (filter) {963 if (server.programs[i].includes(filter)) {964 allFiles.push(server.programs[i]);965 }966 } else {967 allFiles.push(server.programs[i]);968 }969 }970 for (var i = 0; i < server.scripts.length; i++) {971 if (filter) {972 if (server.scripts[i].filename.includes(filter)) {973 allFiles.push(server.scripts[i].filename);974 }975 } else {976 allFiles.push(server.scripts[i].filename);977 }978 }979 for (var i = 0; i < server.messages.length; i++) {980 if (filter) {981 if (server.messages[i] instanceof Message) {982 if (server.messages[i].filename.includes(filter)) {983 allFiles.push(server.messages[i].filename);984 }985 } else if (server.messages[i].includes(filter)) {986 allFiles.push(server.messages[i]);987 }988 } else {989 if (server.messages[i] instanceof Message) {990 allFiles.push(server.messages[i].filename);991 } else {992 allFiles.push(server.messages[i]);993 }994 }995 }996 for (var i = 0; i < server.textFiles.length; i++) {997 if (filter) {998 if (server.textFiles[i].fn.includes(filter)) {999 allFiles.push(server.textFiles[i].fn);1000 }1001 } else {1002 allFiles.push(server.textFiles[i].fn);1003 }1004 }1005 //Sort the files alphabetically then print each1006 allFiles.sort();1007 return allFiles;1008 },1009 ps : function(ip=workerScript.serverIp) {1010 if (workerScript.checkingRam) {1011 return updateStaticRam("ps", CONSTANTS.ScriptScanRamCost);1012 }1013 updateDynamicRam("ps", CONSTANTS.ScriptScanRamCost);1014 var server = getServer(ip);1015 if (server == null){1016 workerScript.scriptRef.log("ps() failed. Invalid IP or hostname passed in: " + ip);1017 throw makeRuntimeRejectMsg(workerScript, "ps() failed. Invalid IP or hostname passed in: " + ip);1018 }1019 const processes = [];1020 for(const i in server.runningScripts) {1021 const script = server.runningScripts[i];1022 processes.push({filename:script.filename, threads: script.threads, args: script.args.slice()})1023 }1024 return processes;1025 },1026 hasRootAccess : function(ip) {1027 if (workerScript.checkingRam) {1028 return updateStaticRam("hasRootAccess", CONSTANTS.ScriptHasRootAccessRamCost);1029 }1030 updateDynamicRam("hasRootAccess", CONSTANTS.ScriptHasRootAccessRamCost);1031 if (ip===undefined){1032 throw makeRuntimeRejectMsg(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument");1033 }1034 var server = getServer(ip);1035 if (server == null){1036 workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);1037 throw makeRuntimeRejectMsg(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);1038 }1039 return server.hasAdminRights;1040 },1041 getIp : function() {1042 if (workerScript.checkingRam) {1043 return updateStaticRam("getIp", CONSTANTS.ScriptGetHostnameRamCost);1044 }1045 updateDynamicRam("getIp", CONSTANTS.ScriptGetHostnameRamCost);1046 var scriptServer = getServer(workerScript.serverIp);1047 if (scriptServer == null) {1048 throw makeRuntimeRejectMsg(workerScript, "Could not find server. This is a bug in the game. Report to game dev");1049 }1050 return scriptServer.ip;1051 },1052 getHostname : function(){1053 if (workerScript.checkingRam) {1054 return updateStaticRam("getHostname", CONSTANTS.ScriptGetHostnameRamCost);1055 }1056 updateDynamicRam("getHostname", CONSTANTS.ScriptGetHostnameRamCost);1057 var scriptServer = getServer(workerScript.serverIp);1058 if (scriptServer == null) {1059 throw makeRuntimeRejectMsg(workerScript, "Could not find server. This is a bug in the game. Report to game dev");1060 }1061 return scriptServer.hostname;1062 },1063 getHackingLevel : function(){1064 if (workerScript.checkingRam) {1065 return updateStaticRam("getHackingLevel", CONSTANTS.ScriptGetHackingLevelRamCost);1066 }1067 updateDynamicRam("getHackingLevel", CONSTANTS.ScriptGetHackingLevelRamCost);1068 Player.updateSkillLevels();1069 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) {1070 workerScript.scriptRef.log("getHackingLevel() returned " + Player.hacking_skill);1071 }1072 return Player.hacking_skill;1073 },1074 getHackingMultipliers : function() {1075 if (workerScript.checkingRam) {1076 return updateStaticRam("getHackingMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1077 }1078 updateDynamicRam("getHackingMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1079 return {1080 chance: Player.hacking_chance_mult,1081 speed: Player.hacking_speed_mult,1082 money: Player.hacking_money_mult,1083 growth: Player.hacking_grow_mult,1084 };1085 },1086 getHacknetMultipliers : function() {1087 if (workerScript.checkingRam) {1088 return updateStaticRam("getHacknetMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1089 }1090 updateDynamicRam("getHacknetMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1091 return {1092 production: Player.hacknet_node_money_mult,1093 purchaseCost: Player.hacknet_node_purchase_cost_mult,1094 ramCost: Player.hacknet_node_ram_cost_mult,1095 coreCost: Player.hacknet_node_core_cost_mult,1096 levelCost: Player.hacknet_node_level_cost_mult,1097 };1098 },1099 getBitNodeMultipliers: function() {1100 if (workerScript.checkingRam) {1101 return updateStaticRam("getBitNodeMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1102 }1103 updateDynamicRam("getBitNodeMultipliers", CONSTANTS.ScriptGetMultipliersRamCost);1104 if (!hasAISF) {1105 throw makeRuntimeRejectMsg(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run.");1106 }1107 let copy = Object.assign({}, BitNodeMultipliers);1108 return copy;1109 },1110 getServerMoneyAvailable : function(ip){1111 if (workerScript.checkingRam) {1112 return updateStaticRam("getServerMoneyAvailable", CONSTANTS.ScriptGetServerRamCost);1113 }1114 updateDynamicRam("getServerMoneyAvailable", CONSTANTS.ScriptGetServerRamCost);1115 var server = getServer(ip);1116 if (server == null) {1117 workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);1118 throw makeRuntimeRejectMsg(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);1119 }1120 if (server.hostname == "home") {1121 //Return player's money1122 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {1123 workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + formatNumber(Player.money.toNumber(), 2));1124 }1125 return Player.money.toNumber();1126 }1127 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {1128 workerScript.scriptRef.log("getServerMoneyAvailable() returned " + formatNumber(server.moneyAvailable, 2) + " for " + server.hostname);1129 }1130 return server.moneyAvailable;1131 },1132 getServerSecurityLevel : function(ip){1133 if (workerScript.checkingRam) {1134 return updateStaticRam("getServerSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1135 }1136 updateDynamicRam("getServerSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1137 var server = getServer(ip);1138 if (server == null) {1139 workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1140 throw makeRuntimeRejectMsg(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1141 }1142 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) {1143 workerScript.scriptRef.log("getServerSecurityLevel() returned " + formatNumber(server.hackDifficulty, 3) + " for " + server.hostname);1144 }1145 return server.hackDifficulty;1146 },1147 getServerBaseSecurityLevel : function(ip){1148 if (workerScript.checkingRam) {1149 return updateStaticRam("getServerBaseSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1150 }1151 updateDynamicRam("getServerBaseSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1152 var server = getServer(ip);1153 if (server == null) {1154 workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1155 throw makeRuntimeRejectMsg(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1156 }1157 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) {1158 workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + formatNumber(server.baseDifficulty, 3) + " for " + server.hostname);1159 }1160 return server.baseDifficulty;1161 },1162 getServerMinSecurityLevel : function(ip) {1163 if (workerScript.checkingRam) {1164 return updateStaticRam("getServerMinSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1165 }1166 updateDynamicRam("getServerMinSecurityLevel", CONSTANTS.ScriptGetServerRamCost);1167 var server = getServer(ip);1168 if (server == null) {1169 workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1170 throw makeRuntimeRejectMsg(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);1171 }1172 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) {1173 workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + formatNumber(server.minDifficulty, 3) + " for " + server.hostname);1174 }1175 return server.minDifficulty;1176 },1177 getServerRequiredHackingLevel : function(ip) {1178 if (workerScript.checkingRam) {1179 return updateStaticRam("getServerRequiredHackingLevel", CONSTANTS.ScriptGetServerRamCost);1180 }1181 updateDynamicRam("getServerRequiredHackingLevel", CONSTANTS.ScriptGetServerRamCost);1182 var server = getServer(ip);1183 if (server == null) {1184 workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);1185 throw makeRuntimeRejectMsg(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);1186 }1187 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) {1188 workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + formatNumber(server.requiredHackingSkill, 0) + " for " + server.hostname);1189 }1190 return server.requiredHackingSkill;1191 },1192 getServerMaxMoney : function(ip){1193 if (workerScript.checkingRam) {1194 return updateStaticRam("getServerMaxMoney", CONSTANTS.ScriptGetServerRamCost);1195 }1196 updateDynamicRam("getServerMaxMoney", CONSTANTS.ScriptGetServerRamCost);1197 var server = getServer(ip);1198 if (server == null) {1199 workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);1200 throw makeRuntimeRejectMsg(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);1201 }1202 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) {1203 workerScript.scriptRef.log("getServerMaxMoney() returned " + formatNumber(server.moneyMax, 0) + " for " + server.hostname);1204 }1205 return server.moneyMax;1206 },1207 getServerGrowth : function(ip) {1208 if (workerScript.checkingRam) {1209 return updateStaticRam("getServerGrowth", CONSTANTS.ScriptGetServerRamCost);1210 }1211 updateDynamicRam("getServerGrowth", CONSTANTS.ScriptGetServerRamCost);1212 var server = getServer(ip);1213 if (server == null) {1214 workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);1215 throw makeRuntimeRejectMsg(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);1216 }1217 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) {1218 workerScript.scriptRef.log("getServerGrowth() returned " + formatNumber(server.serverGrowth, 0) + " for " + server.hostname);1219 }1220 return server.serverGrowth;1221 },1222 getServerNumPortsRequired : function(ip) {1223 if (workerScript.checkingRam) {1224 return updateStaticRam("getServerNumPortsRequired", CONSTANTS.ScriptGetServerRamCost);1225 }1226 updateDynamicRam("getServerNumPortsRequired", CONSTANTS.ScriptGetServerRamCost);1227 var server = getServer(ip);1228 if (server == null) {1229 workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);1230 throw makeRuntimeRejectMsg(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);1231 }1232 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) {1233 workerScript.scriptRef.log("getServerNumPortsRequired() returned " + formatNumber(server.numOpenPortsRequired, 0) + " for " + server.hostname);1234 }1235 return server.numOpenPortsRequired;1236 },1237 getServerRam : function(ip) {1238 if (workerScript.checkingRam) {1239 return updateStaticRam("getServerRam", CONSTANTS.ScriptGetServerRamCost);1240 }1241 updateDynamicRam("getServerRam", CONSTANTS.ScriptGetServerRamCost);1242 var server = getServer(ip);1243 if (server == null) {1244 workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip);1245 throw makeRuntimeRejectMsg(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip);1246 }1247 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) {1248 workerScript.scriptRef.log("getServerRam() returned [" + formatNumber(server.maxRam, 2) + "GB, " + formatNumber(server.ramUsed, 2) + "GB]");1249 }1250 return [server.maxRam, server.ramUsed];1251 },1252 serverExists : function(ip) {1253 if (workerScript.checkingRam) {1254 return updateStaticRam("serverExists", CONSTANTS.ScriptGetServerRamCost);1255 }1256 updateDynamicRam("serverExists", CONSTANTS.ScriptGetServerRamCost);1257 return (getServer(ip) !== null);1258 },1259 fileExists : function(filename,ip=workerScript.serverIp) {1260 if (workerScript.checkingRam) {1261 return updateStaticRam("fileExists", CONSTANTS.ScriptFileExistsRamCost);1262 }1263 updateDynamicRam("fileExists", CONSTANTS.ScriptFileExistsRamCost);1264 if (filename === undefined) {1265 throw makeRuntimeRejectMsg(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])");1266 }1267 var server = getServer(ip);1268 if (server == null) {1269 workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip);1270 throw makeRuntimeRejectMsg(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip);1271 }1272 for (var i = 0; i < server.scripts.length; ++i) {1273 if (filename == server.scripts[i].filename) {1274 return true;1275 }1276 }1277 for (var i = 0; i < server.programs.length; ++i) {1278 if (filename.toLowerCase() == server.programs[i].toLowerCase()) {1279 return true;1280 }1281 }1282 for (var i = 0; i < server.messages.length; ++i) {1283 if (!(server.messages[i] instanceof Message) &&1284 filename.toLowerCase() === server.messages[i]) {1285 return true;1286 }1287 }1288 var txtFile = getTextFile(filename, server);1289 if (txtFile != null) {1290 return true;1291 }1292 return false;1293 },1294 isRunning : function(filename,ip) {1295 if (workerScript.checkingRam) {1296 return updateStaticRam("isRunning", CONSTANTS.ScriptIsRunningRamCost);1297 }1298 updateDynamicRam("isRunning", CONSTANTS.ScriptIsRunningRamCost);1299 if (filename === undefined || ip === undefined) {1300 throw makeRuntimeRejectMsg(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)");1301 }1302 var server = getServer(ip);1303 if (server == null) {1304 workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip);1305 throw makeRuntimeRejectMsg(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip);1306 }1307 var argsForTargetScript = [];1308 for (var i = 2; i < arguments.length; ++i) {1309 argsForTargetScript.push(arguments[i]);1310 }1311 return (findRunningScript(filename, argsForTargetScript, server) != null);1312 },1313 getStockPrice : function(symbol) {1314 if (workerScript.checkingRam) {1315 return updateStaticRam("getStockPrice", CONSTANTS.ScriptGetStockRamCost);1316 }1317 updateDynamicRam("getStockPrice", CONSTANTS.ScriptGetStockRamCost);1318 if (!Player.hasTixApiAccess) {1319 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()");1320 }1321 var stock = SymbolToStockMap[symbol];1322 if (stock == null) {1323 throw makeRuntimeRejectMsg(workerScript, "Invalid stock symbol passed into getStockPrice()");1324 }1325 return parseFloat(stock.price.toFixed(3));1326 },1327 getStockPosition : function(symbol) {1328 if (workerScript.checkingRam) {1329 return updateStaticRam("getStockPosition", CONSTANTS.ScriptGetStockRamCost);1330 }1331 updateDynamicRam("getStockPosition", CONSTANTS.ScriptGetStockRamCost);1332 if (!Player.hasTixApiAccess) {1333 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()");1334 }1335 var stock = SymbolToStockMap[symbol];1336 if (stock == null) {1337 throw makeRuntimeRejectMsg(workerScript, "Invalid stock symbol passed into getStockPosition()");1338 }1339 return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx];1340 },1341 buyStock : function(symbol, shares) {1342 if (workerScript.checkingRam) {1343 return updateStaticRam("buyStock", CONSTANTS.ScriptBuySellStockRamCost);1344 }1345 updateDynamicRam("buyStock", CONSTANTS.ScriptBuySellStockRamCost);1346 if (!Player.hasTixApiAccess) {1347 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use buyStock()");1348 }1349 var stock = SymbolToStockMap[symbol];1350 if (stock == null) {1351 throw makeRuntimeRejectMsg(workerScript, "Invalid stock symbol passed into buyStock()");1352 }1353 if (shares < 0 || isNaN(shares)) {1354 workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to buyStock()");1355 return 0;1356 }1357 shares = Math.round(shares);1358 if (shares === 0) {return 0;}1359 var totalPrice = stock.price * shares;1360 if (Player.money.lt(totalPrice + CONSTANTS.StockMarketCommission)) {1361 workerScript.scriptRef.log("Not enough money to purchase " + formatNumber(shares, 0) + " shares of " +1362 symbol + ". Need $" +1363 formatNumber(totalPrice + CONSTANTS.StockMarketCommission, 2).toString());1364 return 0;1365 }1366 var origTotal = stock.playerShares * stock.playerAvgPx;1367 Player.loseMoney(totalPrice + CONSTANTS.StockMarketCommission);1368 var newTotal = origTotal + totalPrice;1369 stock.playerShares += shares;1370 stock.playerAvgPx = newTotal / stock.playerShares;1371 if (Engine.currentPage == Engine.Page.StockMarket) {1372 updateStockPlayerPosition(stock);1373 }1374 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) {1375 workerScript.scriptRef.log("Bought " + formatNumber(shares, 0) + " shares of " + stock.symbol + " at $" +1376 formatNumber(stock.price, 2) + " per share");1377 }1378 return stock.price;1379 },1380 sellStock : function(symbol, shares) {1381 if (workerScript.checkingRam) {1382 return updateStaticRam("sellStock", CONSTANTS.ScriptBuySellStockRamCost);1383 }1384 updateDynamicRam("sellStock", CONSTANTS.ScriptBuySellStockRamCost);1385 if (!Player.hasTixApiAccess) {1386 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use sellStock()");1387 }1388 var stock = SymbolToStockMap[symbol];1389 if (stock == null) {1390 throw makeRuntimeRejectMsg(workerScript, "Invalid stock symbol passed into sellStock()");1391 }1392 if (shares < 0 || isNaN(shares)) {1393 workerScript.scriptRef.log("ERROR: Invalid 'shares' argument passed to sellStock()");1394 return 0;1395 }1396 shares = Math.round(shares);1397 if (shares > stock.playerShares) {shares = stock.playerShares;}1398 if (shares === 0) {return 0;}1399 var gains = stock.price * shares - CONSTANTS.StockMarketCommission;1400 Player.gainMoney(gains);1401 //Calculate net profit and add to script stats1402 var netProfit = ((stock.price - stock.playerAvgPx) * shares) - CONSTANTS.StockMarketCommission;1403 if (isNaN(netProfit)) {netProfit = 0;}1404 workerScript.scriptRef.onlineMoneyMade += netProfit;1405 Player.scriptProdSinceLastAug += netProfit;1406 stock.playerShares -= shares;1407 if (stock.playerShares == 0) {1408 stock.playerAvgPx = 0;1409 }1410 if (Engine.currentPage == Engine.Page.StockMarket) {1411 updateStockPlayerPosition(stock);1412 }1413 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) {1414 workerScript.scriptRef.log("Sold " + formatNumber(shares, 0) + " shares of " + stock.symbol + " at $" +1415 formatNumber(stock.price, 2) + " per share. Gained " +1416 "$" + formatNumber(gains, 2));1417 }1418 return stock.price;1419 },1420 shortStock(symbol, shares) {1421 if (workerScript.checkingRam) {1422 return updateStaticRam("shortStock", CONSTANTS.ScriptBuySellStockRamCost);1423 }1424 updateDynamicRam("shortStock", CONSTANTS.ScriptBuySellStockRamCost);1425 if (!Player.hasTixApiAccess) {1426 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use shortStock()");1427 }1428 if (Player.bitNodeN !== 8) {1429 if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {1430 throw makeRuntimeRejectMsg(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");1431 }1432 }1433 var stock = SymbolToStockMap[symbol];1434 if (stock == null) {1435 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid stock symbol passed into shortStock()");1436 }1437 var res = shortStock(stock, shares, workerScript);1438 return res ? stock.price : 0;1439 },1440 sellShort(symbol, shares) {1441 if (workerScript.checkingRam) {1442 return updateStaticRam("sellShort", CONSTANTS.ScriptBuySellStockRamCost);1443 }1444 updateDynamicRam("sellShort", CONSTANTS.ScriptBuySellStockRamCost);1445 if (!Player.hasTixApiAccess) {1446 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use sellShort()");1447 }1448 if (Player.bitNodeN !== 8) {1449 if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {1450 throw makeRuntimeRejectMsg(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8");1451 }1452 }1453 var stock = SymbolToStockMap[symbol];1454 if (stock == null) {1455 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid stock symbol passed into sellShort()");1456 }1457 var res = sellShort(stock, shares, workerScript);1458 return res ? stock.price : 0;1459 },1460 placeOrder(symbol, shares, price, type, pos) {1461 if (workerScript.checkingRam) {1462 return updateStaticRam("placeOrder", CONSTANTS.ScriptBuySellStockRamCost);1463 }1464 updateDynamicRam("placeOrder", CONSTANTS.ScriptBuySellStockRamCost);1465 if (!Player.hasTixApiAccess) {1466 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use placeOrder()");1467 }1468 if (Player.bitNodeN !== 8) {1469 if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {1470 throw makeRuntimeRejectMsg(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");1471 }1472 }1473 var stock = SymbolToStockMap[symbol];1474 if (stock == null) {1475 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()");1476 }1477 var orderType, orderPos;1478 type = type.toLowerCase();1479 if (type.includes("limit") && type.includes("buy")) {1480 orderType = OrderTypes.LimitBuy;1481 } else if (type.includes("limit") && type.includes("sell")) {1482 orderType = OrderTypes.LimitSell;1483 } else if (type.includes("stop") && type.includes("buy")) {1484 orderType = OrderTypes.StopBuy;1485 } else if (type.includes("stop") && type.includes("sell")) {1486 orderType = OrderTypes.StopSell;1487 } else {1488 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");1489 }1490 pos = pos.toLowerCase();1491 if (pos.includes("l")) {1492 orderPos = PositionTypes.Long;1493 } else if (pos.includes('s')) {1494 orderPos = PositionTypes.Short;1495 } else {1496 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");1497 }1498 return placeOrder(stock, shares, price, orderType, orderPos, workerScript);1499 },1500 cancelOrder(symbol, shares, price, type, pos) {1501 if (workerScript.checkingRam) {1502 return updateStaticRam("cancelOrder", CONSTANTS.ScriptBuySellStockRamCost);1503 }1504 updateDynamicRam("cancelOrder", CONSTANTS.ScriptBuySellStockRamCost);1505 if (!Player.hasTixApiAccess) {1506 throw makeRuntimeRejectMsg(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()");1507 }1508 if (Player.bitNodeN !== 8) {1509 if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {1510 throw makeRuntimeRejectMsg(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8");1511 }1512 }1513 var stock = SymbolToStockMap[symbol];1514 if (stock == null) {1515 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()");1516 }1517 if (isNaN(shares) || isNaN(price)) {1518 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric");1519 }1520 var orderType, orderPos;1521 type = type.toLowerCase();1522 if (type.includes("limit") && type.includes("buy")) {1523 orderType = OrderTypes.LimitBuy;1524 } else if (type.includes("limit") && type.includes("sell")) {1525 orderType = OrderTypes.LimitSell;1526 } else if (type.includes("stop") && type.includes("buy")) {1527 orderType = OrderTypes.StopBuy;1528 } else if (type.includes("stop") && type.includes("sell")) {1529 orderType = OrderTypes.StopSell;1530 } else {1531 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");1532 }1533 pos = pos.toLowerCase();1534 if (pos.includes("l")) {1535 orderPos = PositionTypes.Long;1536 } else if (pos.includes('s')) {1537 orderPos = PositionTypes.Short;1538 } else {1539 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");1540 }1541 var params = {1542 stock: stock,1543 shares: shares,1544 price: price,1545 type: orderType,1546 pos: orderPos1547 };1548 return cancelOrder(params, workerScript);1549 },1550 getPurchasedServerLimit : function() {1551 if (workerScript.checkingRam) {1552 return updateStaticRam("getPurchasedServerLimit", CONSTANTS.ScriptGetPurchasedServerLimit);1553 }1554 updateDynamicRam("getPurchasedServerLimit", CONSTANTS.ScriptGetPurchasedServerLimit);1555 return CONSTANTS.PurchasedServerLimit;1556 },1557 getPurchasedServerMaxRam: function() {1558 if (workerScript.checkingRam) {1559 return updateStaticRam("getPurchasedServerMaxRam", CONSTANTS.ScriptGetPurchasedServerMaxRam);1560 }1561 updateDynamicRam("getPurchasedServerMaxRam", CONSTANTS.ScriptGetPurchasedServerMaxRam);1562 return CONSTANTS.PurchasedServerMaxRam;1563 },1564 getPurchasedServerCost: function(ram) {1565 if (workerScript.checkingRam) {1566 return updateStaticRam("getPurchasedServerCost", CONSTANTS.ScriptGetPurchaseServerRamCost);1567 }1568 updateDynamicRam("getPurchasedServerCost", CONSTANTS.ScriptGetPurchaseServerRamCost);1569 let cost = 0;1570 try {1571 cost = getPurchaseServerRamCostGuard(ram);1572 } catch (e) {1573 workerScript.scriptRef.log("ERROR: 'getPurchasedServerCost()' " + e.message);1574 return "";1575 }1576 return cost;1577 },1578 purchaseServer : function(hostname, ram) {1579 if (workerScript.checkingRam) {1580 return updateStaticRam("purchaseServer", CONSTANTS.ScriptPurchaseServerRamCost);1581 }1582 updateDynamicRam("purchaseServer", CONSTANTS.ScriptPurchaseServerRamCost);1583 var hostnameStr = String(hostname);1584 hostnameStr = hostnameStr.replace(/\s+/g, '');1585 if (hostnameStr == "") {1586 workerScript.scriptRef.log("ERROR: Passed empty string for hostname argument of purchaseServer()");1587 return "";1588 }1589 if (Player.purchasedServers.length >= CONSTANTS.PurchasedServerLimit) {1590 workerScript.scriptRef.log("ERROR: You have reached the maximum limit of " + CONSTANTS.PurchasedServerLimit +1591 " servers. You cannot purchase any more.");1592 return "";1593 }1594 let cost = 0;1595 try {1596 cost = getPurchaseServerRamCostGuard(ram);1597 } catch (e) {1598 workerScript.scriptRef.log("ERROR: 'purchaseServer()' " + e.message);1599 return "";1600 }1601 if (Player.money.lt(cost)) {1602 workerScript.scriptRef.log("ERROR: Not enough money to purchase server. Need $" + formatNumber(cost, 2));1603 return "";1604 }1605 var newServ = new Server({1606 ip: createRandomIp(),1607 hostname: hostnameStr,1608 organizationName: "",1609 isConnectedTo: false,1610 adminRights: true,1611 purchasedByPlayer: true,1612 maxRam: ram,1613 });1614 AddToAllServers(newServ);1615 Player.purchasedServers.push(newServ.ip);1616 var homeComputer = Player.getHomeComputer();1617 homeComputer.serversOnNetwork.push(newServ.ip);1618 newServ.serversOnNetwork.push(homeComputer.ip);1619 Player.loseMoney(cost);1620 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) {1621 workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + formatNumber(cost, 2));1622 }1623 return newServ.hostname;1624 },1625 deleteServer : function(hostname) {1626 if (workerScript.checkingRam) {1627 return updateStaticRam("deleteServer", CONSTANTS.ScriptPurchaseServerRamCost);1628 }1629 updateDynamicRam("deleteServer", CONSTANTS.ScriptPurchaseServerRamCost);1630 var hostnameStr = String(hostname);1631 hostnameStr = hostnameStr.replace(/\s\s+/g, '');1632 var server = GetServerByHostname(hostnameStr);1633 if (server == null) {1634 workerScript.scriptRef.log("ERROR: Could not find server with hostname " + hostnameStr + ". deleteServer() failed");1635 return false;1636 }1637 if (!server.purchasedByPlayer || server.hostname === "home") {1638 workerScript.scriptRef.log("ERROR: Server " + server.hostname + " is not a purchased server. " +1639 "Cannot be deleted. deleteServer() failed");1640 return false;1641 }1642 var ip = server.ip;1643 //Can't delete server you're currently connected to1644 if (server.isConnectedTo) {1645 workerScript.scriptRef.log("ERROR: deleteServer() failed because you are currently connected to the server you are trying to delete");1646 return false;1647 }1648 //A server cannot delete itself1649 if (ip === workerScript.serverIp) {1650 workerScript.scriptRef.log("ERROR: Cannot call deleteServer() on self. deleteServer() failed");1651 return false;1652 }1653 //Delete all scripts running on server1654 if (server.runningScripts.length > 0) {1655 workerScript.scriptRef.log("ERROR: Cannot delete server " + server.hostname + " because it still has scripts running.");1656 return false;1657 }1658 //Delete from player's purchasedServers array1659 var found = false;1660 for (var i = 0; i < Player.purchasedServers.length; ++i) {1661 if (ip == Player.purchasedServers[i]) {1662 found = true;1663 Player.purchasedServers.splice(i, 1);1664 break;1665 }1666 }1667 if (!found) {1668 workerScript.scriptRef.log("ERROR: Could not identify server " + server.hostname +1669 "as a purchased server. This is likely a bug please contact game dev");1670 return false;1671 }1672 //Delete from all servers1673 delete AllServers[ip];1674 //Delete from home computer1675 found = false;1676 var homeComputer = Player.getHomeComputer();1677 for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {1678 if (ip == homeComputer.serversOnNetwork[i]) {1679 homeComputer.serversOnNetwork.splice(i, 1);1680 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) {1681 workerScript.scriptRef.log("Deleted server " + hostnameStr);1682 }1683 return true;1684 }1685 }1686 //Wasn't found on home computer1687 workerScript.scriptRef.log("ERROR: Could not find server " + server.hostname +1688 "as a purchased server. This is likely a bug please contact game dev");1689 return false;1690 },1691 getPurchasedServers : function(hostname=true) {1692 if (workerScript.checkingRam) {1693 return updateStaticRam("getPurchasedServers", CONSTANTS.ScriptPurchaseServerRamCost);1694 }1695 updateDynamicRam("getPurchasedServers", CONSTANTS.ScriptPurchaseServerRamCost);1696 var res = [];1697 Player.purchasedServers.forEach(function(ip) {1698 if (hostname) {1699 var server = getServer(ip);1700 if (server == null) {1701 throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find server in getPurchasedServers(). This is a bug please report to game dev");1702 }1703 res.push(server.hostname);1704 } else {1705 res.push(ip);1706 }1707 });1708 return res;1709 },1710 write : function(port, data="", mode="a") {1711 if (workerScript.checkingRam) {1712 return updateStaticRam("write", CONSTANTS.ScriptReadWriteRamCost);1713 }1714 updateDynamicRam("write", CONSTANTS.ScriptReadWriteRamCost);1715 if (!isNaN(port)) { //Write to port1716 //Port 1-101717 port = Math.round(port);1718 if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {1719 throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to write to invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid.");1720 }1721 var port = NetscriptPorts[port-1];1722 if (port == null || !(port instanceof NetscriptPort)) {1723 throw makeRuntimeRejectMsg(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");1724 }1725 return port.write(data);1726 } else if (isString(port)) { //Write to text file1727 var fn = port;1728 var server = getServer(workerScript.serverIp);1729 if (server == null) {1730 throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev");1731 }1732 var txtFile = getTextFile(fn, server);1733 if (txtFile == null) {1734 txtFile = createTextFile(fn, data, server);1735 return true;1736 }1737 if (mode === "w") {1738 txtFile.write(data);1739 } else {1740 txtFile.append(data);1741 }1742 return true;1743 } else {1744 throw makeRuntimeRejectMsg(workerScript, "Invalid argument passed in for write: " + port);1745 }1746 },1747 read : function(port) {1748 if (workerScript.checkingRam) {1749 return updateStaticRam("read", CONSTANTS.ScriptReadWriteRamCost);1750 }1751 updateDynamicRam("read", CONSTANTS.ScriptReadWriteRamCost);1752 if (!isNaN(port)) { //Read from port1753 //Port 1-101754 port = Math.round(port);1755 if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {1756 throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to read from invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid.");1757 }1758 var port = NetscriptPorts[port-1];1759 if (port == null || !(port instanceof NetscriptPort)) {1760 throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");1761 }1762 return port.read();1763 } else if (isString(port)) { //Read from text file1764 var fn = port;1765 var server = getServer(workerScript.serverIp);1766 if (server == null) {1767 throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev");1768 }1769 var txtFile = getTextFile(fn, server);1770 if (txtFile !== null) {1771 return txtFile.text;1772 } else {1773 return "";1774 }1775 } else {1776 throw makeRuntimeRejectMsg(workerScript, "Invalid argument passed in for read(): " + port);1777 }1778 },1779 peek : function(port) {1780 if (workerScript.checkingRam) {1781 return updateStaticRam("peek", CONSTANTS.ScriptReadWriteRamCost);1782 }1783 updateDynamicRam("peek", CONSTANTS.ScriptReadWriteRamCost);1784 if (isNaN(port)) {1785 throw makeRuntimeRejectMsg(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + CONSTANTS.NumNetscriptPorts);1786 }1787 port = Math.round(port);1788 if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {1789 throw makeRuntimeRejectMsg(workerScript, "ERROR: peek() called with invalid argument. Must be a port number between 1 and " + CONSTANTS.NumNetscriptPorts);1790 }1791 var port = NetscriptPorts[port-1];1792 if (port == null || !(port instanceof NetscriptPort)) {1793 throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");1794 }1795 return port.peek();1796 },1797 clear : function(port) {1798 if (workerScript.checkingRam) {1799 return updateStaticRam("clear", CONSTANTS.ScriptReadWriteRamCost);1800 }1801 updateDynamicRam("clear", CONSTANTS.ScriptReadWriteRamCost);1802 if (!isNaN(port)) { //Clear port1803 port = Math.round(port);1804 if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {1805 throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to clear invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid");1806 }1807 var port = NetscriptPorts[port-1];1808 if (port == null || !(port instanceof NetscriptPort)) {1809 throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");1810 }1811 return port.clear();1812 } else if (isString(port)) { //Clear text file1813 var fn = port;1814 var server = getServer(workerScript.serverIp);1815 if (server == null) {1816 throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev");1817 }1818 var txtFile = getTextFile(fn, server);1819 if (txtFile != null) {1820 txtFile.write("");1821 }1822 } else {1823 throw makeRuntimeRejectMsg(workerScript, "Invalid argument passed in for clear(): " + port);1824 }1825 return 0;1826 },1827 getPortHandle : function(port) {1828 if (workerScript.checkingRam) {1829 return updateStaticRam("getPortHandle", CONSTANTS.ScriptReadWriteRamCost * 10);1830 }1831 updateDynamicRam("getPortHandle", CONSTANTS.ScriptReadWriteRamCost * 10);1832 if (isNaN(port)) {1833 throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + CONSTANTS.NumNetscriptPorts);1834 }1835 port = Math.round(port);1836 if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {1837 throw makeRuntimeRejectMsg(workerScript, "ERROR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid");1838 }1839 var port = NetscriptPorts[port-1];1840 if (port == null || !(port instanceof NetscriptPort)) {1841 throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");1842 }1843 return port;1844 },1845 rm : function(fn) {1846 if (workerScript.checkingRam) {1847 return updateStaticRam("rm", CONSTANTS.ScriptReadWriteRamCost);1848 }1849 updateDynamicRam("rm", CONSTANTS.ScriptReadWriteRamCost);1850 var s = getServer(workerScript.serverIp);1851 if (s == null) {1852 throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev");1853 }1854 if (fn.includes(".exe")) {1855 for (var i = 0; i < s.programs.length; ++i) {1856 if (s.programs[i] === fn) {1857 s.programs.splice(i, 1);1858 return true;1859 }1860 }1861 } else if (isScriptFilename(fn)) {1862 for (var i = 0; i < s.scripts.length; ++i) {1863 if (s.scripts[i].filename === fn) {1864 //Check that the script isnt currently running1865 for (var j = 0; j < s.runningScripts.length; ++j) {1866 if (s.runningScripts[j].filename === fn) {1867 workerScript.scriptRef.log("Cannot delete a script that is currently running!");1868 return false;1869 }1870 }1871 s.scripts.splice(i, 1);1872 return true;1873 }1874 }1875 } else if (fn.endsWith(".lit")) {1876 for (var i = 0; i < s.messages.length; ++i) {1877 var f = s.messages[i];1878 if (!(f instanceof Message) && isString(f) && f === fn) {1879 s.messages.splice(i, 1);1880 return true;1881 }1882 }1883 } else if (fn.endsWith(".txt")) {1884 for (var i = 0; i < s.textFiles.length; ++i) {1885 if (s.textFiles[i].fn === fn) {1886 s.textFiles.splice(i, 1);1887 return true;1888 }1889 }1890 }1891 return false;1892 },1893 scriptRunning : function(scriptname, ip) {1894 if (workerScript.checkingRam) {1895 return updateStaticRam("scriptRunning", CONSTANTS.ScriptArbScriptRamCost);1896 }1897 updateDynamicRam("scriptRunning", CONSTANTS.ScriptArbScriptRamCost);1898 var server = getServer(ip);1899 if (server == null) {1900 workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip);1901 throw makeRuntimeRejectMsg(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip);1902 }1903 for (var i = 0; i < server.runningScripts.length; ++i) {1904 if (server.runningScripts[i].filename == scriptname) {1905 return true;1906 }1907 }1908 return false;1909 },1910 scriptKill : function(scriptname, ip) {1911 if (workerScript.checkingRam) {1912 return updateStaticRam("scriptKill", CONSTANTS.ScriptArbScriptRamCost);1913 }1914 updateDynamicRam("scriptKill", CONSTANTS.ScriptArbScriptRamCost);1915 var server = getServer(ip);1916 if (server == null) {1917 workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip);1918 throw makeRuntimeRejectMsg(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip);1919 }1920 var suc = false;1921 for (var i = 0; i < server.runningScripts.length; ++i) {1922 if (server.runningScripts[i].filename == scriptname) {1923 killWorkerScript(server.runningScripts[i], server.ip);1924 suc = true;1925 }1926 }1927 return suc;1928 },1929 getScriptName : function() {1930 if (workerScript.checkingRam) {return 0;}1931 return workerScript.name;1932 },1933 getScriptRam : function (scriptname, ip=workerScript.serverIp) {1934 if (workerScript.checkingRam) {1935 return updateStaticRam("getScriptRam", CONSTANTS.ScriptGetScriptRamCost);1936 }1937 updateDynamicRam("getScriptRam", CONSTANTS.ScriptGetScriptRamCost);1938 var server = getServer(ip);1939 if (server == null) {1940 workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip);1941 throw makeRuntimeRejectMsg(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip);1942 }1943 for (var i = 0; i < server.scripts.length; ++i) {1944 if (server.scripts[i].filename == scriptname) {1945 return server.scripts[i].ramUsage;1946 }1947 }1948 return 0;1949 },1950 getHackTime : function(ip) {1951 if (workerScript.checkingRam) {1952 return updateStaticRam("getHackTime", CONSTANTS.ScriptGetHackTimeRamCost);1953 }1954 updateDynamicRam("getHackTime", CONSTANTS.ScriptGetHackTimeRamCost);1955 var server = getServer(ip);1956 if (server == null) {1957 workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);1958 throw makeRuntimeRejectMsg(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);1959 }1960 return scriptCalculateHackingTime(server); //Returns seconds1961 },1962 getGrowTime : function(ip) {1963 if (workerScript.checkingRam) {1964 return updateStaticRam("getGrowTime", CONSTANTS.ScriptGetHackTimeRamCost);1965 }1966 updateDynamicRam("getGrowTime", CONSTANTS.ScriptGetHackTimeRamCost);1967 var server = getServer(ip);1968 if (server == null) {1969 workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);1970 throw makeRuntimeRejectMsg(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);1971 }1972 return scriptCalculateGrowTime(server) / 1000; //Returns seconds1973 },1974 getWeakenTime : function(ip) {1975 if (workerScript.checkingRam) {1976 return updateStaticRam("getWeakenTime", CONSTANTS.ScriptGetHackTimeRamCost);1977 }1978 updateDynamicRam("getWeakenTime", CONSTANTS.ScriptGetHackTimeRamCost);1979 var server = getServer(ip);1980 if (server == null) {1981 workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);1982 throw makeRuntimeRejectMsg(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);1983 }1984 return scriptCalculateWeakenTime(server) / 1000; //Returns seconds1985 },1986 getScriptIncome : function(scriptname, ip) {1987 if (workerScript.checkingRam) {1988 return updateStaticRam("getScriptIncome", CONSTANTS.ScriptGetScriptRamCost);1989 }1990 updateDynamicRam("getScriptIncome", CONSTANTS.ScriptGetScriptRamCost);1991 if (arguments.length === 0) {1992 //Get total script income1993 var res = [];1994 res.push(updateActiveScriptsItems());1995 res.push(Player.scriptProdSinceLastAug / (Player.playtimeSinceLastAug/1000));1996 return res;1997 } else {1998 //Get income for a particular script1999 var server = getServer(ip);2000 if (server == null) {2001 workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);2002 throw makeRuntimeRejectMsg(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);2003 }2004 var argsForScript = [];2005 for (var i = 2; i < arguments.length; ++i) {2006 argsForScript.push(arguments[i]);2007 }2008 var runningScriptObj = findRunningScript(scriptname, argsForScript, server);2009 if (runningScriptObj == null) {2010 workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + arrayToString(argsForScript));2011 return -1;2012 }2013 return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime;2014 }2015 },2016 getScriptExpGain : function(scriptname, ip) {2017 if (workerScript.checkingRam) {2018 return updateStaticRam("getScriptExpGain", CONSTANTS.ScriptGetScriptRamCost);2019 }2020 updateDynamicRam("getScriptExpGain", CONSTANTS.ScriptGetScriptRamCost);2021 if (arguments.length === 0) {2022 var total = 0;2023 for (var i = 0; i < workerScripts.length; ++i) {2024 total += (workerScripts[i].scriptRef.onlineExpGained / workerScripts[i].scriptRef.onlineRunningTime);2025 }2026 return total;2027 } else {2028 //Get income for a particular script2029 var server = getServer(ip);2030 if (server == null) {2031 workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);2032 throw makeRuntimeRejectMsg(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);2033 }2034 var argsForScript = [];2035 for (var i = 2; i < arguments.length; ++i) {2036 argsForScript.push(arguments[i]);2037 }2038 var runningScriptObj = findRunningScript(scriptname, argsForScript, server);2039 if (runningScriptObj == null) {2040 workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + arrayToString(argsForScript));2041 return -1;2042 }2043 return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime;2044 }2045 },2046 getTimeSinceLastAug : function() {2047 if (workerScript.checkingRam) {2048 return updateStaticRam("getTimeSinceLastAug", CONSTANTS.ScriptGetHackTimeRamCost);2049 }2050 updateDynamicRam("getTimeSinceLastAug", CONSTANTS.ScriptGetHackTimeRamCost);2051 return Player.playtimeSinceLastAug;2052 },2053 prompt : function(txt) {2054 if (workerScript.checkingRam) {return 0;}2055 if (yesNoBoxOpen) {2056 workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open");2057 return false;2058 }2059 if (!isString(txt)) {txt = String(txt);}2060 var yesBtn = yesNoBoxGetYesButton(), noBtn = yesNoBoxGetNoButton();2061 yesBtn.innerHTML = "Yes";2062 noBtn.innerHTML = "No";2063 return new Promise(function(resolve, reject) {2064 yesBtn.addEventListener("click", ()=>{2065 yesNoBoxClose();2066 resolve(true);2067 });2068 noBtn.addEventListener("click", ()=>{2069 yesNoBoxClose();2070 resolve(false);2071 });2072 yesNoBoxCreate(txt);2073 });2074 },2075 getFavorToDonate: function() {2076 if (workerScript.checkingRam) {2077 return updateStaticRam("getFavorToDonate", CONSTANTS.ScriptGetFavorToDonate);2078 }2079 updateDynamicRam("getFavorToDonate", CONSTANTS.ScriptGetFavorToDonate);2080 return Math.floor(CONSTANTS.BaseFavorToDonate * BitNodeMultipliers.RepToDonateToFaction);2081 },2082 /* Singularity Functions */2083 universityCourse : function(universityName, className) {2084 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost;2085 if (Player.bitNodeN !== 4) {ramCost *= 8;}2086 if (workerScript.checkingRam) {2087 return updateStaticRam("universityCourse", ramCost);2088 }2089 updateDynamicRam("universityCourse", ramCost);2090 if (Player.bitNodeN != 4) {2091 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2092 throw makeRuntimeRejectMsg(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2093 return false;2094 }2095 }2096 if (inMission) {2097 workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission.");2098 return;2099 }2100 if (Player.isWorking) {2101 var txt = Player.singularityStopWork();2102 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {2103 workerScript.scriptRef.log(txt);2104 }2105 }2106 var costMult, expMult;2107 switch(universityName.toLowerCase()) {2108 case Locations.AevumSummitUniversity.toLowerCase():2109 if (Player.city != Locations.Aevum) {2110 workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed");2111 return false;2112 }2113 Player.location = Locations.AevumSummitUniversity;2114 costMult = 4;2115 expMult = 3;2116 break;2117 case Locations.Sector12RothmanUniversity.toLowerCase():2118 if (Player.city != Locations.Sector12) {2119 workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed");2120 return false;2121 }2122 Player.location = Locations.Sector12RothmanUniversity;2123 costMult = 3;2124 expMult = 2;2125 break;2126 case Locations.VolhavenZBInstituteOfTechnology.toLowerCase():2127 if (Player.city != Locations.Volhaven) {2128 workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed");2129 return false;2130 }2131 Player.location = Locations.VolhavenZBInstituteOfTechnology;2132 costMult = 5;2133 expMult = 4;2134 break;2135 default:2136 workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed");2137 return false;2138 }2139 var task;2140 switch(className.toLowerCase()) {2141 case "Study Computer Science".toLowerCase():2142 task = CONSTANTS.ClassStudyComputerScience;2143 break;2144 case "Data Structures".toLowerCase():2145 task = CONSTANTS.ClassDataStructures;2146 break;2147 case "Networks".toLowerCase():2148 task = CONSTANTS.ClassNetworks;2149 break;2150 case "Algorithms".toLowerCase():2151 task = CONSTANTS.ClassAlgorithms;2152 break;2153 case "Management".toLowerCase():2154 task = CONSTANTS.ClassManagement;2155 break;2156 case "Leadership".toLowerCase():2157 task = CONSTANTS.ClassLeadership;2158 break;2159 default:2160 workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed");2161 return false;2162 }2163 Player.startClass(costMult, expMult, task);2164 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) {2165 workerScript.scriptRef.log("Started " + task + " at " + universityName);2166 }2167 return true;2168 },2169 gymWorkout : function(gymName, stat) {2170 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost;2171 if (Player.bitNodeN !== 4) {ramCost *= 8;}2172 if (workerScript.checkingRam) {2173 return updateStaticRam("gymWorkout", ramCost);2174 }2175 updateDynamicRam("gymWorkout", ramCost);2176 if (Player.bitNodeN != 4) {2177 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2178 throw makeRuntimeRejectMsg(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2179 return false;2180 }2181 }2182 if (inMission) {2183 workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission.");2184 return;2185 }2186 if (Player.isWorking) {2187 var txt = Player.singularityStopWork();2188 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {2189 workerScript.scriptRef.log(txt);2190 }2191 }2192 var costMult, expMult;2193 switch(gymName.toLowerCase()) {2194 case Locations.AevumCrushFitnessGym.toLowerCase():2195 if (Player.city != Locations.Aevum) {2196 workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed");2197 return false;2198 }2199 Player.location = Locations.AevumCrushFitnessGym;2200 costMult = 3;2201 expMult = 2;2202 break;2203 case Locations.AevumSnapFitnessGym.toLowerCase():2204 if (Player.city != Locations.Aevum) {2205 workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed");2206 return false;2207 }2208 Player.location = Locations.AevumSnapFitnessGym;2209 costMult = 10;2210 expMult = 5;2211 break;2212 case Locations.Sector12IronGym.toLowerCase():2213 if (Player.city != Locations.Sector12) {2214 workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed");2215 return false;2216 }2217 Player.location = Locations.Sector12IronGym;2218 costMult = 1;2219 expMult = 1;2220 break;2221 case Locations.Sector12PowerhouseGym.toLowerCase():2222 if (Player.city != Locations.Sector12) {2223 workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed");2224 return false;2225 }2226 Player.location = Locations.Sector12PowerhouseGym;2227 costMult = 20;2228 expMult = 10;2229 break;2230 case Locations.VolhavenMilleniumFitnessGym:2231 if (Player.city != Locations.Volhaven) {2232 workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed");2233 return false;2234 }2235 Player.location = Locations.VolhavenMilleniumFitnessGym;2236 costMult = 7;2237 expMult = 4;2238 break;2239 default:2240 workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed");2241 return false;2242 }2243 switch(stat.toLowerCase()) {2244 case "strength".toLowerCase():2245 case "str".toLowerCase():2246 Player.startClass(costMult, expMult, CONSTANTS.ClassGymStrength);2247 break;2248 case "defense".toLowerCase():2249 case "def".toLowerCase():2250 Player.startClass(costMult, expMult, CONSTANTS.ClassGymDefense);2251 break;2252 case "dexterity".toLowerCase():2253 case "dex".toLowerCase():2254 Player.startClass(costMult, expMult, CONSTANTS.ClassGymDexterity);2255 break;2256 case "agility".toLowerCase():2257 case "agi".toLowerCase():2258 Player.startClass(costMult, expMult, CONSTANTS.ClassGymAgility);2259 break;2260 default:2261 workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed");2262 return false;2263 }2264 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) {2265 workerScript.scriptRef.log("Started training " + stat + " at " + gymName);2266 }2267 return true;2268 },2269 travelToCity(cityname) {2270 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost;2271 if (Player.bitNodeN !== 4) {ramCost *= 8;}2272 if (workerScript.checkingRam) {2273 return updateStaticRam("travelToCity", ramCost);2274 }2275 updateDynamicRam("travelToCity", ramCost);2276 if (Player.bitNodeN != 4) {2277 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2278 throw makeRuntimeRejectMsg(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2279 return false;2280 }2281 }2282 switch(cityname) {2283 case Locations.Aevum:2284 case Locations.Chongqing:2285 case Locations.Sector12:2286 case Locations.NewTokyo:2287 case Locations.Ishima:2288 case Locations.Volhaven:2289 if(Player.money.lt(CONSTANTS.TravelCost)) {2290 workerScript.scriptRef.log("ERROR: not enough money to travel with travelToCity().");2291 throw makeRuntimeRejectMsg(workerScript, "ERROR: not enough money to travel with travelToCity().");2292 }2293 Player.loseMoney(CONSTANTS.TravelCost);2294 Player.city = cityname;2295 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) {2296 workerScript.scriptRef.log("Traveled to " + cityname);2297 }2298 return true;2299 default:2300 workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity().");2301 return false;2302 }2303 },2304 purchaseTor() {2305 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost;2306 if (Player.bitNodeN !== 4) {ramCost *= 8;}2307 if (workerScript.checkingRam) {2308 return updateStaticRam("purchaseTor", ramCost);2309 }2310 updateDynamicRam("purchaseTor", ramCost);2311 if (Player.bitNodeN != 4) {2312 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2313 throw makeRuntimeRejectMsg(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2314 return false;2315 }2316 }2317 if (SpecialServerIps["Darkweb Server"] != null) {2318 workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed");2319 return false;2320 }2321 if (Player.money.lt(CONSTANTS.TorRouterCost)) {2322 workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed");2323 return false;2324 }2325 Player.loseMoney(CONSTANTS.TorRouterCost);2326 var darkweb = new Server({2327 ip:createRandomIp(), hostname:"darkweb", organizationName:"",2328 isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:12329 });2330 AddToAllServers(darkweb);2331 SpecialServerIps.addIp("Darkweb Server", darkweb.ip);2332 const purchaseTor = document.getElementById("location-purchase-tor");2333 purchaseTor.setAttribute("class", "a-link-button-bought");2334 purchaseTor.innerHTML = "TOR Router - Purchased";2335 Player.getHomeComputer().serversOnNetwork.push(darkweb.ip);2336 darkweb.serversOnNetwork.push(Player.getHomeComputer().ip);2337 Player.gainIntelligenceExp(CONSTANTS.IntelligenceSingFnBaseExpGain);2338 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) {2339 workerScript.scriptRef.log("You have purchased a Tor router!");2340 }2341 return true;2342 },2343 purchaseProgram(programName) {2344 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost;2345 if (Player.bitNodeN !== 4) {ramCost *= 8;}2346 if (workerScript.checkingRam) {2347 return updateStaticRam("purchaseProgram", ramCost);2348 }2349 updateDynamicRam("purchaseProgram", ramCost);2350 if (Player.bitNodeN != 4) {2351 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2352 throw makeRuntimeRejectMsg(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2353 return false;2354 }2355 }2356 if (SpecialServerIps["Darkweb Server"] == null) {2357 workerScript.scriptRef.log("ERROR: You do not have the TOR router. purchaseProgram() failed.");2358 return false;2359 }2360 programName = programName.toLowerCase();2361 let item = null;2362 for(const key in DarkWebItems) {2363 const i = DarkWebItems[key];2364 if(i.program.toLowerCase() == programName) {2365 item = i;2366 }2367 }2368 if(item == null) {2369 workerScript.scriptRef.log("ERROR: Invalid program name passed into purchaseProgram().");2370 return false;2371 }2372 if(Player.money.lt(item.price)) {2373 workerScript.scriptRef.log("Not enough money to purchase " + item.program);2374 return false;2375 }2376 if(Player.hasProgram(item.program)) {2377 workerScript.scriptRef.log('You already have the '+item.program+' program');2378 return true;2379 }2380 Player.loseMoney(item.price);2381 Player.getHomeComputer().programs.push(item.program);2382 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {2383 workerScript.scriptRef.log("You have purchased the "+item.program+" program. The new program can be found on your home computer.");2384 }2385 return true;2386 },2387 getStats : function() {2388 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost / 4;2389 if (Player.bitNodeN !== 4) {ramCost *= 8;}2390 if (workerScript.checkingRam) {2391 return updateStaticRam("getStats", ramCost);2392 }2393 updateDynamicRam("getStats", ramCost);2394 if (Player.bitNodeN != 4) {2395 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2396 throw makeRuntimeRejectMsg(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2397 return {};2398 }2399 }2400 return {2401 hacking: Player.hacking_skill,2402 strength: Player.strength,2403 defense: Player.defense,2404 dexterity: Player.dexterity,2405 agility: Player.agility,2406 charisma: Player.charisma,2407 intelligence: Player.intelligence2408 }2409 },2410 getCharacterInformation : function() {2411 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost / 4;2412 if (Player.bitNodeN !== 4) {ramCost *= 8;}2413 if (workerScript.checkingRam) {2414 return updateStaticRam("getCharacterInformation", ramCost);2415 }2416 updateDynamicRam("getCharacterInformation", ramCost);2417 if (Player.bitNodeN != 4) {2418 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2419 throw makeRuntimeRejectMsg(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2420 return {};2421 }2422 }2423 var companyPositionTitle = "";2424 if (Player.companyPosition instanceof CompanyPosition) {2425 companyPositionTitle = Player.companyPosition.positionName;2426 }2427 return {2428 bitnode: Player.bitNodeN,2429 company: Player.companyName,2430 jobTitle: companyPositionTitle,2431 city: Player.city,2432 factions: Player.factions.slice(),2433 tor: SpecialServerIps.hasOwnProperty("Darkweb Server"),2434 timeWorked: Player.timeWorked,2435 workHackExpGain: Player.workHackExpGained,2436 workStrExpGain: Player.workStrExpGained,2437 workDefExpGain: Player.workDefExpGained,2438 workDexExpGain: Player.workDexExpGained,2439 workAgiExpGain: Player.workAgiExpGained,2440 workChaExpGain: Player.workChaExpGained,2441 workRepGain: Player.workRepGained,2442 workMoneyGain: Player.workMoneyGained,2443 };2444 },2445 isBusy : function() {2446 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost / 4;2447 if (Player.bitNodeN !== 4) {ramCost *= 8;}2448 if (workerScript.checkingRam) {2449 return updateStaticRam("isBusy", ramCost);2450 }2451 updateDynamicRam("isBusy", ramCost);2452 if (Player.bitNodeN != 4) {2453 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2454 throw makeRuntimeRejectMsg(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2455 return;2456 }2457 }2458 return Player.isWorking;2459 },2460 stopAction : function() {2461 var ramCost = CONSTANTS.ScriptSingularityFn1RamCost / 2;2462 if (Player.bitNodeN !== 4) {ramCost *= 8;}2463 if (workerScript.checkingRam) {2464 return updateStaticRam("stopAction", ramCost);2465 }2466 updateDynamicRam("stopAction", ramCost);2467 if (Player.bitNodeN != 4) {2468 if (!(hasSingularitySF && singularitySFLvl >= 1)) {2469 throw makeRuntimeRejectMsg(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");2470 return false;2471 }2472 }2473 if (Player.isWorking) {2474 var txt = Player.singularityStopWork();2475 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) {2476 workerScript.scriptRef.log(txt);2477 }2478 return true;2479 }2480 return false;2481 },2482 upgradeHomeRam : function() {2483 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2484 if (Player.bitNodeN !== 4) {ramCost *= 8;}2485 if (workerScript.checkingRam) {2486 return updateStaticRam("upgradeHomeRam", ramCost);2487 }2488 updateDynamicRam("upgradeHomeRam", ramCost);2489 if (Player.bitNodeN != 4) {2490 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2491 throw makeRuntimeRejectMsg(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2492 return false;2493 }2494 }2495 const cost = Player.getUpgradeHomeRamCost();2496 if (Player.money.lt(cost)) {2497 workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money");2498 return false;2499 }2500 var homeComputer = Player.getHomeComputer();2501 homeComputer.maxRam *= 2;2502 Player.loseMoney(cost);2503 Player.gainIntelligenceExp(CONSTANTS.IntelligenceSingFnBaseExpGain);2504 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) {2505 workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");2506 }2507 return true;2508 },2509 getUpgradeHomeRamCost : function() {2510 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost / 2;2511 if (Player.bitNodeN !== 4) {ramCost *= 8;}2512 if (workerScript.checkingRam) {2513 return updateStaticRam("getUpgradeHomeRamCost", ramCost);2514 }2515 updateDynamicRam("getUpgradeHomeRamCost", ramCost);2516 if (Player.bitNodeN != 4) {2517 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2518 throw makeRuntimeRejectMsg(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2519 return false;2520 }2521 }2522 return Player.getUpgradeHomeRamCost();2523 },2524 workForCompany : function() {2525 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2526 if (Player.bitNodeN !== 4) {ramCost *= 8;}2527 if (workerScript.checkingRam) {2528 return updateStaticRam("workForCompany", ramCost);2529 }2530 updateDynamicRam("workForCompany", ramCost);2531 if (Player.bitNodeN != 4) {2532 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2533 throw makeRuntimeRejectMsg(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2534 return false;2535 }2536 }2537 if (inMission) {2538 workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission.");2539 return;2540 }2541 if (Player.companyPosition == "" || !(Player.companyPosition instanceof CompanyPosition)) {2542 workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job");2543 return false;2544 }2545 if (Player.isWorking) {2546 var txt = Player.singularityStopWork();2547 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {2548 workerScript.scriptRef.log(txt);2549 }2550 }2551 if (Player.companyPosition.isPartTimeJob()) {2552 Player.startWorkPartTime();2553 } else {2554 Player.startWork();2555 }2556 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {2557 workerScript.scriptRef.log("Began working at " + Player.companyName + " as a " + Player.companyPosition.positionName);2558 }2559 return true;2560 },2561 applyToCompany : function(companyName, field) {2562 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2563 if (Player.bitNodeN !== 4) {ramCost *= 8;}2564 if (workerScript.checkingRam) {2565 return updateStaticRam("applyToCompany", ramCost);2566 }2567 updateDynamicRam("applyToCompany", ramCost);2568 if (Player.bitNodeN != 4) {2569 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2570 throw makeRuntimeRejectMsg(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2571 return false;2572 }2573 }2574 if (!companyExists(companyName)) {2575 workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist.");2576 return false;2577 }2578 Player.location = companyName;2579 var res;2580 switch (field.toLowerCase()) {2581 case "software":2582 res = Player.applyForSoftwareJob(true);2583 break;2584 case "software consultant":2585 res = Player.applyForSoftwareConsultantJob(true);2586 break;2587 case "it":2588 res = Player.applyForItJob(true);2589 break;2590 case "security engineer":2591 res = Player.applyForSecurityEngineerJob(true);2592 break;2593 case "network engineer":2594 res = Player.applyForNetworkEngineerJob(true);2595 break;2596 case "business":2597 res = Player.applyForBusinessJob(true);2598 break;2599 case "business consultant":2600 res = Player.applyForBusinessConsultantJob(true);2601 break;2602 case "security":2603 res = Player.applyForSecurityJob(true);2604 break;2605 case "agent":2606 res = Player.applyForAgentJob(true);2607 break;2608 case "employee":2609 res = Player.applyForEmployeeJob(true);2610 break;2611 case "part-time employee":2612 res = Player.applyForPartTimeEmployeeJob(true);2613 break;2614 case "waiter":2615 res = Player.applyForWaiterJob(true);2616 break;2617 case "part-time waiter":2618 res = Player.applyForPartTimeWaiterJob(true);2619 break;2620 default:2621 workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed");2622 return false;2623 }2624 //The Player object's applyForJob function can return string with special error messages2625 if (isString(res)) {2626 workerScript.scriptRef.log(res);2627 return false;2628 }2629 if (res) {2630 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {2631 workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + Player.companyPosition.positionName);2632 }2633 } else {2634 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) {2635 workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field.");2636 }2637 }2638 return res;2639 },2640 getCompanyRep : function(companyName) {2641 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost / 2;2642 if (Player.bitNodeN !== 4) {ramCost *= 8;}2643 if (workerScript.checkingRam) {2644 return updateStaticRam("getCompanyRep", ramCost);2645 }2646 updateDynamicRam("getCompanyRep", ramCost);2647 if (Player.bitNodeN != 4) {2648 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2649 throw makeRuntimeRejectMsg(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2650 return false;2651 }2652 }2653 var company = Companies[companyName];2654 if (company == null || !(company instanceof Company)) {2655 workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName);2656 return -1;2657 }2658 return company.playerReputation;2659 },2660 getCompanyFavor : function(companyName) {2661 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost / 4;2662 if (Player.bitNodeN !== 4) {ramCost *= 8;}2663 if (workerScript.checkingRam) {2664 return updateStaticRam("getCompanyFavor", ramCost);2665 }2666 updateDynamicRam("getCompanyFavor", ramCost);2667 if (Player.bitNodeN != 4) {2668 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2669 throw makeRuntimeRejectMsg(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2670 return false;2671 }2672 }2673 var company = Companies[companyName];2674 if (company == null || !(company instanceof Company)) {2675 workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName);2676 return -1;2677 }2678 return company.favor;2679 },2680 getCompanyFavorGain : function(companyName) {2681 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost / 4;2682 if (Player.bitNodeN !== 4) {ramCost *= 8;}2683 if (workerScript.checkingRam) {2684 return updateStaticRam("getCompanyFavorGain", ramCost);2685 }2686 updateDynamicRam("getCompanyFavorGain", ramCost);2687 if (Player.bitNodeN != 4) {2688 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2689 throw makeRuntimeRejectMsg(workerScript, "Cannot run getCompanyFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2690 return -1;2691 }2692 }2693 var company = Companies[companyName];2694 if (company == null || !(company instanceof Company)) {2695 workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavorGain(): " + companyName);2696 return -1;2697 }2698 return company.getFavorGain()[0];2699 },2700 checkFactionInvitations : function() {2701 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2702 if (Player.bitNodeN !== 4) {ramCost *= 8;}2703 if (workerScript.checkingRam) {2704 return updateStaticRam("checkFactionInvitations", ramCost);2705 }2706 updateDynamicRam("checkFactionInvitations", ramCost);2707 if (Player.bitNodeN != 4) {2708 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2709 throw makeRuntimeRejectMsg(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2710 return false;2711 }2712 }2713 //Make a copy of Player.factionInvitations2714 return Player.factionInvitations.slice();2715 },2716 joinFaction : function(name) {2717 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2718 if (Player.bitNodeN !== 4) {ramCost *= 8;}2719 if (workerScript.checkingRam) {2720 return updateStaticRam("joinFaction", ramCost);2721 }2722 updateDynamicRam("joinFaction", ramCost);2723 if (Player.bitNodeN != 4) {2724 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2725 throw makeRuntimeRejectMsg(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2726 return false;2727 }2728 }2729 if (!factionExists(name)) {2730 workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist.");2731 return false;2732 }2733 if (!Player.factionInvitations.includes(name)) {2734 workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");2735 return false;2736 }2737 var index = Player.factionInvitations.indexOf(name);2738 if (index === -1) {2739 //Redundant and should never happen...2740 workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");2741 return false;2742 }2743 Player.factionInvitations.splice(index, 1);2744 var fac = Factions[name];2745 joinFaction(fac);2746 Player.gainIntelligenceExp(CONSTANTS.IntelligenceSingFnBaseExpGain);2747 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) {2748 workerScript.scriptRef.log("Joined the " + name + " faction.");2749 }2750 return true;2751 },2752 workForFaction : function(name, type) {2753 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2754 if (Player.bitNodeN !== 4) {ramCost *= 8;}2755 if (workerScript.checkingRam) {2756 return updateStaticRam("workForFaction", ramCost);2757 }2758 updateDynamicRam("workForFaction", ramCost);2759 if (Player.bitNodeN != 4) {2760 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2761 throw makeRuntimeRejectMsg(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2762 return false;2763 }2764 }2765 // if the player is in a gang and the target faction is any of the gang faction, fail2766 if(Player.inGang() && AllGangs[name] !== undefined) {2767 workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not offer work at the moment.");2768 return;2769 }2770 if (inMission) {2771 workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission.");2772 return;2773 }2774 if (!factionExists(name)) {2775 workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist.");2776 return false;2777 }2778 if (!Player.factions.includes(name)) {2779 workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name);2780 return false;2781 }2782 if (Player.isWorking) {2783 var txt = Player.singularityStopWork();2784 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) {2785 workerScript.scriptRef.log(txt);2786 }2787 }2788 var fac = Factions[name];2789 //Arrays listing factions that allow each time of work2790 var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",2791 "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",2792 "OmniTek Incorporated", "Four Sigma", "KuaiGong International",2793 "Fulcrum Secret Technologies", "BitRunners", "The Black Hand",2794 "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum",2795 "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",2796 "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"];2797 var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",2798 "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",2799 "OmniTek Incorporated", "Four Sigma", "KuaiGong International",2800 "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",2801 "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army",2802 "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"];2803 var scWkAvailable = ["ECorp", "MegaCorp",2804 "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",2805 "OmniTek Incorporated", "Four Sigma", "KuaiGong International",2806 "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum",2807 "Ishima", "Volhaven", "Speakers for the Dead",2808 "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"];2809 switch (type.toLowerCase()) {2810 case "hacking":2811 case "hacking contracts":2812 case "hackingcontracts":2813 if (!hackAvailable.includes(fac.name)) {2814 workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed");2815 return false;2816 }2817 Player.startFactionHackWork(fac);2818 workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name);2819 return true;2820 case "field":2821 case "fieldwork":2822 case "field work":2823 if (!fdWkAvailable.includes(fac.name)) {2824 workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed");2825 return false;2826 }2827 Player.startFactionFieldWork(fac);2828 workerScript.scriptRef.log("Started carrying out field missions for " + fac.name);2829 return true;2830 case "security":2831 case "securitywork":2832 case "security work":2833 if (!scWkAvailable.includes(fac.name)) {2834 workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed");2835 return false;2836 }2837 Player.startFactionSecurityWork(fac);2838 workerScript.scriptRef.log("Started serving as security details for " + fac.name);2839 return true;2840 default:2841 workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type);2842 }2843 return true;2844 },2845 getFactionRep : function(name) {2846 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost / 4;2847 if (Player.bitNodeN !== 4) {ramCost *= 8;}2848 if (workerScript.checkingRam) {2849 return updateStaticRam("getFactionRep", ramCost);2850 }2851 updateDynamicRam("getFactionRep", ramCost);2852 if (Player.bitNodeN != 4) {2853 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2854 throw makeRuntimeRejectMsg(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2855 return -1;2856 }2857 }2858 if (!factionExists(name)) {2859 workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist.");2860 return -1;2861 }2862 return Factions[name].playerReputation;2863 },2864 getFactionFavor : function(name) {2865 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2866 if (Player.bitNodeN !== 4) {ramCost *= 8;}2867 if (workerScript.checkingRam) {2868 return updateStaticRam("getFactionFavor", ramCost);2869 }2870 updateDynamicRam("getFactionFavor", ramCost);2871 if (Player.bitNodeN != 4) {2872 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2873 throw makeRuntimeRejectMsg(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2874 return -1;2875 }2876 }2877 if (!factionExists(name)) {2878 workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist.");2879 return -1;2880 }2881 return Factions[name].favor;2882 },2883 getFactionFavorGain: function(name){2884 var ramCost = CONSTANTS.ScriptSingularityFn2RamCost;2885 if (Player.bitNodeN !== 4) {ramCost *= 8;}2886 if (workerScript.checkingRam) {2887 return updateStaticRam("getFactionFavorGain", ramCost);2888 }2889 updateDynamicRam("getFactionFavorGain", ramCost);2890 if (Player.bitNodeN != 4) {2891 if (!(hasSingularitySF && singularitySFLvl >= 2)) {2892 throw makeRuntimeRejectMsg(workerScript, "Cannot run getFactionFavorGain(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");2893 return -1;2894 }2895 }2896 if (!factionExists(name)) {2897 workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavorGain() does not exist.");2898 return -1;2899 }2900 return Factions[name].getFavorGain()[0];2901 },2902 createProgram : function(name) {2903 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;2904 if (Player.bitNodeN !== 4) {ramCost *= 8;}2905 if (workerScript.checkingRam) {2906 return updateStaticRam("createProgram", ramCost);2907 }2908 updateDynamicRam("createProgram", ramCost);2909 if (Player.bitNodeN != 4) {2910 if (!(hasSingularitySF && singularitySFLvl >= 3)) {2911 throw makeRuntimeRejectMsg(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");2912 return false;2913 }2914 }2915 if (inMission) {2916 workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission.");2917 return;2918 }2919 if (Player.isWorking) {2920 var txt = Player.singularityStopWork();2921 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {2922 workerScript.scriptRef.log(txt);2923 }2924 }2925 name = name.toLowerCase();2926 let p = null;2927 for (const key in Programs) {2928 if(Programs[key].name.toLowerCase() == name) {2929 p = Programs[key];2930 }2931 }2932 if (p == null) {2933 workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name);2934 return false;2935 }2936 if (Player.hasProgram(p.name)) {2937 workerScript.scriptRef.log('ERROR: createProgram() failed because you already have the ' + p.name + ' program');2938 return false;2939 }2940 if (!p.create.req()) {2941 workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create " + p.name + " (level " + p.create.level + " req)");2942 return false2943 }2944 Player.startCreateProgramWork(p.name, p.create.time, p.create.level);2945 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {2946 workerScript.scriptRef.log("Began creating program: " + name);2947 }2948 return true;2949 },2950 commitCrime : function(crimeRoughName) {2951 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;2952 if (Player.bitNodeN !== 4) {ramCost *= 8;}2953 if (workerScript.checkingRam) {2954 return updateStaticRam("commitCrime", ramCost);2955 }2956 updateDynamicRam("commitCrime", ramCost);2957 if (Player.bitNodeN != 4) {2958 if (!(hasSingularitySF && singularitySFLvl >= 3)) {2959 throw makeRuntimeRejectMsg(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");2960 return;2961 }2962 }2963 if (inMission) {2964 workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission.");2965 return;2966 }2967 if (Player.isWorking) {2968 var txt = Player.singularityStopWork();2969 if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) {2970 workerScript.scriptRef.log(txt);2971 }2972 }2973 //Set Location to slums2974 switch(Player.city) {2975 case Locations.Aevum:2976 Player.location = Locations.AevumSlums;2977 break;2978 case Locations.Chongqing:2979 Player.location = Locations.ChongqingSlums;2980 break;2981 case Locations.Sector12:2982 Player.location = Locations.Sector12Slums;2983 break;2984 case Locations.NewTokyo:2985 Player.location = Locations.NewTokyoSlums;2986 break;2987 case Locations.Ishima:2988 Player.location = Locations.IshimaSlums;2989 break;2990 case Locations.Volhaven:2991 Player.location = Locations.VolhavenSlums;2992 break;2993 default:2994 console.log("Invalid Player.city value");2995 }2996 const crime = findCrime(crimeRoughName.toLowerCase());2997 if(crime == null) { // couldn't find crime2998 throw makeRuntimeRejectMsg(workerScript, "Invalid crime passed into commitCrime(): " + crimeRoughName);2999 }3000 if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) {3001 workerScript.scriptRef.log("Attempting to commit crime: "+crime.name+"...");3002 }3003 return crime.commit(CONSTANTS.CrimeSingFnDivider, {workerscript: workerScript});3004 },3005 getCrimeChance : function(crimeRoughName) {3006 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3007 if (Player.bitNodeN !== 4) {ramCost *= 8;}3008 if (workerScript.checkingRam) {3009 return updateStaticRam("getCrimeChance", ramCost);3010 }3011 updateDynamicRam("getCrimeChance", ramCost);3012 if (Player.bitNodeN != 4) {3013 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3014 throw makeRuntimeRejectMsg(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3015 return;3016 }3017 }3018 const crime = findCrime(crimeRoughName.toLowerCase());3019 if(crime == null) {3020 throw makeRuntimeRejectMsg(workerScript, "Invalid crime passed into getCrimeChance(): " + crime);3021 }3022 return crime.successRate();3023 },3024 getOwnedAugmentations : function(purchased=false) {3025 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3026 if (Player.bitNodeN !== 4) {ramCost *= 8;}3027 if (workerScript.checkingRam) {3028 return updateStaticRam("getOwnedAugmentations", ramCost);3029 }3030 updateDynamicRam("getOwnedAugmentations", ramCost);3031 if (Player.bitNodeN != 4) {3032 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3033 throw makeRuntimeRejectMsg(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3034 return [];3035 }3036 }3037 var res = [];3038 for (var i = 0; i < Player.augmentations.length; ++i) {3039 res.push(Player.augmentations[i].name);3040 }3041 if (purchased) {3042 for (var i = 0; i < Player.queuedAugmentations.length; ++i) {3043 res.push(Player.queuedAugmentations[i].name);3044 }3045 }3046 return res;3047 },3048 getOwnedSourceFiles : function() {3049 let ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3050 if (Player.bitNodeN !== 4) {ramCost *= 8;}3051 if (workerScript.checkingRam) {3052 return updateStaticRam("getOwnedSourceFiles", ramCost);3053 }3054 updateDynamicRam("getOwnedSourceFiles", ramCost);3055 if (Player.bitNodeN != 4) {3056 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3057 throw makeRuntimeRejectMsg(workerScript, "Cannot run getOwnedSourceFiles(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3058 return [];3059 }3060 }3061 let res = [];3062 for (let i = 0; i < Player.sourceFiles.length; ++i) {3063 res.push({n: Player.sourceFiles[i].n, lvl: Player.sourceFiles[i].lvl});3064 }3065 return res;3066 },3067 getAugmentationsFromFaction : function(facname) {3068 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3069 if (Player.bitNodeN !== 4) {ramCost *= 8;}3070 if (workerScript.checkingRam) {3071 return updateStaticRam("getAugmentationsFromFaction", ramCost);3072 }3073 updateDynamicRam("getAugmentationsFromFaction", ramCost);3074 if (Player.bitNodeN != 4) {3075 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3076 throw makeRuntimeRejectMsg(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3077 return [];3078 }3079 }3080 if (!factionExists(facname)) {3081 workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname);3082 return [];3083 }3084 var fac = Factions[facname];3085 var res = [];3086 for (var i = 0; i < fac.augmentations.length; ++i) {3087 res.push(fac.augmentations[i]);3088 }3089 return res;3090 },3091 getAugmentationCost : function(name) {3092 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3093 if (Player.bitNodeN !== 4) {ramCost *= 8;}3094 if (workerScript.checkingRam) {3095 return updateStaticRam("getAugmentationCost", ramCost);3096 }3097 updateDynamicRam("getAugmentationCost", ramCost);3098 if (Player.bitNodeN != 4) {3099 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3100 throw makeRuntimeRejectMsg(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3101 return false;3102 }3103 }3104 if (!augmentationExists(name)) {3105 workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name);3106 return [-1, -1];3107 }3108 var aug = Augmentations[name];3109 return [aug.baseRepRequirement, aug.baseCost];3110 },3111 purchaseAugmentation : function(faction, name) {3112 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3113 if (Player.bitNodeN !== 4) {ramCost *= 8;}3114 if (workerScript.checkingRam) {3115 return updateStaticRam("purchaseAugmentation", ramCost);3116 }3117 updateDynamicRam("purchaseAugmentation", ramCost);3118 if (Player.bitNodeN != 4) {3119 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3120 throw makeRuntimeRejectMsg(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3121 return false;3122 }3123 }3124 var fac = Factions[faction];3125 if (fac == null || !(fac instanceof Faction)) {3126 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction);3127 return false;3128 }3129 if (!fac.augmentations.includes(name)) {3130 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation");3131 return false;3132 }3133 var aug = Augmentations[name];3134 if (aug == null || !(aug instanceof Augmentation)) {3135 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name);3136 return false;3137 }3138 var isNeuroflux = false;3139 if (aug.name === AugmentationNames.NeuroFluxGovernor) {3140 isNeuroflux = true;3141 }3142 if (!isNeuroflux) {3143 for (var j = 0; j < Player.queuedAugmentations.length; ++j) {3144 if (Player.queuedAugmentations[j].name === aug.name) {3145 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);3146 return false;3147 }3148 }3149 for (var j = 0; j < Player.augmentations.length; ++j) {3150 if (Player.augmentations[j].name === aug.name) {3151 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);3152 return false;3153 }3154 }3155 }3156 if (fac.playerReputation < aug.baseRepRequirement) {3157 workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name);3158 return false;3159 }3160 var res = purchaseAugmentation(aug, fac, true);3161 workerScript.scriptRef.log(res);3162 if (isString(res) && res.startsWith("You purchased")) {3163 Player.gainIntelligenceExp(CONSTANTS.IntelligenceSingFnBaseExpGain);3164 return true;3165 } else {3166 return false;3167 }3168 },3169 installAugmentations : function(cbScript) {3170 var ramCost = CONSTANTS.ScriptSingularityFn3RamCost;3171 if (Player.bitNodeN !== 4) {ramCost *= 8;}3172 if (workerScript.checkingRam) {3173 return updateStaticRam("installAugmentations", ramCost);3174 }3175 updateDynamicRam("installAugmentations", ramCost);3176 if (Player.bitNodeN != 4) {3177 if (!(hasSingularitySF && singularitySFLvl >= 3)) {3178 throw makeRuntimeRejectMsg(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");3179 return false;3180 }3181 }3182 if (Player.queuedAugmentations.length === 0) {3183 workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed");3184 return false;3185 }3186 Player.gainIntelligenceExp(CONSTANTS.IntelligenceSingFnBaseExpGain);3187 workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed");3188 installAugmentations(cbScript);3189 return true;3190 },3191 //Bladeburner API3192 bladeburner : {3193 getContractNames : function() {3194 if (workerScript.checkingRam) {3195 return updateStaticRam("getContractNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3196 }3197 updateDynamicRam("getContractNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3198 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3199 return Player.bladeburner.getContractNamesNetscriptFn();3200 }3201 throw makeRuntimeRejectMsg(workerScript, "getContractNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3202 "at the Bladeburner division or because you do not have Source-File 7");3203 },3204 getOperationNames : function() {3205 if (workerScript.checkingRam) {3206 return updateStaticRam("getOperationNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3207 }3208 updateDynamicRam("getOperationNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3209 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3210 return Player.bladeburner.getOperationNamesNetscriptFn();3211 }3212 throw makeRuntimeRejectMsg(workerScript, "getOperationNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3213 "at the Bladeburner division or because you do not have Source-File 7");3214 },3215 getBlackOpNames : function() {3216 if (workerScript.checkingRam) {3217 return updateStaticRam("getBlackOpNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3218 }3219 updateDynamicRam("getBlackOpNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3220 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3221 return Player.bladeburner.getBlackOpNamesNetscriptFn();3222 }3223 throw makeRuntimeRejectMsg(workerScript, "getBlackOpNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3224 "at the Bladeburner division or because you do not have Source-File 7");3225 },3226 getGeneralActionNames : function() {3227 if (workerScript.checkingRam) {3228 return updateStaticRam("getGeneralActionNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3229 }3230 updateDynamicRam("getGeneralActionNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3231 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3232 return Player.bladeburner.getGeneralActionNamesNetscriptFn();3233 }3234 throw makeRuntimeRejectMsg(workerScript, "getGeneralActionNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3235 "at the Bladeburner division or because you do not have Source-File 7");3236 },3237 getSkillNames : function() {3238 if (workerScript.checkingRam) {3239 return updateStaticRam("getSkillNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3240 }3241 updateDynamicRam("getSkillNames", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 10);3242 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3243 return Player.bladeburner.getSkillNamesNetscriptFn();3244 }3245 throw makeRuntimeRejectMsg(workerScript, "getSkillNames() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3246 "at the Bladeburner division or because you do not have Source-File 7");3247 },3248 startAction : function(type="", name="") {3249 if (workerScript.checkingRam) {3250 return updateStaticRam("startAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3251 }3252 updateDynamicRam("startAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3253 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3254 try {3255 return Player.bladeburner.startActionNetscriptFn(type, name, workerScript);3256 } catch(e) {3257 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.startAction() failed with exception: " + e);3258 }3259 }3260 throw makeRuntimeRejectMsg(workerScript, "startAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3261 "at the Bladeburner division or because you do not have Source-File 7");3262 },3263 stopBladeburnerAction : function() {3264 if (workerScript.checkingRam) {3265 return updateStaticRam("stopBladeburnerAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 2);3266 }3267 updateDynamicRam("stopBladeburnerAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 2);3268 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3269 return Player.bladeburner.resetAction();3270 }3271 throw makeRuntimeRejectMsg(workerScript, "stopBladeburnerAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3272 "at the Bladeburner division or because you do not have Source-File 7");3273 },3274 getCurrentAction : function() {3275 if (workerScript.checkingRam) {3276 return updateStaticRam("getCurrentAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 4);3277 }3278 updateDynamicRam("getCurrentAction", CONSTANTS.ScriptBladeburnerApiBaseRamCost / 4);3279 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3280 let res = Player.bladeburner.getTypeAndNameFromActionId(Player.bladeburner.action);3281 if (res.type === "Idle" && res.name === "Idle") {3282 return null;3283 } else {3284 return res;3285 }3286 }3287 throw makeRuntimeRejectMsg(workerScript, "getCurrentAction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3288 "at the Bladeburner division or because you do not have Source-File 7");3289 },3290 getActionTime : function(type="", name="") {3291 if (workerScript.checkingRam) {3292 return updateStaticRam("getActionTime", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3293 }3294 updateDynamicRam("getActionTime", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3295 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3296 try {3297 return Player.bladeburner.getActionTimeNetscriptFn(type, name, workerScript);3298 } catch(e) {3299 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getActionTime() failed with exception: " + e);3300 }3301 }3302 throw makeRuntimeRejectMsg(workerScript, "getActionTime() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3303 "at the Bladeburner division or because you do not have Source-File 7");3304 },3305 getActionEstimatedSuccessChance : function(type="", name="") {3306 if (workerScript.checkingRam) {3307 return updateStaticRam("getActionEstimatedSuccessChance", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3308 }3309 updateDynamicRam("getActionEstimatedSuccessChance", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3310 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3311 try {3312 return Player.bladeburner.getActionEstimatedSuccessChanceNetscriptFn(type, name, workerScript);3313 } catch(e) {3314 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getActionEstimatedSuccessChance() failed with exception: " + e);3315 }3316 }3317 throw makeRuntimeRejectMsg(workerScript, "getActionEstimatedSuccessChance() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3318 "at the Bladeburner division or because you do not have Source-File 7");3319 },3320 getActionCountRemaining : function(type="", name="") {3321 if (workerScript.checkingRam) {3322 return updateStaticRam("getActionCountRemaining", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3323 }3324 updateDynamicRam("getActionCountRemaining", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3325 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3326 try {3327 return Player.bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);3328 } catch(e) {3329 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getActionCountRemaining() failed with exception: " + e);3330 }3331 }3332 throw makeRuntimeRejectMsg(workerScript, "getActionCountRemaining() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3333 "at the Bladeburner division or because you do not have Source-File 7");3334 },3335 getActionMaxLevel: function(type="", name="") {3336 if (workerScript.checkingRam) {3337 return updateStaticRam("getActionMaxLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3338 }3339 updateDynamicRam("getActionMaxLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3340 checkBladeburnerAccess(workerScript, "getActionMaxLevel");3341 try {3342 var errorLogText = unknownBladeburnerActionErrorMessage("getActionMaxLevel", type, name);3343 const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name);3344 if (actionId == null) {3345 workerScript.log(errorLogText);3346 return -1;3347 }3348 const actionObj = Player.bladeburner.getActionObject(actionId);3349 if (actionObj == null) {3350 workerScript.log(errorLogText);3351 return -1;3352 }3353 return actionObj.maxLevel;3354 } catch(err) {3355 throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionMaxLevel", err));3356 }3357 },3358 getActionCurrentLevel: function(type="", name="") {3359 if (workerScript.checkingRam) {3360 return updateStaticRam("getActionCurrentLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3361 }3362 updateDynamicRam("getActionCurrentLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3363 checkBladeburnerAccess(workerScript, "getActionCurrentLevel");3364 try {3365 var errorLogText = unknownBladeburnerActionErrorMessage("getActionCurrentLevel", type, name);3366 const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name);3367 if (actionId == null) {3368 workerScript.log(errorLogText);3369 return -1;3370 }3371 const actionObj = Player.bladeburner.getActionObject(actionId);3372 if (actionObj == null) {3373 workerScript.log(errorLogText);3374 return -1;3375 }3376 return actionObj.level;3377 } catch(err) {3378 throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionCurrentLevel", err));3379 }3380 },3381 getActionAutolevel: function(type="", name="") {3382 if (workerScript.checkingRam) {3383 return updateStaticRam("getActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3384 }3385 updateDynamicRam("getActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3386 checkBladeburnerAccess(workerScript, "getActionAutolevel");3387 try {3388 var errorLogText = unknownBladeburnerActionErrorMessage("getActionAutolevel", type, name);3389 const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name);3390 if (actionId == null) {3391 workerScript.log(errorLogText);3392 return false;3393 }3394 const actionObj = Player.bladeburner.getActionObject(actionId);3395 if (actionObj == null) {3396 workerScript.log(errorLogText);3397 return false;3398 }3399 return actionObj.autoLevel;3400 } catch(err) {3401 throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("getActionAutolevel", err));3402 }3403 },3404 setActionAutolevel: function(type="", name="", autoLevel=true) {3405 if (workerScript.checkingRam) {3406 return updateStaticRam("setActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3407 }3408 updateDynamicRam("setActionAutolevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3409 checkBladeburnerAccess(workerScript, "setActionAutolevel");3410 try {3411 var errorLogText = unknownBladeburnerActionErrorMessage("setActionAutolevel", type, name);3412 const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name);3413 if (actionId == null) {3414 workerScript.log(errorLogText);3415 return;3416 }3417 const actionObj = Player.bladeburner.getActionObject(actionId);3418 if (actionObj == null) {3419 workerScript.log(errorLogText);3420 return;3421 }3422 actionObj.autoLevel = autoLevel;3423 } catch(err) {3424 throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("setActionAutolevel", err));3425 }3426 },3427 setActionLevel: function(type="", name="", level=1) {3428 if (workerScript.checkingRam) {3429 return updateStaticRam("setActionLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3430 }3431 updateDynamicRam("setActionLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3432 checkBladeburnerAccess(workerScript, "setActionLevel");3433 try {3434 var errorLogText = unknownBladeburnerActionErrorMessage("setActionLevel", type, name);3435 const actionId = Player.bladeburner.getActionIdFromTypeAndName(type, name);3436 if (actionId == null) {3437 workerScript.log(errorLogText);3438 return;3439 }3440 const actionObj = Player.bladeburner.getActionObject(actionId);3441 if (actionObj == null) {3442 workerScript.log(errorLogText);3443 return;3444 }3445 if(level > actionObj.maxLevel) {3446 workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level exceeds max level for given action.`);3447 return;3448 }3449 if(level < 1) {3450 workerScript.log(`ERROR: bladeburner.${setActionLevel}() failed because level is below 1.`);3451 return;3452 }3453 actionObj.level = level;3454 } catch(err) {3455 throw makeRuntimeRejectMsg(workerScript, unknownBladeburnerExceptionMessage("setActionLevel", err));3456 }3457 },3458 getRank : function() {3459 if (workerScript.checkingRam) {3460 return updateStaticRam("getRank", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3461 }3462 updateDynamicRam("getRank", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3463 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3464 return Player.bladeburner.rank;3465 }3466 throw makeRuntimeRejectMsg(workerScript, "getRank() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3467 "at the Bladeburner division or because you do not have Source-File 7");3468 },3469 getSkillPoints : function() {3470 if (workerScript.checkingRam) {3471 return updateStaticRam("getSkillPoints", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3472 }3473 updateDynamicRam("getSkillPoints", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3474 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3475 return Player.bladeburner.skillPoints;3476 }3477 throw makeRuntimeRejectMsg(workerScript, "getSkillPoints() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3478 "at the Bladeburner division or because you do not have Source-File 7");3479 },3480 getSkillLevel : function(skillName="") {3481 if (workerScript.checkingRam) {3482 return updateStaticRam("getSkillLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3483 }3484 updateDynamicRam("getSkillLevel", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3485 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3486 try {3487 return Player.bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);3488 } catch(e) {3489 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getSkillLevel() failed with exception: " + e);3490 }3491 }3492 throw makeRuntimeRejectMsg(workerScript, "getSkillLevel() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3493 "at the Bladeburner division or because you do not have Source-File 7");3494 },3495 upgradeSkill : function(skillName) {3496 if (workerScript.checkingRam) {3497 return updateStaticRam("upgradeSkill", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3498 }3499 updateDynamicRam("upgradeSkill", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3500 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3501 try {3502 return Player.bladeburner.upgradeSkillNetscriptFn(skillName, workerScript);3503 } catch(e) {3504 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.upgradeSkill() failed with exception: " + e);3505 }3506 }3507 throw makeRuntimeRejectMsg(workerScript, "upgradeSkill() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3508 "at the Bladeburner division or because you do not have Source-File 7");3509 },3510 getTeamSize : function(type="", name="") {3511 if (workerScript.checkingRam) {3512 return updateStaticRam("getTeamSize", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3513 }3514 updateDynamicRam("getTeamSize", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3515 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3516 try {3517 return Player.bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);3518 } catch(e) {3519 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getTeamSize() failed with exception: " + e);3520 }3521 }3522 throw makeRuntimeRejectMsg(workerScript, "getTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3523 "at the Bladeburner division or because you do not have Source-File 7");3524 },3525 setTeamSize : function(type="", name="", size) {3526 if (workerScript.checkingRam) {3527 return updateStaticRam("setTeamSize", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3528 }3529 updateDynamicRam("setTeamSize", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3530 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3531 try {3532 return Player.bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);3533 } catch(e) {3534 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.setTeamSize() failed with exception: " + e);3535 }3536 }3537 throw makeRuntimeRejectMsg(workerScript, "setTeamSize() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3538 "at the Bladeburner division or because you do not have Source-File 7");3539 },3540 getCityEstimatedPopulation : function(cityName) {3541 if (workerScript.checkingRam) {3542 return updateStaticRam("getCityEstimatedPopulation", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3543 }3544 updateDynamicRam("getCityEstimatedPopulation", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3545 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3546 try {3547 return Player.bladeburner.getCityEstimatedPopulationNetscriptFn(cityName, workerScript);3548 } catch(e) {3549 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getCityEstimatedPopulation() failed with exception: " + e);3550 }3551 }3552 throw makeRuntimeRejectMsg(workerScript, "getCityEstimatedPopulation() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3553 "at the Bladeburner division or because you do not have Source-File 7");3554 },3555 getCityEstimatedCommunities : function(cityName) {3556 if (workerScript.checkingRam) {3557 return updateStaticRam("getCityEstimatedCommunities", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3558 }3559 updateDynamicRam("getCityEstimatedCommunities", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3560 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3561 try {3562 return Player.bladeburner.getCityEstimatedCommunitiesNetscriptFn(cityName, workerScript);3563 } catch(e) {3564 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getCityEstimatedCommunities() failed with exception: " + e);3565 }3566 }3567 throw makeRuntimeRejectMsg(workerScript, "getCityEstimatedCommunities() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3568 "at the Bladeburner division or because you do not have Source-File 7");3569 },3570 getCityChaos : function(cityName) {3571 if (workerScript.checkingRam) {3572 return updateStaticRam("getCityChaos", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3573 }3574 updateDynamicRam("getCityChaos", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3575 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3576 try {3577 return Player.bladeburner.getCityChaosNetscriptFn(cityName, workerScript);3578 } catch(e) {3579 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.getCityChaos() failed with exception: " + e);3580 }3581 }3582 throw makeRuntimeRejectMsg(workerScript, "getCityChaos() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3583 "at the Bladeburner division or because you do not have Source-File 7");3584 },3585 switchCity : function(cityName) {3586 if (workerScript.checkingRam) {3587 return updateStaticRam("switchCity", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3588 }3589 updateDynamicRam("switchCity", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3590 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3591 try {3592 return Player.bladeburner.switchCityNetscriptFn(cityName, workerScript);3593 } catch(e) {3594 throw makeRuntimeRejectMsg(workerScript, "Bladeburner.switchCity() failed with exception: " + e);3595 }3596 }3597 throw makeRuntimeRejectMsg(workerScript, "switchCity() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3598 "at the Bladeburner division or because you do not have Source-File 7");3599 },3600 getStamina : function() {3601 if (workerScript.checkingRam) {3602 return updateStaticRam("getStamina", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3603 }3604 updateDynamicRam("getStamina", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3605 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3606 return [Player.bladeburner.stamina, Player.bladeburner.maxStamina];3607 }3608 throw makeRuntimeRejectMsg(workerScript, "getStamina() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3609 "at the Bladeburner division or because you do not have Source-File 7");3610 },3611 joinBladeburnerFaction : function() {3612 if (workerScript.checkingRam) {3613 return updateStaticRam("joinBladeburnerFaction", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3614 }3615 updateDynamicRam("joinBladeburnerFaction", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3616 if (Player.bladeburner instanceof Bladeburner && (Player.bitNodeN === 7 || hasBladeburner2079SF)) {3617 return Player.bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);3618 }3619 throw makeRuntimeRejectMsg(workerScript, "joinBladeburnerFaction() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3620 "at the Bladeburner division or because you do not have Source-File 7");3621 },3622 joinBladeburnerDivision : function() {3623 if (workerScript.checkingRam) {3624 return updateStaticRam("joinBladeburnerDivision", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3625 }3626 updateDynamicRam("joinBladeburnerDivision", CONSTANTS.ScriptBladeburnerApiBaseRamCost);3627 if ((Player.bitNodeN === 7 || hasBladeburner2079SF)) {3628 if (Player.bladeburner instanceof Bladeburner) {3629 return true; //Already member3630 } else if (Player.strength >= 100 && Player.defense >= 100 &&3631 Player.dexterity >= 100 && Player.agility >= 100) {3632 Player.bladeburner = new Bladeburner({new:true});3633 workerScript.log("You have been accepted into the Bladeburner division");3634 return true;3635 } else {3636 workerScript.log("You do not meet the requirements for joining the Bladeburner division");3637 return false;3638 }3639 }3640 throw makeRuntimeRejectMsg(workerScript, "joinBladeburnerDivision() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " +3641 "at the Bladeburner division or because you do not have Source-File 7");3642 }3643 }3644 } //End return3645} //End NetscriptFunction()3646export {NetscriptFunctions, initSingularitySFFlags, hasSingularitySF, hasBn11SF,...

Full Screen

Full Screen

NetscriptEvaluator.js

Source:NetscriptEvaluator.js Github

copy

Full Screen

1import {BitNodeMultipliers} from "./BitNode";2import {CONSTANTS} from "./Constants";3import {Player} from "./Player";4import {Environment} from "./NetscriptEnvironment";5import {WorkerScript, addWorkerScript} from "./NetscriptWorker";6import {Server, getServer} from "./Server";7import {Settings} from "./Settings";8import {Script, findRunningScript,9 RunningScript} from "./Script";10import {parse, Node} from "../utils/acorn";11import {arrayToString} from "../utils/helpers/arrayToString";12import {isValidIPAddress} from "../utils/helpers/isValidIPAddress";13import {isString} from "../utils/helpers/isString";14var Promise = require("bluebird");15Promise.config({16 warnings: false,17 longStackTraces: false,18 cancellation: true,19 monitoring: false20});21/* Evaluator22 * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser23 *24 * Returns a promise25 */26function evaluate(exp, workerScript) {27 return Promise.delay(Settings.CodeInstructionRunTime).then(function() {28 var env = workerScript.env;29 if (env.stopFlag) {return Promise.reject(workerScript);}30 if (exp == null) {31 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression", exp));32 }33 if (env.stopFlag) {return Promise.reject(workerScript);}34 switch (exp.type) {35 case "BlockStatement":36 case "Program":37 var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment38 return evaluateProgPromise.then(function(w) {39 return Promise.resolve(workerScript);40 }).catch(function(e) {41 if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") {42 return Promise.reject(e);43 } else if (isString(e)) {44 workerScript.errorMessage = e;45 return Promise.reject(workerScript);46 } else if (e instanceof WorkerScript) {47 return Promise.reject(e);48 } else {49 return Promise.reject(workerScript);50 }51 });52 break;53 case "Literal":54 return Promise.resolve(exp.value);55 break;56 case "Identifier":57 //Javascript constructor() method can be used as an exploit to run arbitrary code58 if (exp.name == "constructor") {59 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp));60 }61 if (!(exp.name in env.vars)){62 return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp));63 }64 return Promise.resolve(env.get(exp.name))65 break;66 case "ExpressionStatement":67 return evaluate(exp.expression, workerScript);68 break;69 case "ArrayExpression":70 var argPromises = exp.elements.map(function(arg) {71 return evaluate(arg, workerScript);72 });73 return Promise.all(argPromises).then(function(array) {74 return Promise.resolve(array)75 });76 break;77 case "CallExpression":78 return evaluate(exp.callee, workerScript).then(function(func) {79 return Promise.map(exp.arguments, function(arg) {80 return evaluate(arg, workerScript);81 }).then(function(args) {82 if (func instanceof Node) { //Player-defined function83 //Create new Environment for the function84 //Should be automatically garbage collected...85 var funcEnv = env.extend();86 //Define function arguments in this new environment87 for (var i = 0; i < func.params.length; ++i) {88 var arg;89 if (i >= args.length) {90 arg = null;91 } else {92 arg = args[i];93 }94 funcEnv.def(func.params[i].name, arg);95 }96 //Create a new WorkerScript for this function evaluation97 var funcWorkerScript = new WorkerScript(workerScript.scriptRef);98 funcWorkerScript.serverIp = workerScript.serverIp;99 funcWorkerScript.env = funcEnv;100 workerScript.fnWorker = funcWorkerScript;101 return evaluate(func.body, funcWorkerScript).then(function(res) {102 //If the function finished successfuly, that means there103 //was no return statement since a return statement rejects. So resolve to null104 workerScript.fnWorker = null;105 return Promise.resolve(null);106 }).catch(function(e) {107 if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") {108 //Return statement from function109 return Promise.resolve(e[1]);110 workerScript.fnWorker = null;111 } else if (isString(e)) {112 return Promise.reject(makeRuntimeRejectMsg(workerScript, e));113 } else if (e instanceof WorkerScript) {114 //Parse out the err message from the WorkerScript and re-reject115 var errorMsg = e.errorMessage;116 var errorTextArray = errorMsg.split("|");117 if (errorTextArray.length === 4) {118 errorMsg = errorTextArray[3];119 return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg));120 } else {121 if (env.stopFlag) {122 return Promise.reject(workerScript);123 } else {124 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function"));125 }126 }127 } else if (e instanceof Error) {128 return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString()));129 }130 });131 } else if (exp.callee.type === "MemberExpression"){132 return evaluate(exp.callee.object, workerScript).then(function(object) {133 try {134 if (func === "NETSCRIPTFOREACH") {135 return evaluateForeach(object, args, workerScript).then(function(res) {136 return Promise.resolve(res);137 }).catch(function(e) {138 return Promise.reject(e);139 });140 }141 var res = func.apply(object,args);142 return Promise.resolve(res);143 } catch (e) {144 return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp));145 }146 });147 } else {148 try {149 var out = func.apply(null,args);150 if (out instanceof Promise){151 return out.then(function(res) {152 return Promise.resolve(res)153 }).catch(function(e) {154 if (isScriptErrorMessage(e)) {155 //Functions don't have line number appended in error message, so add it156 var num = getErrorLineNumber(exp, workerScript);157 e += " (Line " + num + ")";158 }159 return Promise.reject(e);160 });161 } else {162 return Promise.resolve(out);163 }164 } catch (e) {165 if (isScriptErrorMessage(e)) {166 if (isScriptErrorMessage(e)) {167 //Functions don't have line number appended in error message, so add it168 var num = getErrorLineNumber(exp, workerScript);169 e += " (Line " + num + ")";170 }171 return Promise.reject(e);172 } else {173 return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp));174 }175 }176 }177 });178 });179 break;180 case "MemberExpression":181 return evaluate(exp.object, workerScript).then(function(object) {182 if (exp.computed){183 return evaluate(exp.property, workerScript).then(function(index) {184 if (index >= object.length) {185 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp));186 }187 return Promise.resolve(object[index]);188 }).catch(function(e) {189 if (e instanceof WorkerScript || isScriptErrorMessage(e)) {190 return Promise.reject(e);191 } else {192 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp));193 }194 });195 } else {196 if (exp.property.name === "constructor") {197 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp));198 }199 if (object != null && object instanceof Array && exp.property.name === "forEach") {200 return "NETSCRIPTFOREACH";201 }202 try {203 return Promise.resolve(object[exp.property.name])204 } catch (e) {205 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp));206 }207 }208 });209 break;210 case "LogicalExpression":211 case "BinaryExpression":212 return evalBinary(exp, workerScript);213 break;214 case "UnaryExpression":215 return evalUnary(exp, workerScript);216 break;217 case "AssignmentExpression":218 return evalAssignment(exp, workerScript);219 break;220 case "VariableDeclaration":221 return evalVariableDeclaration(exp, workerScript);222 break;223 case "UpdateExpression":224 if (exp.argument.type==="Identifier"){225 if (exp.argument.name in env.vars){226 if (exp.operator === "++" || exp.operator === "--") {227 switch (exp.operator) {228 case "++":229 env.set(exp.argument.name,env.get(exp.argument.name)+1);230 break;231 case "--":232 env.set(exp.argument.name,env.get(exp.argument.name)-1);233 break;234 default: break;235 }236 return Promise.resolve(env.get(exp.argument.name));237 }238 //Not sure what prefix UpdateExpressions there would be besides ++/--239 if (exp.prefix){240 return Promise.resolve(env.get(exp.argument.name))241 }242 switch (exp.operator){243 default:244 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp));245 }246 return Promise.resolve(env.get(exp.argument.name))247 } else {248 return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp));249 }250 } else {251 return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp));252 }253 break;254 case "EmptyStatement":255 return Promise.resolve(false);256 break;257 case "ReturnStatement":258 return evaluate(exp.argument, workerScript).then(function(res) {259 return Promise.reject(["RETURNSTATEMENT", res]);260 });261 break;262 case "BreakStatement":263 return Promise.reject("BREAKSTATEMENT");264 break;265 case "ContinueStatement":266 return Promise.reject("CONTINUESTATEMENT");267 break;268 case "IfStatement":269 return evaluateIf(exp, workerScript);270 break;271 case "SwitchStatement":272 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp));273 break;274 case "WhileStatement":275 return evaluateWhile(exp, workerScript).then(function(res) {276 return Promise.resolve(res);277 }).catch(function(e) {278 if (e == "BREAKSTATEMENT" ||279 (e instanceof WorkerScript && e.errorMessage == "BREAKSTATEMENT")) {280 return Promise.resolve("whileLoopBroken");281 } else {282 return Promise.reject(e);283 }284 });285 break;286 case "ForStatement":287 return evaluate(exp.init, workerScript).then(function(expInit) {288 return evaluateFor(exp, workerScript);289 }).then(function(forLoopRes) {290 return Promise.resolve("forLoopDone");291 }).catch(function(e) {292 if (e == "BREAKSTATEMENT" ||293 (e instanceof WorkerScript && e.errorMessage == "BREAKSTATEMENT")) {294 return Promise.resolve("forLoopBroken");295 } else {296 return Promise.reject(e);297 }298 });299 break;300 case "FunctionDeclaration":301 if (exp.id && exp.id.name) {302 env.set(exp.id.name, exp);303 return Promise.resolve(true);304 } else {305 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp));306 }307 break;308 case "ImportDeclaration":309 return evaluateImport(exp, workerScript).then(function(res) {310 return Promise.resolve(res);311 }).catch(function(e) {312 return Promise.reject(e);313 });314 break;315 case "ThrowStatement":316 return evaluate(exp.argument, workerScript).then(function(res) {317 return Promise.reject(makeRuntimeRejectMsg(workerScript, res));318 });319 break;320 default:321 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp));322 break;323 } //End switch324 }).catch(function(e) {325 return Promise.reject(e);326 }); // End Promise327}328function evalBinary(exp, workerScript){329 return evaluate(exp.left, workerScript).then(function(expLeft) {330 //Short circuiting331 if (expLeft && exp.operator === "||") {332 return Promise.resolve(expLeft);333 }334 if (!expLeft && exp.operator === "&&") {335 return Promise.resolve(expLeft);336 }337 return evaluate(exp.right, workerScript).then(function(expRight) {338 switch (exp.operator){339 case "===":340 case "==":341 return Promise.resolve(expLeft===expRight);342 break;343 case "!==":344 case "!=":345 return Promise.resolve(expLeft!==expRight);346 break;347 case "<":348 return Promise.resolve(expLeft<expRight);349 break;350 case "<=":351 return Promise.resolve(expLeft<=expRight);352 break;353 case ">":354 return Promise.resolve(expLeft>expRight);355 break;356 case ">=":357 return Promise.resolve(expLeft>=expRight);358 break;359 case "+":360 return Promise.resolve(expLeft+expRight);361 break;362 case "-":363 return Promise.resolve(expLeft-expRight);364 break;365 case "*":366 return Promise.resolve(expLeft*expRight);367 break;368 case "/":369 if (expRight === 0) {370 return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero"));371 } else {372 return Promise.resolve(expLeft/expRight);373 }374 break;375 case "%":376 return Promise.resolve(expLeft%expRight);377 break;378 case "in":379 return Promise.resolve(expLeft in expRight);380 break;381 case "instanceof":382 return Promise.resolve(expLeft instanceof expRight);383 break;384 case "||":385 return Promise.resolve(expLeft || expRight);386 break;387 case "&&":388 return Promise.resolve(expLeft && expRight);389 break;390 default:391 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator));392 }393 });394 });395}396function evalUnary(exp, workerScript){397 var env = workerScript.env;398 if (env.stopFlag) {return Promise.reject(workerScript);}399 return evaluate(exp.argument, workerScript).then(function(res) {400 if (exp.operator == "!") {401 return Promise.resolve(!res);402 } else if (exp.operator == "-") {403 if (isNaN(res)) {404 return Promise.resolve(res);405 } else {406 return Promise.resolve(-1 * res);407 }408 } else {409 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator));410 }411 });412}413//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional)414//The return value is an array of the form:415// [0th index (leftmost), array name, 1st index, 2nd index, ...]416function getArrayElement(exp, workerScript) {417 var indices = [];418 return evaluate(exp.property, workerScript).then(function(idx) {419 if (isNaN(idx)) {420 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx));421 } else {422 if (exp.object.name === undefined && exp.object.object) {423 return getArrayElement(exp.object, workerScript).then(function(res) {424 res.push(idx);425 indices = res;426 return Promise.resolve(indices);427 }).catch(function(e) {428 return Promise.reject(e);429 });430 } else {431 indices.push(idx);432 indices.push(exp.object.name);433 return Promise.resolve(indices);434 }435 }436 });437}438function evalAssignment(exp, workerScript) {439 var env = workerScript.env;440 if (env.stopFlag) {return Promise.reject(workerScript);}441 if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") {442 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left)));443 }444 if (exp.operator !== "=" && !(exp.left.name in env.vars)){445 return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined"));446 }447 return evaluate(exp.right, workerScript).then(function(expRight) {448 if (exp.left.type == "MemberExpression") {449 if (!exp.left.computed) {450 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to an object's property. This is currently unsupported in Netscript", exp));451 }452 //Assign to array element453 //Array object designed by exp.left.object.name454 //Index designated by exp.left.property455 return getArrayElement(exp.left, workerScript).then(function(res) {456 if (!(res instanceof Array) || res.length < 2) {457 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev"));458 }459 //The array name is the second value460 var arrName = res.splice(1, 1);461 arrName = arrName[0];462 var res;463 try {464 res = env.setArrayElement(arrName, res, expRight);465 } catch (e) {466 return Promise.reject(makeRuntimeRejectMsg(workerScript, e));467 }468 return Promise.resolve(res);469 }).catch(function(e) {470 return Promise.reject(e);471 });472 } else {473 //Other assignments474 try {475 var assign;476 switch (exp.operator) {477 case "=":478 assign = expRight; break;479 case "+=":480 assign = env.get(exp.left.name) + expRight; break;481 case "-=":482 assign = env.get(exp.left.name) - expRight; break;483 case "*=":484 assign = env.get(exp.left.name) * expRight; break;485 case "/=":486 assign = env.get(exp.left.name) / expRight; break;487 case "%=":488 assign = env.get(exp.left.name) % expRight; break;489 default:490 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented"));491 }492 env.set(exp.left.name, assign);493 return Promise.resolve(assign);494 } catch (e) {495 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString()));496 }497 }498 });499}500function evalVariableDeclaration(exp, workerScript) {501 var env = workerScript.env;502 if (env.stopFlag) {return Promise.reject(workerScript);}503 if (!(exp.declarations instanceof Array)) {504 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Variable declarations parsed incorrectly. This may be a syntax error"));505 }506 if (exp.kind !== "var") {507 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Only 'var' declarations are currently allowed (let, const, etc. are not allowed)"));508 }509 return Promise.all(exp.declarations.map((decl)=>{510 evalVariableDeclarator(decl, workerScript);511 })).then(function(res) {512 return Promise.resolve(res);513 });514}515//A Variable Declaration contains an array of Variable Declarators516function evalVariableDeclarator(exp, workerScript) {517 var env = workerScript.env;518 if (exp.type !== "VariableDeclarator") {519 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid AST Node passed into evalVariableDeclarator: " + exp.type));520 }521 if (exp.init == null) {522 env.set(exp.id.name, null);523 return Promise.resolve(null);524 } else {525 return evaluate(exp.init, workerScript).then(function(initValue) {526 env.set(exp.id.name, initValue);527 });528 }529}530function evaluateIf(exp, workerScript, i) {531 var env = workerScript.env;532 return evaluate(exp.test, workerScript).then(function(condRes) {533 if (condRes) {534 return evaluate(exp.consequent, workerScript).then(function(res) {535 return Promise.resolve(true);536 }, function(e) {537 return Promise.reject(e);538 });539 } else if (exp.alternate) {540 return evaluate(exp.alternate, workerScript).then(function(res) {541 return Promise.resolve(true);542 }, function(e) {543 return Promise.reject(e);544 });545 } else {546 return Promise.resolve("endIf");547 }548 });549}550//Evaluate the looping part of a for loop (Initialization block is NOT done in here)551function evaluateFor(exp, workerScript) {552 var env = workerScript.env;553 if (env.stopFlag) {return Promise.reject(workerScript);}554 return new Promise(function(resolve, reject) {555 function recurse() {556 //Don't return a promise so the promise chain is broken on each recursion (saving memory)557 evaluate(exp.test, workerScript).then(function(resCond) {558 if (resCond) {559 return evaluate(exp.body, workerScript).then(function(res) {560 return evaluate(exp.update, workerScript);561 }).catch(function(e) {562 if (e == "CONTINUESTATEMENT" ||563 (e instanceof WorkerScript && e.errorMessage == "CONTINUESTATEMENT")) {564 //Continue statement, recurse to next iteration565 return evaluate(exp.update, workerScript).then(function(resPostloop) {566 return evaluateFor(exp, workerScript);567 }).then(function(foo) {568 return Promise.resolve("endForLoop");569 }).catch(function(e) {570 return Promise.reject(e);571 });572 } else {573 return Promise.reject(e);574 }575 }).then(recurse, reject).catch(function(e) {576 return Promise.reject(e);577 });578 } else {579 resolve();580 }581 }).catch(function(e) {582 reject(e);583 });584 }585 recurse();586 });587}588function evaluateForeach(arr, args, workerScript) {589 console.log("evaluateForeach called");590 if (!(arr instanceof Array)) {591 return Promise.reject("Invalid array passed into forEach");592 }593 if (!(args instanceof Array) && args.length != 1) {594 return Promise.reject("Invalid argument passed into forEach");595 }596 var func = args[0];597 if (typeof func !== "function") {598 return Promise.reject("Invalid function passed into forEach");599 }600 console.log(func);601 return new Promise(function(resolve, reject) {602 //Don't return a promise so the promise chain is broken on each recursion603 function recurse(i) {604 console.log("recurse() called with i: " + i);605 if (i >= arr.length) {606 resolve();607 } else {608 return Promise.delay(Settings.CodeInstructionRunTime).then(function() {609 console.log("About to apply function");610 var res = func.apply(null, [arr[i]]);611 console.log("Applied function");612 ++i;613 Promise.resolve(res).then(function(val) {614 recurse(i);615 }, reject).catch(function(e) {616 return Promise.reject(e);617 });618 });619 }620 }621 recurse(0);622 });623}624function evaluateWhile(exp, workerScript) {625 var env = workerScript.env;626 if (env.stopFlag) {return Promise.reject(workerScript);}627 return new Promise(function (resolve, reject) {628 function recurse() {629 //Don't return a promise so the promise chain is broken on each recursion (saving memory)630 evaluate(exp.test, workerScript).then(function(resCond) {631 if (resCond) {632 return evaluate(exp.body, workerScript).catch(function(e) {633 if (e == "CONTINUESTATEMENT" ||634 (e instanceof WorkerScript && e.errorMessage == "CONTINUESTATEMENT")) {635 //Continue statement, recurse636 return evaluateWhile(exp, workerScript).then(function(foo) {637 return Promise.resolve("endWhileLoop");638 }, function(e) {639 return Promise.reject(e);640 });641 } else {642 return Promise.reject(e);643 }644 }).then(recurse, reject).catch(function(e) {645 return Promise.reject(e);646 });647 } else {648 resolve();649 }650 }).catch(function(e) {651 reject(e);652 });653 }654 recurse();655 });656}657function evaluateProg(exp, workerScript, index) {658 var env = workerScript.env;659 if (env.stopFlag) {return Promise.reject(workerScript);}660 if (index >= exp.body.length) {661 return Promise.resolve("progFinished");662 } else {663 //Evaluate this line of code in the prog664 //After the code finishes evaluating, evaluate the next line recursively665 return evaluate(exp.body[index], workerScript).then(function(res) {666 return evaluateProg(exp, workerScript, index + 1);667 }).then(function(res) {668 return Promise.resolve(workerScript);669 }).catch(function(e) {670 return Promise.reject(e);671 });672 }673}674function evaluateImport(exp, workerScript, checkingRam=false) {675 //When its checking RAM, it exports an array of nodes for each imported function676 var ramCheckRes = [];677 var env = workerScript.env;678 if (env.stopFlag) {679 if (checkingRam) {return ramCheckRes;}680 return Promise.reject(workerScript);681 }682 //Get source script and name of all functions to import683 var scriptName = exp.source.value;684 var namespace, namespaceObj, allFns = false, fnNames = [];685 if (exp.specifiers.length === 1 && exp.specifiers[0].type === "ImportNamespaceSpecifier") {686 allFns = true;687 namespace = exp.specifiers[0].local.name;688 } else {689 for (var i = 0; i < exp.specifiers.length; ++i) {690 fnNames.push(exp.specifiers[i].local.name);691 }692 }693 //Get the code694 var server = getServer(workerScript.serverIp), code = "";695 if (server == null) {696 if (checkingRam) {return ramCheckRes;}697 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to identify server. This is a bug please report to dev", exp));698 }699 for (var i = 0; i < server.scripts.length; ++i) {700 if (server.scripts[i].filename === scriptName) {701 code = server.scripts[i].code;702 break;703 }704 }705 if (code === "") {706 if (checkingRam) {return ramCheckRes;}707 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Could not find script " + scriptName + " to import", exp));708 }709 //Create the AST710 try {711 var ast = parse(code, {sourceType:"module"});712 } catch(e) {713 console.log("Failed to parse import script");714 if (checkingRam) {return ramCheckRes;}715 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to import functions from " + scriptName +716 " This is most likely due to a syntax error in the imported script", exp));717 }718 if (allFns) {719 //A namespace is implemented as a JS obj720 env.set(namespace, {});721 namespaceObj = env.get(namespace);722 }723 //Search through the AST for all imported functions724 var queue = [ast];725 while (queue.length != 0) {726 var node = queue.shift();727 switch (node.type) {728 case "BlockStatement":729 case "Program":730 for (var i = 0; i < node.body.length; ++i) {731 if (node.body[i] instanceof Node) {732 queue.push(node.body[i]);733 }734 }735 break;736 case "FunctionDeclaration":737 if (node.id && node.id.name) {738 if (allFns) {739 //Import all functions under this namespace740 if (checkingRam) {741 ramCheckRes.push(node);742 } else {743 namespaceObj[node.id.name] = node;744 }745 } else {746 //Only import specified functions747 if (fnNames.includes(node.id.name)) {748 if (checkingRam) {749 ramCheckRes.push(node);750 } else {751 env.set(node.id.name, node);752 }753 }754 }755 } else {756 if (checkingRam) {return ramCheckRes;}757 return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration in imported script " + scriptName, exp));758 }759 break;760 default:761 break;762 }763 for (var prop in node) {764 if (node.hasOwnProperty(prop)) {765 if (node[prop] instanceof Node) {766 queue.push(node[prop]);767 }768 }769 }770 }771 if (!checkingRam) {workerScript.scriptRef.log("Imported functions from " + scriptName);}772 if (checkingRam) {return ramCheckRes;}773 return Promise.resolve(true);774}775function killNetscriptDelay(workerScript) {776 if (workerScript instanceof WorkerScript) {777 if (workerScript.delay) {778 clearTimeout(workerScript.delay);779 workerScript.delayResolve();780 }781 }782}783function netscriptDelay(time, workerScript) {784 return new Promise(function(resolve, reject) {785 workerScript.delay = setTimeout(()=>{786 workerScript.delay = null;787 resolve();788 }, time);789 workerScript.delayResolve = resolve;790 });791}792function makeRuntimeRejectMsg(workerScript, msg, exp=null) {793 var lineNum = "";794 if (exp != null) {795 var num = getErrorLineNumber(exp, workerScript);796 lineNum = " (Line " + num + ")"797 }798 return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg + lineNum;799}800//Run a script from inside a script using run() command801function runScriptFromScript(server, scriptname, args, workerScript, threads=1) {802 //Check if the script is already running803 var runningScriptObj = findRunningScript(scriptname, args, server);804 if (runningScriptObj != null) {805 workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname);806 return Promise.resolve(false);807 }808 //'null/undefined' arguments are not allowed809 for (var i = 0; i < args.length; ++i) {810 if (args[i] == null) {811 workerScript.scriptRef.log("ERROR: Cannot execute a script with null/undefined as an argument");812 return Promise.resolve(false);813 }814 }815 //Check if the script exists and if it does run it816 for (var i = 0; i < server.scripts.length; ++i) {817 if (server.scripts[i].filename == scriptname) {818 //Check for admin rights and that there is enough RAM availble to run819 var script = server.scripts[i];820 var ramUsage = script.ramUsage;821 threads = Math.round(Number(threads)); //Convert to number and round822 ramUsage = ramUsage * threads;823 var ramAvailable = server.maxRam - server.ramUsed;824 if (server.hasAdminRights == false) {825 workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!");826 return Promise.resolve(false);827 } else if (ramUsage > ramAvailable){828 workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!");829 return Promise.resolve(false);830 } else {831 //Able to run script832 if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.exec == null && workerScript.disableLogs.run == null && workerScript.disableLogs.spawn == null) {833 workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + arrayToString(args) + ". May take a few seconds to start up...");834 }835 var runningScriptObj = new RunningScript(script, args);836 runningScriptObj.threads = threads;837 server.runningScripts.push(runningScriptObj); //Push onto runningScripts838 addWorkerScript(runningScriptObj, server);839 return Promise.resolve(true);840 }841 }842 }843 workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname);844 return Promise.resolve(false);845}846function getErrorLineNumber(exp, workerScript) {847 var code = workerScript.scriptRef.scriptRef.code;848 //Split code up to the start of the node849 try {850 code = code.substring(0, exp.start);851 return (code.match(/\n/g) || []).length + 1;852 } catch(e) {853 return -1;854 }855}856function isScriptErrorMessage(msg) {857 if (!isString(msg)) {return false;}858 let splitMsg = msg.split("|");859 if (splitMsg.length != 4){860 return false;861 }862 var ip = splitMsg[1];863 if (!isValidIPAddress(ip)) {864 return false;865 }866 return true;867}868//The same as Player's calculateHackingChance() function but takes in the server as an argument869function scriptCalculateHackingChance(server) {870 var difficultyMult = (100 - server.hackDifficulty) / 100;871 var skillMult = (1.75 * Player.hacking_skill) + (0.2 * Player.intelligence);872 var skillChance = (skillMult - server.requiredHackingSkill) / skillMult;873 var chance = skillChance * difficultyMult * Player.hacking_chance_mult;874 if (chance > 1) {return 1;}875 if (chance < 0) {return 0;}876 else {return chance;}877}878//The same as Player's calculateHackingTime() function but takes in the server as an argument879function scriptCalculateHackingTime(server) {880 var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;881 var skillFactor = (2.5 * difficultyMult + 500) / (Player.hacking_skill + 50 + (0.1 * Player.intelligence));882 var hackingTime = 5 * skillFactor / Player.hacking_speed_mult; //This is in seconds883 return hackingTime;884}885//The same as Player's calculateExpGain() function but takes in the server as an argument886function scriptCalculateExpGain(server) {887 if (server.baseDifficulty == null) {888 server.baseDifficulty = server.hackDifficulty;889 }890 return (server.baseDifficulty * Player.hacking_exp_mult * 0.3 + 3) * BitNodeMultipliers.HackExpGain;891}892//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument893function scriptCalculatePercentMoneyHacked(server) {894 var difficultyMult = (100 - server.hackDifficulty) / 100;895 var skillMult = (Player.hacking_skill - (server.requiredHackingSkill - 1)) / Player.hacking_skill;896 var percentMoneyHacked = difficultyMult * skillMult * Player.hacking_money_mult / 240;897 if (percentMoneyHacked < 0) {return 0;}898 if (percentMoneyHacked > 1) {return 1;}899 return percentMoneyHacked * BitNodeMultipliers.ScriptHackMoney;900}901//Amount of time to execute grow() in milliseconds902function scriptCalculateGrowTime(server) {903 var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;904 var skillFactor = (2.5 * difficultyMult + 500) / (Player.hacking_skill + 50 + (0.1 * Player.intelligence));905 var growTime = 16 * skillFactor / Player.hacking_speed_mult; //This is in seconds906 return growTime * 1000;907}908//Amount of time to execute weaken() in milliseconds909function scriptCalculateWeakenTime(server) {910 var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;911 var skillFactor = (2.5 * difficultyMult + 500) / (Player.hacking_skill + 50 + (0.1 * Player.intelligence));912 var weakenTime = 20 * skillFactor / Player.hacking_speed_mult; //This is in seconds913 return weakenTime * 1000;914}915export {makeRuntimeRejectMsg, netscriptDelay, runScriptFromScript,916 scriptCalculateHackingChance, scriptCalculateHackingTime,917 scriptCalculateExpGain, scriptCalculatePercentMoneyHacked,918 scriptCalculateGrowTime, scriptCalculateWeakenTime, evaluate,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1workerScript.onMessage = function(message) {2 console.log("message from worker", message);3 workerScript.sendMessage("message from main script");4}5workerScript.onMessage = function(message) {6 console.log("message from main script", message);7 workerScript.sendMessage("message from worker");8}9workerScript.onMessage = function(message) {10 console.log("message from worker", message);11 workerScript.sendMessage("message from main script");12}13workerScript.onMessage = function(message) {14 console.log("message from main script", message);15 workerScript.sendMessage("message from worker");16}17workerScript.onMessage = function(message) {18 console.log("message from worker", message);19 workerScript.sendMessage("message from main script");20}21workerScript.onMessage = function(message) {22 console.log("message from main script", message);23 workerScript.sendMessage("message from worker");24}25workerScript.onMessage = function(message) {26 console.log("message from worker", message);27 workerScript.sendMessage("message from main script");28}29workerScript.onMessage = function(message) {30 console.log("message from main script", message);31 workerScript.sendMessage("message from worker");32}33workerScript.onMessage = function(message) {34 console.log("message from worker", message);35 workerScript.sendMessage("message from main script");36}37workerScript.onMessage = function(message) {38 console.log("message from main script", message);39 workerScript.sendMessage("message from worker");40}41workerScript.onMessage = function(message) {42 console.log("message from worker", message);43 workerScript.sendMessage("message from main script

Full Screen

Using AI Code Generation

copy

Full Screen

1workerScript.onMessage = function(message) {2 console.log("Message received from worker: ", message);3 workerScript.sendMessage("Hello from test.js");4}5workerScript.onMessage = function(message) {6 console.log("Message received from main script: ", message);7 workerScript.sendMessage("Hello from worker.js");8}9workerScript.sendMessage("Hello from worker.js");10workerScript.onMessage = function(message) {11 console.log("Message received from worker: ", message);12 workerScript.sendMessage("Hello from test.js");13}14workerScript.onMessage = function(message) {15 console.log("Message received from main script: ", message);16 workerScript.sendMessage("Hello from worker.js");17}18workerScript.sendMessage("Hello from worker.js");19workerScript.onMessage = function(message) {20 console.log("Message received from worker: ", message);21 workerScript.sendMessage("Hello from test.js");22}23workerScript.onMessage = function(message) {24 console.log("Message received from main script: ", message);25 workerScript.sendMessage("Hello from worker.js");26}27workerScript.sendMessage("Hello from worker.js");28workerScript.onMessage = function(message) {29 console.log("Message received from worker: ", message);30 workerScript.sendMessage("Hello from test.js");31}32workerScript.onMessage = function(message) {33 console.log("Message received from main script: ", message);34 workerScript.sendMessage("Hello from worker.js");35}36workerScript.sendMessage("Hello from worker.js");37workerScript.onMessage = function(message) {38 console.log("Message received from worker: ", message);39 workerScript.sendMessage("Hello from test.js");40}41workerScript.onMessage = function(message) {42 console.log("Message received from main

Full Screen

Using AI Code Generation

copy

Full Screen

1workerScript.onMessage = function(message) {2 workerScript.sendMessage("Hello back to you!");3}4workerScript.onMessage = function(message) {5}6workerScript.onMessage = function(message) {7 workerScript.sendMessage("Hello back to you!");8}9workerScript.onMessage = function(message) {10}11workerScript.onMessage = function(message) {12 workerScript.sendMessage("Hello back to you!");13}14workerScript.onMessage = function(message) {15}16workerScript.onMessage = function(message) {17 workerScript.sendMessage("Hello back to you!");18}19workerScript.onMessage = function(message) {20}21workerScript.onMessage = function(message) {22 workerScript.sendMessage("Hello back to you!");23}24workerScript.onMessage = function(message) {25}26workerScript.onMessage = function(message) {27 workerScript.sendMessage("Hello back to you!");28}29workerScript.onMessage = function(message) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var worker = new Worker('worker.js');2worker.onmessage = function(e) {3 document.getElementById("result").innerHTML = e.data;4};5onmessage = function(e) {6 postMessage(e.data);7};

Full Screen

Using AI Code Generation

copy

Full Screen

1workerScript.onMessage = function(msg) {2 console.log("workerScript.onMessage: " + msg);3 workerScript.sendMessage("hello from workerScript");4}5workerScript.sendMessage("hello from workerScript");6workerScript.onMessage = function(msg) {7 console.log("workerScript.onMessage: " + msg);8}9workerScript.onMessage = function(msg) {10 console.log("workerScript.onMessage: " + msg);11 workerScript.sendMessage("hello from workerScript");12}13workerScript.sendMessage("hello from workerScript");14workerScript.onMessage = function(msg) {15 console.log("workerScript.onMessage: " + msg);16}17workerScript.onMessage = function(msg) {18 console.log("workerScript.onMessage: " + msg);19 workerScript.sendMessage("hello from workerScript");20}21workerScript.sendMessage("hello from workerScript");22workerScript.onMessage = function(msg) {23 console.log("workerScript.onMessage: " + msg);24}25workerScript.onMessage = function(msg) {26 console.log("workerScript.onMessage: " + msg);27 workerScript.sendMessage("hello from workerScript");28}29workerScript.sendMessage("hello from workerScript");30workerScript.onMessage = function(msg) {31 console.log("workerScript.onMessage: " + msg);32}33workerScript.onMessage = function(msg) {34 console.log("workerScript.onMessage: " + msg);35 workerScript.sendMessage("hello from workerScript");36}37workerScript.sendMessage("hello from workerScript");38workerScript.onMessage = function(msg) {39 console.log("workerScript.onMessage: " + msg);40}41workerScript.onMessage = function(msg) {42 console.log("workerScript.onMessage: " + msg);43 workerScript.sendMessage("hello from workerScript");44}

Full Screen

Using AI Code Generation

copy

Full Screen

1var workerScript = require('workerScript');2workerScript.onmessage = function (e) {3 workerScript.postMessage('I am worker script');4};5var workerScript = require('workerScript');6workerScript.onmessage = function (e) {7 console.log(e.data);8 workerScript.postMessage('I am main script');9};10var workerScript = require('workerScript');11workerScript.onmessage = function (e) {12 workerScript.postMessage('I am worker script');13};14var workerScript = require('workerScript');15workerScript.onmessage = function (e) {16 console.log(e.data);17 workerScript.postMessage('I am main script');18};19var workerScript = require('workerScript');20workerScript.onmessage = function (e) {21 workerScript.postMessage('I am worker script');22};23var workerScript = require('workerScript');24workerScript.onmessage = function (e) {25 console.log(e.data);26 workerScript.postMessage('I am main script');27};28var workerScript = require('workerScript');29workerScript.onmessage = function (e) {30 workerScript.postMessage('I am worker script');31};32var workerScript = require('workerScript');33workerScript.onmessage = function (e) {34 console.log(e.data);35 workerScript.postMessage('I am main script');36};37var workerScript = require('workerScript');38workerScript.onmessage = function (e) {39 workerScript.postMessage('I am worker script');40};41var workerScript = require('workerScript');42workerScript.onmessage = function (e) {43 console.log(e.data);44 workerScript.postMessage('I am main script');45};

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful