← Back to Skills Marketplace
tarnadas

Orderly Sdk Debugging

by Mario Reder · GitHub ↗ · v1.0.0
cross-platform ✓ Security Clean
525
Downloads
0
Stars
1
Active Installs
1
Versions
Install in OpenClaw
/install orderly-sdk-debugging
Description
Debug and troubleshoot common issues with the Orderly SDK including errors, WebSocket issues, authentication problems, and trading failures.
README (SKILL.md)

Orderly Network: SDK Debugging

A comprehensive guide to debugging common issues, handling errors, and troubleshooting problems with the Orderly SDK.

When to Use

  • Fixing build errors
  • Debugging WebSocket connections
  • Handling API errors
  • Troubleshooting authentication issues
  • Investigating trading failures

Prerequisites

  • Orderly SDK installed
  • Basic debugging knowledge
  • Browser DevTools familiarity

1. Build & Setup Errors

Buffer is not defined

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:

npm install -D vite-plugin-node-polyfills
// 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

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:

/* 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'; */

2. Common Error Codes

API Error Codes

Code Message Cause Solution
-1000 Unknown error Server error Retry request
-1002 Unauthorized Invalid/expired key Re-authenticate
-1003 Too many requests Rate limit Implement backoff
-1102 Invalid parameter Wrong order params Validate inputs

Order Error Codes

Code Message Cause Solution
-2001 Insufficient balance Not enough USDC Deposit more funds
-2002 Order would trigger liquidation Risk too high Reduce position size
-2004 Price out of range Price too far from mark Adjust limit price
-2005 Order quantity too small Below minimum Increase quantity

Withdrawal Error Codes

Code Message Cause Solution
-3001 Insufficient balance Not enough available Check unsettled PnL
-3002 Withdrawal amount too small Below minimum Increase amount

3. WebSocket Connection

Monitor Connection Status

import { useWsStatus, WsNetworkStatus } from '@orderly.network/hooks';

function ConnectionIndicator() {
  const wsStatus = useWsStatus();

  return (
    \x3Cdiv className="connection-status">
      {wsStatus === WsNetworkStatus.Connected && (
        \x3Cspan className="text-green-500">● Connected\x3C/span>
      )}
      {wsStatus === WsNetworkStatus.Unstable && (
        \x3Cspan className="text-yellow-500">● Reconnecting...\x3C/span>
      )}
      {wsStatus === WsNetworkStatus.Disconnected && (
        \x3Cspan className="text-red-500">● Disconnected\x3C/span>
      )}
    \x3C/div>
  );
}

WebSocket Status Values

Status Description
Connected WebSocket is connected and working
Unstable Connection dropped, attempting reconnect
Disconnected Connection lost, not reconnecting

4. Account State Issues

Check Account State

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 \x3Cp>Wallet not connected\x3C/p>;
    case AccountStatusEnum.Connected:
      return \x3Cp>Wallet connected, not signed in\x3C/p>;
    case AccountStatusEnum.NotSignedIn:
      return \x3Cp>Need to sign message to create Orderly key\x3C/p>;
    case AccountStatusEnum.SignedIn:
      return \x3Cp>Fully authenticated\x3C/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 networkId
No user ID Account not registered Complete signup

5. Order Submission Errors

Validate Before Submit

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,
  });
}

Debug Order Rejection

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;
  }
}

6. Deposit/Withdrawal Errors

Debug Deposit

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');
      }
    }
  };
}

7. Debugging Hooks

Enable Debug Mode

// 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);

8. Network Issues

CORS Errors

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

Rate Limiting

// Implement exponential backoff
async function withRetry(fn, maxRetries = 3, baseDelay = 1000) {
  for (let attempt = 0; attempt \x3C maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (error.code === -1003 && attempt \x3C 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;
      }
    }
  }
}

9. Error Boundary

Wrap your app with an error boundary:

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 (
        \x3Cdiv className="error-fallback">
          \x3Ch2>Something went wrong\x3C/h2>
          \x3Cpre>{this.state.error?.message}\x3C/pre>
          \x3Cbutton onClick={() => window.location.reload()}>Reload Page\x3C/button>
        \x3C/div>
      );
    }
    return this.props.children;
  }
}

10. Debugging Checklist

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?

Wallet Not Connecting

  • WalletConnectorProvider configured?
  • Correct wallet adapters installed?
  • Chain supported for network?
  • User approved connection in wallet?

