orderly-sdk-debugging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Orderly 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 defined
Cause: Wallet libraries use Node.js built-ins (Buffer, crypto) that don't exist in browsers.
Solution: Add
vite-plugin-node-polyfills
:
bash
npm install -D vite-plugin-node-polyfills
ts
// 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-polyfills
插件:
bash
npm install -D vite-plugin-node-polyfills
ts
// 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
@orderly.network/ui
has a CSS file.
Solution: Only import from
@orderly.network/ui
:
css
/* 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'
原因:只有
@orderly.network/ui
包包含CSS文件。
解决方案:仅从
@orderly.network/ui
导入CSS:
css
/* 正确方式 - 只有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错误码

CodeMessageCauseSolution
-1000
Unknown errorServer errorRetry request
-1002
UnauthorizedInvalid/expired keyRe-authenticate
-1003
Too many requestsRate limitImplement backoff
-1102
Invalid parameterWrong order paramsValidate inputs
错误码错误信息原因解决方案
-1000
未知错误服务器错误重试请求
-1002
未授权密钥无效/已过期重新认证
-1003
请求过于频繁触发速率限制实现退避机制
-1102
参数无效订单参数错误验证输入内容

Order Error Codes

订单错误码

CodeMessageCauseSolution
-2001
Insufficient balanceNot enough USDCDeposit more funds
-2002
Order would trigger liquidationRisk too highReduce position size
-2004
Price out of rangePrice too far from markAdjust limit price
-2005
Order quantity too smallBelow minimumIncrease quantity
错误码错误信息原因解决方案
-2001
余额不足USDC余额不足存入更多资金
-2002
订单将触发清算风险过高降低仓位规模
-2004
价格超出范围价格偏离标记价过多调整限价
-2005
订单数量过小低于最低要求增加订单数量

Withdrawal Error Codes

提现错误码

CodeMessageCauseSolution
-3001
Insufficient balanceNot enough availableCheck unsettled PnL
-3002
Withdrawal amount too smallBelow minimumIncrease amount
错误码错误信息原因解决方案
-3001
余额不足可用余额不足检查未结算盈亏
-3002
提现金额过小低于最低要求提高提现金额

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状态值说明

StatusDescription
Connected
WebSocket is connected and working
Unstable
Connection dropped, attempting reconnect
Disconnected
Connection lost, not reconnecting
状态值描述
Connected
WebSocket已连接且正常工作
Unstable
连接断开,正在尝试重连
Disconnected
连接丢失,未进行重连

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

常见账户问题

IssueCauseSolution
Stuck on "Connected"User didn't signPrompt for signature
Key expired365-day expiryRe-authenticate
Wrong networkTestnet vs mainnetCheck
networkId
No user IDAccount not registeredComplete signup
问题原因解决方案
停留在“已连接”状态用户未签署消息提示用户进行签名
密钥过期有效期为365天重新认证
网络错误测试网与主网混淆检查
networkId
配置
无用户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 CORS
Solutions:
  1. SDK handles CORS automatically
  2. Check you're not calling API directly without SDK
Access to fetch at 'https://api.orderly.org/...' has been blocked by CORS
解决方案:
  1. SDK会自动处理CORS问题
  2. 检查是否绕过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是否已连接?
  • networkId
    配置是否正确(主网vs测试网)?
  • 用户是否已认证以获取私有数据?
  • 是否检查了浏览器控制台的错误信息?

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 - 依赖包安装