lightcone 0.7.1

Rust SDK for the Lightcone Protocol — unified native + WASM client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Admin sub-client — metadata, referral management, and on-chain admin operations.

use crate::client::LightconeClient;
use crate::domain::admin::{
    AdminLogEvent, AdminLogEventsQuery, AdminLogEventsResponse, AdminLogMetricHistoryQuery,
    AdminLogMetricHistoryResponse, AdminLogMetricsQuery, AdminLogMetricsResponse,
    AdminLoginRequest, AdminLoginResponse, AdminNonceResponse, AllocateCodesRequest,
    AllocateCodesResponse, CreateNotificationRequest, CreateNotificationResponse,
    DismissNotificationRequest, DismissNotificationResponse, ListCodesRequest, ListCodesResponse,
    ReferralConfig, RevokeRequest, RevokeResponse, UnifiedMetadataRequest, UnifiedMetadataResponse,
    UnrevokeRequest, UnrevokeResponse, UpdateCodeRequest, UpdateCodeResponse, UpdateConfigRequest,
    UploadMarketDeploymentAssetsRequest, UploadMarketDeploymentAssetsResponse, WhitelistRequest,
    WhitelistResponse,
};
use crate::error::SdkError;
use crate::http::RetryPolicy;
use crate::program::instructions;
#[cfg(feature = "solana-rpc")]
use crate::program::types::CreateMarketParams;
use crate::program::types::{
    ActivateMarketParams, AddDepositMintParams, ConditionalMetadataParams, CreateOrderbookParams,
    DepositAndSwapParams, MatchOrdersMultiParams, SetAuthorityParams, SetFeeReceiverParams,
    SetManagerParams, SetMarketFeesParams, SettleMarketParams, WhitelistDepositTokenParams,
};
use solana_instruction::Instruction;
use solana_pubkey::Pubkey;
use solana_transaction::Transaction;

pub struct Admin<'a> {
    pub(crate) client: &'a LightconeClient,
}

impl<'a> Admin<'a> {
    // ── Admin auth ─────────────────────────────────────────────────────

    /// Fetch admin login nonce and message to sign.
    pub async fn get_admin_nonce(&self) -> Result<AdminNonceResponse, SdkError> {
        let url = format!("{}/api/admin/nonce", self.client.http.base_url());
        self.client.http.get(&url, RetryPolicy::None).await
    }

    /// Admin login — verifies signature and stores session cookie for subsequent admin requests.
    /// On native, the HTTP client auto-captures the `admin_token` cookie from Set-Cookie headers.
    /// On WASM, the browser handles cookie storage automatically.
    pub async fn admin_login(
        &self,
        message: &str,
        signature_bs58: &str,
        pubkey_bytes: &[u8],
    ) -> Result<AdminLoginResponse, SdkError> {
        let url = format!("{}/api/admin/login", self.client.http.base_url());
        let request = AdminLoginRequest {
            message: message.to_string(),
            signature_bs58: signature_bs58.to_string(),
            pubkey_bytes: pubkey_bytes.to_vec(),
        };
        self.client
            .http
            .post(&url, &request, RetryPolicy::None)
            .await
    }

    /// Admin logout — attempts to clear the server-side cookie and always clears the internal token.
    pub async fn admin_logout(&self) -> Result<(), SdkError> {
        let url = format!("{}/api/admin/logout", self.client.http.base_url());
        let _ = self
            .client
            .http
            .admin_post::<serde_json::Value, _>(&url, &serde_json::json!({}), RetryPolicy::None)
            .await;
        self.client.http.clear_admin_token().await;
        Ok(())
    }

    // ── Admin API methods ──────────────────────────────────────────────

