Skip to content

Commit

Permalink
feat: auto import R4
Browse files Browse the repository at this point in the history
  • Loading branch information
mindrunner committed Jul 14, 2024
1 parent 6c86241 commit e675811
Show file tree
Hide file tree
Showing 6 changed files with 223 additions and 23 deletions.
54 changes: 54 additions & 0 deletions src/main/basedbot/basedbot.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import {
getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID,
} from '@solana/spl-token'
import { getParsedTokenAccountsByOwner } from '@staratlas/data-source'
import BN from 'bn.js'

import { Sentry } from '../../sentry'

import { config } from '../../config'
import { logger } from '../../logger'
import { sleep } from '../../service/sleep'
import { connection } from '../../service/sol'
import { keyPair } from '../../service/wallet'

import { mineBiomass } from './fsm/configs/mine-biomass'
Expand All @@ -18,6 +26,7 @@ import { mineSilicia } from './fsm/configs/mine-silicia'
import { mineTitaniumOre } from './fsm/configs/mine-titanium-ore'
import { createMiningStrategy } from './fsm/mine'
import { Strategy } from './fsm/strategy'
import { depositCargo } from './lib/sage/act/deposit-cargo'
import { settleFleet } from './lib/sage/state/settle-fleet'
import { getPlayerContext, Player } from './lib/sage/state/user-account'
import {
Expand All @@ -30,6 +39,7 @@ import {
mineableByCoordinates,
WorldMap,
} from './lib/sage/state/world-map'
// eslint-disable-next-line import/max-dependencies
import { Coordinates } from './lib/util/coordinates'

// eslint-disable-next-line require-await
Expand Down Expand Up @@ -69,13 +79,57 @@ const applyStrategy = (
return strategy.send(fleetInfo)
}

const importR4 = async (player: Player): Promise<void> => {
await Promise.all(
[
player.game.data.mints.food,
player.game.data.mints.ammo,
player.game.data.mints.fuel,
player.game.data.mints.repairKit,
].map(async (mint) => {
//TODO: Make it easier to get the amount of a token
// This is being used in multiple places
const allTokenAccounts = await getParsedTokenAccountsByOwner(
connection,
player.signer.publicKey(),
TOKEN_PROGRAM_ID,
)

const sourceTokenAccount = getAssociatedTokenAddressSync(
mint,
player.signer.publicKey(),
true,
)
const [mintTokenAccount] = allTokenAccounts.filter((it) =>
it.address.equals(sourceTokenAccount),
)
const amountAtOrigin = new BN(mintTokenAccount.amount.toString())

if (amountAtOrigin.gtn(0)) {
logger.info(
`Importing R4 for ${mint.toBase58()}: ${amountAtOrigin}`,
)

await depositCargo(
player,
player.homeStarbase,
mint,
amountAtOrigin,
)
}
}),
)
}

const basedbot = async (botConfig: BotConfig) => {
const { player, map } = botConfig
const fleets = await getUserFleets(player)
const fleetInfos = await Promise.all(
fleets.map((f) => getFleetInfo(f, player, map)),
)

await importR4(player)

await Promise.all(
fleetInfos.map((fleetInfo) => settleFleet(fleetInfo, player, map)),
)
Expand Down
98 changes: 98 additions & 0 deletions src/main/basedbot/lib/sage/act/deposit-cargo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID,
} from '@solana/spl-token'
import { PublicKey } from '@solana/web3.js'
import {
createAssociatedTokenAccountIdempotent,
getParsedTokenAccountsByOwner,
InstructionReturn,
ixReturnsToIxs,
} from '@staratlas/data-source'
import { Starbase } from '@staratlas/sage'
import BN from 'bn.js'

import { connection } from '../../../../../service/sol'
import { sendAndConfirmInstructions } from '../../../../../service/sol/send-and-confirm-tx'
import { programs } from '../../programs'
import { depositCargoIx } from '../ix/import-cargo'
import { getCargoType } from '../state/cargo-types'
import {
getCargoPodsForStarbasePlayer,
getStarbasePlayer,
} from '../state/starbase-player'
import { Player } from '../state/user-account'

export const depositCargo = async (
player: Player,
starbase: Starbase,
mint: PublicKey,
amount: BN,
// eslint-disable-next-line max-params
): Promise<void> => {
const instructions: InstructionReturn[] = []

const starbasePlayer = await getStarbasePlayer(player, starbase, programs)

const sourceTokenAccount = getAssociatedTokenAddressSync(
mint,
player.signer.publicKey(),
)

const cargoPodTo = await getCargoPodsForStarbasePlayer(
starbasePlayer,
programs,
)
const destinationTokenAccount = getAssociatedTokenAddressSync(
mint,
cargoPodTo.key,
true,
)

instructions.push(
createAssociatedTokenAccountIdempotent(mint, cargoPodTo.key, true)
.instructions,
)

const cargoType = getCargoType(player.cargoTypes, player.game, mint)

const allTokenAccounts = await getParsedTokenAccountsByOwner(
connection,
player.signer.publicKey(),
TOKEN_PROGRAM_ID,
)

const [cargoTokenAccount] = allTokenAccounts.filter((it) =>
it.address.equals(sourceTokenAccount),
)

if (!cargoTokenAccount) {
throw new Error('Cargo token account not found')
}
const amountAtOrigin = new BN(cargoTokenAccount.amount.toString())

if (!cargoTokenAccount) {
throw new Error('Cargo not found at origin')
}
if (amountAtOrigin.lt(new BN(amount))) {
throw new Error('Not enough cargo available at origin')
}

instructions.push(
depositCargoIx(
player,
starbase,
starbasePlayer,
cargoPodTo.key,
sourceTokenAccount,
destinationTokenAccount,
cargoType.key,
programs,
amount,
),
)

await sendAndConfirmInstructions(
await ixReturnsToIxs(instructions, player.signer),
)
}
11 changes: 2 additions & 9 deletions src/main/basedbot/lib/sage/act/exit-respawn.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import { ixReturnsToIxs } from '@staratlas/data-source'
import { Starbase } from '@staratlas/sage'

import { logger } from '../../../../../logger'
import { sendAndConfirmInstructions } from '../../../../../service/sol/send-and-confirm-tx'
import { programs } from '../../programs'
import { Coordinates } from '../../util/coordinates'
import { exitRespawnIx } from '../ix/exit-respawn'
import { starbaseByCoordinates } from '../state/starbase-by-coordinates'
import { getStarbasePlayer } from '../state/starbase-player'
import { Player } from '../state/user-account'
import { FleetInfo } from '../state/user-fleets'

export const exitRespawn = async (
fleetInfo: FleetInfo,
location: Coordinates,
starbase: Starbase,
player: Player,
): Promise<void> => {
const { fleet } = fleetInfo
Expand All @@ -23,12 +22,6 @@ export const exitRespawn = async (
return
}

const starbase = await starbaseByCoordinates(location)

if (!starbase) {
throw new Error(`No starbase found at ${location}`)
}

const starbasePlayer = await getStarbasePlayer(player, starbase, programs)

const ix = exitRespawnIx(
Expand Down
40 changes: 40 additions & 0 deletions src/main/basedbot/lib/sage/ix/import-cargo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { PublicKey } from '@solana/web3.js'
import { InstructionReturn } from '@staratlas/data-source'
import { Starbase, StarbasePlayer } from '@staratlas/sage'
import BN from 'bn.js'

import { StarAtlasPrograms } from '../../programs'
import { Player } from '../state/user-account'

export const depositCargoIx = (
player: Player,
starbase: Starbase,
starbasePlayer: StarbasePlayer,
cargoPodTo: PublicKey,
tokenFrom: PublicKey,
tokenTo: PublicKey,
cargoType: PublicKey,
programs: StarAtlasPrograms,
amount: BN,
// eslint-disable-next-line max-params
): InstructionReturn =>
StarbasePlayer.depositCargoToGame(
programs.sage,
programs.cargo,
starbasePlayer.key,
player.signer,
player.profile.key,
player.profileFaction.key,
starbase.key,
cargoPodTo,
cargoType,
player.game.data.cargo.statsDefinition,
tokenFrom,
tokenTo,
player.game.key,
player.game.data.gameState,
{
amount,
keyIndex: 0,
},
)
8 changes: 1 addition & 7 deletions src/main/basedbot/lib/sage/state/settle-fleet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { now } from '../../../../../dayjs'
import { logger } from '../../../../../logger'
import { Coordinates } from '../../util/coordinates'
import { endMine } from '../act/end-mine'
import { endMove } from '../act/end-move'
import { exitRespawn } from '../act/exit-respawn'
Expand Down Expand Up @@ -47,12 +46,7 @@ export const settleFleet = async (
const { ETA } = fleetInfo.fleetState.data

if (ETA.isBefore(now())) {
// TODO: Respawn at Home Base based on Faction
await exitRespawn(
fleetInfo,
Coordinates.fromNumber(-40, 30),
player,
)
await exitRespawn(fleetInfo, player.homeStarbase, player)
}
break
}
Expand Down
35 changes: 28 additions & 7 deletions src/main/basedbot/lib/sage/state/user-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import {
import { PlayerProfile } from '@staratlas/player-profile'
import { PointsModifier } from '@staratlas/points'
import { ProfileFactionAccount } from '@staratlas/profile-faction'
import { Game } from '@staratlas/sage'
import { Game, Starbase } from '@staratlas/sage'

import { connection } from '../../../../../service/sol'
import { programs, xpCategoryIds } from '../../programs'
import { Coordinates } from '../../util/coordinates'

import { getCargoType, getCargoTypes } from './cargo-types'
import { sageGame } from './game'
import { starbaseByCoordinates } from './starbase-by-coordinates'

export type XpAccounts = {
councilRank: XpAccount
Expand All @@ -38,6 +40,7 @@ export type Player = {
xpAccounts: XpAccounts
signer: AsyncSigner
game: Game
homeStarbase: Starbase
cargoTypes: Array<CargoType>
fuelCargoType: CargoType
foodCargoType: CargoType
Expand Down Expand Up @@ -164,6 +167,29 @@ export const getPlayerContext = async (
const game = await sageGame()
const cargoTypes = await getCargoTypes()

let homeCoords

//TODO: add correct Coordinates for each faction
switch (profileFaction.data.data.faction) {
case 0:
homeCoords = Coordinates.fromNumber(0, 0)
break
case 1:
homeCoords = Coordinates.fromNumber(0, 0)
break
case 2:
homeCoords = Coordinates.fromNumber(-40, 30)
break
default:
throw new Error('Unknown faction')
}

const homeStarbase = await starbaseByCoordinates(homeCoords)

if (!homeStarbase) {
throw new Error('No home starbase found')
}

return {
profile: profile.data,
profileFaction: profileFaction.data,
Expand All @@ -172,14 +198,9 @@ export const getPlayerContext = async (
signer: keypairToAsyncSigner(signer),
game,
cargoTypes,
homeStarbase,
fuelCargoType: getCargoType(cargoTypes, game, game.data.mints.fuel),
foodCargoType: getCargoType(cargoTypes, game, game.data.mints.food),
ammoCargoType: getCargoType(cargoTypes, game, game.data.mints.ammo),
}
}

// export const getAccountName = (profileProgram: StarAtlasProgram, account: PlayerProfile): string => {
// const playerNameAddress = PlayerName.findAddress(profileProgram.program as any, account.key)
// const decodedPlayerName = PlayerName.decodeData({
// accountInfo: account.accountInfo, accountId: playerNameAddress }, profileProgram.program as any)
// }

0 comments on commit e675811

Please sign in to comment.