From 1b9a55432a0e621edf2c21c815b58b8cfa23a6d8 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Mon, 18 Sep 2023 22:48:08 +0200 Subject: [javascript] Completely reworked contracting --- nodejs/automation/automation.js | 26 ---------- nodejs/automation/contracting.js | 93 +++++++++++++++++---------------- nodejs/automation/init.js | 37 ++++++++++++++ nodejs/automation/utils.js | 3 ++ nodejs/database/systems.js | 13 +++++ nodejs/main.js | 108 ++------------------------------------- 6 files changed, 108 insertions(+), 172 deletions(-) delete mode 100644 nodejs/automation/automation.js create mode 100644 nodejs/automation/init.js create mode 100644 nodejs/automation/utils.js diff --git a/nodejs/automation/automation.js b/nodejs/automation/automation.js deleted file mode 100644 index 3184c2f..0000000 --- a/nodejs/automation/automation.js +++ /dev/null @@ -1,26 +0,0 @@ -import * as dbConfig from '../database/config.js'; -import * as dbShips from '../database/ships.js'; -import * as exploration from './exploration.js'; - -// This function registers then inits the database -export async function register(symbol, faction) { - const response = await fetch('https://api.spacetraders.io/v2/register', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - symbol: symbol, - faction: faction, - }), - }); - const json = await response.json(); - console.log(JSON.stringify(response, null, 2)); - if (response.error !== undefined) { - throw response; - } - dbConfig.registerAgent(json.data); - exploration.init(); - dbShips.setShip(json.data.ship); - // TODO contract -} diff --git a/nodejs/automation/contracting.js b/nodejs/automation/contracting.js index 525253c..c051b03 100644 --- a/nodejs/automation/contracting.js +++ b/nodejs/automation/contracting.js @@ -1,55 +1,62 @@ import * as mining from './mining.js'; +import * as dbContracts from '../database/contracts.js'; import * as dbShips from '../database/ships.js'; import * as api from '../lib/api.js'; import * as contracts from '../lib/contracts.js'; -import * as ships from '../lib/ships.js'; +import * as libShips from '../lib/ships.js'; import * as systems from '../lib/systems.js'; +import * as utils from './utils.js'; -export async function auto(ctx) { - let ship = dbShips.getShip(ctx.symbol); - // Fetch our contracts in the system the ship currently is in - let cs = await contracts.contracts(); - cs = cs.data.filter(c => c.terms.deliver[0].destinationSymbol.startsWith(ship.nav.systemSymbol)); - if (cs === []) throw `No contract at ${ctx.symbol}'s location`; - let contract = cs[0]; - if (!contract.accepted) { - console.log(new Date(), `accepting contract ${contract.id}`); - await contracts.accept({contract: contract.id}); +export async function init() { + const cs = dbContracts.getContracts(); + cs.forEach(contract => run(contract)); +} + +async function run(contract) { + await contracts.accept({id: contract.id}); + const contractSystem = utils.waypointToSystem(contract.terms.deliver[0].destinationSymbol); + let ships = dbShips.getShipsAt(contractSystem); + ships = ships.filter(ship => ship.registration.role !== 'SATELLITE'); // filter out probes + + switch(contract.type) { + case 'PROCUREMENT': + await runProcurement(contract, ships); + break; + default: + throw `Handling of contract type ${contract.type} is not implemented yet`; } - const good = contract.terms.deliver[0].tradeSymbol; +} + +async function runProcurement(contract, ships) { + // TODO check if contract is fulfilled! + const wantedCargo = contract.terms.deliver[0].tradeSymbol; const deliveryPoint = contract.terms.deliver[0].destinationSymbol; - const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'}); + const asteroidFields = await systems.type({symbol: ships[0].nav.systemSymbol, type: 'ASTEROID_FIELD'}); const asteroidField = asteroidFields[0].symbol; - while (true) { - ship = dbShips.getShip(ctx.symbol); - // If we are in transit, we wait until we arrive - const delay = new Date(ship.nav.route.arrival) - new Date(); - if (delay > 0) await api.sleep(delay); - // Then it depends on where we are - let goodCargo = ship.cargo.inventory.filter(i => i.symbol === good)[0]; - // the switch makes this 'resumable' - switch (ship.nav.waypointSymbol) { - case asteroidField: - let response = await mining.mineUntilFullOf({good: good, symbol: ctx.symbol}); - await ships.navigate({symbol: ctx.symbol, waypoint: deliveryPoint}); - break; - case deliveryPoint: - await ships.dock({symbol: ctx.symbol}); - await ships.refuel({symbol: ctx.symbol}); - if (goodCargo !== undefined) { - console.log(`delivering ${goodCargo.units} of ${good}`); - await contracts.deliver({contract: contract.id, symbol: ctx.symbol, good: good, units: goodCargo.units }); + ships.forEach(async function(ship) { + while (!contract.fulfilled) { + ship = dbShips.getShip(ship.symbol); + let goodCargo = ship.cargo.inventory.filter(i => i.symbol === wantedCargo)[0]; + // If we are in transit, we wait until we arrive + const delay = new Date(ship.nav.route.arrival) - new Date(); + if (delay > 0) await api.sleep(delay); + // Then it depends on where we are + switch (ship.nav.waypointSymbol) { + case asteroidField: + let response = await mining.mineUntilFullOf({good: wantedCargo, symbol: ship.symbol}); + await libShips.navigate({symbol: ship.symbol, waypoint: deliveryPoint}); + break; + case deliveryPoint: + if (goodCargo !== undefined) { // we could be here if a client restart happens right after selling before we navigate away + console.log(`delivering ${goodCargo.units} of ${wantedCargo}`); + await contracts.deliver({contract: contract.id, symbol: ship.symbol, good: wantedCargo, units: goodCargo.units }); + // TODO check if contract is fulfilled! + } + await libShips.navigate({symbol: ship.symbol, waypoint: asteroidField}); + break; + default: + await libShips.navigate({symbol: ship.symbol, waypoint: asteroidField}); } - await ships.navigate({symbol: ctx.symbol, waypoint: asteroidField}); - await ships.dock({symbol: ctx.symbol}); - await ships.refuel({symbol: ctx.symbol}); - await ships.orbit({symbol: ctx.symbol}); - break; - default: - await ships.navigate({symbol: ctx.symbol, waypoint: asteroidField}); - await ships.dock({symbol: ctx.symbol}); - await ships.refuel({symbol: ctx.symbol}); - await ships.orbit({symbol: ctx.symbol}); } - } + }); } diff --git a/nodejs/automation/init.js b/nodejs/automation/init.js new file mode 100644 index 0000000..21131e7 --- /dev/null +++ b/nodejs/automation/init.js @@ -0,0 +1,37 @@ +import * as dbAgents from '../database/agents.js'; +import * as db from '../database/db.js'; +import * as dbContracts from '../database/contracts.js'; +import * as dbShips from '../database/ships.js'; +import * as dbTokens from '../database/tokens.js'; +import * as api from '../lib/api.js'; +import * as ships from '../lib/ships.js'; + +// This function registers then inits the database +export async function init() { + const response = await fetch('https://api.spacetraders.io/v2/register', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + symbol: "ADYXAX", + faction: "COSMIC", + }), + }); + const json = await response.json(); + if (json.error !== undefined) { + switch(json.error?.code) { + case 4111: // 4111 means the agent symbol has already been claimed so no server reset happened + return; + default: + throw json; + } + } + db.reset(); + dbAgents.addAgent(json.data.agent); + dbContracts.setContract(json.data.contract); + dbShips.setShip(json.data.ship); + dbTokens.addToken(json.data.token); + // Temporary fix to fetch the data on the startup probe + ships.ships(); +} diff --git a/nodejs/automation/utils.js b/nodejs/automation/utils.js new file mode 100644 index 0000000..01ce1ad --- /dev/null +++ b/nodejs/automation/utils.js @@ -0,0 +1,3 @@ +export function waypointToSystem(waypoint) { + return waypoint.split('-').slice(0,2).join('-'); +} diff --git a/nodejs/database/systems.js b/nodejs/database/systems.js index dd70d33..f989218 100644 --- a/nodejs/database/systems.js +++ b/nodejs/database/systems.js @@ -4,6 +4,7 @@ const addSystemStatement = db.prepare(`INSERT INTO systems(data) VALUES (json(?) const getSystemStatement = db.prepare(`SELECT data FROM systems WHERE data->>'symbol' = ?;`); const getSystemUpdatedStatement = db.prepare(`SELECT updated FROM systems WHERE data->>'symbol' = ?;`); const getSystemsCountStatement = db.prepare(`SELECT COUNT(data) as data FROM systems;`); +const setSystemStatement = db.prepare(`UPDATE systems SET data = json(:data), updated = :date WHERE data->>'symbol' = :symbol;`); const setSystemWaypointsStatement = db.prepare(`UPDATE systems SET data = (SELECT json_set(data, '$.waypoints', json(:waypoints)) FROM systems WHERE data->>'symbol' = :symbol), updated = :date WHERE data->>'symbol' = :symbol;`); export function addSystem(data) { @@ -34,6 +35,18 @@ export function getSystemUpdated(symbol) { return updated.updated; } +export function setSystem(data) { + if (getSystem(data.symbol) === null) { + addSystem(data); + } else { + return setSystemStatement.run({ + data: JSON.stringify(data), + date: new Date().toISOString(), + symbol: data.symbol, + }).changes; + } +} + export function setSystemWaypoints(symbol, waypoints) { return setSystemWaypointsStatement.run({ date: new Date().toISOString(), diff --git a/nodejs/main.js b/nodejs/main.js index 6785301..ef05bc7 100755 --- a/nodejs/main.js +++ b/nodejs/main.js @@ -1,108 +1,10 @@ -import * as automation from './automation/automation.js'; import * as autoContracting from './automation/contracting.js'; -import * as autoMining from './automation/mining.js'; +import * as autoExploring from './automation/exploration.js'; +import * as autoInit from './automation/init.js'; import * as api from './lib/api.js'; import * as contracts from './lib/contracts.js'; import * as ships from './lib/ships.js'; -import * as systems from './lib/systems.js'; -function usage() { - console.log(`autoContractForShip [ship_symbol] run a contract extraction-delivery loop for the ship. -contracts.contracts List your contracts. -my-agent Fetch your agent's status. -register [symbol] [faction] Registers your agent then inits the database -ships.ship [ship_symbol] Retrieve a ship's status. -ships Retrieve all of your ships. -status Servers' status`); -} - -switch(process.argv[2]) { -case 'autoContractForShip': - await autoContracting.auto({symbol: process.argv[3]}); - break; -case 'autoMiningForShip': - await autoMining.mineUntilFullOf({symbol: process.argv[3], good: 'NON_EXISTENT'}); - break; -case 'my-agent': - api.debugLog(await api.send({endpoint: '/my/agent'})); - break; -case 'register': - if (process.argv[3] !== undefined && process.argv[4] !== undefined) { - automation.register(process.argv[3], process.argv[4]); - } else { - usage(); - } - break; -case 'ships': - api.debugLog(await api.send({endpoint: '/my/ships'})); - break; -case 'status': - api.debugLog(await api.send({endpoint: '/'})); - break; -default: - // wip and manual actions - switch(process.argv[2]) { - case 'contracts.accept': - api.debugLog(await contracts.accept({contract: process.argv[3]})); - break; - case 'contracts.contracts': - api.debugLog(await contracts.contracts()); - break; - case 'contracts.fulfill': - api.debugLog(await contracts.fulfill({contract: process.argv[3]})); - break; - case 'ships.dock': - api.debugLog(await ships.dock({symbol: process.argv[3]})); - break; - case 'ships.jump': - api.debugLog(await ships.jump({ship: process.argv[3], system: process.argv[4]})); - break; - //case 'market': - // api.send({endpoint: `/systems/${process.argv[3]}/waypoints/${process.argv[4]}/market`}); - // break; - case 'ships.navigate': - api.debugLog(await ships.navigate({symbol: process.argv[3], waypoint: process.argv[4]})); - break; - case 'ships.negotiate': - api.debugLog(await ships.negotiate({ship: process.argv[3]})); - break; - case 'ships.orbit': - api.debugLog(await ships.orbit({symbol: process.argv[3]})); - break; - case 'ships.purchase': - api.debugLog(await ships.purchase({shipType: process.argv[3], waypoint: process.argv[4]})); - break; - case 'ships.refuel': - api.debugLog(await ships.refuel({symbol: process.argv[3]})); - break; - case 'ships.sell': - api.debugLog(await ships.sell({symbol: process.argv[3], good: process.argv[4], units: process.argv[5]})); - break; - case 'ships.ship': - api.debugLog(await ships.ship({symbol: process.argv[3]})); - break; - case 'ships.survey': - api.debugLog(await ships.survey({symbol: process.argv[3]})); - break; - case 'systems.asteroids': - api.debugLog(await systems.type({symbol: process.argv[3], type: 'ASTEROID_FIELD'})); - break; - case 'systems.jumpGate': - api.debugLog(await systems.type({symbol: process.argv[3], type: 'JUMP_GATE'})); - break; - case 'systems.shipyard': - api.debugLog(await systems.shipyard({symbol: process.argv[3]})); - break; - case 'systems.shipyards': - api.debugLog(await systems.trait({symbol: process.argv[3], trait: 'SHIPYARD'})); - break; - case 'systems.system': - api.debugLog(await systems.system({symbol: process.argv[3]})); - break; - case 'systems.waypoints': - api.debugLog(await systems.waypoints({symbol: process.argv[3]})); - break; - default: - usage(); - } -} +await autoInit.init(); +autoContracting.init(); +autoExploring.init(); -- cgit v1.2.3