Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 61 additions & 49 deletions apps/api/src/billing/config/env.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,66 @@ import { AUDITOR } from "@src/deployment/config/provider.config";

dotenv.config({ path: "env/.env.funding-wallet-index" });

export const envSchema = z.object({
OLD_MASTER_WALLET_MNEMONIC: z.string().optional(),
FUNDING_WALLET_MNEMONIC: z.string().optional(),
FUNDING_WALLET_MNEMONIC_V1: z.string().optional(),
FUNDING_WALLET_MNEMONIC_V2: z.string().optional(),
DERIVATION_WALLET_MNEMONIC: z.string().optional(),
DERIVATION_WALLET_MNEMONIC_V1: z.string().optional(),
DERIVATION_WALLET_MNEMONIC_V2: z.string().optional(),
NETWORK: z.enum(["mainnet", "testnet", "sandbox"]),
RPC_NODE_ENDPOINT: z.string(),
TRIAL_ALLOWANCE_EXPIRATION_DAYS: z.number({ coerce: true }).default(30),
TRIAL_DEPLOYMENT_ALLOWANCE_AMOUNT: z.number({ coerce: true }),
TRIAL_FEES_ALLOWANCE_AMOUNT: z.number({ coerce: true }),
TRIAL_DEPLOYMENT_CLEANUP_HOURS: z.number({ coerce: true }).default(24),
DEPLOYMENT_GRANT_DENOM: z.enum(["uakt", "uact"]),
GAS_SAFETY_MULTIPLIER: z.number({ coerce: true }).default(1.8),
AVERAGE_GAS_PRICE: z.number({ coerce: true }).default(0.025),
FEE_ALLOWANCE_REFILL_THRESHOLD: z.number({ coerce: true }),
FEE_ALLOWANCE_REFILL_AMOUNT: z.number({ coerce: true }),
DEPLOYMENT_ALLOWANCE_REFILL_AMOUNT: z.number({ coerce: true }),
ALLOWANCE_REFILL_BATCH_SIZE: z.number({ coerce: true }).default(10),
WALLET_BATCHING_INTERVAL_MS: z.number().optional().default(1000),
STRIPE_SECRET_KEY: z.string(),
STRIPE_PRODUCT_ID: z.string(),
STRIPE_WEBHOOK_SECRET: z.string(),
STRIPE_ENABLE_COUPONS: z.enum(["true", "false"]).default("false"),
CONSOLE_WEB_PAYMENT_LINK: z.string(),
MANAGED_WALLET_LEASE_ALLOWED_AUDITORS: z
.string()
.default(AUDITOR)
.transform(val => (val ? val.split(",").map(addr => addr.trim()) : [])),
MANAGED_WALLET_TRIAL_MIN_TOP_UP_AMOUNT: z.number({ coerce: true }).min(20).default(100),
MANAGED_WALLET_TRIAL_BLOCKED_GPU_MODELS: z
.string()
.default("nvidia/b300,nvidia/b200,nvidia/h200,nvidia/h100,nvidia/pro6000se,nvidia/pro6000we,nvidia/a100,nvidia/rtx5090,nvidia/rtx4090,nvidia/rtx3090")
.transform(val =>
val
? val
.split(",")
.map(entry => entry.trim().toLowerCase())
.filter(Boolean)
: []
)
.refine(entries => entries.every(entry => /^[a-z0-9._-]+\/[a-z0-9._-]+$/.test(entry)), {
message: "MANAGED_WALLET_TRIAL_BLOCKED_GPU_MODELS entries must be in 'vendor/model' format"
}),
MASTER_WALLET_TARGET_ACT_BALANCE: z.number({ coerce: true }).default(10_000_000_000),
TX_SIGNER_BASE_URL: z.string()
});
export const envSchema = z
.object({
OLD_MASTER_WALLET_MNEMONIC: z.string().optional(),
FUNDING_WALLET_MNEMONIC: z.string().optional(),
FUNDING_WALLET_MNEMONIC_V1: z.string().optional(),
FUNDING_WALLET_MNEMONIC_V2: z.string().optional(),
DERIVATION_WALLET_MNEMONIC: z.string().optional(),
DERIVATION_WALLET_MNEMONIC_V1: z.string().optional(),
DERIVATION_WALLET_MNEMONIC_V2: z.string().optional(),
NETWORK: z.enum(["mainnet", "testnet", "sandbox"]),
RPC_NODE_ENDPOINT: z.string(),
TRIAL_ALLOWANCE_EXPIRATION_DAYS: z.number({ coerce: true }).default(30),
TRIAL_DEPLOYMENT_ALLOWANCE_AMOUNT: z.number({ coerce: true }),
TRIAL_FEES_ALLOWANCE_AMOUNT: z.number({ coerce: true }),
TRIAL_DEPLOYMENT_CLEANUP_HOURS: z.number({ coerce: true }).default(24),
DEPLOYMENT_GRANT_DENOM: z.enum(["uakt", "uact"]),
GAS_SAFETY_MULTIPLIER: z.number({ coerce: true }).default(1.8),
AVERAGE_GAS_PRICE: z.number({ coerce: true }).default(0.025),
FEE_ALLOWANCE_REFILL_THRESHOLD: z.number({ coerce: true }),
FEE_ALLOWANCE_REFILL_AMOUNT: z.number({ coerce: true }),
DEPLOYMENT_ALLOWANCE_REFILL_AMOUNT: z.number({ coerce: true }),
ALLOWANCE_REFILL_BATCH_SIZE: z.number({ coerce: true }).default(10),
WALLET_BATCHING_INTERVAL_MS: z.number().optional().default(1000),
STRIPE_SECRET_KEY: z.string(),
STRIPE_PRODUCT_ID: z.string(),
STRIPE_WEBHOOK_SECRET: z.string(),
STRIPE_ENABLE_COUPONS: z.enum(["true", "false"]).default("false"),
CONSOLE_WEB_PAYMENT_LINK: z.string(),
MANAGED_WALLET_LEASE_ALLOWED_AUDITORS: z
.string()
.default(AUDITOR)
.transform(val => (val ? val.split(",").map(addr => addr.trim()) : [])),
MANAGED_WALLET_TRIAL_MIN_TOP_UP_AMOUNT: z.number({ coerce: true }).min(20).default(100),
MANAGED_WALLET_TRIAL_BLOCKED_GPU_MODELS: z
.string()
.default("nvidia/b300,nvidia/b200,nvidia/h200,nvidia/h100,nvidia/pro6000se,nvidia/pro6000we,nvidia/a100,nvidia/rtx5090,nvidia/rtx4090,nvidia/rtx3090")
.transform(val =>
val
? val
.split(",")
.map(entry => entry.trim().toLowerCase())
.filter(Boolean)
: []
)
.refine(entries => entries.every(entry => /^[a-z0-9._-]+\/[a-z0-9._-]+$/.test(entry)), {
message: "MANAGED_WALLET_TRIAL_BLOCKED_GPU_MODELS entries must be in 'vendor/model' format"
}),
MASTER_WALLET_TARGET_ACT_BALANCE: z.number({ coerce: true }).default(10_000_000_000),
MANAGED_WALLET_BID_PRICE_GUARD_ENABLED: z
.enum(["true", "false"])
.default("true")
.transform(val => val === "true"),
MANAGED_WALLET_BID_PRICE_WARN_MULTIPLIER: z.number({ coerce: true }).positive().default(5),
MANAGED_WALLET_BID_PRICE_BLOCK_MULTIPLIER: z.number({ coerce: true }).positive().default(10),
MANAGED_WALLET_BID_PRICE_ABSOLUTE_MAX_UACT: z.number({ coerce: true }).positive().optional(),
TX_SIGNER_BASE_URL: z.string()
})
.refine(config => config.MANAGED_WALLET_BID_PRICE_WARN_MULTIPLIER <= config.MANAGED_WALLET_BID_PRICE_BLOCK_MULTIPLIER, {
message: "MANAGED_WALLET_BID_PRICE_WARN_MULTIPLIER must be less than or equal to MANAGED_WALLET_BID_PRICE_BLOCK_MULTIPLIER",
path: ["MANAGED_WALLET_BID_PRICE_WARN_MULTIPLIER"]
});

