orderly-sdk-debugging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOrderly Network: SDK Debugging
Orderly Network:SDK调试指南
A comprehensive guide to debugging common issues, handling errors, and troubleshooting problems with the Orderly SDK.
本指南全面介绍了如何调试Orderly SDK的常见问题、处理错误以及排查故障。
When to Use
适用场景
- Fixing build errors
- Debugging WebSocket connections
- Handling API errors
- Troubleshooting authentication issues
- Investigating trading failures
- 修复构建错误
- 调试WebSocket连接
- 处理API错误
- 排查认证问题
- 调查交易失败原因
Prerequisites
前置条件
- Orderly SDK installed
- Basic debugging knowledge
- Browser DevTools familiarity
- 已安装Orderly SDK
- 具备基础调试知识
- 熟悉浏览器DevTools
1. Build & Setup Errors
1. 构建与设置错误
Buffer is not defined
Buffer未定义
Uncaught ReferenceError: Buffer is not definedCause: Wallet libraries use Node.js built-ins (Buffer, crypto) that don't exist in browsers.
Solution: Add :
vite-plugin-node-polyfillsbash
npm install -D vite-plugin-node-polyfillsts
// vite.config.ts
import { nodePolyfills } from 'vite-plugin-node-polyfills';
export default defineConfig({
plugins: [
react(),
nodePolyfills({
include: ['buffer', 'crypto', 'stream', 'util'],
globals: {
Buffer: true,
global: true,
process: true,
},
}),
],
});Uncaught ReferenceError: Buffer is not defined原因:钱包库使用了Node.js内置模块(Buffer、crypto),而这些模块在浏览器环境中不存在。
解决方案:添加插件:
vite-plugin-node-polyfillsbash
npm install -D vite-plugin-node-polyfillsts
// vite.config.ts
import { nodePolyfills } from 'vite-plugin-node-polyfills';
export default defineConfig({
plugins: [
react(),
nodePolyfills({
include: ['buffer', 'crypto', 'stream', 'util'],
globals: {
Buffer: true,
global: true,
process: true,
},
}),
],
});CSS Import Not Found
CSS导入未找到
ENOENT: no such file or directory, open '@orderly.network/trading/dist/styles.css'Cause: Only has a CSS file.
@orderly.network/uiSolution: Only import from :
@orderly.network/uicss
/* Correct - only ui package has CSS */
@import '@orderly.network/ui/dist/styles.css';
/* Wrong - these don't exist */
/* @import '@orderly.network/trading/dist/styles.css'; */
/* @import '@orderly.network/portfolio/dist/styles.css'; */ENOENT: no such file or directory, open '@orderly.network/trading/dist/styles.css'原因:只有包包含CSS文件。
@orderly.network/ui解决方案:仅从导入CSS:
@orderly.network/uicss
/* 正确方式 - 只有ui包包含CSS */
@import '@orderly.network/ui/dist/styles.css';
/* 错误方式 - 这些路径不存在 */
/* @import '@orderly.network/trading/dist/styles.css'; */
/* @import '@orderly.network/portfolio/dist/styles.css'; */2. Common Error Codes
2. 常见错误码
API Error Codes
API错误码
| Code | Message | Cause | Solution |
|---|---|---|---|
| Unknown error | Server error | Retry request |
| Unauthorized | Invalid/expired key | Re-authenticate |
| Too many requests | Rate limit | Implement backoff |
| Invalid parameter | Wrong order params | Validate inputs |
| 错误码 | 错误信息 | 原因 | 解决方案 |
|---|---|---|---|
| 未知错误 | 服务器错误 | 重试请求 |
| 未授权 | 密钥无效/已过期 | 重新认证 |
| 请求过于频繁 | 触发速率限制 | 实现退避机制 |
| 参数无效 | 订单参数错误 | 验证输入内容 |
Order Error Codes
订单错误码
| Code | Message | Cause | Solution |
|---|---|---|---|
| Insufficient balance | Not enough USDC | Deposit more funds |
| Order would trigger liquidation | Risk too high | Reduce position size |
| Price out of range | Price too far from mark | Adjust limit price |
| Order quantity too small | Below minimum | Increase quantity |
| 错误码 | 错误信息 | 原因 | 解决方案 |
|---|---|---|---|
| 余额不足 | USDC余额不足 | 存入更多资金 |
| 订单将触发清算 | 风险过高 | 降低仓位规模 |
| 价格超出范围 | 价格偏离标记价过多 | 调整限价 |
| 订单数量过小 | 低于最低要求 | 增加订单数量 |
Withdrawal Error Codes
提现错误码
| Code | Message | Cause | Solution |
|---|---|---|---|
| Insufficient balance | Not enough available | Check unsettled PnL |
| Withdrawal amount too small | Below minimum | Increase amount |
| 错误码 | 错误信息 | 原因 | 解决方案 |
|---|---|---|---|
| 余额不足 | 可用余额不足 | 检查未结算盈亏 |
| 提现金额过小 | 低于最低要求 | 提高提现金额 |
3. WebSocket Connection
3. WebSocket连接
Monitor Connection Status
监控连接状态
tsx
import { useWsStatus, WsNetworkStatus } from '@orderly.network/hooks';
function ConnectionIndicator() {
const wsStatus = useWsStatus();
return (
<div className="connection-status">
{wsStatus === WsNetworkStatus.Connected && (
<span className="text-green-500">● Connected</span>
)}
{wsStatus === WsNetworkStatus.Unstable && (
<span className="text-yellow-500">● Reconnecting...</span>
)}
{wsStatus === WsNetworkStatus.Disconnected && (
<span className="text-red-500">● Disconnected</span>
)}
</div>
);
}tsx
import { useWsStatus, WsNetworkStatus } from '@orderly.network/hooks';
function ConnectionIndicator() {
const wsStatus = useWsStatus();
return (
<div className="connection-status">
{wsStatus === WsNetworkStatus.Connected && (
<span className="text-green-500">● 已连接</span>
)}
{wsStatus === WsNetworkStatus.Unstable && (
<span className="text-yellow-500">● 重连中...</span>
)}
{wsStatus === WsNetworkStatus.Disconnected && (
<span className="text-red-500">● 已断开</span>
)}
</div>
);
}WebSocket Status Values
WebSocket状态值说明
| Status | Description |
|---|---|
| WebSocket is connected and working |
| Connection dropped, attempting reconnect |
| Connection lost, not reconnecting |
| 状态值 | 描述 |
|---|---|
| WebSocket已连接且正常工作 |
| 连接断开,正在尝试重连 |
| 连接丢失,未进行重连 |
4. Account State Issues
4. 账户状态问题
Check Account State
检查账户状态
tsx
import { useAccount, AccountStatusEnum } from '@orderly.network/hooks';
function AccountDebugger() {
const { state, account } = useAccount();
useEffect(() => {
console.log('Account State:', {
status: state.status,
address: state.address,
userId: state.userId,
accountId: state.accountId,
hasOrderlyKey: !!account?.keyStore?.getOrderlyKey(),
});
}, [state, account]);
// Common issues:
switch (state.status) {
case AccountStatusEnum.NotConnected:
return <p>Wallet not connected</p>;
case AccountStatusEnum.Connected:
return <p>Wallet connected, not signed in</p>;
case AccountStatusEnum.NotSignedIn:
return <p>Need to sign message to create Orderly key</p>;
case AccountStatusEnum.SignedIn:
return <p>Fully authenticated</p>;
}
}tsx
import { useAccount, AccountStatusEnum } from '@orderly.network/hooks';
function AccountDebugger() {
const { state, account } = useAccount();
useEffect(() => {
console.log('账户状态:', {
status: state.status,
address: state.address,
userId: state.userId,
accountId: state.accountId,
hasOrderlyKey: !!account?.keyStore?.getOrderlyKey(),
});
}, [state, account]);
// 常见问题处理:
switch (state.status) {
case AccountStatusEnum.NotConnected:
return <p>钱包未连接</p>;
case AccountStatusEnum.Connected:
return <p>钱包已连接,未登录</p>;
case AccountStatusEnum.NotSignedIn:
return <p>需要签署消息以创建Orderly密钥</p>;
case AccountStatusEnum.SignedIn:
return <p>已完成认证</p>;
}
}Common Account Issues
常见账户问题
| Issue | Cause | Solution |
|---|---|---|
| Stuck on "Connected" | User didn't sign | Prompt for signature |
| Key expired | 365-day expiry | Re-authenticate |
| Wrong network | Testnet vs mainnet | Check |
| No user ID | Account not registered | Complete signup |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 停留在“已连接”状态 | 用户未签署消息 | 提示用户进行签名 |
| 密钥过期 | 有效期为365天 | 重新认证 |
| 网络错误 | 测试网与主网混淆 | 检查 |
| 无用户ID | 账户未注册 | 完成注册流程 |
5. Order Submission Errors
5. 订单提交错误
Validate Before Submit
提交前验证
tsx
import { useOrderEntry } from '@orderly.network/hooks';
function OrderDebugger() {
const { formattedOrder, metaState, helper } = useOrderEntry('PERP_ETH_USDC');
// Check for validation errors
if (metaState.errors) {
console.log('Order Errors:', metaState.errors);
}
// Check order readiness
console.log('Order Ready:', {
canSubmit: !metaState.errors && formattedOrder,
maxQty: helper.maxQty,
estLiqPrice: helper.estLiqPrice,
});
}tsx
import { useOrderEntry } from '@orderly.network/hooks';
function OrderDebugger() {
const { formattedOrder, metaState, helper } = useOrderEntry('PERP_ETH_USDC');
// 检查验证错误
if (metaState.errors) {
console.log('订单错误:', metaState.errors);
}
// 检查订单是否可提交
console.log('订单就绪状态:', {
canSubmit: !metaState.errors && formattedOrder,
maxQty: helper.maxQty,
estLiqPrice: helper.estLiqPrice,
});
}Debug Order Rejection
调试订单被拒问题
tsx
async function submitOrderWithDebug(order) {
try {
const result = await submit();
console.log('Order submitted:', result);
} catch (error) {
console.error('Order failed:', {
code: error.code,
message: error.message,
});
if (error.code === -2001) {
console.log('Fix: Deposit more USDC or reduce order size');
} else if (error.code === -2002) {
console.log('Fix: Reduce leverage or position size');
}
throw error;
}
}tsx
async function submitOrderWithDebug(order) {
try {
const result = await submit();
console.log('订单提交成功:', result);
} catch (error) {
console.error('订单提交失败:', {
code: error.code,
message: error.message,
});
if (error.code === -2001) {
console.log('修复方案:存入更多USDC或减小订单规模');
} else if (error.code === -2002) {
console.log('修复方案:降低杠杆或仓位规模');
}
throw error;
}
}6. Deposit/Withdrawal Errors
6. 存币/提币错误
Debug Deposit
调试存币流程
tsx
import { useDeposit } from '@orderly.network/hooks';
function DepositDebugger() {
const { deposit, balance, allowance, approve } = useDeposit();
const handleDeposit = async (amount) => {
console.log('Deposit Debug:', {
amount,
walletBalance: balance,
currentAllowance: allowance,
needsApproval: Number(amount) > Number(allowance),
});
try {
if (Number(amount) > Number(allowance)) {
console.log('Approving USDC...');
await approve(amount);
}
console.log('Depositing...');
const result = await deposit();
console.log('Deposit success:', result);
} catch (error) {
console.error('Deposit failed:', error);
if (error.message.includes('user rejected')) {
console.log('User rejected transaction');
} else if (error.message.includes('insufficient')) {
console.log('Insufficient balance or gas');
}
}
};
}tsx
import { useDeposit } from '@orderly.network/hooks';
function DepositDebugger() {
const { deposit, balance, allowance, approve } = useDeposit();
const handleDeposit = async (amount) => {
console.log('存币调试信息:', {
amount,
walletBalance: balance,
currentAllowance: allowance,
needsApproval: Number(amount) > Number(allowance),
});
try {
if (Number(amount) > Number(allowance)) {
console.log('正在授权USDC...');
await approve(amount);
}
console.log('正在存币...');
const result = await deposit();
console.log('存币成功:', result);
} catch (error) {
console.error('存币失败:', error);
if (error.message.includes('user rejected')) {
console.log('用户拒绝了交易');
} else if (error.message.includes('insufficient')) {
console.log('余额或Gas不足');
}
}
};
}7. Debugging Hooks
7. 调试Hooks
Enable Debug Mode
启用调试模式
tsx
// Log all hook state changes
function useDebugHook(hookName, value) {
useEffect(() => {
console.log(`[${hookName}]`, value);
}, [value, hookName]);
return value;
}
// Usage
const positions = useDebugHook('positions', usePositionStream().positions);tsx
// 记录所有Hook状态变化
function useDebugHook(hookName, value) {
useEffect(() => {
console.log(`[${hookName}]`, value);
}, [value, hookName]);
return value;
}
// 使用示例
const positions = useDebugHook('positions', usePositionStream().positions);8. Network Issues
8. 网络问题
CORS Errors
CORS错误
Access to fetch at 'https://api.orderly.org/...' has been blocked by CORSSolutions:
- SDK handles CORS automatically
- Check you're not calling API directly without SDK
Access to fetch at 'https://api.orderly.org/...' has been blocked by CORS解决方案:
- SDK会自动处理CORS问题
- 检查是否绕过SDK直接调用API
Rate Limiting
速率限制
tsx
// Implement exponential backoff
async function withRetry(fn, maxRetries = 3, baseDelay = 1000) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (error.code === -1003 && attempt < maxRetries - 1) {
const delay = baseDelay * Math.pow(2, attempt);
console.log(`Rate limited, retrying in ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}tsx
// 实现指数退避机制
async function withRetry(fn, maxRetries = 3, baseDelay = 1000) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (error.code === -1003 && attempt < maxRetries - 1) {
const delay = baseDelay * Math.pow(2, attempt);
console.log(`触发速率限制,将在${delay}ms后重试...`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}9. Error Boundary
9. 错误边界
Wrap your app with an error boundary:
tsx
import { ErrorBoundary } from '@orderly.network/react-app';
// Or create custom:
class OrderlyErrorBoundary extends React.Component {
state = { hasError: false, error: undefined };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Orderly Error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong</h2>
<pre>{this.state.error?.message}</pre>
<button onClick={() => window.location.reload()}>Reload Page</button>
</div>
);
}
return this.props.children;
}
}使用错误边界包裹应用:
tsx
import { ErrorBoundary } from '@orderly.network/react-app';
// 或自定义错误边界:
class OrderlyErrorBoundary extends React.Component {
state = { hasError: false, error: undefined };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Orderly错误:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>出现错误</h2>
<pre>{this.state.error?.message}</pre>
<button onClick={() => window.location.reload()}>重新加载页面</button>
</div>
);
}
return this.props.children;
}
}10. Debugging Checklist
10. 调试检查清单
Order Not Submitting
订单无法提交
- Account status is ?
SignedIn - Symbol format correct? (e.g., )
PERP_ETH_USDC - Sufficient balance?
- Order quantity above minimum?
- Limit price within range?
- No validation errors in ?
metaState.errors
- 账户状态是否为?
SignedIn - 交易对格式是否正确?(例如:)
PERP_ETH_USDC - 余额是否充足?
- 订单数量是否高于最低要求?
- 限价是否在允许范围内?
- 中是否存在验证错误?
metaState.errors
Wallet Not Connecting
钱包无法连接
- WalletConnectorProvider configured?
- Correct wallet adapters installed?
- Chain supported for network?
- User approved connection in wallet?
- 是否配置了WalletConnectorProvider?
- 是否安装了正确的钱包适配器?
- 当前网络是否被支持?
- 用户是否在钱包中批准了连接请求?
Data Not Loading
数据无法加载
- WebSocket connected?
- Correct networkId (mainnet vs testnet)?
- User authenticated for private data?
- Check browser console for errors?
- WebSocket是否已连接?
- 配置是否正确(主网vs测试网)?
networkId - 用户是否已认证以获取私有数据?
- 是否检查了浏览器控制台的错误信息?
Deposit/Withdraw Failing
存币/提币失败
- Correct chain selected?
- USDC approved for deposit?
- Sufficient gas for transaction?
- No pending withdrawals?
- Available balance covers withdrawal?
- 是否选择了正确的链?
- USDC是否已授权存币?
- 交易Gas是否充足?
- 是否存在待处理的提现请求?
- 可用余额是否覆盖提现金额?
11. Useful Debug Components
11. 实用调试组件
Full State Debugger
全状态调试器
tsx
function OrderlyDebugPanel() {
const { state } = useAccount();
const wsStatus = useWsStatus();
const { data: accountInfo } = useAccountInfo();
if (!import.meta.env.DEV) return null;
return (
<div className="fixed bottom-4 right-4 bg-black/80 text-white p-4 rounded-lg text-xs">
<h3 className="font-bold mb-2">Debug Panel</h3>
<div>Account: {state.status}</div>
<div>WS: {wsStatus}</div>
<div>Balance: {accountInfo?.freeCollateral?.toFixed(2)} USDC</div>
</div>
);
}tsx
function OrderlyDebugPanel() {
const { state } = useAccount();
const wsStatus = useWsStatus();
const { data: accountInfo } = useAccountInfo();
if (!import.meta.env.DEV) return null;
return (
<div className="fixed bottom-4 right-4 bg-black/80 text-white p-4 rounded-lg text-xs">
<h3 className="font-bold mb-2">调试面板</h3>
<div>账户状态: {state.status}</div>
<div>WS连接状态: {wsStatus}</div>
<div>可用保证金: {accountInfo?.freeCollateral?.toFixed(2)} USDC</div>
</div>
);
}Related Skills
相关技能
- orderly-sdk-dex-architecture - Provider setup
- orderly-sdk-wallet-connection - Wallet integration
- orderly-api-authentication - Auth flow
- orderly-sdk-install-dependency - Package installation
- orderly-sdk-dex-architecture - 提供者设置
- orderly-sdk-wallet-connection - 钱包集成
- orderly-api-authentication - 认证流程
- orderly-sdk-install-dependency - 依赖包安装