Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@avantis/sdk

TypeScript SDK for integrating with the Avantis Trading Platform on Base. Supports both gasless transactions via Gelato and direct EOA transactions.

Installation

npm install @avantis/sdk viem
# or
yarn add @avantis/sdk viem
# or
pnpm add @avantis/sdk viem

Quick Start

EOA (Direct) Transactions

import { createConfig, openTrade, TradeType, approveUSDC, MAX_UINT256 } from '@avantis/sdk';

// Create configuration with EOA
const config = createConfig({
  rpcUrl: 'https://mainnet.base.org',
  eoa: {
    privateKey: '0x...', // Your private key
    gasSettings: {
      maxFeePerGas: 1000000000n, // Optional
      maxPriorityFeePerGas: 100000000n, // Optional
    },
  },
});

// Approve USDC spending (one-time)
await approveUSDC(config, { amount: MAX_UINT256 });

// Open a 10x long position on BTC/USD
const result = await openTrade(config, {
  pairIndex: 0, // BTC/USD
  positionSizeUSDC: 100n * 10n ** 6n, // 100 USDC
  openPrice: 50000n * 10n ** 10n, // $50,000
  buy: true, // Long
  leverage: 10n * 10n ** 10n, // 10x
  tp: 55000n * 10n ** 10n, // Take profit at $55,000
  sl: 48000n * 10n ** 10n, // Stop loss at $48,000
  tradeType: TradeType.MARKET,
  slippage: 10n ** 8n, // 1% slippage
  executionFee: 100000000000000n, // 0.0001 ETH
});

console.log('Trade opened:', result.hash);

Gelato Gasless Transactions

import { createConfig, openTrade, TradeType } from '@avantis/sdk';
import { createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';

// Create a viem wallet client
const account = privateKeyToAccount('0x...');
const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http('https://mainnet.base.org'),
});

// Create configuration with Gelato
const config = createConfig({
  rpcUrl: 'https://mainnet.base.org',
  gelato: {
    apiKey: 'your-gelato-api-key',
    walletClient,
  },
});

// Transactions are now gasless!
const result = await openTrade(config, {
  pairIndex: 0,
  positionSizeUSDC: 100n * 10n ** 6n,
  openPrice: 50000n * 10n ** 10n,
  buy: true,
  leverage: 10n * 10n ** 10n,
  tp: 55000n * 10n ** 10n,
  sl: 0n, // No stop loss
  tradeType: TradeType.MARKET,
  slippage: 10n ** 8n,
  executionFee: 100000000000000n,
});

API Reference

Configuration

createConfig(options)

Creates a configuration object for the SDK.

interface CreateConfigOptions {
  rpcUrl: string;
  contracts?: Partial<ContractAddresses>; // Override default addresses
  gelato?: GelatoConfig;
  eoa?: EOAConfig;
  builderCode?: Hex; // Optional tracking code
}

Trade Functions

openTrade(config, params)

Open a new trade (market, limit, or stop-limit).

interface OpenTradeParams {
  pairIndex: number;
  positionSizeUSDC: bigint; // 6 decimals
  openPrice: bigint; // 10 decimals
  buy: boolean;
  leverage: bigint; // 10 decimals
  tp: bigint; // 10 decimals, 0 for none
  sl: bigint; // 10 decimals, 0 for none
  tradeType: TradeType;
  slippage: bigint; // 10 decimals
  executionFee: bigint; // wei
  liqPrice?: bigint; // 10 decimals
}

closeTrade(config, params)

Close an open market position.

interface CloseTradeParams {
  pairIndex: number;
  index: number;
  collateralToClose: bigint; // 6 decimals
  executionFee: bigint; // wei
}

cancelLimitOrder(config, params)

Cancel a pending limit order.

interface CancelLimitOrderParams {
  pairIndex: number;
  index: number;
}

updateTakeProfit(config, pairIndex, index, newTp)

Update take profit for an open position.

updateStopLoss(config, pairIndex, index, newSl)

Update stop loss for an open position.

Convenience Functions

// Open market orders
openMarketLong(config, params);
openMarketShort(config, params);

// Open limit orders
openLimitLong(config, params);
openLimitShort(config, params);

USDC Approval

approveUSDC(config, params)

Approve USDC spending for the Trading contract.

getUSDCAllowance(config, owner?)

Check current USDC allowance.

getUSDCBalance(config, address?)

Check USDC balance.

approveUSDCIfNeeded(config, requiredAmount, approvalAmount?)

Approve USDC only if current allowance is insufficient.

Constants

import {
  MAX_UINT256, // Maximum approval amount
  DEFAULT_APPROVAL_AMOUNT, // 25,000 USDC
  BASE_MAINNET_ADDRESSES, // Default contract addresses
  TradeType, // MARKET, LIMIT, STOP_LIMIT, MARKET_PNL
  TradeSide, // LONG, SHORT
} from '@avantis/sdk';

Decimal Conventions

Value Decimals Example
USDC amounts 6 100n * 10n**6n = 100 USDC
Prices 10 50000n * 10n**10n = $50,000
Leverage 10 10n * 10n**10n = 10x
Slippage 10 10n**8n = 1%
Execution fees 18 (wei) 100000000000000n = 0.0001 ETH

Error Handling

The SDK throws AvantisError with specific error codes:

import { AvantisError, AvantisErrorCode } from '@avantis/sdk';

try {
  await openTrade(config, params);
} catch (error) {
  if (error instanceof AvantisError) {
    switch (error.code) {
      case AvantisErrorCode.INSUFFICIENT_BALANCE:
        console.log('Not enough USDC');
        break;
      case AvantisErrorCode.TRANSACTION_FAILED:
        console.log('Transaction failed:', error.message);
        break;
      case AvantisErrorCode.GELATO_RELAY_FAILED:
        console.log('Gelato relay failed:', error.details);
        break;
    }
  }
}

Custom Contract Addresses

Override default Base mainnet addresses:

const config = createConfig({
  rpcUrl: 'https://mainnet.base.org',
  contracts: {
    trading: '0x...', // Custom Trading address
    tradingStorage: '0x...', // Custom TradingStorage address
    usdc: '0x...', // Custom USDC address
  },
  eoa: { privateKey: '0x...' },
});

Pair Indices

Common pair indices on Avantis:

Index Pair
0 BTC/USD
1 ETH/USD
... See docs

License

MIT

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages