Cancel Order
How to cancel an existing order via API
Cancel Order
Cancel an existing order.
Endpoint: POST /v1/orders/cancel
Prerequisites: You must have registered a signer first (see Register Signer).
Example:
import axios from "axios";
import { apiClient } from "./risex-core";
import { createPermitParams } from "./create-permit-params";
import { encodeAbiParameters, type Hex } from "viem";
import 'dotenv/config';
const cancelOrder = async (
marketId: number,
orderId: string,
signingKey: `0x${string}`, // From registerSigner
signerAddress: string, // From registerSigner
account: string,
) => {
try {
// Contract addresses
const perpContractAddress = '0x68cAcD54a8c93A3186BF50bE6b78B761F728E1b4' as `0x${string}`;
const authContractAddress = '0x8d8708f9D87ef522c1f99DD579BF6A051e34C28E' as `0x${string}`;
// Encode cancel data (32 bytes)
// Binary layout: (marketId << 192) | orderId
// This packs marketId in the first 8 bytes and orderId in the remaining 24 bytes
const cancelData = (BigInt(marketId) << 192n) | BigInt(orderId);
const cancelDataHex = '0x' + cancelData.toString(16).padStart(64, '0') as Hex;
const encodedData = encodeAbiParameters(
[{ name: 'cancelData', type: 'bytes32' }],
[cancelDataHex]
) as Hex;
// Create permit params with signature
const permitParams = await createPermitParams(
encodedData,
signingKey,
account as `0x${string}`,
signerAddress as `0x${string}`,
perpContractAddress,
authContractAddress,
);
const response = await apiClient.post('/v1/orders/cancel', {
market_id: marketId.toString(),
order_id: orderId,
permit_params: {
account: permitParams.account,
signer: permitParams.signer,
deadline: permitParams.deadline,
signature: permitParams.signature,
nonce: permitParams.nonce,
},
});
console.log('Order cancelled successfully!');
console.log('Response:', response.data);
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
console.error('Cancel order failed:', error.response?.data?.message || error.message);
if (error.response?.data) {
console.error('Error details:', JSON.stringify(error.response.data, null, 2));
}
} else {
console.error('Cancel order failed:', (error as Error).message);
}
throw error;
}
};
export { cancelOrder };
// Example usage:
(async () => {
const signingKey = process.env.SIGNING_KEY as `0x${string}`;
const signerAddress = '0x...'; // Your signer address from registerSigner
const account = '0x...'; // Your main wallet address
await cancelOrder(
1, // BTC market
'12345678', // Order ID from place-order response
signingKey,
signerAddress,
account
);
})();