Skip to content
Merged
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
37 changes: 36 additions & 1 deletion src/handlers/execute-action/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
emitOrderExecutionTelemetryInBackground,
extractOrderTelemetryIds,
} from "../../helpers/order-telemetry";
import { classifyPassiveOrderError } from "../../helpers/passive-order";
import {
safeLogError,
safeLogRedactedError,
Expand Down Expand Up @@ -47,18 +48,36 @@ async function handleCreateOrder(ctx: ExecuteActionContext): Promise<void> {

const orderValue = parsePayloadForAction(ctx, CreateOrderPayloadSchema);
if (orderValue === null) return;
const isPassiveOrder = orderValue.orderIntent === "passive_only";
if (isPassiveOrder && orderValue.orderType !== "limit") {
return ctx.wrappedCallback(
{
code: grpc.status.INVALID_ARGUMENT,
message:
"ValidationError: passive_only order intent requires a limit order",
},
null,
);
}
const createOrderParams = {
...orderValue.params,
...(orderValue.clientOrderId !== undefined && {
clientOrderId: orderValue.clientOrderId,
}),
...(isPassiveOrder && { postOnly: true }),
};
let resolvedOrderTelemetry: {
symbol?: string;
side?: string;
requestedQuantity?: number;
} = {};
let marketMetadataHash: string | undefined;
// A passive error code is a statement about what the VENUE did with our
// submission. Failures before the call (policy resolution, metadata capture)
// never reached the venue, and failures after it leave a real order resting —
// reporting either as a passive rejection would tell the client its rung was
// never placed and invite a duplicate repost.
let submission: "not_attempted" | "in_flight" | "placed" = "not_attempted";
try {
if (!broker) {
return ctx.wrappedCallback(
Expand Down Expand Up @@ -117,6 +136,7 @@ async function handleCreateOrder(ctx: ExecuteActionContext): Promise<void> {
...telemetryIds,
},
);
submission = "in_flight";
const order = await broker.createOrder(
resolution.symbol,
orderValue.orderType,
Expand All @@ -125,6 +145,7 @@ async function handleCreateOrder(ctx: ExecuteActionContext): Promise<void> {
orderValue.price,
createOrderParams,
);
submission = "placed";
const createOrderContext = {
action: "CreateOrder" as const,
cex,
Expand All @@ -149,7 +170,14 @@ async function handleCreateOrder(ctx: ExecuteActionContext): Promise<void> {
undefined,
{ marketMetadataHash },
);
ctx.wrappedCallback(null, { result: JSON.stringify({ ...order }) });
ctx.wrappedCallback(null, {
result: JSON.stringify({
...order,
...(isPassiveOrder && {
passivePlacementOutcome: "accepted_passive",
}),
}),
});
} catch (error) {
rethrowArchiveDurabilityError(error);
safeLogRedactedError("Order Creation failed", error);
Expand Down Expand Up @@ -178,6 +206,13 @@ async function handleCreateOrder(ctx: ExecuteActionContext): Promise<void> {
error,
{ marketMetadataHash },
);
if (isPassiveOrder && submission === "in_flight") {
const passiveErrorCode = classifyPassiveOrderError(error);
return rejectWithGrpcError(ctx, error, {
message: `${passiveErrorCode}: ${sanitizeErrorDetail(error)}`,
preferStableMessageOnly: true,
});
}
ctx.wrappedCallback(
{
code: grpc.status.INTERNAL,
Expand Down
9 changes: 9 additions & 0 deletions src/helpers/grpc/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ export function stableGrpcErrorCode(message: string): grpc.status | undefined {
if (message.startsWith("deposit_amount_mismatch:")) {
return grpc.status.FAILED_PRECONDITION;
}
if (message.startsWith("passive_order_unsupported:")) {
return grpc.status.UNIMPLEMENTED;
}
if (
message.startsWith("passive_order_rejected:") ||
message.startsWith("passive_order_would_cross:")
) {
return grpc.status.FAILED_PRECONDITION;
}
if (
message.startsWith("policy_withdrawal_denied:") ||
message.startsWith("policy_deposit_denied:")
Expand Down
55 changes: 55 additions & 0 deletions src/helpers/passive-order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import ccxt from "@usherlabs/ccxt";
import { getErrorMessage } from "./shared/errors";

export const PASSIVE_ORDER_ERROR_CODES = {
unsupported: "passive_order_unsupported",
rejected: "passive_order_rejected",
wouldCross: "passive_order_would_cross",
} as const;

export type PassiveOrderErrorCode =
(typeof PASSIVE_ORDER_ERROR_CODES)[keyof typeof PASSIVE_ORDER_ERROR_CODES];

function identifiesWouldCross(message: string): boolean {
const normalized = message.toLowerCase();
// Post-only venues reject a crossing limit instead of resting it. Binance
// says it "would immediately match and take"; Hyperliquid and other venues
// use equivalent explicit immediate-execution wording.
return (
normalized.includes("would immediately match and take") ||
/post[\s-]?only\b.*\bwould\b.*\bimmediately\b.*\b(?:execute|fill|match)/.test(
normalized,
) ||
/post[\s-]?only\b.*\bwould\b.*\b(?:execute|fill|match)\w*\b.*\bimmediately/.test(
normalized,
)
);
}

function identifiesUnsupported(message: string): boolean {
const normalized = message.toLowerCase();
return (
/post[\s-]?only\b.*\b(?:not supported|unsupported|does not support)\b/.test(
normalized,
) ||
/\b(?:not supported|unsupported|does not support)\b.*\bpost[\s-]?only\b/.test(
normalized,
)
);
}

export function classifyPassiveOrderError(
error: unknown,
): PassiveOrderErrorCode {
const message = getErrorMessage(error);
if (
error instanceof ccxt.OrderImmediatelyFillable ||
identifiesWouldCross(message)
) {
return PASSIVE_ORDER_ERROR_CODES.wouldCross;
}
if (error instanceof ccxt.NotSupported || identifiesUnsupported(message)) {
return PASSIVE_ORDER_ERROR_CODES.unsupported;
}
return PASSIVE_ORDER_ERROR_CODES.rejected;
}
1 change: 1 addition & 0 deletions src/schemas/action-payloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ const unknownParamsSchema = z.preprocess(

export const CreateOrderPayloadSchema = z.object({
orderType: z.enum(["market", "limit"]).default("limit"),
orderIntent: z.enum(["passive_only"]).optional(),
amount: z.coerce.number().positive(),
fromToken: z.string().min(1),
toToken: z.string().min(1),
Expand Down
9 changes: 9 additions & 0 deletions test/grpc-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ describe("grpc status", () => {
expect(stableGrpcErrorCode("policy_deposit_denied: x")).toBe(
grpc.status.PERMISSION_DENIED,
);
expect(stableGrpcErrorCode("passive_order_unsupported: x")).toBe(
grpc.status.UNIMPLEMENTED,
);
expect(stableGrpcErrorCode("passive_order_rejected: x")).toBe(
grpc.status.FAILED_PRECONDITION,
);
expect(stableGrpcErrorCode("passive_order_would_cross: x")).toBe(
grpc.status.FAILED_PRECONDITION,
);
});

test("mapCcxtErrorToGrpcStatus maps authentication errors", () => {
Expand Down
Loading
Loading