
Product
Announcing Socket Fix 2.0
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
@0xmonaco/core
Advanced tools
⚠️ EARLY DEVELOPMENT WARNING ⚠️
This package is currently in early development (v0.1.0).
Breaking changes are expected and may occur without notice. This version is intended for:
Core SDK implementation for interacting with Monaco Protocol. This SDK provides a comprehensive implementation with Vault and Trading APIs, featuring EIP-712 intent signatures and secure API Gateway integration.
npm install @0xmonaco/core
Before running tests, ensure you have:
A running hardhat node with the Monaco Protocol contracts deployed:
# In the contracts package
cd ../contracts
pnpm hardhat node # Start a local hardhat node
pnpm hardhat deploy --network localhost # Deploy contracts
Create a .env.test
file in the tests directory:
# Create the file
cd packages/core/src/tests
touch .env.test
# Add the following content to .env.test:
echo 'TEST_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' > .env.test
Replace the example private key in .env.test
with your actual test account private key:
Verify your setup:
# Make sure you're in the core package directory
cd packages/core
# Check if .env.test exists and has the correct format
cat src/tests/.env.test
# Should show: TEST_PRIVATE_KEY=0x...
# Run the tests
pnpm test
If you see an error about TEST_PRIVATE_KEY
not being set:
.env.test
exists in packages/core/src/tests
directoryTEST_PRIVATE_KEY=0x1234... pnpm test
The SDK supports both Sei mainnet (pacific-1) and testnet (atlantic-2) networks. Network configurations are automatically handled through the NETWORK_ENDPOINTS
constant:
import { NETWORK_ENDPOINTS } from "@0xmonaco/core";
// Access network configurations by network name
const mainnetConfig = NETWORK_ENDPOINTS.mainnet; // Pacific-1 mainnet
const testnetConfig = NETWORK_ENDPOINTS.testnet; // Atlantic-2 testnet
// Each network config includes:
// - rpcUrl: RPC endpoint for the network
// - apiUrl: API gateway endpoint for the network
import { MonacoSDK } from "@0xmonaco/core";
// Initialize the SDK with private key
const monaco = new MonacoSDK({
privateKey: "0x...", // Your private key
network: "mainnet", // or "testnet"
});
// Vault Operations
async function vaultExample() {
// Check vault balance
const balance = await monaco.vault.getBalance("0x..."); // token address
console.log("Vault balance:", balance.formatted, balance.symbol);
// Check if approval is needed
const needsApproval = await monaco.vault.needsApproval("0x...", parseEther("100"));
if (needsApproval) {
// Approve vault to spend tokens
const approval = await monaco.vault.approve("0x...", parseEther("1000"));
console.log("Approval transaction:", approval.hash);
}
// Deposit tokens
const result = await monaco.vault.deposit("0x...", parseEther("100"));
console.log("Deposit transaction:", result.hash);
}
// Trading Operations
async function tradingExample() {
// Place a limit order
const order = await monaco.trading.placeLimitOrder(
"ETH-USDC", // market
"buy", // side
parseEther("1.0"), // size (1 ETH)
parseUnits("2000", 6) // price (2000 USDC)
);
console.log("Order placed:", order.orderId);
// Place a market order with slippage protection
const marketOrder = await monaco.trading.placeMarketOrder(
"ETH-USDC",
"sell",
parseEther("0.5"),
{ slippageToleranceBps: 50 } // 0.5% max slippage (50 basis points)
);
console.log("Market order placed:", marketOrder.orderId);
// Place a limit order with IOC time in force
const iocOrder = await monaco.trading.placeLimitOrder(
"ETH-USDC",
"buy",
parseEther("1.0"),
parseUnits("2000", 6),
{ timeInForce: "IOC" } // Immediate-or-Cancel
);
console.log("IOC order placed:", iocOrder.orderId);
// Get open orders
const openOrders = await monaco.trading.getOpenOrders({ market: "ETH-USDC" });
console.log("Open orders:", openOrders.length);
// Replace an order (cancel + new)
const replaceResult = await monaco.trading.replaceOrder("order-id", {
market: "ETH-USDC",
side: "buy",
size: parseEther("2.0"),
price: parseUnits("2100", 6),
type: "limit",
timeInForce: "FOK" // Fill-or-Kill
});
console.log("Order replaced:", replaceResult.orderId);
// Cancel an order
const cancelResult = await monaco.trading.cancelOrder("order-id");
console.log("Order cancelled:", cancelResult.status);
}
The main SDK class that provides access to all protocol features.
class MonacoSDK {
readonly vault: VaultAPI;
readonly trading: TradingAPI;
readonly walletClient: WalletClient;
readonly publicClient: PublicClient;
constructor(config: SDKConfig);
}
interface SDKConfig {
/** Private key as hex string (0x-prefixed) */
privateKey?: Hex;
/** Viem Account for advanced account management */
signer?: PrivateKeyAccount;
/** Custom Account implementation (overrides privateKey/signer) */
account?: Account;
/** Optional network override (defaults to 'mainnet') */
network?: Network;
}
The vault API provides secure token management operations:
interface VaultAPI {
// Token approvals
approve(token: string, amount: bigint): Promise<TransactionResult>;
// Deposit and withdrawal
deposit(token: string, amount: bigint): Promise<TransactionResult>;
withdraw(token: string, amount: bigint): Promise<TransactionResult>;
// Balance and allowance queries
getBalance(token: string): Promise<Balance>;
getAllowance(token: string): Promise<bigint>;
needsApproval(token: string, amount: bigint): Promise<boolean>;
}
The trading API provides comprehensive order management with support for different execution policies:
Limit Orders: Standard limit orders with optional timeInForce
parameter
GTC
(Good Till Cancelled): Default behavior, order stays active until filled or cancelledIOC
(Immediate or Cancel): Order fills what it can immediately, then cancels the restFOK
(Fill or Kill): Order must fill completely or not at allMarket Orders: Immediate execution with optional slippage protection
Post-Only Orders: Limit orders that never execute immediately, only add liquidity
interface TradingAPI {
// Order placement
placeLimitOrder(market: string, side: OrderSide, size: bigint, price: bigint, options?: { timeInForce?: TimeInForce }): Promise<OrderResponse>;
placeMarketOrder(market: string, side: OrderSide, size: bigint, options?: { slippageToleranceBps?: number }): Promise<OrderResponse>;
placePostOnlyOrder(market: string, side: OrderSide, size: bigint, price: bigint): Promise<OrderResponse>;
// Order management
replaceOrder(originalOrderId: string, newOrder: { market: string; side: OrderSide; size: bigint; price?: bigint; type: OrderType; timeInForce?: TimeInForce }): Promise<OrderResponse>;
cancelOrder(orderId: string): Promise<CancelOrderResponse>;
// Position management
closePosition(market: string, options?: { maxSlippage?: number }): Promise<ClosePositionResponse>;
// Order queries
getOrder(orderId: string): Promise<Order>;
getOpenOrders(params?: GetOpenOrdersParams): Promise<Order[]>;
getOrderHistory(params: OrderHistoryParams): Promise<PaginatedOrders>;
}
The SDK uses structured error classes for comprehensive error handling:
import { APIError, ContractError, TransactionError, OrderError } from "@0xmonaco/core";
try {
await sdk.vault.deposit(token, amount);
} catch (error) {
if (error instanceof ContractError) {
console.error("Contract error:", error.message);
console.error("Error code:", error.code);
} else if (error instanceof APIError) {
console.error("API error:", error.message);
console.error("Status:", error.status);
} else if (error instanceof TransactionError) {
console.error("Transaction error:", error.message);
} else if (error instanceof OrderError) {
console.error("Order error:", error.message);
console.error("Market:", error.market);
}
}
Error Types:
APIError
: API request failures and communication errorsContractError
: Smart contract operation errorsTransactionError
: Blockchain transaction errorsOrderError
: Trading order specific errorsInvalidConfigError
: Configuration validation errorspackages/core/
├── src/ # Source code
│ ├── api/ # API implementations
│ │ ├── vault/ # Vault operations API
│ │ │ └── api.ts # Vault API implementation with comprehensive docs
│ │ └── trading/ # Trading operations API
│ │ └── api.ts # Trading API implementation with comprehensive docs
│ ├── chains.ts # Chain definitions (Sei mainnet/testnet)
│ ├── errors.ts # Error classes and codes
│ ├── networks.ts # Network endpoint configurations
│ ├── sdk.ts # Main SDK implementation
│ └── index.ts # Public API exports
├── tests/ # Test suite
├── dist/ # Compiled output
├── package.json # Package configuration
└── tsconfig.json # TypeScript configuration
git clone https://github.com/monaco-protocol/monaco-monorepo.git
cd monaco-monorepo
pnpm install
pnpm build --filter @0xmonaco/core
Run the test suite:
pnpm test --filter @0xmonaco/core
The project uses ESLint and Prettier for code formatting. Run the linter:
pnpm lint --filter @0xmonaco/core
We welcome contributions! Please see our Contributing Guide for details.
This project is licensed under the MIT License - see the LICENSE file for details.
For support, please:
FAQs
⚠️ **EARLY DEVELOPMENT WARNING** ⚠️
We found that @0xmonaco/core demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.
Product
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.