Openocean APIs
  • Developer
    • ⚙️APIs
      • Swap API
        • Supported Chains
        • Contracts of Chains
        • Guide
        • API V4
        • API V3
        • SDK
        • Advanced Usage
          • GMX Exclusive API
          • Exact out
      • Gasless API
        • API
      • Limit Order API
        • Guide
        • API
        • Browser Wallet SDK
        • Private Key Wallet SDK
      • Sweep Swap API
        • Guide
        • API
      • DCA API
        • Guide
        • API
        • Browser Wallet SDK
        • Private Key Wallet SDK
      • Meme API
        • Data API
        • Transaction API
        • Websocket API
      • Ticket API
        • API
      • 🤖Swagger
    • 👾Widget
      • Getting Started
      • Customize Theme
      • Other Reference
      • Widget V2
        • Getting Started
    • ℹ️Developer Resources
      • 🚩Common Error Code
      • 📖Developer references & glossary
Powered by GitBook
On this page
  • How to Install the sdk in your project
  • How to use the sdk in your project
  • Setup with Private Key Wallet
  • Creating a Limit Order
  • Canceling a Limit Order
  • Querying Orders
  • Notes
  • Demo
  1. Developer
  2. APIs
  3. Limit Order API

Private Key Wallet SDK

How to Install the sdk in your project

npm i @openocean.finance/limitorder-sdk

How to use the sdk in your project

import { openoceanLimitOrderSdk } from '@openocean.finance/limitorder-sdk';

You can then use all the functions explored by the SDK (API and swapSdk).

Setup with Private Key Wallet

1. Configuration

const privateKey = 'YOUR_PRIVATE_KEY';
const chainId = '8453';
const providerUrl = 'https://base.llamarpc.com';
const baseUrl = 'https://open-api.openocean.finance';

const inToken = {
  address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // USDC
  decimals: 6
};

const outToken = {
  address: '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT
  decimals: 6
};

2. Web3.js Setup

import Web3 from 'web3';
import { openoceanLimitOrderSdk, WalletParams } from '@openocean.finance/limitorder-sdk';

const web3 = new Web3(providerUrl);
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);

const web3Params: WalletParams = {
  provider: web3,
  chainId: chainId,
  chainKey: 'base',
  account: account.address,
};

3. Ethers.js Setup

Ethers v5

import { ethers } from 'ethers';

const ethersProvider = new ethers.providers.JsonRpcProvider(providerUrl);
const signer = new ethers.Wallet(privateKey, ethersProvider);

const ethersParams: WalletParams = {
  provider: ethersProvider,
  signer: signer,
  account: ethersSigner.address,
  chainId: chainId,
  chainKey: 'base',
};

Ethers v6 Warning

If using Ethers v6, make sure to import correctly:

import { JsonRpcProvider, Wallet } from 'ethers';
const provider = new JsonRpcProvider(providerUrl);
const signer = new Wallet(privateKey, provider);

Creating a Limit Order

const orderData = await openoceanLimitOrderSdk.createLimitOrder(
  web3Params, // or ethersParams
  {
    makerTokenAddress: inToken.address,
    makerTokenDecimals: inToken.decimals,
    takerTokenAddress: outToken.address,
    takerTokenDecimals: outToken.decimals,
    makerAmount: (0.1 * 10 ** inToken.decimals).toString(),
    takerAmount: (0.2 * 10 ** outToken.decimals).toString(),
    gasPrice: estimatedGas, // optional
    expire: '6Month'        // optional: '1H', '1D', '6Month' etc.
  }
);

// Submit to OpenOcean
const result = await axios.post(
  `${baseUrl}/v1/${chainId}/limit-order`,
  orderData,
  {
    headers: { 'Content-Type': 'application/json' }
  }
);
console.log('Order created:', result.data);

Canceling a Limit Order

const result = await axios.post(
  `${baseUrl}/v1/${chainId}/limit-order/cancelLimitOrder`,
  { orderHash: order.orderHash }
);

// If on-chain cancel is needed:
await openoceanLimitOrderSdk.cancelLimitOrder(
  web3Params, // or ethersParams
  {
    orderData: order.data,
    gasPrice: '...' // optional
  }
);

Querying Orders

const { data } = await axios.get(
  `${baseUrl}/v1/${chainId}/limit-order/address/${walletAddress}?statuses=[1,2,5]`
);
console.log('User orders:', data.data);

