1
0
Fork 0

Moved the nodejs agent to its own subfolder to make room for my haskell agent

This commit is contained in:
Julien Dessaux 2023-07-01 23:13:13 +02:00
parent 0bc0df0891
commit 36cc33f9e9
Signed by: adyxax
GPG key ID: F92E51B86E07177E
22 changed files with 0 additions and 0 deletions

44
nodejs/.eslintrc.json Normal file
View file

@ -0,0 +1,44 @@
{
"env": {
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:node/recommended"
],
"overrides": [
{
"files": ["*.js"],
"rules": {
"no-constant-condition": "off"
}
}
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"node/no-unsupported-features/es-syntax": [
"error",
{ "ignores": ["modules"] }
]
}
}

View file

@ -0,0 +1,26 @@
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
}

View file

@ -0,0 +1,55 @@
import * as mining from './mining.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 systems from '../lib/systems.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});
}
const good = 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 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 });
}
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});
}
}
}

View file

@ -0,0 +1,21 @@
import * as db from '../database/systems.js';
import * as api from '../lib/api.js';
// Retrieves all systems information, should be called only once after registering
export async function init() {
if (db.isInit()) {
return;
}
for (let page=1; true; ++page) {
const response = await api.send({endpoint: `/systems?limit=20&page=${page}`, priority:100});
if (response.error !== undefined) {
throw response;
}
response.data.forEach(system => db.setSystem(system));
if (response.meta.total <= response.meta.limit * page) {
break;
}
}
console.log('Finished retrieving all systems information');
db.init();
}

View file

@ -0,0 +1,34 @@
import * as dbShips from '../database/ships.js';
import * as api from '../lib/api.js';
import * as ships from '../lib/ships.js';
// example ctx { good: 'SILVER_ORE', symbol: 'ADYXAX-2' }
// returns the number of units of the good the ship holds
export async function mineUntilFullOf(ctx) {
while(true) {
let cargo = await mineUntilFull({symbol: ctx.symbol});
let good = cargo.inventory.filter(i => i.symbol === ctx.good)[0];
const antimatter = cargo.inventory.filter(i => i.symbol === 'ANTIMATTER')[0];
const junk = cargo.inventory.filter(i => i.symbol !== ctx.good && i.symbol !== 'ANTIMATTER');
if ((good?.units ?? 0) + (antimatter?.units ?? 0) >= cargo.capacity * 0.9) { // > 90% full of the valuable goods
return good.units;
} else { // we are full but need to sell junk
for (let i=0; i<junk.length; ++i) {
await ships.sell({symbol: ctx.symbol, good: junk[i].symbol, units: junk[i].units});
}
}
}
}
// example ctx { symbol: 'ADYXAX-2' }
// extract the ship's cargo contents when more than 80% full then returns the ships cargo object
async function mineUntilFull(ctx) {
while(true) {
const ship = dbShips.getShip(ctx.symbol);
if (ship.cargo.units >= ship.cargo.capacity * 0.9) return ship.cargo;
if (await ships.extract({symbol: ctx.symbol}) === null)
ship = await ship(ctx); // refresh the ships status from the server just in case
}
}
// TODO surveying the asteroid field

View file

@ -0,0 +1,8 @@
CREATE TABLE schema_version (
version INTEGER NOT NULL
);
CREATE TABLE config (
id INTEGER PRIMARY KEY,
key TEXT NOT NULL UNIQUE,
value TEXT NOT NULL
);

View file

@ -0,0 +1,6 @@
CREATE TABLE systems (
id INTEGER PRIMARY KEY,
data JSON NOT NULL,
updated DATE DEFAULT NULL
);
CREATE UNIQUE INDEX systems_data_symbol on systems (json_extract(data, '$.symbol'));

View file

@ -0,0 +1,6 @@
CREATE TABLE ships (
id INTEGER PRIMARY KEY,
data JSON NOT NULL,
updated DATE DEFAULT NULL
);
CREATE UNIQUE INDEX ships_data_symbol on ships (json_extract(data, '$.symbol'));

View file