    pub async fn upsert_metadata(
        &self,
        request: &UnifiedMetadataRequest,
    ) -> Result<UnifiedMetadataResponse, SdkError> {
        let url = format!("{}/api/admin/metadata", self.client.http.base_url());
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    /// Upload banner/icon/outcome/token images and metadata for a newly created
    /// market, returning the uploaded URLs. Requires prior `admin_login()`.
    pub async fn upload_market_deployment_assets(
        &self,
        request: &UploadMarketDeploymentAssetsRequest,
    ) -> Result<UploadMarketDeploymentAssetsResponse, SdkError> {
        let url = format!(
            "{}/api/admin/metadata/upload-market-deployment-assets",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn allocate_codes(
        &self,
        request: &AllocateCodesRequest,
    ) -> Result<AllocateCodesResponse, SdkError> {
        let url = format!(
            "{}/api/admin/referral/allocate",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn whitelist(
        &self,
        request: &WhitelistRequest,
    ) -> Result<WhitelistResponse, SdkError> {
        let url = format!(
            "{}/api/admin/referral/whitelist",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn revoke(&self, request: &RevokeRequest) -> Result<RevokeResponse, SdkError> {
        let url = format!("{}/api/admin/referral/revoke", self.client.http.base_url());
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn unrevoke(&self, request: &UnrevokeRequest) -> Result<UnrevokeResponse, SdkError> {
        let url = format!(
            "{}/api/admin/referral/unrevoke",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn create_notification(
        &self,
        request: &CreateNotificationRequest,
    ) -> Result<CreateNotificationResponse, SdkError> {
        let url = format!("{}/api/admin/notifications", self.client.http.base_url());
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn dismiss_notification(
        &self,
        request: &DismissNotificationRequest,
    ) -> Result<DismissNotificationResponse, SdkError> {
        let url = format!(
            "{}/api/admin/notifications/dismiss",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    // ── Referral config / codes ────────────────────────────────────────

    /// Fetch the platform-wide referral configuration.
    ///
    /// Returns `default_code_count` (the number of codes allocated per new user)
    /// and `updated_at`. Requires prior `admin_login()`.
    pub async fn get_referral_config(&self) -> Result<ReferralConfig, SdkError> {
        let url = format!(
            "{}/api/admin/referral/config/get",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, &serde_json::json!({}), RetryPolicy::None)
            .await
    }

    /// Update the platform-wide referral configuration.
    ///
    /// A `None` field leaves the server value unchanged. Requires prior `admin_login()`.
    pub async fn update_referral_config(
        &self,
        request: &UpdateConfigRequest,
    ) -> Result<ReferralConfig, SdkError> {
        let url = format!(
            "{}/api/admin/referral/config/update",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    /// List referral codes with optional owner / batch / code filters.
    ///
    /// Pagination is offset/limit-based. Requires prior `admin_login()`.
    pub async fn list_referral_codes(
        &self,
        request: &ListCodesRequest,
    ) -> Result<ListCodesResponse, SdkError> {
        let url = format!("{}/api/admin/referral/codes", self.client.http.base_url());
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    /// Update the maximum redemption count for a referral code.
    ///
    /// Requires prior `admin_login()`.
    pub async fn update_referral_code(
        &self,
        request: &UpdateCodeRequest,
    ) -> Result<UpdateCodeResponse, SdkError> {
        let url = format!(
            "{}/api/admin/referral/codes/update",
            self.client.http.base_url()
        );
        self.client
            .http
            .admin_post(&url, request, RetryPolicy::None)
            .await
    }

    // ── Admin logs ─────────────────────────────────────────────────────

    /// List structured log events with optional filters.
    ///
    /// Pagination is cursor-based; pass the `next_cursor` from a previous
    /// response to continue. Requires prior `admin_login()`.
    pub async fn list_log_events(
        &self,
        query: &AdminLogEventsQuery,
    ) -> Result<AdminLogEventsResponse, SdkError> {
        let mut url = format!("{}/api/admin/logs/events", self.client.http.base_url());
        if let Ok(qs) = serde_urlencoded::to_string(query) {
            if !qs.is_empty() {
                url = format!("{}?{}", url, qs);
            }
        }
        self.client
            .http
            .admin_get(&url, RetryPolicy::Idempotent)
            .await
    }

    /// Fetch a single log event by its `public_id`.
    ///
    /// Requires prior `admin_login()`.
    pub async fn get_log_event(&self, public_id: &str) -> Result<AdminLogEvent, SdkError> {
        let url = format!(
            "{}/api/admin/logs/events/{}",
            self.client.http.base_url(),
            urlencoding::encode(public_id)
        );
        self.client
            .http
            .admin_get(&url, RetryPolicy::Idempotent)
            .await
    }

    /// Fetch rolled-up log metrics broken down by window and scope.
    ///
    /// Requires prior `admin_login()`.
    pub async fn log_metrics(
        &self,
        query: &AdminLogMetricsQuery,
    ) -> Result<AdminLogMetricsResponse, SdkError> {
        let mut url = format!("{}/api/admin/logs/metrics", self.client.http.base_url());
        if let Ok(qs) = serde_urlencoded::to_string(query) {
            if !qs.is_empty() {
                url = format!("{}?{}", url, qs);
            }
        }
        self.client
            .http
            .admin_get(&url, RetryPolicy::Idempotent)
            .await
    }

    /// Fetch the history (bucketed time-series) of log metrics for a given scope.
    ///
    /// Requires prior `admin_login()`.
    pub async fn log_metric_history(
        &self,
        query: &AdminLogMetricHistoryQuery,
    ) -> Result<AdminLogMetricHistoryResponse, SdkError> {
        let mut url = format!(
            "{}/api/admin/logs/metrics/history",
            self.client.http.base_url()
        );
        if let Ok(qs) = serde_urlencoded::to_string(query) {
            if !qs.is_empty() {
                url = format!("{}?{}", url, qs);
            }
        }
        self.client
            .http
            .admin_get(&url, RetryPolicy::Idempotent)
            .await
    }

    // ── On-chain instruction builders ───────────────────────────────────

    /// Build Initialize instruction.
    pub fn initialize_ix(&self, authority: &Pubkey) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_initialize_ix(authority, pid)
    }

    /// Build Initialize transaction.
    pub fn initialize_tx(&self, authority: &Pubkey) -> Result<Transaction, SdkError> {
        let ix = self.initialize_ix(authority);
        Ok(Transaction::new_with_payer(&[ix], Some(authority)))
    }

    /// Build CreateMarket instruction.
    ///
    /// Async because it fetches the next market ID from on-chain state.
    #[cfg(feature = "solana-rpc")]
    pub async fn create_market_ix(
        &self,
        params: CreateMarketParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        let rpc = crate::rpc::resolve_solana_rpc(self.client).await?;
        let (exchange_pda, _) = crate::program::pda::get_exchange_pda(pid);
        let account = rpc.get_account(&exchange_pda).await.map_err(|e| {
            crate::program::error::SdkError::AccountNotFound(format!("Exchange: {}", e))
        })?;
        let exchange = crate::program::accounts::Exchange::deserialize(&account.data)?;
        let market_id = exchange.market_count;
        Ok(instructions::build_create_market_ix(
            &params, market_id, pid,
        )?)
    }

    /// Build CreateMarket transaction.
    ///
    /// Async because it fetches the next market ID from on-chain state.
    #[cfg(feature = "solana-rpc")]
    pub async fn create_market_tx(
        &self,
        params: CreateMarketParams,
    ) -> Result<Transaction, SdkError> {
        let manager = params.manager;
        let ix = self.create_market_ix(params).await?;
        Ok(Transaction::new_with_payer(&[ix], Some(&manager)))
    }

    /// Build AddDepositMint instruction.
    pub fn add_deposit_mint_ix(
        &self,
        params: &AddDepositMintParams,
        market: &Pubkey,
        num_outcomes: u8,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_add_deposit_mint_ix(
            params,
            market,
            num_outcomes,
            pid,
        )?)
    }

    /// Build AddDepositMint transaction.
    pub fn add_deposit_mint_tx(
        &self,
        params: AddDepositMintParams,
        market: &Pubkey,
        num_outcomes: u8,
    ) -> Result<Transaction, SdkError> {
        let ix = self.add_deposit_mint_ix(&params, market, num_outcomes)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&params.manager)))
    }

    /// Build ActivateMarket instruction.
    pub fn activate_market_ix(&self, params: &ActivateMarketParams) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_activate_market_ix(params, pid)
    }

    /// Build ActivateMarket transaction.
    pub fn activate_market_tx(
        &self,
        params: ActivateMarketParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.activate_market_ix(&params);
        Ok(Transaction::new_with_payer(&[ix], Some(&params.manager)))
    }

    /// Build SettleMarket instruction.
    pub fn settle_market_ix(&self, params: &SettleMarketParams) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_settle_market_ix(params, pid)?)
    }

    /// Build SettleMarket transaction.
    pub fn settle_market_tx(&self, params: SettleMarketParams) -> Result<Transaction, SdkError> {
        let ix = self.settle_market_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&params.oracle)))
    }

    /// Build SetPaused instruction.
    pub fn set_paused_ix(&self, authority: &Pubkey, paused: bool) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_set_paused_ix(authority, paused, pid)
    }

    /// Build SetPaused transaction.
    pub fn set_paused_tx(&self, authority: &Pubkey, paused: bool) -> Result<Transaction, SdkError> {
        let ix = self.set_paused_ix(authority, paused);
        Ok(Transaction::new_with_payer(&[ix], Some(authority)))
    }

    /// Build SetOperator instruction.
    pub fn set_operator_ix(&self, authority: &Pubkey, new_operator: &Pubkey) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_set_operator_ix(authority, new_operator, pid)
    }

    /// Build SetOperator transaction.
    pub fn set_operator_tx(
        &self,
        authority: &Pubkey,
        new_operator: &Pubkey,
    ) -> Result<Transaction, SdkError> {
        let ix = self.set_operator_ix(authority, new_operator);
        Ok(Transaction::new_with_payer(&[ix], Some(authority)))
    }

    /// Build SetAuthority instruction.
    pub fn set_authority_ix(&self, params: &SetAuthorityParams) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_set_authority_ix(params, pid)
    }

    /// Build SetAuthority transaction.
    pub fn set_authority_tx(&self, params: SetAuthorityParams) -> Result<Transaction, SdkError> {
        let ix = self.set_authority_ix(&params);
        Ok(Transaction::new_with_payer(
            &[ix],
            Some(&params.current_authority),
        ))
    }

    /// Build SetManager instruction.
    pub fn set_manager_ix(&self, params: &SetManagerParams) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_set_manager_ix(params, pid)
    }

    /// Build SetManager transaction.
    pub fn set_manager_tx(&self, params: SetManagerParams) -> Result<Transaction, SdkError> {
        let ix = self.set_manager_ix(&params);
        Ok(Transaction::new_with_payer(&[ix], Some(&params.authority)))
    }

    /// Build SetMarketFees instruction.
    pub fn set_market_fees_ix(
        &self,
        params: &SetMarketFeesParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_set_market_fees_ix(params, pid)?)
    }

