Skip to content

Commit

Permalink
fix: optimize fleet creation
Browse files Browse the repository at this point in the history
  • Loading branch information
mindrunner committed Sep 9, 2024
1 parent 3994c8b commit b402500
Show file tree
Hide file tree
Showing 9 changed files with 232 additions and 100 deletions.
34 changes: 20 additions & 14 deletions src/lib/refill-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,25 @@ export const refillPlayer = async (
refill.amount,
)

return Refill.create({
signature: tx,
walletPublicKey: wallet.publicKey,
fleet: shipName,
preBalance: playerBalance.toNumber(),
postBalance: playerBalance.sub(refill.price).toNumber(),
tip: wallet.tip,
price: refill.price.toNumber(),
food: refill.amount.food.toNumber(),
tool: refill.amount.tool.toNumber(),
fuel: refill.amount.fuel.toNumber(),
ammo: refill.amount.ammo.toNumber(),
}).save()
return Promise.all(
tx.map((signature) => {
return Refill.create({
signature,
walletPublicKey: wallet.publicKey,
fleet: shipName,
preBalance: playerBalance.toNumber(),
postBalance: playerBalance
.sub(refill.price)
.toNumber(),
tip: wallet.tip,
price: refill.price.toNumber(),
food: refill.amount.food.toNumber(),
tool: refill.amount.tool.toNumber(),
fuel: refill.amount.fuel.toNumber(),
ammo: refill.amount.ammo.toNumber(),
}).save()
}),
)
} catch (e) {
Sentry.captureException(e)
logger.error(
Expand Down Expand Up @@ -132,5 +138,5 @@ export const refillPlayer = async (

await Wallet.update({ publicKey: wallet.publicKey }, { nextRefill })

return fleetRefills.filter((f): f is Refill => f !== null)
return fleetRefills.filter((f): f is Refill[] => f !== null).flat()
}
25 changes: 15 additions & 10 deletions src/lib/telegram/commands/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,27 @@ export const withdraw = (bot: Telegraf<ContextMessageUpdate>): void => {
await ctx.reply(
`Sending ${withdrawAmount} ATLAS to ${ctx.user.publicKey}`,
)
const signature = await sendAtlas(
const signatures = await sendAtlas(
new PublicKey(ctx.user.publicKey),
withdrawAmount.toNumber(),
)

await ctx.reply(`https://solscan.io/tx/${signature}`)
const amount = -withdrawAmount

await Transaction.create({
wallet,
amount,
signature,
time: dayjs().toDate(),
originalAmount: amount,
resource: 'ATLAS',
}).save()
await Promise.all(
signatures.map(async (signature) => {
await ctx.reply(`https://solscan.io/tx/${signature}`)

return Transaction.create({
wallet,
amount,
signature,
time: dayjs().toDate(),
originalAmount: amount,
resource: 'ATLAS',
}).save()
}),
)
})
})
}
54 changes: 51 additions & 3 deletions src/main/basedbot/basedbot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,47 @@ import {
TOKEN_PROGRAM_ID,
} from '@solana/spl-token'
import { PublicKey } from '@solana/web3.js'
import { getParsedTokenAccountsByOwner } from '@staratlas/data-source'
import { Fleet, Game } from '@staratlas/sage'
import {
getParsedTokenAccountsByOwner,
ixReturnsToIxs,
} from '@staratlas/data-source'
import {
Fleet,
Game,
getCleanPodsByStarbasePlayerAccounts,
getPodCleanupInstructions,
Starbase,
} from '@staratlas/sage'
import BN from 'bn.js'

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

import { logger } from '../../logger'
import { sleep } from '../../service/sleep'
import { connection } from '../../service/sol'
import { sendAndConfirmInstructions } from '../../service/sol/send-and-confirm-tx'
import { keyPair } from '../../service/wallet'

import { getFleetStrategy } from './fleet-strategies/get-fleet-strategy'
import { StrategyConfig } from './fleet-strategies/strategy-config'
import { createInfoStrategy } from './fsm/info'
import { programs } from './lib/programs'
import { createFleet, FleetShip } from './lib/sage/act/create-fleet'
import { depositCargo } from './lib/sage/act/deposit-cargo'
import { ensureShips } from './lib/sage/act/deposit-ship'
import { getCargoStatsDefinition } from './lib/sage/state/cargo-stats-definition'
import { sageGame } from './lib/sage/state/game'
import { settleFleet } from './lib/sage/state/settle-fleet'
import { getStarbasePlayer } from './lib/sage/state/starbase-player'
import { getPlayerContext, Player } from './lib/sage/state/user-account'
import {
FleetInfo,
getFleetInfo,
getUserFleets,
} from './lib/sage/state/user-fleets'
import { getMapContext, WorldMap } from './lib/sage/state/world-map'
import { getName } from './lib/sage/util'
// eslint-disable-next-line import/max-dependencies
import { getName } from './lib/sage/util'