Notes

  • Ethers v5 vs v6:

    • v5 uses new ethers.providers.JsonRpcProvider() and Wallet()

    • v6 uses JsonRpcProvider and Wallet from ethers6, and BigInt types

    • SDK supports both, but ensure correct version imports

  • Gas Price:

    • For Web3.js: await web3.eth.getGasPrice()

    • For Ethers: await provider.getFeeData().gasPrice

  • Order Expiration Options:

    • '1H', '6H', '12H', '1D', '3D', '1W', '6Month'

Demo

import { openoceanLimitOrderSdk, WalletParams } from '@openocean.finance/limitorder-sdk';
import Web3 from "web3";
import { ethers } from "ethers5";
import { JsonRpcProvider, Wallet } from "ethers6";

import axios from "axios";


const chainId = '8453'
const providerUrl = 'https://base.llamarpc.com';

// Wallet private key - please replace with your actual private key
const privateKey = 'your private key'

const inToken = {
  "address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "decimals": 6,
  "symbol": "USDC",
}
// Token configuration for WETH
const outToken = {
  "address": "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2",
  "decimals": 6,
  "symbol": "USDT"
}


// OpenOcean API base URL
const baseUrl = 'https://open-api.openocean.finance'

// Initialize providers and signers
// Web3.js setup
const web3 = new Web3(providerUrl);
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);


// Ethers.js setup
//ethers v5
const ethersProvider = new ethers.providers.JsonRpcProvider(providerUrl) 
const ethersSigner = new ethers.Wallet(privateKey, ethersProvider);

// ethers v6
// const ethersProvider = new JsonRpcProvider(providerUrl);
// const ethersSigner = new Wallet(privateKey, ethersProvider);


// Initialize Web3.js WalletParams
const web3Params: WalletParams = {
  provider: web3,
  chainId: chainId,
  chainKey: 'base',
  account: account.address,
  // mode: 'Dca'
};

// Initialize Ethers.js WalletParams
const ethersParams: WalletParams = {
  provider: ethersProvider,
  chainId: chainId,
  chainKey: 'base',
  account: ethersSigner.address,
  // mode: 'Dca',

  signer: ethersSigner
};

/**
 * Create limit order using Web3.js
 * This function creates a limit order to exchange 0.1 USDC for 0.2 USDT using Web3.js.
 */
async function testCreateWeb3() {
  try {
    // Get current gas price from the network
    const gasPrice = await web3.eth.getGasPrice();
    console.log('Web3 gasPrice:', gasPrice);

    // Build limit order data
    const orderData = await openoceanLimitOrderSdk.createLimitOrder(
      web3Params,
      {
        makerTokenAddress: inToken.address,
        makerTokenDecimals: inToken.decimals,
        takerTokenAddress: outToken.address,
        takerTokenDecimals: outToken.decimals,
        makerAmount: (0.1 * (10 ** inToken.decimals)).toString(),
        takerAmount: (0.2 * (10 ** outToken.decimals)).toString(),
        gasPrice: parseInt((Number(gasPrice) * 1.2) + ''),
        expire: '6Month'
      }
    );

    // Submit the order to OpenOcean API
    const result = await axios.post(
      `${baseUrl}/v1/${chainId}/limit-order`,
      orderData,
      {
        headers: {
          'Content-Type': 'application/json',
        }
      }
    );

    console.log('Web3.js create order result:', result.data);
    return result.data;
  } catch (error) {
    console.error('Web3.js create order failed:', error);
    throw error;
  }
}

/**
 * Create limit order using Ethers.js
 * This function creates a limit order to exchange 0.1 USDC for 0.2 USDT using Ethers.js.
 */
async function testCreateEthers() {
  try {
    // Get current gas price from the network
    const feeData = await ethersProvider.getFeeData();
    const gasPrice = feeData.gasPrice || BigInt(0);
    console.log('Ethers gasPrice:', gasPrice);

    // Build limit order data
    const orderData = await openoceanLimitOrderSdk.createLimitOrder(
      ethersParams,
      {
        makerTokenAddress: inToken.address,
        makerTokenDecimals: inToken.decimals,
        takerTokenAddress: outToken.address,
        takerTokenDecimals: outToken.decimals,
        makerAmount: (0.1 * (10 ** inToken.decimals)).toString(),
        takerAmount: (0.2 * (10 ** outToken.decimals)).toString(),
        gasPrice: parseInt((Number(gasPrice) * 1.2) + ''),
        expire: '6Month'
      }
    );

    // Submit the order to OpenOcean API
    const result = await axios.post(
      `${baseUrl}/v1/${chainId}/limit-order`,
      orderData,
      {
        headers: {
          'Content-Type': 'application/json',
        }
      }
    );

    console.log('Ethers.js create order result:', result.data);
    return result.data;
  } catch (error) {
    console.error('Ethers.js create order failed:', error);
    throw error;
  }
}