Data Not Loading

  • WebSocket connected?
  • Correct networkId (mainnet vs testnet)?
  • User authenticated for private data?
  • Check browser console for errors?

Deposit/Withdraw Failing

  • Correct chain selected?
  • USDC approved for deposit?
  • Sufficient gas for transaction?
  • No pending withdrawals?
  • Available balance covers withdrawal?

11. Useful Debug Components

Full State Debugger

function OrderlyDebugPanel() {
  const { state } = useAccount();
  const wsStatus = useWsStatus();
  const { data: accountInfo } = useAccountInfo();

  if (!import.meta.env.DEV) return null;

  return (
    \x3Cdiv className="fixed bottom-4 right-4 bg-black/80 text-white p-4 rounded-lg text-xs">
      \x3Ch3 className="font-bold mb-2">Debug Panel\x3C/h3>
      \x3Cdiv>Account: {state.status}\x3C/div>
      \x3Cdiv>WS: {wsStatus}\x3C/div>
      \x3Cdiv>Balance: {accountInfo?.freeCollateral?.toFixed(2)} USDC\x3C/div>
    \x3C/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
Usage Guidance
This is an instruction-only debugging guide for the Orderly SDK and is internally coherent. Before using: (1) don't paste or share private keys or seed phrases when following examples — use test accounts or testnets; (2) when running npm install commands, prefer verifying package sources and versions; (3) be aware example logs may print identifiers (address, userId, accountId); avoid sending those to untrusted endpoints. If you need the skill to run platform-side code, review any code you execute locally for sensitive operations first.
Capability Analysis
Type: OpenClaw Skill Name: orderly-sdk-debugging Version: 1.0.0 The skill bundle provides legitimate documentation and code snippets for debugging the Orderly Network SDK. It covers common build errors, API error codes, and state management in SKILL.md without any signs of malicious intent, data exfiltration, or harmful instructions.
Capability Assessment
Purpose & Capability
Name and description match the SKILL.md content: the document contains debugging guidance, code snippets, and troubleshooting steps for the Orderly SDK and related browser/build issues. No unrelated capabilities or external services are requested.
Instruction Scope
The instructions stay within SDK debugging scope: build fixes, WebSocket/account/order error handling, and example code. They do log account state in examples (address, userId, accountId, key presence) but do not instruct reading arbitrary system files, sending data to unexpected endpoints, or exfiltrating secrets.
Install Mechanism
No install spec or code files are present. The only actionable instruction is an example to install a common dev dependency (vite-plugin-node-polyfills) which is proportional to the described browser polyfill problem.
Credentials
The skill declares no required environment variables, credentials, or config paths. Example snippets access SDK state (account, key store) which is expected for debugging; there are no requests for unrelated credentials.
Persistence & Privilege
Skill is not always-enabled and does not request persistent privileges or modify other skills or system settings. It is user-invocable and can be used on demand.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install orderly-sdk-debugging
  3. After installation, invoke the skill by name or use /orderly-sdk-debugging
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.0.0
Initial release of the orderly-sdk-debugging skill. - Provides troubleshooting steps for build errors, common API, order, and withdrawal issues. - Includes code samples to monitor WebSocket and account status. - Details error codes and suggested solutions for authentication, order submission, and network problems. - Offers diagnostic patterns for deposit/withdrawal issues and debugging custom hooks. - Suitable for developers using Orderly SDK in browser environments.
Metadata
Slug orderly-sdk-debugging
Version 1.0.0
License
All-time Installs 1
Active Installs 1
Total Versions 1
Frequently Asked Questions

What is Orderly Sdk Debugging?

Debug and troubleshoot common issues with the Orderly SDK including errors, WebSocket issues, authentication problems, and trading failures. It is an AI Agent Skill for Claude Code / OpenClaw, with 525 downloads so far.

How do I install Orderly Sdk Debugging?

Run "/install orderly-sdk-debugging" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Orderly Sdk Debugging free?

Yes, Orderly Sdk Debugging is completely free (open-source). You can download, install and use it at no cost.

Which platforms does Orderly Sdk Debugging support?

Orderly Sdk Debugging is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Orderly Sdk Debugging?

It is built and maintained by Mario Reder (@tarnadas); the current version is v1.0.0.

💬 Comments