export type BillingConfig = z.infer<typeof envSchema>;
67 changes: 67 additions & 0 deletions apps/api/src/billing/lib/lease-messages/lease-messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { MsgCreateLease } from "@akashnetwork/chain-sdk/private-types/akash.v1beta5";
import type { Bid, BidHttpService } from "@akashnetwork/http-sdk";
import type { EncodeObject } from "@cosmjs/proto-signing";
import assert from "http-assert";

type LeaseBidId = NonNullable<MsgCreateLease["bidId"]>;

/**
* A lease bid id paired with the bids it resolves to: the full set of bids on the same
* order (`orderBids`, useful for peer comparisons) and the specific `accepted` bid the
* lease message references.
*/
export interface ResolvedLeaseBid {
bidId: LeaseBidId;
orderBids: Bid[];
accepted: Bid;
}

/**
* Extracts the bid IDs from every MsgCreateLease message in a decoded transaction.
* A MsgCreateLease references the bid being accepted via its bidId; messages of any
* other type are ignored.
*/
export function getLeaseBidIds(messages: EncodeObject[]): LeaseBidId[] {
return messages
.filter(message => message.typeUrl === `/${MsgCreateLease.$type}`)
.map(message => (message.value as MsgCreateLease).bidId)
.filter((id): id is LeaseBidId => !!id);
}