// eslint-disable-next-line require-await
export const create = async (): Promise<void> => {
Expand Down Expand Up @@ -170,6 +183,39 @@ const ensureFleets = async (
)
}

const cleanupPods = async (player: Player, game: Game, starbase: Starbase) => {
const starbasePlayer = await getStarbasePlayer(player, starbase, programs)
const podCleanup = await getCleanPodsByStarbasePlayerAccounts(
connection,
programs.cargo,
starbasePlayer.key,
)
const [cargoStatsDefinition] = await getCargoStatsDefinition()

if (!podCleanup) {
logger.info('Nothing to Clean up')

return
}

const ixs = getPodCleanupInstructions(
podCleanup,
programs.sage,
programs.cargo,
starbasePlayer.key,
starbase.key,
player.profile.key,
player.profileFaction.key,
cargoStatsDefinition.key,
game.key,
game.data.gameState,
player.signer,
0,
)

await sendAndConfirmInstructions(await ixReturnsToIxs(ixs, player.signer))
}

const basedbot = async (botConfig: BotConfig) => {
logger.info(
'-------------------------------------------------------------------------------------',
Expand All @@ -183,6 +229,8 @@ const basedbot = async (botConfig: BotConfig) => {
fleets.map((f) => getFleetInfo(f, player, map)),
)

await cleanupPods(player, game, player.homeStarbase)

await Promise.all([
importR4(player, game),
ensureFleets(player, game, fleets, botConfig.fleetStrategies),
Expand Down
13 changes: 9 additions & 4 deletions src/main/basedbot/fleet-strategies/atlasnet-fc-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,26 @@ const getRandomFleetForFaction = (faction: Faction): FleetShips => {
},
]
default:
throw new Error('Unknwon Faction')
throw new Error('Unknown Faction')
}
}

export const atlasnetFcStrategy =
(count: number) =>
(map: WorldMap, player: Player, game: Game): StrategyConfig => {
(
map: WorldMap,
player: Player,
game: Game,
seed: string = 'basedbot',
): StrategyConfig => {
const strategyMap: StrategyMap = makeStrategyMap()
const chance = new Chance()
const chance = new Chance(seed)
const sectors = galaxySectorsData()
.filter((sector) => sector.closestFaction === player.faction)
.sort((a, b) => a.name.localeCompare(b.name))

for (let i = 0; i < count; i++) {
strategyMap.set(`${chance.animal()} Fleet [${i}]`, {
strategyMap.set(`${chance.animal()} Fleet`, {
fleet: getRandomFleetForFaction(player.faction),
strategy: createMiningStrategy(
mine(
Expand Down
14 changes: 7 additions & 7 deletions src/main/basedbot/fleet-strategies/get-fleet-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ export const getFleetStrategy = (
case 'AePY3wEoUFcFuXeUU9X26YK6tNKQMZovBgvY54LK2B8N':
return mainnetLuStrategy(map, player, game)
case 'CgHvzwGbwWv3CwLTvEgeqSKeD8EwMdTfiiCG3dFrKVVC':
// return atlasnetFcStrategy(5)(map, player, game)
return disbandAllStrategy(map, player, game)
return atlasnetFcStrategy(10)(map, player, game, 'mud')
// return disbandAllStrategy(map, player, game)
case '9KBrgWVjsmdZ3YEjcsa3wrbbJREgZgS7vDbgoz2aHaNm':
// return atlasnetFcStrategy(5)(map, player, game)
return disbandAllStrategy(map, player, game)
return atlasnetFcStrategy(10)(map, player, game, 'ustur')
// return disbandAllStrategy(map, player, game)
case 'FUwHSqujzcPD44SDZYJXuk73NbkEyYQwcLMioHhpjbx2':
// return atlasnetFcStrategy(5)(map, player, game)
return disbandAllStrategy(map, player, game)
return atlasnetFcStrategy(10)(map, player, game, 'oni')
// return disbandAllStrategy(map, player, game)
case '34ghznSJCYEMrS1aC55UYZZUuxfuurA9441aKnigmYyz':
// return atlasnetFcStrategy(5)(map, player, game)
// return atlasnetFcStrategy(10)(map, player, game, 'le.local')
return disbandAllStrategy(map, player, game)
default:
throw new Error('Unknown strategy')
Expand Down
1 change: 0 additions & 1 deletion src/main/basedbot/lib/sage/act/load-cargo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export const loadCargo = async (
cargoTokenAccount.delegatedAmount.toString(),
)


if (fuelAmountAtOrigin.lt(new BN(amount))) {
throw new Error('Not enough cargo available at origin Starbase')
}
Expand Down
4 changes: 2 additions & 2 deletions src/service/fleet/refill-fleet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const refillFleet = async (
player: PublicKey,
fleetUnit: ShipStakingInfo,
amounts: Amounts,
): Promise<string> => {
): Promise<string[]> => {
const [foodAccount, fuelAccount, ammoAccount, toolAccount] =
await Promise.all([
getAccount(keyPair.publicKey, resource.food),
Expand Down Expand Up @@ -93,5 +93,5 @@ export const refillFleet = async (
)
}

return await sendAndConfirmInstructions(instructions)
return sendAndConfirmInstructions(instructions)
}
56 changes: 29 additions & 27 deletions src/service/gm/market.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import {
createTransferCheckedInstruction,
getAssociatedTokenAddressSync,
getOrCreateAssociatedTokenAccount,
} from '@solana/spl-token'
import { Keypair, PublicKey } from '@solana/web3.js'
import {
GmClientService,
GmOrderbookService,
Order,
getAssociatedTokenAddress,
} from '@staratlas/factory'
import { GmClientService, GmOrderbookService, Order } from '@staratlas/factory'
import Big from 'big.js'

import { Sentry } from '../../sentry'
Expand Down Expand Up @@ -62,23 +58,27 @@ export const getBalanceAtlas = async (pubKey: PublicKey): Promise<Big> => {
}
}

export const sendAtlas = async (
export const sendAtlas = (
receiver: PublicKey,
amount: number,
): Promise<string> => {
): Promise<string[]> => {
const instructions = [
createTransferCheckedInstruction(
await getAssociatedTokenAddress(keyPair.publicKey, resource.atlas),
getAssociatedTokenAddressSync(
resource.atlas,
keyPair.publicKey,
true,
),
resource.atlas,
await getAssociatedTokenAddress(receiver, resource.atlas),
getAssociatedTokenAddressSync(resource.atlas, receiver, true),
keyPair.publicKey,
Big(amount).mul(100000000).toNumber(),
8,
[],
),
]

return await sendAndConfirmInstructions(instructions)
return sendAndConfirmInstructions(instructions)
}

export const getBalanceMarket = async (
Expand Down Expand Up @@ -115,7 +115,7 @@ export const initOrderBook = async (): Promise<void> => {
export const buyResource = async (
res: PublicKey,
amount: Big,
): Promise<string> => {
): Promise<string[]> => {
const orders = gmOrderbookService
.getSellOrdersByCurrencyAndItem(
resource.atlas.toString(),
Expand All @@ -135,23 +135,25 @@ export const buyResource = async (

logger.info(`Buying ${amount.toFixed(0)} ${res} for ${order.uiPrice} each`)

return await sendAndConfirmInstructions(exchangeTx.transaction.instructions)
return sendAndConfirmInstructions(exchangeTx.transaction.instructions)
}
export const buyResources = async (amount: Amounts): Promise<string[]> => {
const res = await Promise.all([
amount.food.gt(0)
? buyResource(resource.food, amount.food)
: Promise.resolve(''),
amount.ammo.gt(0)
? buyResource(resource.ammo, amount.ammo)
: Promise.resolve(''),
amount.fuel.gt(0)
? buyResource(resource.fuel, amount.fuel)
: Promise.resolve(''),
amount.tool.gt(0)
? buyResource(resource.tool, amount.tool)
: Promise.resolve(''),
])
const res = (
await Promise.all([
amount.food.gt(0)
? buyResource(resource.food, amount.food)
: Promise.resolve(''),
amount.ammo.gt(0)
? buyResource(resource.ammo, amount.ammo)
: Promise.resolve(''),
amount.fuel.gt(0)
? buyResource(resource.fuel, amount.fuel)
: Promise.resolve(''),
amount.tool.gt(0)
? buyResource(resource.tool, amount.tool)
: Promise.resolve(''),
])
).flat()

return res.filter((r) => r !== '')
}
Loading

0 comments on commit b402500

Please sign in to comment.