@ -0,0 +1,6 @@
CREATE TABLE surveys (
id INTEGER PRIMARY KEY,
data JSON NOT NULL
);
CREATE INDEX surveys_data_symbol on surveys (json_extract(data, '$.symbol'));
CREATE INDEX surveys_data_expiration on surveys (json_extract(data, '$.expiration'));

23
nodejs/database/config.js Normal file
View file

@ -0,0 +1,23 @@
import db from './db.js';
const getTokenStatement = db.prepare(`SELECT value->>'token' as token from config where key = 'register_data';`);
const registerAgentStatement = db.prepare(`INSERT INTO config(key, value) VALUES ('register_data', json(?));`);
export function getToken() {
try {
return getTokenStatement.get().token;
} catch (err) {
console.log(err);
return null;
}
}
export function registerAgent(data) {
try {
registerAgentStatement.run(JSON.stringify(data));
return true;
} catch (err) {
console.log(err);
return false;
}
}

33
nodejs/database/db.js Normal file
View file

@ -0,0 +1,33 @@
import fs from 'fs';
import Database from 'better-sqlite3';
const allMigrations = [
'database/000_init.sql',
'database/001_systems.sql',
'database/002_ships.sql',
'database/003_surveys.sql',
];
const db = new Database(
process.env.NODE_ENV === 'test' ? 'test.db' : 'spacetraders.db',
process.env.NODE_ENV === 'development' ? { verbose: console.log } : null
);
db.pragma('foreign_keys = ON');
db.pragma('journal_mode = WAL');
db.transaction(function migrate() {
let version;
try {
version = db.prepare('SELECT version FROM schema_version').get().version;
} catch {
version = 0;
}
if (version === allMigrations.length) return;
while (version < allMigrations.length) {
db.exec(fs.readFileSync(allMigrations[version], 'utf8'));
version++;
}
db.exec(`DELETE FROM schema_version; INSERT INTO schema_version (version) VALUES (${version});`);
})();
export default db;

82
nodejs/database/ships.js Normal file
View file

@ -0,0 +1,82 @@
import db from './db.js';
const getShipStatement = db.prepare(`SELECT data FROM ships WHERE data->>'symbol' = ?;`);
const setShipStatement = db.prepare(`INSERT INTO ships(data, updated) VALUES (json(?), ?);`);
const setShipCargoStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.cargo', json(:cargo)) FROM ships WHERE data->>'symbol' = :symbol), updated = :date WHERE data->>'symbol' = :symbol;`);
const setShipFuelStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.fuel', json(:fuel)) FROM ships WHERE data->>'symbol' = :symbol), updated = :date WHERE data->>'symbol' = :symbol;`);
const setShipNavStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.nav', json(:nav)) FROM ships WHERE data->>'symbol' = :symbol), updated = :date WHERE data->>'symbol' = :symbol;`);
const updateShipStatement = db.prepare(`UPDATE ships SET data = json(:data), updated = :date WHERE data->>'symbol' = :symbol;`);
export function getShip(symbol) {
try {
const data = getShipStatement.get(symbol);
if (data === undefined) {
return null;
}
return JSON.parse(data.data);
} catch (err) {
console.log(err);
return null;
}
}
export function setShip(data) {
if (getShip(data.symbol) === null) {
try {
return setShipStatement.run(JSON.stringify(data), new Date().toISOString()).lastInsertRowid;
} catch (err) {
console.log(err);
return null;
}
} else {
try {
return updateShipStatement.run({
data: JSON.stringify(data),
date: new Date().toISOString(),
symbol: data.symbol,
}).changes;
} catch (err) {
console.log(err);
return null;
}
}
}
export function setShipCargo(symbol, cargo) {
try {
setShipCargoStatement.run({
cargo: JSON.stringify(cargo),
date: new Date().toISOString(),
symbol: symbol,
}).changes;
} catch (err) {
console.log(err);
return null;
}
}
export function setShipFuel(symbol, fuel) {
try {
setShipFuelStatement.run({
date: new Date().toISOString(),
fuel: JSON.stringify(fuel),
symbol: symbol,
}).changes;
} catch (err) {
console.log(err);
return null;
}
}
export function setShipNav(symbol, nav) {
try {
setShipNavStatement.run({
date: new Date().toISOString(),
nav: JSON.stringify(nav),
symbol: symbol,
}).changes;
} catch (err) {
console.log(err);
return null;
}
}