/**
 * Cancel limit order using Web3.js
 * This function cancels the first order in the user's order list using Web3.js.
 */
async function testCancelWeb3() {
  try {

    // Get user's order list
    const orderList = await getOrderList(account.address);

    if (orderList && orderList.length) {
      const order = orderList[0];
      // Try to cancel via OpenOcean API
      const result = await axios.post(
        `${baseUrl}/v1/${chainId}/limit-order/cancelLimitOrder`,
        { orderHash: order.orderHash }
      );

      // If API cancellation fails, try on-chain cancellation
      const { status } = (result && result.data && result.data.data) || {};
      console.log('Web3.js cancel order result:', result.data.data);
      if (!(status === 3 || status === 4)) {
        const gasPrice = await web3.eth.getGasPrice();
        console.log('Web3 gasPrice:', gasPrice);
        const res = await openoceanLimitOrderSdk.cancelLimitOrder(
          web3Params,
          {
            orderData: order.data,
            // gasPrice: gasPrice.toString(),
          }
        );
        console.log('Web3.js cancel order result:', res);
        return res;
      }
    } else {
      console.log('No orders found to cancel');
    }
  } catch (error) {
    console.error('Web3.js cancel order failed:', error);
    throw error;
  }
}

/**
 * Cancel limit order using Ethers.js
 * This function cancels the first order in the user's order list using Ethers.js.
 */
async function testCancelEthers() {
  try {
    // Get user's order list
    const orderList = await getOrderList(ethersSigner.address);

    if (orderList && orderList.length) {
      const order = orderList[0];
      // Try to cancel via OpenOcean API
      const result = await axios.post(
        `${baseUrl}/v1/${chainId}/limit-order/cancelLimitOrder`,
        { orderHash: order.orderHash });
      console.log('Ethers.js cancel order result:', result.data.data);
      const { status } = (result && result.data && result.data.data) || {};
      if (!(status === 3 || status === 4)) {
        const feeData = await ethersProvider.getFeeData();
        const gasPrice = feeData.gasPrice || BigInt(0);

        const res = await openoceanLimitOrderSdk.cancelLimitOrder(
          ethersParams,
          {
            orderData: order.data,
            gasPrice: gasPrice.toString(),
          }
        );
        console.log('Ethers.js cancel order result:', res);
        return res;
      }
    } else {
      console.log('No orders found to cancel');
    }
  } catch (error) {
    console.error('Ethers.js cancel order failed:', error);
    throw error;
  }
}

/**
 * Get user's limit order list
 * This function fetches the user's limit orders with status 1 (active), 2 (filled), or 5 (expired).
 * @param address User wallet address
 * @returns Array of order objects
 */
async function getOrderList(address: string) {
  try {
    const reqUrl = `${baseUrl}/v1/${chainId}/limit-order/address/${address}?page=1&limit=100&statuses=[1,2,5]&sortBy=createDateTime&exclude=0`;
    const { data } = await axios.get(reqUrl);
    return data ? data.data : [];
  } catch (error) {
    console.error('Failed to get order list:', error);
    throw error;
  }
}

// Test cases
async function runTests() {
  try {
    console.log('Starting tests...');

    // Test Web3.js create order
    console.log('\nTesting Web3.js create order:');
    await testCreateWeb3();

    // Test Ethers.js create order
    console.log('\nTesting Ethers.js create order:');
    await testCreateEthers();


    // Test Web3.js cancel order
    console.log('\nTesting Web3.js cancel order:');
    await testCancelWeb3();

    // Test Ethers.js cancel order
    console.log('\nTesting Ethers.js cancel order:');
    await testCancelEthers();

    console.log('\nAll tests completed!');
  } catch (error) {
    console.error('Error during testing:', error);
  }
}

// Run tests
// runTests();

// Or run individual tests
// testCreateWeb3();
// testCreateEthers();

// testCancelWeb3();
// testCancelEthers();

// getOrderList(account.address);
// getOrderList(ethersSigner.address);
// getOrderList(browserWalletParams.account);
PreviousBrowser Wallet SDKNextSweep Swap API

Last updated 1 day ago

⚙️