    /// Build SetMarketFees transaction.
    pub fn set_market_fees_tx(&self, params: SetMarketFeesParams) -> Result<Transaction, SdkError> {
        let payer = params.manager;
        let ix = self.set_market_fees_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&payer)))
    }

    /// Build SetFeeReceiver instruction.
    pub fn set_fee_receiver_ix(
        &self,
        params: &SetFeeReceiverParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_set_fee_receiver_ix(params, pid)?)
    }

    /// Build SetFeeReceiver transaction.
    pub fn set_fee_receiver_tx(
        &self,
        params: SetFeeReceiverParams,
    ) -> Result<Transaction, SdkError> {
        let payer = params.authority;
        let ix = self.set_fee_receiver_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&payer)))
    }

    /// Build WhitelistDepositToken instruction.
    pub fn whitelist_deposit_token_ix(&self, params: &WhitelistDepositTokenParams) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_whitelist_deposit_token_ix(params, pid)
    }

    /// Build WhitelistDepositToken transaction.
    pub fn whitelist_deposit_token_tx(
        &self,
        params: WhitelistDepositTokenParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.whitelist_deposit_token_ix(&params);
        Ok(Transaction::new_with_payer(&[ix], Some(&params.authority)))
    }

    /// Build CreateConditionalMetadata instruction.
    pub fn create_conditional_metadata_ix(
        &self,
        params: &ConditionalMetadataParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_create_conditional_metadata_ix(
            params, pid,
        )?)
    }

    /// Build CreateConditionalMetadata transaction.
    pub fn create_conditional_metadata_tx(
        &self,
        params: ConditionalMetadataParams,
    ) -> Result<Transaction, SdkError> {
        let payer = params.manager;
        let ix = self.create_conditional_metadata_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&payer)))
    }

    /// Build UpdateConditionalMetadata instruction.
    pub fn update_conditional_metadata_ix(
        &self,
        params: &ConditionalMetadataParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_update_conditional_metadata_ix(
            params, pid,
        )?)
    }

    /// Build UpdateConditionalMetadata transaction.
    pub fn update_conditional_metadata_tx(
        &self,
        params: ConditionalMetadataParams,
    ) -> Result<Transaction, SdkError> {
        let payer = params.manager;
        let ix = self.update_conditional_metadata_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&payer)))
    }

    /// Build CreateOrderbook instruction.
    pub fn create_orderbook_ix(
        &self,
        params: &CreateOrderbookParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_create_orderbook_ix(params, pid)?)
    }

    /// Build CreateOrderbook transaction.
    pub fn create_orderbook_tx(
        &self,
        params: CreateOrderbookParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.create_orderbook_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&params.manager)))
    }

    /// Build MatchOrdersMulti instruction.
    pub fn match_orders_multi_ix(
        &self,
        params: &MatchOrdersMultiParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_match_orders_multi_ix(params, pid)?)
    }

    /// Build MatchOrdersMulti transaction.
    pub fn match_orders_multi_tx(
        &self,
        params: MatchOrdersMultiParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.match_orders_multi_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&params.operator)))
    }

    /// Build DepositAndSwap instruction.
    pub fn deposit_and_swap_ix(
        &self,
        params: &DepositAndSwapParams,
    ) -> Result<Instruction, SdkError> {
        let pid = &self.client.program_id;
        Ok(instructions::build_deposit_and_swap_ix(params, pid)?)
    }

    /// Build DepositAndSwap transaction.
    pub fn deposit_and_swap_tx(
        &self,
        params: DepositAndSwapParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.deposit_and_swap_ix(&params)?;
        Ok(Transaction::new_with_payer(&[ix], Some(&params.operator)))
    }
}