View file

@ -0,0 +1,19 @@
import db from './db.js';
const deleteExpiredSurveysStatement = db.prepare(`DELETE FROM surveys WHERE data->>'expiration' < ?;`);
const getSurveysStatement = db.prepare(`SELECT data FROM surveys WHERE data->>'symbol' = ?;`);
const setSurveysStatement = db.prepare(`INSERT INTO surveys(data) VALUES (json(?));`);
export function deleteExpired() {
return deleteExpiredSurveysStatement.run(new Date().toISOString()).changes;
}
export function get(symbol) {
deleteExpired();
return getSurveysStatement.all(symbol);
}
export function set(survey) {
deleteExpired();
return setSurveysStatement.run(JSON.stringify(survey));
}

View file

@ -0,0 +1,71 @@
import db from './db.js';
const getSystemStatement = db.prepare(`SELECT data FROM systems WHERE data->>'symbol' = ?;`);
const getSystemUpdatedStatement = db.prepare(`SELECT updated FROM systems WHERE data->>'symbol' = ?;`);
const initStatement = db.prepare(`INSERT INTO config(key, value) VALUES ('systems_initialized', TRUE);`);
const isInitStatement = db.prepare(`SELECT value FROM config WHERE key = 'systems_initialized'`);
const setSystemStatement = db.prepare(`INSERT INTO systems(data) VALUES (json(?));`);
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 init() {
try {
return initStatement.run().lastInsertRowid;
} catch (err) {
return null;
}
}
export function isInit() {
try {
return isInitStatement.get().value === '1';
} catch (err) {
return false;
}
}
export function getSystem(symbol) {
try {
const data = getSystemStatement.get(symbol);
if (data === undefined) {
return null;
}
return JSON.parse(data.data);
} catch (err) {
console.log(err);
return null;
}
}
export function getSystemUpdated(symbol) {
try {
const updated = getSystemUpdatedStatement.get(symbol);
if (updated === undefined) {
return null;
}
return updated.updated;
} catch (err) {
console.log(err);
return null;
}
}
export function setSystem(data) {
try {
return setSystemStatement.run(JSON.stringify(data)).lastInsertRowid;
} catch (err) {
return null;
}
}
export function setSystemWaypoints(symbol, waypoints) {
try {
return setSystemWaypointsStatement.run({
date: new Date().toISOString(),
symbol: symbol,
waypoints: JSON.stringify(waypoints),
}).changes;
} catch (err) {
console.log(err);
return null;
}
}

140
nodejs/lib/api.js Normal file
View file

