Skip to content

Commit

Permalink
unsmell
Browse files Browse the repository at this point in the history
  • Loading branch information
Sladuca committed Sep 10, 2024
2 parents 64455c5 + c5c1040 commit 60af5e9
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 13 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@
"peerDependencies": {
"typescript": "^5.6.2"
},
"version": "0.0.28"
"version": "0.0.29"
}
18 changes: 16 additions & 2 deletions src/helpers/units.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import type { Nullable } from "../types/empty";

// -- time

export type Epoch = number;

const MILLS_PER_EPOCH = 1000 * 60;

export function currentEpoch(): Epoch {
return Math.floor(Date.now() / MILLS_PER_EPOCH);
}

export function epochToDate(epoch: Epoch): Date {
return new Date(epoch * MILLS_PER_EPOCH);
}

// -- currency

export type Cents = number;
export type Centicents = number;

// --

interface PriceWholeToCenticentsReturn {
centicents: Nullable<Centicents>;
invalid: boolean;
Expand Down
10 changes: 5 additions & 5 deletions src/lib/buy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,14 @@ async function buyOrderAction(options: SfBuyOptions) {
const durationInHours = durationSeconds / 3600;

// In the future, we should read from a price chart of yesterday's prices.
const todoEstimatedPriceInCents = 250;
const estimatedPrice =
todoEstimatedPriceInCents * quantity * durationInHours;
const estimatedPriceInDollars = estimatedPrice;
// For now, we'll just suggest 2.50 / gpu-hour as a default
const todoEstimatedPricePerNodeCents = 250 * 8; // $2.50 / gpu-hour * 8 gpus
const estimatedPriceInCents =
todoEstimatedPricePerNodeCents * quantity * durationInHours; // multiply by desired quantity and duration to get total estimated price in cents

console.log(`No one is selling this right now. To ask someone to sell it to you, add a price you're willing to pay. For example:
sf buy -i ${options.type} -d "${durationInHours}h" -n ${quantity} -p "$${(estimatedPriceInDollars / 100).toFixed(2)}"
sf buy -i ${options.type} -d "${durationInHours}h" -n ${quantity} -p "$${(estimatedPriceInCents / 100).toFixed(2)}"
`);

return process.exit(1);
Expand Down
91 changes: 86 additions & 5 deletions src/lib/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,40 @@ import {
logSessionTokenExpiredAndQuit,
} from "../helpers/errors";
import { getApiUrl } from "../helpers/urls";
import { currentEpoch, epochToDate } from "../helpers/units";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import chalk from "chalk";

dayjs.extend(utc);

// development only commands
export function registerDev(program: Command) {
if (process.env.IS_DEVELOPMENT_CLI_ENV) {
// config
registerConfig(program);

// time
registerEpoch(program);
program.command("utc").action(async () => {
const unixEpochSecondsNow = dayjs().unix();
console.log(unixEpochSecondsNow);
console.log(
chalk.green(dayjs().utc().format("dddd, MMMM D, YYYY h:mm:ss A")),
);

process.exit(0);
});

// self
program.command("me").action(async () => {
const accountId = await getLoggedInAccountId();
console.log(accountId);

process.exit(0);
});
program.command("epoch").action(async () => {
const MILLS_PER_EPOCH = 1000 * 60 * 60;
console.log(Math.floor(Date.now() / MILLS_PER_EPOCH));

process.exit(0);
});
// connection
program.command("ping").action(async () => {
const data = await pingServer();
console.log(data);
Expand Down Expand Up @@ -90,6 +106,70 @@ async function removeConfigAction() {

// --

function registerEpoch(program: Command) {
const epochCmd = program
.command("epoch [timestamps...]")
.description("Get current epoch timestamp or convert given timestamps")
.action(async (timestamps: string[]) => {
if (timestamps.length === 0) {
const epoch = currentEpoch();
console.log(epoch);
} else {
const colorDiffedEpochs = colorDiffEpochs(timestamps);

timestamps.forEach((epochTimestamp, i) => {
const date = epochToDate(Number.parseInt(epochTimestamp));
console.log(
`${colorDiffedEpochs[i]} | ${chalk.yellow(dayjs(date).format("hh:mm A MM-DD-YYYY"))} Local`,
);
});
}

process.exit(0);
});

epochCmd
.command("now")
.description("Get current epoch timestamp")
.action(async () => {
const epoch = currentEpoch();
console.log(epoch);
process.exit(0);
});
}

function colorDiffEpochs(epochStrings: string[]): string[] {
const minLength = Math.min(...epochStrings.map((num) => num.length));

// function to find the common prefix between all numbers
const findCommonPrefix = (arr: string[]): string => {
let prefix = "";
for (let i = 0; i < minLength; i++) {
const currentChar = arr[0][i];
if (arr.every((num) => num[i] === currentChar)) {
prefix += currentChar;
} else {
break;
}
}

return prefix;
};

// find the common prefix for all numbers
const commonPrefix = findCommonPrefix(epochStrings);

return epochStrings.map((num) => {
const prefix = num.startsWith(commonPrefix) ? commonPrefix : "";
const rest = num.slice(prefix.length);

// return the string with appropriate coloring (gray for common prefix, white for the rest)
return chalk.gray(prefix) + chalk.white(rest);
});
}

// --

async function getLoggedInAccountId() {
const loggedIn = await isLoggedIn();
if (!loggedIn) {
Expand All @@ -108,6 +188,7 @@ async function getLoggedInAccountId() {
if (response.status === 401) {
logSessionTokenExpiredAndQuit();
}
console.log(response);

logAndQuit("Failed to fetch account info");
}
Expand Down

0 comments on commit 60af5e9

Please sign in to comment.