Skip to content

Commit

Permalink
incluindo publicaçõeso de pokémon comparando com o indice do ouro
Browse files Browse the repository at this point in the history
  • Loading branch information
antonioconselheiro committed Dec 4, 2023
1 parent 39a71ed commit fb95c6c
Show file tree
Hide file tree
Showing 6 changed files with 116 additions and 37 deletions.
5 changes: 3 additions & 2 deletions packages/btc2poke/src/bitcoin-price.resultset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ export interface BitcoinPriceResultset {
// eslint-disable-next-line @typescript-eslint/naming-convention
readonly asset_id_base: 'BTC',
// eslint-disable-next-line @typescript-eslint/naming-convention
readonly asset_id_quote: 'USD',
// format example: 27933.7491211105
readonly asset_id_quote: 'USD' | 'XAUT',
// USD format example: 27933.7491211105
// XAUT format example: 20.618489926641793730922817107
readonly rate: number
}
4 changes: 2 additions & 2 deletions packages/btc2poke/src/bitcoin-price.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ export class BitcoinPriceService {
this.coinApiSecret = this.readCoinApiSecret();
}

async getBitcoinUSDPrice(): Promise<BitcoinPriceResultset> {
async getBitcoinPrice(to: 'USD' | 'XAUT'): Promise<BitcoinPriceResultset> {
return axios({
method: 'GET',
baseURL: process.env['COINAPI_BASE_URL'],
url: '/v1/exchangerate/BTC/USD/',
url: `/v1/exchangerate/BTC/${to}/`,
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
'X-CoinAPI-Key': this.coinApiSecret
Expand Down
16 changes: 13 additions & 3 deletions packages/btc2poke/src/bitcoin-to-pokemon.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { PokemonResultset } from './pokemon.resultset';

export class BitcoinToPokemonService {

private readonly missigno: PokemonResultset = {
private readonly missigNumber: PokemonResultset = {
id: null,
name: 'Missingno',
types: ['Out of Range Exception'],
Expand All @@ -21,16 +21,26 @@ export class BitcoinToPokemonService {

private static instance: BitcoinToPokemonService | null = null;

convert(bitcoinPrice: BitcoinPriceResultset): PokemonResultset {
convertFromDolar(bitcoinPrice: BitcoinPriceResultset): PokemonResultset {
const baseThousand = 1000;
const pokenumber = Math.floor(bitcoinPrice.rate / baseThousand);
const pokeindex = String(pokenumber) as keyof typeof pokelist;
if (pokelist[pokeindex]) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { id: Number(pokeindex), ...pokelist[pokeindex] } as PokemonResultset;
} else {
return this.missigno;
return this.missigNumber;
}
}

convertFromGold(bitcoinPrice: BitcoinPriceResultset): PokemonResultset {
const pokenumber = Math.floor(bitcoinPrice.rate);
const pokeindex = String(pokenumber) as keyof typeof pokelist;
if (pokelist[pokeindex]) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { id: Number(pokeindex), ...pokelist[pokeindex] } as PokemonResultset;
} else {
return this.missigNumber;
}
}
}
94 changes: 76 additions & 18 deletions packages/btc2poke/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,59 +30,117 @@ class main {

this.scheduleTimes.forEach(time => {
console.info('scheduling', time);
schedule.scheduleJob(time, () => this.run(nostrBoot).catch(e => console.error(e)));
schedule.scheduleJob(time, () => {
this.checkDolar(nostrBoot).catch(e => console.error(e));
this.checkGold(nostrBoot).catch(e => console.error(e));
});
});
}

async run(nostrBoot: NostrBoot): Promise<void> {
console.info('bitcoin price checking...');
const bitcoinPrice = await this.bitcoinPriceService.getBitcoinUSDPrice();
async checkGold(nostrBoot: NostrBoot): Promise<void> {
console.info('bitcoin price checking in gold...');
const bitcoinPrice = await this.bitcoinPriceService.getBitcoinPrice('XAUT');
console.info('bitcoin price: ', bitcoinPrice);
const pokemon = this.bitcoinToPokemonService.convert(bitcoinPrice);
const status = this.publishMemoryService.getStatus(pokemon.id);
const pokemon = this.bitcoinToPokemonService.convertFromGold(bitcoinPrice);
const status = this.publishMemoryService.getStatus(pokemon.id, 'gold');
let message = '';

if (status === PostContentStatus.NOT_PUBLISHED_RECENTLY) {
message = this.generateMessage(pokemon, bitcoinPrice);
message = this.generateDolarMessage(pokemon, bitcoinPrice);
} else if (status === PostContentStatus.RECENT_POST) {
message = this.generateMessage(pokemon, bitcoinPrice, true);
message = this.generateDolarMessage(pokemon, bitcoinPrice, true);
} else if (status === PostContentStatus.LAST_POST) {
console.info('already posted this, ignoring...', pokemon);
}

if (message) {
this.publishMemoryService.register(pokemon.id);
this.publishMemoryService.register(pokemon.id, 'gold');
console.info(message);
nostrBoot.publish(message);
}

return Promise.resolve();
}

private generateMessage(
async checkDolar(nostrBoot: NostrBoot): Promise<void> {
console.info('bitcoin price checking in usd...');
const bitcoinPrice = await this.bitcoinPriceService.getBitcoinPrice('USD');
console.info('bitcoin price: ', bitcoinPrice);
const pokemon = this.bitcoinToPokemonService.convertFromDolar(bitcoinPrice);
const status = this.publishMemoryService.getStatus(pokemon.id, 'dolar');
let message = '';

if (status === PostContentStatus.NOT_PUBLISHED_RECENTLY) {
message = this.generateDolarMessage(pokemon, bitcoinPrice);
} else if (status === PostContentStatus.RECENT_POST) {
message = this.generateDolarMessage(pokemon, bitcoinPrice, true);
} else if (status === PostContentStatus.LAST_POST) {
console.info('already posted this, ignoring...', pokemon);
}

if (message) {
this.publishMemoryService.register(pokemon.id, 'dolar');
console.info(message);
nostrBoot.publish(message);
}

return Promise.resolve();
}

private generateGoldMessage(
pokemon: PokemonResultset,
bitcoinPrice: BitcoinPriceResultset,
hasRecentlyPosted = false
): string {
const hundred = 100;
const formattedValue = Math.floor(bitcoinPrice.rate * hundred) / hundred;
let message = '';

if (pokemon.id) {
const ascended = this.publishMemoryService.hasAscended(pokemon.id, 'gold');
if (ascended === true) {
message = 'Bitcoin has INCREASED in GOLD. ';
} else if (ascended === false) {
message = 'Bitcoin has DECREASED in GOLD. ';
}

message += `The current price is ${formattedValue} troy ounce, the pokémon #${pokemon.id} is ${pokemon.name} ${hasRecentlyPosted ? 'again ': ' '}(${pokemon.types.join(', ')}) #bitcoin #pokemon #zap https://nostr.build/${pokemon.img}`;
} else {
if (bitcoinPrice.rate < 1) {
message += 'It was an honor to break together ladies and gentlemen. ';
} else {
message += 'Well, Bitcoin grow faster than Nintendo was able to launch pokémons. '
}

message += `The current price is ${formattedValue}, the pokémon is ${pokemon.name} (${pokemon.types.join(', ')}) #bitcoin #pokemon #zap https://nostr.build/${pokemon.img}`;
}

return message;
}

private generateDolarMessage(
pokemon: PokemonResultset,
bitcoinPrice: BitcoinPriceResultset,
hasRecentlyPosted = false
): string {
const thousand = 1000;
const formattedValue = this.formateBtcValue(bitcoinPrice);
const formattedValue = this.formatBtcValueInDolar(bitcoinPrice);
let message = '';

//Qual a cotação do bitcoin em pokémons, considerando somente os digitos dos milhares, na cotação do dólar
if (pokemon.id) {
const ascended = this.publishMemoryService.hasAscended(pokemon.id);
const ascended = this.publishMemoryService.hasAscended(pokemon.id, 'dolar');
if (ascended === true) {
message = 'Bitcoin value went up. ';
message = 'Bitcoin has INCREASED in DOLLAR. ';
} else if (ascended === false) {
message = 'Bitcoin value decreased. ';
message = 'Bitcoin has DECREASED in DOLLAR. ';
}

message += `The current price is ${formattedValue}, the pokémon #${pokemon.id} is ${pokemon.name} ${hasRecentlyPosted ? 'again ': ' '}(${pokemon.types.join(', ')}) #bitcoin #pokemon #zap https://nostr.build/${pokemon.img}`;
} else {
if (bitcoinPrice.rate < thousand) {
message += 'It was an honor to break together ladies and gentlemen. ';
} else {
message += 'Well, it seems to me that Bitcoin rose faster than nintendo was able to launch pokemons. '
message += 'Well, Bitcoin grow faster than Nintendo was able to launch pokémons. '
}

message += `The current price is ${formattedValue}, the pokémon is ${pokemon.name} (${pokemon.types.join(', ')}) #bitcoin #pokemon #zap https://nostr.build/${pokemon.img}`;
Expand All @@ -91,11 +149,11 @@ class main {
return message;
}

formateBtcValue(bitcoinPrice: BitcoinPriceResultset): string {
formatBtcValueInDolar(bitcoinPrice: BitcoinPriceResultset): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: bitcoinPrice.asset_id_quote,
}).format(bitcoinPrice.rate);
}).format(bitcoinPrice.rate);
}
}

Expand Down
30 changes: 18 additions & 12 deletions packages/btc2poke/src/publish-memory.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as fs from 'fs';
import { PostContentStatus } from './post-content-status.enum';
import { IRecentPublishedMemory } from './recent-published-memory.interface';

export class PublishMemoryService {
static getInstance(): PublishMemoryService {
Expand All @@ -13,7 +14,10 @@ export class PublishMemoryService {
private static instance: PublishMemoryService | null = null;

private filename = process.env['APP_JSON_FILE_DATABASE'] || 'default.json';
private memory: (number | null)[] = [];
private memory: IRecentPublishedMemory = {
dolar: [],
gold: []
};
private constructor() {
this.loadFile();
}
Expand All @@ -27,28 +31,30 @@ export class PublishMemoryService {
}
}

register(pokeid: number | null): void {
this.memory.shift();
this.memory.push(pokeid);
register(pokeid: number | null, asset: 'dolar' | 'gold'): void {
this.memory[asset].shift();
if (pokeid) {
this.memory[asset].push(pokeid);
}
fs.writeFileSync(this.filename, JSON.stringify(this.memory));
}

getStatus(pokeid: number | null): PostContentStatus {
const lastPublishIndex = this.memory.length - 1;
if (!this.memory.length) {
getStatus(pokeid: number | null, asset: 'dolar' | 'gold'): PostContentStatus {
const lastPublishIndex = this.memory[asset].length - 1;
if (!this.memory[asset].length) {
return PostContentStatus.NOT_PUBLISHED_RECENTLY;
} else if (this.memory[lastPublishIndex] === pokeid) {
} else if (this.memory[asset][lastPublishIndex] === pokeid) {
return PostContentStatus.LAST_POST;
} else if (this.memory[0] === pokeid) {
} else if (this.memory[asset][0] === pokeid) {
return PostContentStatus.RECENT_POST;
}

return PostContentStatus.NOT_PUBLISHED_RECENTLY;
}

hasAscended(newPokeId: number): boolean | null {
const lastPublishIndex = this.memory.length - 1;
const lastValue = this.memory[lastPublishIndex];
hasAscended(newPokeId: number, asset: 'dolar' | 'gold'): boolean | null {
const lastPublishIndex = this.memory[asset].length - 1;
const lastValue = this.memory[asset][lastPublishIndex];
if (lastValue === null) {
return null;
}
Expand Down
4 changes: 4 additions & 0 deletions packages/btc2poke/src/recent-published-memory.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface IRecentPublishedMemory {
gold: number[];
dolar: number[];
}

0 comments on commit fb95c6c

Please sign in to comment.