/**
* Resolves every MsgCreateLease bid id in a transaction to its on-chain bids.
*
* A MsgCreateLease only references a bid, so the bids for each referenced order are fetched
* (deduplicated by dseq, in parallel) and the accepted bid is matched within its order. Throws
* 403 if a referenced bid cannot be found. Returns an empty list when there are no lease messages.
*/
export async function resolveLeaseBids(messages: EncodeObject[], owner: string, bidHttpService: BidHttpService): Promise<ResolvedLeaseBid[]> {
const leaseBidIds = getLeaseBidIds(messages);
if (leaseBidIds.length === 0) return [];

const uniqueDseqs = Array.from(new Set(leaseBidIds.map(id => id.dseq.toString())));
const bidsByDseq = new Map<string, Bid[]>();
await Promise.all(
uniqueDseqs.map(async dseq => {
bidsByDseq.set(dseq, await bidHttpService.list(owner, dseq));
})
);

return leaseBidIds.map(bidId => {
const orderBids = bidsByDseq.get(bidId.dseq.toString()) ?? [];
const accepted = orderBids.find(
b =>
b.bid.id.owner === bidId.owner &&
b.bid.id.gseq === bidId.gseq &&
b.bid.id.oseq === bidId.oseq &&
b.bid.id.provider === bidId.provider &&
b.bid.id.bseq === bidId.bseq
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
assert(
accepted,
403,
`Referenced lease bid not found: dseq=${bidId.dseq}, gseq=${bidId.gseq}, oseq=${bidId.oseq}, provider=${bidId.provider}, bseq=${bidId.bseq}`
);
return { bidId, orderBids, accepted };
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import { MsgCreateDeployment } from "@akashnetwork/chain-sdk/private-types/akash.v1beta4";
import { MsgCreateLease } from "@akashnetwork/chain-sdk/private-types/akash.v1beta5";
import type { Bid } from "@akashnetwork/http-sdk";
import type { BidHttpService } from "@akashnetwork/http-sdk";
import type { EncodeObject } from "@cosmjs/proto-signing";
import { describe, expect, it } from "vitest";
import { mock } from "vitest-mock-extended";

import type { BillingConfigService } from "@src/billing/services/billing-config/billing-config.service";
import type { LoggerService } from "@src/core";
import { LeaseBidPriceGuardService } from "./lease-bid-price-guard.service";

import { mockConfigService } from "@test/mocks/config-service.mock";
import { createBid } from "@test/seeders/bid.seeder";
import { createUserWallet } from "@test/seeders/user-wallet.seeder";

const OWNER = "akash1owner";
const ACCEPTED = { dseq: "111", gseq: 1, oseq: 1, bseq: 1, provider: "akash1prov" };

describe(LeaseBidPriceGuardService.name, () => {
describe("relative limit", () => {
it("blocks the lease and alerts when the accepted bid reaches the block multiple of the cheapest competing bid", async () => {
const { service, logger } = setup({
bids: [pricedBid(ACCEPTED, 9_519_658), pricedBid({ ...ACCEPTED, provider: "akash1cheap", bseq: 2 }, 4.81)]
});

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).rejects.toMatchObject({
status: 403,
message: expect.stringContaining("cheapest competing bid")
});
expect(logger.error).toHaveBeenCalledWith(
expect.objectContaining({ event: "LEASE_BLOCKED_EXCESSIVE_BID_PRICE", reason: "relative", provider: "akash1prov", denom: "uact" })
);
});

it("allows but warns when the accepted bid is between the warn and block multiples", async () => {
const { service, logger } = setup({
warnMultiplier: 5,
blockMultiplier: 10,
bids: [pricedBid(ACCEPTED, 600), pricedBid({ ...ACCEPTED, provider: "akash1cheap", bseq: 2 }, 100)]
});

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(expect.objectContaining({ event: "LEASE_BID_PRICE_WARNING", ratio: 6 }));
expect(logger.error).not.toHaveBeenCalled();
});

it("allows silently when the accepted bid is below the warn multiple", async () => {
const { service, logger } = setup({
bids: [pricedBid(ACCEPTED, 300), pricedBid({ ...ACCEPTED, provider: "akash1cheap", bseq: 2 }, 100)]
});

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
expect(logger.warn).not.toHaveBeenCalled();
expect(logger.error).not.toHaveBeenCalled();
});

it("allows when the accepted bid is the cheapest on the order", async () => {
const { service } = setup({
bids: [pricedBid(ACCEPTED, 100), pricedBid({ ...ACCEPTED, provider: "akash1other", bseq: 2 }, 9_000_000)]
});

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
});
});

describe("absolute limit", () => {
it("blocks a sole bidder priced above the per-denom ceiling", async () => {
const { service, logger } = setup({ absoluteMaxUact: 1000, bids: [pricedBid(ACCEPTED, 2000)] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).rejects.toMatchObject({ status: 403 });
expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ event: "LEASE_BLOCKED_EXCESSIVE_BID_PRICE", reason: "absolute" }));
});

it("allows a sole bidder priced below the per-denom ceiling", async () => {
const { service } = setup({ absoluteMaxUact: 1000, bids: [pricedBid(ACCEPTED, 500)] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
});

it("allows a sole bidder at any price when no ceiling is configured", async () => {
const { service } = setup({ absoluteMaxUact: undefined, bids: [pricedBid(ACCEPTED, 9_519_658)] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
});

it("applies the ceiling independently of the relative check when peers exist", async () => {
const { service, logger } = setup({
absoluteMaxUact: 300,
bids: [pricedBid(ACCEPTED, 400), pricedBid({ ...ACCEPTED, provider: "akash1cheap", bseq: 2 }, 100)]
});

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).rejects.toMatchObject({ status: 403 });
expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ reason: "absolute" }));
});

it("does not apply the ceiling to a non-uact denom", async () => {
const { service } = setup({ absoluteMaxUact: 1000, bids: [pricedBid(ACCEPTED, 2000, "uakt")] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
});
});

describe("guard activation", () => {
it("is a no-op and skips fetching bids when the guard is disabled", async () => {
const { service, bidHttpService } = setup({ enabled: false, bids: [pricedBid(ACCEPTED, 9_519_658)] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).resolves.toBeUndefined();
expect(bidHttpService.list).not.toHaveBeenCalled();
});

it("is a no-op when there are no lease messages", async () => {
const { service, bidHttpService } = setup({});

await expect(service.validateLeaseBidPrices([deploymentMessage()], createUserWallet())).resolves.toBeUndefined();
expect(bidHttpService.list).not.toHaveBeenCalled();
});
});

it("rejects with 403 when the referenced bid cannot be resolved", async () => {
const { service } = setup({ bids: [pricedBid({ ...ACCEPTED, provider: "akash1other" }, 100)] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).rejects.toMatchObject({
status: 403,
message: expect.stringContaining("Referenced lease bid not found")
});
});

it("rejects with 403 when the bid owner does not match the lease message owner", async () => {
const foreignBid = createBid({ owner: "akash1someoneelse", ...ACCEPTED });
foreignBid.bid.price = { denom: "uakt", amount: "100" };
const { service } = setup({ bids: [foreignBid] });

await expect(service.validateLeaseBidPrices([leaseMessage(ACCEPTED)], createUserWallet())).rejects.toMatchObject({
status: 403,
message: expect.stringContaining("Referenced lease bid not found")
});
});

it("evaluates each order independently and blocks the offending one", async () => {
const cheapOrder = { dseq: "111", gseq: 1, oseq: 1, bseq: 1, provider: "akash1prov" };
const absurdOrder = { dseq: "111", gseq: 2, oseq: 1, bseq: 1, provider: "akash1prov" };
const { service, logger } = setup({
bids: [
pricedBid(cheapOrder, 100),
pricedBid({ ...cheapOrder, provider: "akash1peer", bseq: 2 }, 100),
pricedBid(absurdOrder, 9_519_658),
pricedBid({ ...absurdOrder, provider: "akash1peer", bseq: 2 }, 4.81)
]
});

await expect(service.validateLeaseBidPrices([leaseMessage(cheapOrder), leaseMessage(absurdOrder)], createUserWallet())).rejects.toMatchObject({
status: 403
});
expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ reason: "relative", gseq: 2 }));
});

function pricedBid(ids: { dseq: string; gseq: number; oseq: number; bseq: number; provider: string }, amount: number, denom = "uact"): Bid {
const bid = createBid({ owner: OWNER, ...ids });
bid.bid.price = { denom, amount: amount.toString() };
return bid;
}

function leaseMessage(bidId: { dseq: string; gseq: number; oseq: number; bseq: number; provider: string }): EncodeObject {
return {
typeUrl: `/${MsgCreateLease.$type}`,
value: MsgCreateLease.fromPartial({ bidId: { owner: OWNER, ...bidId } })
};
}

function deploymentMessage(): EncodeObject {
return { typeUrl: `/${MsgCreateDeployment.$type}`, value: MsgCreateDeployment.fromPartial({}) };
}

function setup(input: {
enabled?: boolean;
warnMultiplier?: number;
blockMultiplier?: number;
absoluteMaxUact?: number;
bids?: Bid[];
}) {
const config = mockConfigService<BillingConfigService>({
MANAGED_WALLET_BID_PRICE_GUARD_ENABLED: input.enabled ?? true,
MANAGED_WALLET_BID_PRICE_WARN_MULTIPLIER: input.warnMultiplier ?? 5,
MANAGED_WALLET_BID_PRICE_BLOCK_MULTIPLIER: input.blockMultiplier ?? 10,
MANAGED_WALLET_BID_PRICE_ABSOLUTE_MAX_UACT: input.absoluteMaxUact
});
const bidHttpService = mock<BidHttpService>();
bidHttpService.list.mockResolvedValue(input.bids ?? []);
const logger = mock<LoggerService>();
const service = new LeaseBidPriceGuardService(config, bidHttpService, logger);
return { service, config, bidHttpService, logger };
}
});
Loading