@0xmonaco/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +421 -0
- package/dist/api/auth/api.d.ts +198 -0
- package/dist/api/auth/api.d.ts.map +1 -0
- package/dist/api/auth/api.js +359 -0
- package/dist/api/auth/api.js.map +1 -0
- package/dist/api/auth/index.d.ts +6 -0
- package/dist/api/auth/index.d.ts.map +1 -0
- package/dist/api/auth/index.js +5 -0
- package/dist/api/auth/index.js.map +1 -0
- package/dist/api/index.d.ts +8 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +8 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/trading/api.d.ts +152 -0
- package/dist/api/trading/api.d.ts.map +1 -0
- package/dist/api/trading/api.js +229 -0
- package/dist/api/trading/api.js.map +1 -0
- package/dist/api/trading/index.d.ts +6 -0
- package/dist/api/trading/index.d.ts.map +1 -0
- package/dist/api/trading/index.js +5 -0
- package/dist/api/trading/index.js.map +1 -0
- package/dist/api/vault/api.d.ts +224 -0
- package/dist/api/vault/api.d.ts.map +1 -0
- package/dist/api/vault/api.js +514 -0
- package/dist/api/vault/api.js.map +1 -0
- package/dist/api/vault/index.d.ts +6 -0
- package/dist/api/vault/index.d.ts.map +1 -0
- package/dist/api/vault/index.js +5 -0
- package/dist/api/vault/index.js.map +1 -0
- package/dist/chains.d.ts +90 -0
- package/dist/chains.d.ts.map +1 -0
- package/dist/chains.js +56 -0
- package/dist/chains.js.map +1 -0
- package/dist/errors.d.ts +132 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +165 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/networks.d.ts +8 -0
- package/dist/networks.d.ts.map +1 -0
- package/dist/networks.js +16 -0
- package/dist/networks.js.map +1 -0
- package/dist/sdk.d.ts +76 -0
- package/dist/sdk.d.ts.map +1 -0
- package/dist/sdk.js +203 -0
- package/dist/sdk.js.map +1 -0
- package/package.json +38 -0
package/README.md
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
# Monaco Core SDK
|
|
2
|
+
|
|
3
|
+
⚠️ **EARLY DEVELOPMENT WARNING** ⚠️
|
|
4
|
+
|
|
5
|
+
This package is currently in **early development** (v0.1.0).
|
|
6
|
+
|
|
7
|
+
**Breaking changes are expected** and may occur without notice. This version is intended for:
|
|
8
|
+
- Early adopters and testing
|
|
9
|
+
- Development and experimentation
|
|
10
|
+
- Feedback collection
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @0xmonaco/core
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
### 🏦 **Vault Operations**
|
|
25
|
+
- **Token Approvals**: ERC20 token approvals for vault usage
|
|
26
|
+
- **Deposits**: Secure token deposits with EIP-712 signatures
|
|
27
|
+
- **Withdrawals**: Token withdrawals with cryptographic validation
|
|
28
|
+
- **Balance Queries**: Real-time vault balance tracking
|
|
29
|
+
- **Allowance Management**: Efficient approval checking and management
|
|
30
|
+
|
|
31
|
+
### 📈 **Trading Operations**
|
|
32
|
+
- **Order Types**: Limit (with timeInForce: GTC/IOC/FOK), Market, Post-Only orders
|
|
33
|
+
- **Order Management**: Place, replace (cancel + new), and cancel orders
|
|
34
|
+
- **Position Management**: Close positions with slippage control
|
|
35
|
+
- **Order Queries**: Open orders, order history, and individual order details
|
|
36
|
+
- **Real-time Updates**: Live order status and execution tracking
|
|
37
|
+
|
|
38
|
+
### 🔐 **Security Features**
|
|
39
|
+
- **EIP-712 Signatures**: Type-safe, structured data signing
|
|
40
|
+
- **Intent-Based Authorization**: Every action explicitly authorized
|
|
41
|
+
- **API Gateway Integration**: Secure communication with Monaco backend
|
|
42
|
+
- **Nonce Protection**: Replay attack prevention
|
|
43
|
+
- **TLS Encryption**: Secure API communications
|
|
44
|
+
|
|
45
|
+
## Test Setup
|
|
46
|
+
|
|
47
|
+
Before running tests, ensure you have:
|
|
48
|
+
|
|
49
|
+
1. A running hardhat node with the Monaco Protocol contracts deployed:
|
|
50
|
+
```bash
|
|
51
|
+
# In the contracts package
|
|
52
|
+
cd ../contracts
|
|
53
|
+
pnpm hardhat node # Start a local hardhat node
|
|
54
|
+
pnpm hardhat deploy --network localhost # Deploy contracts
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
2. Create a `.env.test` file in the tests directory:
|
|
58
|
+
```bash
|
|
59
|
+
# Create the file
|
|
60
|
+
cd packages/core/src/tests
|
|
61
|
+
touch .env.test
|
|
62
|
+
|
|
63
|
+
# Add the following content to .env.test:
|
|
64
|
+
echo 'TEST_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' > .env.test
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
3. Replace the example private key in `.env.test` with your actual test account private key:
|
|
68
|
+
- The private key must be a 0x-prefixed 64-character hex string
|
|
69
|
+
- The account must have enough ETH on the local hardhat network for transactions
|
|
70
|
+
- Never commit real private keys to version control
|
|
71
|
+
|
|
72
|
+
4. Verify your setup:
|
|
73
|
+
```bash
|
|
74
|
+
# Make sure you're in the core package directory
|
|
75
|
+
cd packages/core
|
|
76
|
+
|
|
77
|
+
# Check if .env.test exists and has the correct format
|
|
78
|
+
cat src/tests/.env.test
|
|
79
|
+
# Should show: TEST_PRIVATE_KEY=0x...
|
|
80
|
+
|
|
81
|
+
# Run the tests
|
|
82
|
+
pnpm test
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
If you see an error about `TEST_PRIVATE_KEY` not being set:
|
|
86
|
+
1. Double check that `.env.test` exists in `packages/core/src/tests` directory
|
|
87
|
+
2. Make sure the private key format is correct (0x-prefixed, 64 characters)
|
|
88
|
+
3. Try running the tests with the environment variable directly:
|
|
89
|
+
```bash
|
|
90
|
+
TEST_PRIVATE_KEY=0x1234... pnpm test
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Network Support
|
|
94
|
+
|
|
95
|
+
The SDK supports both Sei mainnet (pacific-1) and testnet (atlantic-2) networks. Network configurations are automatically handled through the `NETWORK_ENDPOINTS` constant:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { NETWORK_ENDPOINTS } from "@0xmonaco/core";
|
|
99
|
+
|
|
100
|
+
// Access network configurations by network name
|
|
101
|
+
const mainnetConfig = NETWORK_ENDPOINTS.mainnet; // Pacific-1 mainnet
|
|
102
|
+
const testnetConfig = NETWORK_ENDPOINTS.testnet; // Atlantic-2 testnet
|
|
103
|
+
|
|
104
|
+
// Each network config includes:
|
|
105
|
+
// - rpcUrl: RPC endpoint for the network
|
|
106
|
+
// - apiUrl: API gateway endpoint for the network
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Quick Start
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { MonacoSDK } from "@0xmonaco/core";
|
|
113
|
+
|
|
114
|
+
// Initialize the SDK with private key
|
|
115
|
+
const monaco = new MonacoSDK({
|
|
116
|
+
privateKey: "0x...", // Your private key
|
|
117
|
+
network: "mainnet", // or "testnet"
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// Vault Operations
|
|
121
|
+
async function vaultExample() {
|
|
122
|
+
// Check vault balance
|
|
123
|
+
const balance = await monaco.vault.getBalance("0x..."); // token address
|
|
124
|
+
console.log("Vault balance:", balance.formatted, balance.symbol);
|
|
125
|
+
|
|
126
|
+
// Check if approval is needed
|
|
127
|
+
const needsApproval = await monaco.vault.needsApproval("0x...", parseEther("100"));
|
|
128
|
+
if (needsApproval) {
|
|
129
|
+
// Approve vault to spend tokens
|
|
130
|
+
const approval = await monaco.vault.approve("0x...", parseEther("1000"));
|
|
131
|
+
console.log("Approval transaction:", approval.hash);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Deposit tokens
|
|
135
|
+
const result = await monaco.vault.deposit("0x...", parseEther("100"));
|
|
136
|
+
console.log("Deposit transaction:", result.hash);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Trading Operations
|
|
140
|
+
async function tradingExample() {
|
|
141
|
+
// Place a limit order
|
|
142
|
+
const order = await monaco.trading.placeLimitOrder(
|
|
143
|
+
"ETH-USDC", // market
|
|
144
|
+
"buy", // side
|
|
145
|
+
parseEther("1.0"), // size (1 ETH)
|
|
146
|
+
parseUnits("2000", 6) // price (2000 USDC)
|
|
147
|
+
);
|
|
148
|
+
console.log("Order placed:", order.orderId);
|
|
149
|
+
|
|
150
|
+
// Place a market order with slippage protection
|
|
151
|
+
const marketOrder = await monaco.trading.placeMarketOrder(
|
|
152
|
+
"ETH-USDC",
|
|
153
|
+
"sell",
|
|
154
|
+
parseEther("0.5"),
|
|
155
|
+
{ slippageToleranceBps: 50 } // 0.5% max slippage (50 basis points)
|
|
156
|
+
);
|
|
157
|
+
console.log("Market order placed:", marketOrder.orderId);
|
|
158
|
+
|
|
159
|
+
// Place a limit order with IOC time in force
|
|
160
|
+
const iocOrder = await monaco.trading.placeLimitOrder(
|
|
161
|
+
"ETH-USDC",
|
|
162
|
+
"buy",
|
|
163
|
+
parseEther("1.0"),
|
|
164
|
+
parseUnits("2000", 6),
|
|
165
|
+
{ timeInForce: "IOC" } // Immediate-or-Cancel
|
|
166
|
+
);
|
|
167
|
+
console.log("IOC order placed:", iocOrder.orderId);
|
|
168
|
+
|
|
169
|
+
// Get open orders
|
|
170
|
+
const openOrders = await monaco.trading.getOpenOrders({ market: "ETH-USDC" });
|
|
171
|
+
console.log("Open orders:", openOrders.length);
|
|
172
|
+
|
|
173
|
+
// Replace an order (cancel + new)
|
|
174
|
+
const replaceResult = await monaco.trading.replaceOrder("order-id", {
|
|
175
|
+
market: "ETH-USDC",
|
|
176
|
+
side: "buy",
|
|
177
|
+
size: parseEther("2.0"),
|
|
178
|
+
price: parseUnits("2100", 6),
|
|
179
|
+
type: "limit",
|
|
180
|
+
timeInForce: "FOK" // Fill-or-Kill
|
|
181
|
+
});
|
|
182
|
+
console.log("Order replaced:", replaceResult.orderId);
|
|
183
|
+
|
|
184
|
+
// Cancel an order
|
|
185
|
+
const cancelResult = await monaco.trading.cancelOrder("order-id");
|
|
186
|
+
console.log("Order cancelled:", cancelResult.status);
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## API Reference
|
|
191
|
+
|
|
192
|
+
### MonacoSDK
|
|
193
|
+
|
|
194
|
+
The main SDK class that provides access to all protocol features.
|
|
195
|
+
|
|
196
|
+
```typescript
|
|
197
|
+
class MonacoSDK {
|
|
198
|
+
readonly vault: VaultAPI;
|
|
199
|
+
readonly trading: TradingAPI;
|
|
200
|
+
readonly walletClient: WalletClient;
|
|
201
|
+
readonly publicClient: PublicClient;
|
|
202
|
+
|
|
203
|
+
constructor(config: SDKConfig);
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Configuration
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
interface SDKConfig {
|
|
211
|
+
/** Private key as hex string (0x-prefixed) */
|
|
212
|
+
privateKey?: Hex;
|
|
213
|
+
|
|
214
|
+
/** Viem Account for advanced account management */
|
|
215
|
+
signer?: PrivateKeyAccount;
|
|
216
|
+
|
|
217
|
+
/** Custom Account implementation (overrides privateKey/signer) */
|
|
218
|
+
account?: Account;
|
|
219
|
+
|
|
220
|
+
/** Optional network override (defaults to 'mainnet') */
|
|
221
|
+
network?: Network;
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Vault API
|
|
226
|
+
|
|
227
|
+
The vault API provides secure token management operations:
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
interface VaultAPI {
|
|
231
|
+
// Token approvals
|
|
232
|
+
approve(token: string, amount: bigint): Promise<TransactionResult>;
|
|
233
|
+
|
|
234
|
+
// Deposit and withdrawal
|
|
235
|
+
deposit(token: string, amount: bigint): Promise<TransactionResult>;
|
|
236
|
+
withdraw(token: string, amount: bigint): Promise<TransactionResult>;
|
|
237
|
+
|
|
238
|
+
// Balance and allowance queries
|
|
239
|
+
getBalance(token: string): Promise<Balance>;
|
|
240
|
+
getAllowance(token: string): Promise<bigint>;
|
|
241
|
+
needsApproval(token: string, amount: bigint): Promise<boolean>;
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Trading API
|
|
246
|
+
|
|
247
|
+
The trading API provides comprehensive order management with support for different execution policies:
|
|
248
|
+
|
|
249
|
+
#### Order Types and Execution Policies
|
|
250
|
+
|
|
251
|
+
- **Limit Orders**: Standard limit orders with optional `timeInForce` parameter
|
|
252
|
+
- `GTC` (Good Till Cancelled): Default behavior, order stays active until filled or cancelled
|
|
253
|
+
- `IOC` (Immediate or Cancel): Order fills what it can immediately, then cancels the rest
|
|
254
|
+
- `FOK` (Fill or Kill): Order must fill completely or not at all
|
|
255
|
+
|
|
256
|
+
- **Market Orders**: Immediate execution with optional slippage protection
|
|
257
|
+
- **Post-Only Orders**: Limit orders that never execute immediately, only add liquidity
|
|
258
|
+
|
|
259
|
+
#### Order Management
|
|
260
|
+
|
|
261
|
+
- **Replace Orders**: Cancel existing order and place a new one (atomic operation)
|
|
262
|
+
- **Cancel Orders**: Cancel any open order by ID
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
interface TradingAPI {
|
|
266
|
+
// Order placement
|
|
267
|
+
placeLimitOrder(market: string, side: OrderSide, size: bigint, price: bigint, options?: { timeInForce?: TimeInForce }): Promise<OrderResponse>;
|
|
268
|
+
placeMarketOrder(market: string, side: OrderSide, size: bigint, options?: { slippageToleranceBps?: number }): Promise<OrderResponse>;
|
|
269
|
+
placePostOnlyOrder(market: string, side: OrderSide, size: bigint, price: bigint): Promise<OrderResponse>;
|
|
270
|
+
|
|
271
|
+
// Order management
|
|
272
|
+
replaceOrder(originalOrderId: string, newOrder: { market: string; side: OrderSide; size: bigint; price?: bigint; type: OrderType; timeInForce?: TimeInForce }): Promise<OrderResponse>;
|
|
273
|
+
cancelOrder(orderId: string): Promise<CancelOrderResponse>;
|
|
274
|
+
|
|
275
|
+
// Position management
|
|
276
|
+
closePosition(market: string, options?: { maxSlippage?: number }): Promise<ClosePositionResponse>;
|
|
277
|
+
|
|
278
|
+
// Order queries
|
|
279
|
+
getOrder(orderId: string): Promise<Order>;
|
|
280
|
+
getOpenOrders(params?: GetOpenOrdersParams): Promise<Order[]>;
|
|
281
|
+
getOrderHistory(params: OrderHistoryParams): Promise<PaginatedOrders>;
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### Error Handling
|
|
286
|
+
|
|
287
|
+
The SDK uses structured error classes for comprehensive error handling:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
import { APIError, ContractError, TransactionError, OrderError } from "@0xmonaco/core";
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
await sdk.vault.deposit(token, amount);
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if (error instanceof ContractError) {
|
|
296
|
+
console.error("Contract error:", error.message);
|
|
297
|
+
console.error("Error code:", error.code);
|
|
298
|
+
} else if (error instanceof APIError) {
|
|
299
|
+
console.error("API error:", error.message);
|
|
300
|
+
console.error("Status:", error.status);
|
|
301
|
+
} else if (error instanceof TransactionError) {
|
|
302
|
+
console.error("Transaction error:", error.message);
|
|
303
|
+
} else if (error instanceof OrderError) {
|
|
304
|
+
console.error("Order error:", error.message);
|
|
305
|
+
console.error("Market:", error.market);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
**Error Types:**
|
|
311
|
+
- `APIError`: API request failures and communication errors
|
|
312
|
+
- `ContractError`: Smart contract operation errors
|
|
313
|
+
- `TransactionError`: Blockchain transaction errors
|
|
314
|
+
- `OrderError`: Trading order specific errors
|
|
315
|
+
- `InvalidConfigError`: Configuration validation errors
|
|
316
|
+
|
|
317
|
+
## Development
|
|
318
|
+
|
|
319
|
+
### Project Structure
|
|
320
|
+
|
|
321
|
+
```
|
|
322
|
+
packages/core/
|
|
323
|
+
├── src/ # Source code
|
|
324
|
+
│ ├── api/ # API implementations
|
|
325
|
+
│ │ ├── vault/ # Vault operations API
|
|
326
|
+
│ │ │ └── api.ts # Vault API implementation with comprehensive docs
|
|
327
|
+
│ │ └── trading/ # Trading operations API
|
|
328
|
+
│ │ └── api.ts # Trading API implementation with comprehensive docs
|
|
329
|
+
│ ├── chains.ts # Chain definitions (Sei mainnet/testnet)
|
|
330
|
+
│ ├── errors.ts # Error classes and codes
|
|
331
|
+
│ ├── networks.ts # Network endpoint configurations
|
|
332
|
+
│ ├── sdk.ts # Main SDK implementation
|
|
333
|
+
│ └── index.ts # Public API exports
|
|
334
|
+
├── tests/ # Test suite
|
|
335
|
+
├── dist/ # Compiled output
|
|
336
|
+
├── package.json # Package configuration
|
|
337
|
+
└── tsconfig.json # TypeScript configuration
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### Development Setup
|
|
341
|
+
|
|
342
|
+
1. Clone the repository:
|
|
343
|
+
```bash
|
|
344
|
+
git clone https://github.com/monaco-protocol/monaco-monorepo.git
|
|
345
|
+
cd monaco-monorepo
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
2. Install dependencies:
|
|
349
|
+
```bash
|
|
350
|
+
pnpm install
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
3. Build the package:
|
|
354
|
+
```bash
|
|
355
|
+
pnpm build --filter @0xmonaco/core
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
### Testing
|
|
359
|
+
|
|
360
|
+
Run the test suite:
|
|
361
|
+
```bash
|
|
362
|
+
pnpm test --filter @0xmonaco/core
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### Code Style
|
|
366
|
+
|
|
367
|
+
The project uses ESLint and Prettier for code formatting. Run the linter:
|
|
368
|
+
```bash
|
|
369
|
+
pnpm lint --filter @0xmonaco/core
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
## Security Features
|
|
373
|
+
|
|
374
|
+
### EIP-712 Intent Signatures
|
|
375
|
+
- **Type-safe signing**: Structured data with domain separation
|
|
376
|
+
- **Intent-based authorization**: Every action explicitly authorized
|
|
377
|
+
- **Nonce protection**: Prevents replay attacks
|
|
378
|
+
- **Domain validation**: Ensures signatures are valid for specific contracts
|
|
379
|
+
|
|
380
|
+
### API Gateway Integration
|
|
381
|
+
- **Secure communication**: TLS encryption for all API calls
|
|
382
|
+
- **Signature validation**: Backend validates all signed intents
|
|
383
|
+
- **Rate limiting**: Protection against abuse
|
|
384
|
+
- **Audit logging**: Complete transaction history
|
|
385
|
+
|
|
386
|
+
### On-chain Security
|
|
387
|
+
- **Smart contract validation**: All operations validated on-chain
|
|
388
|
+
- **Multi-signature support**: Advanced security for institutional users
|
|
389
|
+
- **Emergency stops**: Circuit breakers for critical situations
|
|
390
|
+
|
|
391
|
+
## Performance Considerations
|
|
392
|
+
|
|
393
|
+
- **Batch operations**: Efficient handling of multiple operations
|
|
394
|
+
- **Connection pooling**: Optimized API connections
|
|
395
|
+
- **Caching**: Smart caching of frequently accessed data
|
|
396
|
+
- **Async operations**: Non-blocking operations for better UX
|
|
397
|
+
|
|
398
|
+
## Contributing
|
|
399
|
+
|
|
400
|
+
We welcome contributions! Please see our [Contributing Guide](../../docs/contributing.mdx) for details.
|
|
401
|
+
|
|
402
|
+
### Development Workflow
|
|
403
|
+
1. Fork the repository
|
|
404
|
+
2. Create a feature branch
|
|
405
|
+
3. Make your changes
|
|
406
|
+
4. Add tests for new functionality
|
|
407
|
+
5. Ensure all tests pass
|
|
408
|
+
6. Submit a pull request
|
|
409
|
+
|
|
410
|
+
## License
|
|
411
|
+
|
|
412
|
+
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
|
|
413
|
+
|
|
414
|
+
## Support
|
|
415
|
+
|
|
416
|
+
For support, please:
|
|
417
|
+
|
|
418
|
+
- Open an issue on GitHub
|
|
419
|
+
- Join our [Discord community](https://discord.gg/monaco)
|
|
420
|
+
- Visit our [documentation site](https://docs.monaco.xyz)
|
|
421
|
+
- Check our [API documentation](../../docs/api-reference.mdx)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth API Implementation
|
|
3
|
+
*
|
|
4
|
+
* Handles authentication operations including challenge creation, signature verification,
|
|
5
|
+
* and backend authentication. All operations go through the API Gateway.
|
|
6
|
+
*
|
|
7
|
+
* This class provides a complete interface for authentication on the Monaco protocol,
|
|
8
|
+
* including frontend wallet authentication and backend service authentication.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* const authAPI = new AuthAPIImpl(walletClient, apiUrl, chain);
|
|
13
|
+
*
|
|
14
|
+
* // Complete authentication flow
|
|
15
|
+
* const authResult = await authAPI.authenticate(clientId);
|
|
16
|
+
*
|
|
17
|
+
* // Or step-by-step flow
|
|
18
|
+
* const challenge = await authAPI.createChallenge(userAddress, clientId);
|
|
19
|
+
* const signature = await authAPI.signChallenge(challenge.message);
|
|
20
|
+
* const authResult = await authAPI.verifySignature(
|
|
21
|
+
* userAddress,
|
|
22
|
+
* signature,
|
|
23
|
+
* challenge.nonce,
|
|
24
|
+
* clientId
|
|
25
|
+
* );
|
|
26
|
+
*
|
|
27
|
+
* // Authenticate backend service
|
|
28
|
+
* const backendAuth = await authAPI.authenticateBackend(secretKey);
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
import { type WalletClient, type Chain } from "viem";
|
|
32
|
+
import { type AuthAPI, type ChallengeResponse, type VerifyResponse, type BackendAuthResponse, type TokenRefreshResponse } from "@0xmonaco/types";
|
|
33
|
+
export declare class AuthAPIImpl implements AuthAPI {
|
|
34
|
+
private readonly walletClient;
|
|
35
|
+
private readonly apiUrl;
|
|
36
|
+
private readonly chain;
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new AuthAPI instance.
|
|
39
|
+
*
|
|
40
|
+
* @param walletClient - The viem wallet client for signing operations
|
|
41
|
+
* @param apiUrl - The base URL for the Monaco API Gateway
|
|
42
|
+
* @param chain - The blockchain network configuration
|
|
43
|
+
*/
|
|
44
|
+
constructor(walletClient: WalletClient, apiUrl: string, chain: Chain);
|
|
45
|
+
/**
|
|
46
|
+
* Complete authentication flow for frontend applications.
|
|
47
|
+
*
|
|
48
|
+
* This method handles the entire authentication process:
|
|
49
|
+
* 1. Creates a challenge
|
|
50
|
+
* 2. Signs the challenge message
|
|
51
|
+
* 3. Verifies the signature and returns JWT tokens
|
|
52
|
+
*
|
|
53
|
+
* @param clientId - Client ID of the application
|
|
54
|
+
* @returns Promise resolving to the verification response with JWT tokens
|
|
55
|
+
* @throws {APIError} When authentication fails
|
|
56
|
+
* @throws {InvalidConfigError} When wallet account is not available
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* // Complete authentication in one call
|
|
61
|
+
* const authResult = await authAPI.authenticate("my-app-client-id");
|
|
62
|
+
* console.log(`Access token: ${authResult.access_token}`);
|
|
63
|
+
* console.log(`User ID: ${authResult.user.id}`);
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
authenticate(clientId: string): Promise<VerifyResponse>;
|
|
67
|
+
/**
|
|
68
|
+
* Signs a challenge message using the wallet client.
|
|
69
|
+
*
|
|
70
|
+
* Signs the provided message using the wallet's private key.
|
|
71
|
+
* This is used in the authentication flow to prove ownership of the wallet.
|
|
72
|
+
*
|
|
73
|
+
* @param message - The message to sign
|
|
74
|
+
* @returns Promise resolving to the signature
|
|
75
|
+
* @throws {InvalidConfigError} When wallet account is not available
|
|
76
|
+
* @throws {APIError} When signing fails
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```typescript
|
|
80
|
+
* const challenge = await authAPI.createChallenge(address, clientId);
|
|
81
|
+
* const signature = await authAPI.signChallenge(challenge.message);
|
|
82
|
+
* console.log(`Signature: ${signature}`);
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
signChallenge(message: string): Promise<string>;
|
|
86
|
+
/**
|
|
87
|
+
* Creates a challenge for frontend authentication.
|
|
88
|
+
*
|
|
89
|
+
* Generates a unique nonce and message that the user must sign with their wallet.
|
|
90
|
+
* This is the first step in the authentication flow for frontend applications.
|
|
91
|
+
*
|
|
92
|
+
* @param address - Wallet address of the user
|
|
93
|
+
* @param clientId - Client ID of the application
|
|
94
|
+
* @returns Promise resolving to the challenge response
|
|
95
|
+
* @throws {APIError} When challenge creation fails
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```typescript
|
|
99
|
+
* const challenge = await authAPI.createChallenge(
|
|
100
|
+
* "0x1234...",
|
|
101
|
+
* "my-app-client-id"
|
|
102
|
+
* );
|
|
103
|
+
* console.log(`Challenge message: ${challenge.message}`);
|
|
104
|
+
* console.log(`Nonce: ${challenge.nonce}`);
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
createChallenge(address: string, clientId: string): Promise<ChallengeResponse>;
|
|
108
|
+
/**
|
|
109
|
+
* Verifies a signature for frontend authentication.
|
|
110
|
+
*
|
|
111
|
+
* Validates the signature against the challenge and returns JWT tokens for
|
|
112
|
+
* authenticated API access. This is the second step in the authentication flow.
|
|
113
|
+
*
|
|
114
|
+
* @param address - Wallet address of the user
|
|
115
|
+
* @param signature - Signature of the challenge message
|
|
116
|
+
* @param nonce - Nonce from the challenge response
|
|
117
|
+
* @param clientId - Client ID of the application
|
|
118
|
+
* @returns Promise resolving to the verification response with JWT tokens
|
|
119
|
+
* @throws {APIError} When signature verification fails
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* // First create a challenge
|
|
124
|
+
* const challenge = await authAPI.createChallenge(address, clientId);
|
|
125
|
+
*
|
|
126
|
+
* // User signs the challenge message with their wallet
|
|
127
|
+
* const signature = await wallet.signMessage(challenge.message);
|
|
128
|
+
*
|
|
129
|
+
* // Verify the signature and get tokens
|
|
130
|
+
* const authResult = await authAPI.verifySignature(
|
|
131
|
+
* address,
|
|
132
|
+
* signature,
|
|
133
|
+
* challenge.nonce,
|
|
134
|
+
* clientId
|
|
135
|
+
* );
|
|
136
|
+
*
|
|
137
|
+
* console.log(`Access token: ${authResult.accessToken}`);
|
|
138
|
+
* console.log(`User ID: ${authResult.user.id}`);
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
verifySignature(address: string, signature: string, nonce: string, clientId: string): Promise<VerifyResponse>;
|
|
142
|
+
/**
|
|
143
|
+
* Authenticates a backend service using a secret key.
|
|
144
|
+
*
|
|
145
|
+
* Returns JWT tokens for API access. This method is used for backend services
|
|
146
|
+
* that need to authenticate with the Monaco API Gateway.
|
|
147
|
+
*
|
|
148
|
+
* @param secretKey - Secret key of the application
|
|
149
|
+
* @returns Promise resolving to the backend auth response with JWT tokens
|
|
150
|
+
* @throws {APIError} When backend authentication fails
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```typescript
|
|
154
|
+
* const backendAuth = await authAPI.authenticateBackend("my-secret-key");
|
|
155
|
+
* console.log(`Backend access token: ${backendAuth.accessToken}`);
|
|
156
|
+
* console.log(`Application: ${backendAuth.application.name}`);
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
authenticateBackend(secretKey: string): Promise<BackendAuthResponse>;
|
|
160
|
+
/**
|
|
161
|
+
* Refreshes an access token using a refresh token.
|
|
162
|
+
*
|
|
163
|
+
* Obtains a new access token using a valid refresh token. This is useful for
|
|
164
|
+
* maintaining long-term authentication without requiring the user to sign
|
|
165
|
+
* a new challenge.
|
|
166
|
+
*
|
|
167
|
+
* @param refreshToken - The refresh token to use
|
|
168
|
+
* @returns Promise resolving to new access and refresh tokens
|
|
169
|
+
* @throws {APIError} When token refresh fails
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```typescript
|
|
173
|
+
* const newTokens = await authAPI.refreshToken(refreshToken);
|
|
174
|
+
* console.log(`New access token: ${newTokens.accessToken}`);
|
|
175
|
+
* console.log(`Expires at: ${new Date(newTokens.expiresAt * 1000)}`);
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
refreshToken(refreshToken: string): Promise<TokenRefreshResponse>;
|
|
179
|
+
/**
|
|
180
|
+
* Revokes a refresh token.
|
|
181
|
+
*
|
|
182
|
+
* Invalidates a refresh token, preventing it from being used to obtain
|
|
183
|
+
* new access tokens. This is useful for logout functionality or when
|
|
184
|
+
* a token has been compromised.
|
|
185
|
+
*
|
|
186
|
+
* @param refreshToken - The refresh token to revoke
|
|
187
|
+
* @returns Promise resolving when the token is revoked
|
|
188
|
+
* @throws {APIError} When token revocation fails
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```typescript
|
|
192
|
+
* await authAPI.revokeToken(refreshToken);
|
|
193
|
+
* console.log("Token revoked successfully");
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
revokeToken(refreshToken: string): Promise<void>;
|
|
197
|
+
}
|
|
198
|
+
//# sourceMappingURL=api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/api/auth/api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,KAAK,EAAE,MAAM,MAAM,CAAC;AACrD,OAAO,EACL,KAAK,OAAO,EACZ,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EAC1B,MAAM,iBAAiB,CAAC;AAGzB,qBAAa,WAAY,YAAW,OAAO;IASvC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAVxB;;;;;;OAMG;gBAEgB,YAAY,EAAE,YAAY,EAC1B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK;IAG/B;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAgC7D;;;;;;;;;;;;;;;;;OAiBG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA0BrD;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAqCpF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACG,eAAe,CACnB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,cAAc,CAAC;IA4C1B;;;;;;;;;;;;;;;;OAgBG;IACG,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAwC1E;;;;;;;;;;;;;;;;;OAiBG;IACG,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAkCvE;;;;;;;;;;;;;;;;OAgBG;IACG,WAAW,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CA2BvD"}
|