@ -0,0 +1,140 @@
import * as fs from 'fs';
import * as events from 'events';
import { getToken } from '../database/config.js';
import { PriorityQueue } from './priority_queue.js';
// queue processor module variables
const bus = new events.EventEmitter(); // a bus to notify the queue processor to start processing messages
let busy = false; // true if we are already sending api requests.
let backoffSeconds = 0;
let running = false;
// other module variables
let headers = undefined; // a file scope variable so that we only evaluate these once.
let queue = new PriorityQueue(); // a priority queue to hold api calls we want to send, allows for throttling.
// a single queue processor should be running at any time, otherwise there will be trouble!
async function queue_processor() {
if (running) {
throw 'refusing to start a second queue processor';
}
running = true;
while(true) {
try {
if (backoffSeconds > 0) {
await sleep(backoffSeconds * 1000);
backoffSeconds = 0;
}
if (queue.isEmpty()) {
busy = false;
await new Promise(resolve => bus.once('send', resolve));
busy = true;
}
const before = new Date();
await send_this(queue.dequeue().element);
const duration = new Date() - before;
if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development
await sleep(400 - duration);
}
} catch (e) {
running = false;
throw e;
}
}
}
queue_processor();
// send takes a request object as argument and an optional context ctx
// example request: {
// endpoint: the path part of the url to call,
// method: HTTP method for `fetch` call, defaults to 'GET',
// payload: optional json object that will be send along with the request,
// priority: optional priority value (defaults to 10, lower than 10 means the message will be sent faster)
// }
export function send(request, ctx) {
return new Promise((resolve, reject) => {
let data = {
ctx: ctx,
reject: reject,
request: request,
resolve: resolve,
};
queue.enqueue(data, request.priority ? request.priority : 10);
if (!busy) {
bus.emit('send'); // the queue was previously empty, let's wake up the queue_processor
}
});
}
// send_this take a data object as argument built in the send function above
async function send_this(data) {
if (headers === undefined) {
const token = getToken();
if (token === null) {
throw 'Could not get token from the database. Did you init or register yet?';
}
headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
let options = {
headers: headers,
};
if (data.request.method !== undefined) {
options['method'] = data.request.method;
}
if (data.request.payload !== undefined) {
options['body'] = JSON.stringify(data.request.payload);
}
fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'});
try {
let response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}`, options);
response = await response.json();
switch(response.error?.code) {
//case 401: // TODO 401 means a server reset happened
// TODO reject all promises in queue
// close database file
// rm database file
// logrotate
// spawnSync
// break;
case 429: // 429 means rate limited, let's hold back as instructed
backoffSeconds = response.error.data.retryAfter;
queue.enqueue(data, 1);
break;
case 503: // 503 means maintenance mode, let's hold back for 1 minute
backoffSeconds = 60;
queue.enqueue(data, 1);
break;
default: // no error!
fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'});
return data.resolve(response);
}
} catch (err) {
fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'});
switch(err.cause?.code) {
case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds
backoffSeconds = 5;
queue.enqueue(data, 1);
break;
case 'ECONNRESET':
queue.enqueue(data, 1);
break;
case 'UND_ERR_CONNECT_TIMEOUT':
queue.enqueue(data, 1);
break;
default:
data.reject(response);
}
}
}
export function debugLog(ctx) {
console.log(`--- ${Date()} -----------------------------------------------------------------------------`);
console.log(JSON.stringify(ctx, null, 2));
}
export function sleep(delay) {
return new Promise((resolve) => setTimeout(resolve, delay))
}

26
nodejs/lib/contracts.js Normal file
View file

@ -0,0 +1,26 @@
import * as api from './api.js';
import * as dbShips from '../database/ships.js';
export async function accept(ctx) {
return await api.send({endpoint: `/my/contracts/${ctx.contract}/accept`, method: 'POST'});
}
export async function contracts() {
return await api.send({endpoint: '/my/contracts'});
}
export async function deliver(ctx) {
const response = await api.send({ endpoint: `/my/contracts/${ctx.contract}/deliver`, method: 'POST', payload: {
shipSymbol: ctx.symbol,
tradeSymbol: ctx.good,
units: ctx.units,
}});
if (response.error !== undefined) {
throw response;
}
dbShips.setShipCargo(ctx.symbol, response.data.cargo);
}
export async function fulfill(ctx) {
return await api.send({ endpoint: `/my/contracts/${ctx.contract}/fulfill`, method: 'POST'});
}

View file

@ -0,0 +1,39 @@
export class QElement {
constructor(element, priority) {
this.element = element;
this.priority = priority;
}
}
export class PriorityQueue {
constructor(elt) {
this.items = [];
if (elt !== undefined) {
this.enqueue(elt, 0);
}
}
enqueue(element, priority) {
let qElement = new QElement(element, priority);
for (let i = 0; i < this.items.length; ++i) {
if (this.items[i].priority > qElement.priority) {
this.items.splice(i, 0, qElement);
return;
}
}
this.items.push(qElement);
}
dequeue() {
return this.items.shift(); // we would use pop to get the highest priority, shift() gives us the lowest priority
}
front() {
return this.items[0];
}
rear() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}

187
nodejs/lib/ships.js Normal file
View file

@ -0,0 +1,187 @@
import * as api from './api.js';
import * as dbConfig from '../database/config.js';
import * as dbShips from '../database/ships.js';
import * as dbSurveys from '../database/surveys.js';
import * as systems from '../lib/systems.js';
export async function extract(ctx) {
const ship = dbShips.getShip(ctx.symbol);
const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'});
// TODO if there are multiple fields, find the closest one?
await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol});
await orbit(ctx);
// TODO handle surveying?
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/extract`, method: 'POST'});
if (response.error !== undefined) {
switch(response.error.code) {
case 4000: // ship is on cooldown
await api.sleep(response.error.data.cooldown.remainingSeconds * 1000);
return await extract(ctx);
case 4228: // ship is full
return null;
default: // yet unhandled error
throw response;
}
} else {
dbShips.setShipCargo(ctx.symbol, response.data.cargo);
await api.sleep(response.data.cooldown.remainingSeconds*1000);
}
return response;
}
export async function dock(ctx) {
const ship = dbShips.getShip(ctx.symbol);
if (ship.nav.status === 'DOCKED') {
return null;
}
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/dock`, method: 'POST'});
if (response.error !== undefined) {
switch(response.error.code) {
case 4214: // ship is in transit
await api.sleep(response.error.data.secondsToArrival * 1000);
return await dock(ctx);
default: // yet unhandled error
throw response;
}
}
dbShips.setShipNav(ctx.symbol, response.data.nav);
return response;
}
function hasMount(shipSymbol, mountSymbol) {
const ship = dbShips.getShip(shipSymbol);
return ship.mounts.filter(s => s.symbol === mountSymbol).length > 0;
}
export async function jump(ctx) {
// TODO
const response = await api.send({endpoint: `/my/ships/${ctx.ship}/jump`, method: 'POST', payload: { systemSymbol: ctx.system }});
await api.sleep(response.data.cooldown.remainingSeconds*1000);
return response;
}
export async function navigate(ctx) {
const ship = dbShips.getShip(ctx.symbol);
if (ship.nav.waypointSymbol === ctx.waypoint) {
return await orbit(ctx);
}
await orbit(ctx);
// TODO if we do not have enough fuel, make a stop to refuel along the way or drift to the destination
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/navigate`, method: 'POST', payload: { waypointSymbol: ctx.waypoint }});
if (response.error !== undefined) {
switch(response.error.code) {
case 4214: // ship is in transit
await api.sleep(response.error.data.secondsToArrival * 1000);
return await navigate(ctx);
default: // yet unhandled error
throw response;
}
}
dbShips.setShipFuel(ctx.symbol, response.data.fuel);
dbShips.setShipNav(ctx.symbol, response.data.nav);
const delay = new Date(response.data.nav.route.arrival) - new Date();
await api.sleep(delay);
response.data.nav.status = 'IN_ORBIT';
dbShips.setShipNav(ctx.symbol, response.data.nav);
await refuel(ctx);
return response;
}
export async function negotiate(ctx) {
// TODO
return await api.send({endpoint: `/my/ships/${ctx.ship}/negotiate/contract`, method: 'POST'});
}
export async function orbit(ctx) {
const ship = dbShips.getShip(ctx.symbol);
if (ship.nav.status === 'IN_ORBIT') {
return null;
}
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/orbit`, method: 'POST'});
if (response.error !== undefined) {
switch(response.error.code) {
case 4214: // ship is in transit
await api.sleep(response.error.data.secondsToArrival * 1000);
return await orbit(ctx);
default: // yet unhandled error
throw response;
}
}
dbShips.setShipNav(ctx.symbol, response.data.nav);
return response;
}
export async function purchase(ctx) {
const response = await api.send({endpoint: '/my/ships', method: 'POST', payload: {
shipType: ctx.shipType,
waypointSymbol: ctx.waypoint,
}});
if (response.error !== undefined) {
throw response;
}
dbShips.setShip(response.data.ship);
return response.data;
}
export async function refuel(ctx) {
const ship = dbShips.getShip(ctx.symbol);
if (ship.fuel.current >= ship.fuel.capacity * 0.9) {
return null;
}
// TODO check if our current waypoint has a marketplace (and sells fuel)?
await dock(ctx);
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/refuel`, method: 'POST'});
if (response.error !== undefined) {
throw response;
}
dbShips.setShipFuel(ctx.symbol, response.data.fuel);
// TODO track credits
return response;
}
export async function sell(ctx) {
// TODO check if our current waypoint has a marketplace (and sells fuel)?
await dock(ctx);
const ship = dbShips.getShip(ctx.symbol);
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/sell`, method: 'POST', payload: { symbol: ctx.good, units: ctx.units }});
if (response.error !== undefined) {
throw response;
}
dbShips.setShipCargo(ctx.symbol, response.data.cargo);
// TODO track credits
return response;
}
export async function ship(ctx) {
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}`});
if (response.error !== undefined) {
throw response;
}
dbShips.setShip(response.data);
return response;
}
export async function survey(ctx) {
if (!hasMount(ctx.symbol, 'MOUNT_SURVEYOR_I')) { // we check if a surveyor is mounted on the ship
return null;
}
const ship = dbShips.getShip(ctx.symbol);
const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'});
// TODO if there are multiple fields, find the closest one?
await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol});
await orbit(ctx);
const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/survey`, method: 'POST'});
api.debugLog(response);
if (response.error !== undefined) {
switch(response.error.code) {
case 4000: // ship is on cooldown
await api.sleep(response.error.data.cooldown.remainingSeconds * 1000);
return await survey(ctx);
default: // yet unhandled error
throw response;
}
}
dbSurveys.set(response.data.surveys[0]);
await api.sleep(response.data.cooldown.remainingSeconds*1000);
return response;
}

68
nodejs/lib/systems.js Normal file
View file

@ -0,0 +1,68 @@
import * as api from './api.js';
import * as db from '../database/systems.js';
// Retrieves a shipyard's information for ctx.symbol
export async function shipyard(ctx) {
const systemSymbol = ctx.symbol.match(/([^-]+-[^-]+)/)[1]; // TODO generalise this extraction
console.log(systemSymbol);
return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`});
}
// Retrieves the system's information for ctx.symbol and caches it in the database
export async function system(ctx) {
let s = db.getSystem(ctx.symbol);
if (s === null) {
const response = await api.send({endpoint: `/systems/${ctx.symbol}`});
if (response.error !== undefined) {
switch(response.error.code) {
case 404:
throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`;
default: // yet unhandled error
throw response;
}
}
s = response.data;
db.setSystem(s);
}
return s;
}
// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol
export async function trait(ctx) {
const w = await waypoints(ctx);
return w.filter(s => s.traits.some(t => t.symbol === ctx.trait));
}
// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol
export async function type(ctx, response) {
const w = await waypoints(ctx);
return w.filter(s => s.type === ctx.type);
}
// Retrieves the system's information for ctx.symbol and caches it in the database
export async function waypoints(ctx) {
await system(ctx);
let updated = db.getSystemUpdated(ctx.symbol);
// TODO handle uncharted systems
if (updated === null) {
let waypoints = [];
for (let page=1; true; ++page) {
const response = await api.send({endpoint: `/systems/${ctx.symbol}/waypoints?limit=20&page=${page}`, priority: 98});
if (response.error !== undefined) {
switch(response.error.code) {
case 404:
throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`;
default: // yet unhandled error
throw response;
}
}
waypoints = waypoints.concat(response.data);
if (response.meta.total <= response.meta.limit * page) {
break;
}
}
db.setSystemWaypoints(ctx.symbol, waypoints);
return waypoints;
}
return db.getSystem(ctx.symbol).waypoints;
}

108
nodejs/main.js Executable file
View file

@ -0,0 +1,108 @@
import * as automation from './automation/automation.js';
import * as autoContracting from './automation/contracting.js';
import * as autoMining from './automation/mining.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();
}
}

1598
nodejs/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

11
nodejs/package.json Normal file
View file

@ -0,0 +1,11 @@
{
"type": "module",
"engines": {
"node": ">=18.10.0"
},
"dependencies": {
"better-sqlite3": "^8.3.0",
"eslint": "^8.30.0",
"eslint-plugin-node": "^11.1.0"
}
}