-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathArkController.cs
More file actions
4443 lines (3885 loc) · 196 KB
/
Copy pathArkController.cs
File metadata and controls
4443 lines (3885 loc) · 196 KB
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.HostedServices;
using BTCPayServer.Lightning;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.PayoutProcessors;
using BTCPayServer.Plugins.ArkPayServer.Data;
using BTCPayServer.Plugins.ArkPayServer.Exceptions;
using BTCPayServer.Plugins.ArkPayServer.Lightning;
using BTCPayServer.Plugins.ArkPayServer.Models;
using BTCPayServer.Plugins.ArkPayServer.Models.Api;
using BTCPayServer.Plugins.ArkPayServer.PaymentHandler;
using BTCPayServer.Plugins.ArkPayServer.Payouts.Ark;
using BTCPayServer.Plugins.ArkPayServer.Services;
using BTCPayServer.Plugins.ArkPayServer.Services.WalletLogger;
using BTCPayServer.Rating;
using BTCPayServer.Security;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NArk.Abstractions;
using NArk.Abstractions.Fees;
using NArk.Abstractions.Intents;
using NArk.Swaps.Boltz;
using NArk.Swaps.Boltz.Client;
using NArk.Core.Contracts;
using NArk.Hosting;
using NArk.Core.Services;
using NArk.Core.Transport;
using NArk.Abstractions.Blockchain;
using NArk.Abstractions.Contracts;
using NArk.Abstractions.Extensions;
using NArk.Abstractions.VTXOs;
using NArk.Swaps.Abstractions;
using NArk.Abstractions.Wallets;
using NArk.Swaps.Models;
using NArk.Storage.EfCore.Entities;
using NArk.Core.Wallet;
using LNURL;
using NBitcoin;
using NBitcoin.DataEncoders;
using NBitcoin.Scripting;
using NBitcoin.Secp256k1;
using ArkIntent = NArk.Abstractions.Intents.ArkIntent;
namespace BTCPayServer.Plugins.ArkPayServer.Controllers;
[Route("plugins/ark")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public class ArkController(
BoltzLimitsValidator? boltzLimitsValidator,
BoltzClient? boltzClient,
ArkNetworkConfig arkNetworkConfig,
IAuthorizationService authorizationService,
ArkPayoutHandler arkPayoutHandler,
StoreRepository storeRepository,
PaymentMethodHandlerDictionary paymentMethodHandlerDictionary,
IClientTransport clientTransport,
ArkOperatorHealthService arkOperatorHealth,
ArkadeSpendingService arkadeSpendingService,
ArkAutomatedPayoutSenderFactory payoutSenderFactory,
PayoutProcessorService payoutProcessorService,
PullPaymentHostedService pullPaymentHostedService,
EventAggregator eventAggregator,
IIntentGenerationService intentGenerationService,
IIntentStorage intentStorage,
IWalletProvider walletProvider,
ISpendingService arkadeSpender,
AssetMetadataService assetMetadataService,
AssetCurrencyRegistrar assetCurrencyRegistrar,
IFeeEstimator feeEstimator,
IContractService contractService,
IBitcoinBlockchain bitcoinTimeChainProvider,
VtxoSynchronizationService vtxoSyncService,
IContractStorage contractStorage,
ISwapStorage swapStorage,
IVtxoStorage vtxoStorage,
IWalletStorage walletStorage,
IDbContextFactory<ArkPluginDbContext> dbContextFactory,
IHttpClientFactory httpClientFactory,
BoardingUtxoSyncService boardingUtxoSyncService,
IWalletLogStore walletLogStore,
RecoveryStatusTracker recoveryStatusTracker,
IServiceProvider serviceProvider,
ILogger<ArkController> logger) : Controller
{
// Post-operation VTXO refresh only needs to catch updates since the operation
// started. A 5-minute buffer absorbs clock skew and batch-round latency while
// keeping the arkd indexer query bounded for wallets with lots of history.
private static readonly TimeSpan PostOpVtxoPollBuffer = TimeSpan.FromMinutes(5);
private static DateTimeOffset PostOpVtxoPollSince() => DateTimeOffset.UtcNow - PostOpVtxoPollBuffer;
[HttpGet("stores/{storeId}/initial-setup")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public IActionResult InitialSetup(string storeId)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
var config = GetConfig<ArkadePaymentMethodConfig>(ArkadePlugin.ArkadePaymentMethodId, store);
if (config?.WalletId == null)
{
return View(new InitialWalletSetupViewModel());
}
return RedirectToAction("StoreOverview", new { storeId });
}
[HttpPost("stores/{storeId}/initial-setup")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> InitialSetup(string storeId, InitialWalletSetupViewModel model)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
try
{
var walletSettings = await GetFromInputWallet(model.Wallet, model.Mode);
if (walletSettings.Wallet is not null)
{
try
{
var serverInfo = await clientTransport.GetServerInfoAsync(HttpContext.RequestAborted);
// Watch-only import: walletSettings.Wallet carries the
// account descriptor verbatim. Hand it to NArk's
// CreateWatchOnlyWallet helper (added in dotnet-sdk#107)
// which leaves Secret null on the resulting ArkWalletInfo
// so DefaultWalletProvider.GetSignerAsync returns null
// unless an IRemoteSignerTransport claims the wallet.
// The factory throws on an unparseable descriptor and the
// outer try/catch surfaces that to the form below.
var wallet = walletSettings.IsWatchOnlyDescriptor
? await WalletFactory.CreateWatchOnlyWallet(
walletSettings.Wallet,
destination: walletSettings.Destination,
serverInfo,
metadata: null,
HttpContext.RequestAborted)
: await WalletFactory.CreateWallet(
walletSettings.Wallet,
walletSettings.Destination,
serverInfo,
HttpContext.RequestAborted);
// Signer is automatically registered via WalletSaved event
await walletStorage.UpsertWallet(wallet, updateIfExists: true, HttpContext.RequestAborted);
if (wallet.WalletType == WalletType.SingleKey)
{
await contractService.DeriveContract(
wallet.Id,
NextContractPurpose.SendToSelf,
ContractActivityState.Active,
metadata: new Dictionary<string, string> { ["Source"] = "Default" },
cancellationToken: HttpContext.RequestAborted);
}
walletSettings = walletSettings with { WalletId = wallet.Id };
}
catch (Exception ex)
{
TempData[WellKnownTempData.ErrorMessage] = DescribeArkError(ex, "Could not update wallet");
return View(model);
}
}
// On import, recover the wallet in the background (off the request thread —
// a gap-limit scan polls arkd per index): discover contracts across derivation
// indices + server signers (incl. legacy/deprecated), restore swaps, finalize
// pending txs, resync funds, then sync boarding UTXOs.
StartBackgroundRecovery(walletSettings.WalletId!);
var config = new ArkadePaymentMethodConfig(walletSettings.WalletId!, walletSettings.IsOwnedByStore);
store.SetPaymentMethodConfig(paymentMethodHandlerDictionary[ArkadePlugin.ArkadePaymentMethodId], config);
// Set Arkade as the default payment method
store.SetDefaultPaymentId(ArkadePlugin.ArkadePaymentMethodId);
// Enable Lightning by default if not already configured. Skip watch-only wallets:
// Arkade-backed Lightning needs batch participation (signing), and without a paired
// remote signer the wallet would accept LN invoices at checkout but fail at
// settlement after the customer has already committed to paying. The merchant can
// still flip it on manually once a companion signer is paired.
var lightningPaymentMethodId = GetLightningPaymentMethod();
var existingLnConfig = store.GetPaymentMethodConfig<LightningPaymentMethodConfig>(lightningPaymentMethodId, paymentMethodHandlerDictionary);
if (existingLnConfig == null && !walletSettings.IsWatchOnlyDescriptor)
{
var lnurlPaymentMethodId = PaymentTypes.LNURL.GetPaymentMethodId("BTC");
var lnConfig = new LightningPaymentMethodConfig()
{
ConnectionString = $"type=arkade;wallet-id={config.WalletId}",
};
store.SetPaymentMethodConfig(paymentMethodHandlerDictionary[lightningPaymentMethodId], lnConfig);
store.SetPaymentMethodConfig(paymentMethodHandlerDictionary[lnurlPaymentMethodId], new LNURLPaymentMethodConfig
{
UseBech32Scheme = true,
LUD12Enabled = false
});
var blob = store.GetStoreBlob();
blob.SetExcluded(lightningPaymentMethodId, false);
blob.OnChainWithLnInvoiceFallback = true;
store.SetStoreBlob(blob);
}
await storeRepository.UpdateStore(store);
// If a new HD wallet was generated, redirect to seed backup page
if (walletSettings is { IsNewlyGeneratedWallet: true, Wallet: not null })
{
return this.RedirectToRecoverySeedBackup(new RecoverySeedBackupViewModel
{
ReturnUrl = Url.Action(nameof(StoreOverview), new { storeId }),
IsStored = true,
RequireConfirm = true,
CryptoCode = "ARK",
Mnemonic = walletSettings.Wallet
});
}
TempData[WellKnownTempData.SuccessMessage] = "Arkade payment method updated.";
return RedirectToAction(nameof(StoreOverview), new { storeId });
}
catch (Exception ex)
{
ModelState.AddModelError(nameof(model.Wallet), ex.Message);
return View(model);
}
}
/// <summary>
/// Starts unified wallet recovery for <paramref name="walletId"/> on a background
/// thread (a gap-limit scan polls arkd per index), tracking status for the overview.
/// Discovers contracts (incl. legacy deprecated-signer scripts) + the derivation
/// index, restores swaps, finalizes pending txs and resyncs offchain funds, then
/// syncs boarding (on-chain) UTXOs. <c>IWalletRecoveryService</c> is only registered
/// when swaps (Boltz) are configured; without it this degrades to a boarding-only sync.
/// </summary>
private void StartBackgroundRecovery(string walletId)
{
var recoveryService = serviceProvider.GetService<NArk.Swaps.Recovery.IWalletRecoveryService>();
_ = Task.Run(async () =>
{
try
{
recoveryStatusTracker.SetRunning(walletId);
var contractsRecovered = 0;
var swapsAudited = 0;
var fundsSynced = 0;
if (recoveryService is not null)
{
var report = await recoveryService.RecoverAsync(walletId, cancellationToken: CancellationToken.None);
contractsRecovered = report.ContractsRecovered;
swapsAudited = report.SwapAudit.Count;
fundsSynced = report.FundsScriptsSynced;
}
// Boarding (on-chain) UTXOs aren't covered by offchain recovery.
var boardingContracts = (await contractStorage.GetContracts(
walletIds: [walletId], cancellationToken: CancellationToken.None))
.Where(c => c.Type == ArkBoardingContract.ContractType).ToList();
if (boardingContracts.Count > 0)
await boardingUtxoSyncService.SyncAsync(boardingContracts, CancellationToken.None);
recoveryStatusTracker.SetCompleted(walletId,
recoveryService is not null ? contractsRecovered : boardingContracts.Count,
swapsAudited, fundsSynced);
}
catch (Exception ex)
{
recoveryStatusTracker.SetFailed(walletId, ex.Message);
logger.LogWarning(ex, "Background wallet recovery failed for wallet {WalletId}", walletId);
}
});
}
[HttpPost("stores/{storeId}/rescan")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Rescan(string storeId)
{
var (store, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
if (!config!.GeneratedByStore || string.IsNullOrEmpty(config.WalletId))
return RedirectWithError(nameof(StoreOverview),
"Rescan requires a store-managed wallet.", new { storeId });
StartBackgroundRecovery(config.WalletId);
return RedirectWithSuccess(nameof(StoreOverview),
"Wallet rescan started — contracts, funds and swaps will refresh shortly.", new { storeId });
}
[HttpGet("stores/{storeId}/overview")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> StoreOverview(CancellationToken cancellationToken)
{
var (store, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
var wallet = await walletStorage.GetWalletById(config!.WalletId!, cancellationToken);
var destination = wallet?.Destination;
// Get balances with error handling - indexer service may be unavailable
ArkBalancesViewModel? balances = null;
try
{
balances = await GetArkBalances(config.WalletId!, cancellationToken);
}
catch (Exception ex)
{
TempData[WellKnownTempData.ErrorMessage] = DescribeArkError(ex, "Unable to fetch balances");
}
var signerAvailable = await walletProvider.GetAddressProviderAsync(config.WalletId!, cancellationToken) != null;
// Get the default/active contract address
string? defaultAddress = null;
if (wallet?.WalletType == WalletType.SingleKey)
{
// SingleKey: compute the deterministic default address directly from the wallet key
var terms = await clientTransport.GetServerInfoAsync(cancellationToken);
var descriptor = OutputDescriptor.Parse(wallet.AccountDescriptor, terms.Network);
var defaultContract = new ArkPaymentContract(terms.SignerKey, terms.UnilateralExit, descriptor);
defaultAddress = defaultContract.GetArkAddress().ToString(terms.Network.ChainName == ChainName.Mainnet);
}
// Check Ark Operator connection
var (arkOperatorConnected, arkOperatorError) = await CheckServiceConnectionAsync(
ct => clientTransport.GetServerInfoAsync(ct), cancellationToken);
// Check Boltz connection and get cached limits
var (boltzConnected, boltzError, boltzLimits) = await GetBoltzConnectionStatusAsync(cancellationToken);
// Determine if user can manage private keys (spend/view keys)
// Allowed if: wallet was generated by this store OR user is server admin
var canManagePrivateKeys = config!.GeneratedByStore ||
(await authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded;
// Get recent VTXOs for the overview (latest 5, including spent)
IReadOnlyCollection<ArkVtxo> recentVtxos = [];
HashSet<OutPoint> spendableOutpoints = [];
Dictionary<string, ArkContractEntity> vtxoContracts = new();
var totalVtxoCount = 0;
try
{
var allCoins = await arkadeSpender.GetAvailableCoins(config.WalletId!, cancellationToken);
spendableOutpoints = allCoins.Select(c => c.Outpoint).ToHashSet();
var vtxos = await vtxoStorage.GetVtxos(
walletIds: [config.WalletId!],
includeSpent: true,
take: 5,
cancellationToken: cancellationToken);
recentVtxos = vtxos.ToList();
// Get total count (all VTXOs including spent)
var allVtxos = await vtxoStorage.GetVtxos(
walletIds: [config.WalletId!],
includeSpent: true,
cancellationToken: cancellationToken);
totalVtxoCount = allVtxos.Count();
// Get contract info for VTXOs
var vtxoScripts = recentVtxos.Select(v => v.Script).Distinct().ToArray();
var contracts = await contractStorage.GetContracts(
walletIds: [config.WalletId!],
scripts: vtxoScripts,
cancellationToken: cancellationToken);
vtxoContracts = contracts.ToDictionary(c => c.Script);
}
catch (Exception)
{
// Silently ignore - VTXOs section will show empty
}
// Get recent intents (latest 5)
IReadOnlyCollection<ArkIntent> recentIntents = [];
try
{
recentIntents = await intentStorage.GetIntents(
walletIds:[config.WalletId!], skip: 0, take: 5, states: [ArkIntentState.BatchInProgress, ArkIntentState.BatchSucceeded, ArkIntentState.WaitingForBatch, ArkIntentState.WaitingToSubmit], cancellationToken: cancellationToken);
}
catch (Exception)
{
// Silently ignore - intents section will show empty
}
// Get recent swaps (latest 5)
IReadOnlyCollection<NArk.Swaps.Models.ArkSwap> recentSwaps = [];
try
{
recentSwaps = await swapStorage.GetSwaps(
walletIds: [config.WalletId!], take: 5, status: [ArkSwapStatus.Pending , ArkSwapStatus.Settled], cancellationToken: cancellationToken);
}
catch (Exception)
{
// Silently ignore - swaps section will show empty
}
// Tracked assets (managed list) — Ticker/Name/Decimals are cached on
// the config, so the list renders without indexer round-trips.
var trackedAssetRows = config.Assets.Select(a => new TrackedAssetRow
{
AssetId = a.AssetId,
CurrencyCode = a.CurrencyCode,
Ticker = a.Ticker,
Name = a.Name,
Decimals = a.Decimals,
RateScript = a.RateScript,
Enabled = a.Enabled,
}).ToList();
return View(new StoreOverviewViewModel
{
StoreId = store!.Id,
IsDestinationSweepEnabled = destination is not null,
IsLightningEnabled = IsArkadeLightningEnabled(),
Balances = balances,
WalletId = config.WalletId,
Destination = destination,
SignerAvailable = signerAvailable,
DefaultAddress = defaultAddress,
AllowSubDustAmounts = config.AllowSubDustAmounts,
BoardingEnabled = config.BoardingEnabled,
MinBoardingAmountSats = config.MinBoardingAmountSats,
TrackedAssets = trackedAssetRows,
Wallet = wallet?.Secret,
WalletType = wallet?.WalletType ?? WalletType.SingleKey,
CanManagePrivateKeys = canManagePrivateKeys,
RecoveryStatus = config.WalletId is { } recoveryWalletId ? recoveryStatusTracker.Get(recoveryWalletId) : null,
ArkOperatorUrl = arkNetworkConfig.ArkUri,
ArkOperatorConnected = arkOperatorConnected,
ArkOperatorError = ArkOperatorAvailability.DescribeMessage(arkOperatorError),
BoltzUrl = arkNetworkConfig.BoltzUri,
BoltzConnected = boltzConnected,
BoltzError = boltzError,
BoltzReverseMinAmount = boltzLimits?.ReverseMinAmount,
BoltzReverseMaxAmount = boltzLimits?.ReverseMaxAmount,
BoltzReverseFeePercentage = boltzLimits?.ReverseFeePercentage,
BoltzReverseMinerFee = boltzLimits?.ReverseMinerFee,
BoltzSubmarineMinAmount = boltzLimits?.SubmarineMinAmount,
BoltzSubmarineMaxAmount = boltzLimits?.SubmarineMaxAmount,
BoltzSubmarineFeePercentage = boltzLimits?.SubmarineFeePercentage,
BoltzSubmarineMinerFee = boltzLimits?.SubmarineMinerFee,
RecentVtxos = recentVtxos,
SpendableOutpoints = spendableOutpoints,
VtxoContracts = vtxoContracts,
TotalVtxoCount = totalVtxoCount,
RecentIntents = recentIntents,
RecentSwaps = recentSwaps
});
}
[HttpGet("stores/{storeId}/wallet-log")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> DownloadWalletLog(string storeId)
{
var (_, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
var walletId = config!.WalletId!;
var stream = walletLogStore.OpenForRead(walletId);
if (stream is null)
{
TempData[WellKnownTempData.SuccessMessage] =
"No diagnostic log entries have been recorded for this wallet yet. " +
"Use the wallet (send / receive / sync) and try again.";
return RedirectToAction(nameof(StoreOverview), new { storeId });
}
var filename = $"arkade-wallet-{walletId}-{DateTime.UtcNow:yyyyMMddTHHmmssZ}.log";
return File(stream, "text/plain; charset=utf-8", filename);
}
[HttpPost("stores/{storeId}/show-private-key")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> ShowPrivateKey(string storeId)
{
var (store, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
var wallet = await walletStorage.GetWalletById(config!.WalletId);
if (wallet?.Secret == null)
return NotFound();
return this.RedirectToRecoverySeedBackup(new RecoverySeedBackupViewModel
{
ReturnUrl = Url.Action(nameof(StoreOverview), new { storeId }),
IsStored = true,
RequireConfirm = false,
CryptoCode = "ARK",
Mnemonic = wallet.Secret
});
}
/// <summary>
/// Receive page: shows existing manual receive address or prompts to generate one.
/// </summary>
[HttpGet("stores/{storeId}/receive")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Receive(string storeId, CancellationToken cancellationToken)
{
var (store, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
var model = new ArkReceiveViewModel();
try
{
var existingAddress = await FindManualReceiveAddress(config!.WalletId!, cancellationToken);
if (existingAddress != null)
model.Address = existingAddress;
var existingBoarding = await FindManualBoardingAddress(config.WalletId!, cancellationToken);
if (existingBoarding != null)
model.BoardingAddress = existingBoarding;
}
catch (Exception ex)
{
TempData[WellKnownTempData.ErrorMessage] = DescribeArkError(ex, "Failed to check receive address");
}
return View(model);
}
[HttpPost("stores/{storeId}/receive")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Receive(string storeId, string command, CancellationToken cancellationToken)
{
var (store, config, errorResult) = await ValidateStoreAndConfig();
if (errorResult != null) return errorResult;
try
{
var model = new ArkReceiveViewModel();
var terms = await clientTransport.GetServerInfoAsync(cancellationToken);
if (command == "generate-boarding-address")
{
var boardingContract = (ArkBoardingContract)await contractService.DeriveContract(
config!.WalletId!,
NextContractPurpose.Boarding,
ContractActivityState.AwaitingFundsBeforeDeactivate,
metadata: new Dictionary<string, string> { ["Source"] = "manual" },
cancellationToken: cancellationToken);
model.BoardingAddress = boardingContract.GetOnchainAddress(terms.Network).ToString();
// Preserve existing ark address if any
var existingAddress = await FindManualReceiveAddress(config.WalletId!, cancellationToken);
if (existingAddress != null) model.Address = existingAddress;
}
else
{
var contract = await contractService.DeriveContract(
config!.WalletId!,
NextContractPurpose.Receive,
ContractActivityState.AwaitingFundsBeforeDeactivate,
metadata: new Dictionary<string, string> { ["Source"] = "manual" },
cancellationToken: cancellationToken);
model.Address = contract.GetArkAddress().ToString(terms.Network.ChainName == ChainName.Mainnet);
// Preserve existing boarding address if any
var existingBoarding = await FindManualBoardingAddress(config.WalletId!, cancellationToken);
if (existingBoarding != null) model.BoardingAddress = existingBoarding;
}
return View(model);
}
catch (Exception ex)
{
TempData[WellKnownTempData.ErrorMessage] = DescribeArkError(ex, "Failed to generate address");
}
return RedirectToAction(nameof(Receive), new { storeId });
}
private async Task<string?> FindManualReceiveAddress(string walletId, CancellationToken cancellationToken)
{
var existingContracts = await contractStorage.GetContracts(
walletIds: [walletId],
isActive: true,
contractTypes: [ArkPaymentContract.ContractType],
cancellationToken: cancellationToken);
var manualContract = existingContracts
.FirstOrDefault(c =>
c.ActivityState == ContractActivityState.AwaitingFundsBeforeDeactivate &&
c.Metadata?.GetValueOrDefault("Source") == "manual");
if (manualContract == null) return null;
var terms = await clientTransport.GetServerInfoAsync(cancellationToken);
var script = Script.FromHex(manualContract.Script);
var serverKey = terms.SignerKey.Extract().XOnlyPubKey;
var arkAddr = ArkAddress.FromScriptPubKey(script, serverKey);
return arkAddr.ToString(terms.Network.ChainName == ChainName.Mainnet);
}
private async Task<string?> FindManualBoardingAddress(string walletId, CancellationToken cancellationToken)
{
var existingContracts = await contractStorage.GetContracts(
walletIds: [walletId],
isActive: true,
contractTypes: [ArkBoardingContract.ContractType],
cancellationToken: cancellationToken);
var boardingEntity = existingContracts
.FirstOrDefault(c =>
c.ActivityState == ContractActivityState.AwaitingFundsBeforeDeactivate &&
c.Metadata?.GetValueOrDefault("Source") is "manual" or "manual-boarding");
if (boardingEntity == null) return null;
var terms = await clientTransport.GetServerInfoAsync(cancellationToken);
var boardingContract = (ArkBoardingContract)ArkContractParser.Parse(boardingEntity.Type, boardingEntity.AdditionalData, terms.Network)!;
return boardingContract.GetOnchainAddress(terms.Network).ToString();
}
/// <summary>
/// Legacy redirect - SpendOverview now redirects to Send wizard.
/// </summary>
[HttpGet("stores/{storeId}/spend")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public IActionResult SpendOverview(string storeId, string[]? destinations, string? vtxoOutpoints)
{
// Convert old parameters to new format
var vtxos = vtxoOutpoints;
var destinationsParam = destinations != null && destinations.Length > 0
? string.Join(",", destinations)
: null;
return RedirectToAction(nameof(Send), new { storeId, vtxos, destinations = destinationsParam });
}
private async Task<IntentBuilderViewModel> BuildIntentBuilderViewModel(
string storeId,
string walletId,
string vtxoOutpointsRaw,
bool isIntent,
ArkBalancesViewModel balances,
CancellationToken token)
{
var model = new IntentBuilderViewModel
{
StoreId = storeId,
IsIntent = isIntent,
VtxoOutpointsRaw = vtxoOutpointsRaw,
Balances = balances,
LightningAvailable = true // TODO: Check if Lightning is configured
};
// Parse outpoints and load VTXO details
var outpointStrings = vtxoOutpointsRaw.Split(',', StringSplitOptions.RemoveEmptyEntries);
var parsedOutpoints = ParseOutpoints(outpointStrings);
var selectedVtxos = await vtxoStorage.GetVtxos(
outpoints: parsedOutpoints.ToList(),
walletIds: [walletId],
includeSpent: true,
cancellationToken: token);
foreach (var vtxo in selectedVtxos)
{
model.SelectedVtxos.Add(new SelectedVtxoViewModel
{
Outpoint = $"{vtxo.TransactionId}:{vtxo.TransactionOutputIndex}",
TransactionId = vtxo.TransactionId,
OutputIndex = vtxo.TransactionOutputIndex,
Amount = (long)vtxo.Amount,
ExpiresAt = vtxo.ExpiresAt,
IsRecoverable = vtxo.Swept,
CanSpendOffchain = !vtxo.IsSpent() && !vtxo.Swept
});
}
model.TotalSelectedAmount = model.SelectedVtxos.Sum(v => v.Amount);
return model;
}
[HttpPost("stores/{storeId}/spend")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> SpendOverview(SpendOverviewViewModel model, CancellationToken token)
{
if (string.IsNullOrWhiteSpace(model.Destination))
return BadRequest();
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
var disposableLock = default(IDisposable);
try
{
var payout = Uri.TryCreate(model.Destination, UriKind.Absolute, out var uriResult)
? uriResult.ParseQueryString().Get("payout")
: null;
if (!string.IsNullOrEmpty(payout))
{
disposableLock = await arkPayoutHandler.PayoutLocker.LockOrNullAsync(payout, 0, token);
if (disposableLock is null)
{
TempData[WellKnownTempData.ErrorMessage] = "Payment failed: the payout is locked";
return RedirectToAction(nameof(SpendOverview),
new {storeId = store.Id, destinations = model.PrefilledDestination});
}
}
var maybeProof = await arkadeSpendingService.Spend(store, model.Destination, token);
//check if destination is a uri and if it has a payout querystring, extract value
if (!string.IsNullOrEmpty(payout))
{
var proof = new ArkPayoutProof()
{
TransactionId = uint256.Parse(maybeProof),
DetectedInBackground = false
};
var result = await pullPaymentHostedService.MarkPaid(new MarkPayoutRequest()
{
PayoutId = payout,
Proof = arkPayoutHandler.SerializeProof(proof)
});
TempData[WellKnownTempData.SuccessMessage] =
$"Payment sent to {model.Destination} with payout {payout} result {result}";
}
else
{
TempData[WellKnownTempData.SuccessMessage] = $"Payment sent to {model.Destination}";
}
model.PrefilledDestination.Remove(model.Destination);
return RedirectToAction(nameof(SpendOverview),
new {storeId = store.Id, destinations = model.PrefilledDestination});
}
catch (IncompleteArkadeSetupException e)
{
TempData[WellKnownTempData.ErrorMessage] = "Payment failed: incomplete arkade setup!";
return RedirectToAction(nameof(InitialSetup), new {storeId = store.Id});
}
catch (MalformedPaymentDestination e)
{
TempData[WellKnownTempData.ErrorMessage] = "Payment failed: malfomed destination!";
return RedirectToAction(nameof(SpendOverview),
new {storeId = store.Id, destinations = model.PrefilledDestination});
}
catch (ArkadePaymentFailedException e)
{
TempData[WellKnownTempData.ErrorMessage] = DescribeArkError(e, "Payment failed: reason");
return RedirectToAction(nameof(SpendOverview),
new {storeId = store.Id, destinations = model.PrefilledDestination});
}
finally
{
if(disposableLock is not null)
{
disposableLock.Dispose();
}
}
}
[HttpPost("stores/{storeId}/build-intent")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> BuildIntent(string storeId, IntentBuilderViewModel model, CancellationToken token)
{
var (store, config, errorResult) = await ValidateStoreAndConfig(requireOwnedByStore: true);
if (errorResult != null) return errorResult;
// Get the selected coins
var outpointStrings = model.VtxoOutpointsRaw?.Split(',', StringSplitOptions.RemoveEmptyEntries) ?? [];
var selectedCoins = await GetCoinsForOutpoints(config!.WalletId!, outpointStrings.ToList(), token);
if (selectedCoins.Count == 0)
{
model.Errors.Add("No valid VTXOs selected.");
model.Balances = await GetArkBalances(config.WalletId!, token);
await ReloadSelectedVtxos(model, config.WalletId!, token);
return View("IntentBuilder", model);
}
var totalInputAmount = selectedCoins.Sum(c => c.TxOut.Value.Satoshi);
// Get valid outputs (non-empty destinations)
var validOutputs = model.Outputs.Where(o => !string.IsNullOrWhiteSpace(o.Destination)).ToList();
// Check for Lightning - only single output allowed
var lightningOutputs = validOutputs.Where(o =>
o.Destination.StartsWith("ln", StringComparison.OrdinalIgnoreCase) ||
o.Destination.StartsWith("lightning:", StringComparison.OrdinalIgnoreCase)).ToList();
if (lightningOutputs.Any() && validOutputs.Count > 1)
{
model.Errors.Add("Lightning payments only support a single output.");
model.Balances = await GetArkBalances(config!.WalletId!, token);
await ReloadSelectedVtxos(model, config.WalletId!, token);
return View("IntentBuilder", model);
}
try
{
// If single Lightning output, use existing spend flow
if (lightningOutputs.Count == 1)
{
var lnDestination = lightningOutputs[0].Destination
.Replace("lightning:", "", StringComparison.OrdinalIgnoreCase);
await arkadeSpendingService.Spend(store!, lnDestination, token);
TempData[WellKnownTempData.SuccessMessage] = "Lightning payment initiated successfully.";
return RedirectToAction(nameof(Vtxos), new { storeId });
}
// Build ArkTxOut array from outputs
var serverInfo = await clientTransport.GetServerInfoAsync(token);
var arkOutputs = new List<ArkTxOut>();
foreach (var output in validOutputs)
{
var parseResult = ParseOutputDestination(output, serverInfo.Network);
if (parseResult.Destination == null)
{
output.Error = "Invalid destination address.";
model.Errors.Add($"Invalid destination: {output.Destination}");
continue;
}
// Amount priority: destination-specified > user-specified > (single output: send all)
var outputAmount = parseResult.Amount ?? (output.AmountBtc.HasValue ? Money.Coins(output.AmountBtc.Value) : null);
if (outputAmount == null || outputAmount == Money.Zero)
{
if (validOutputs.Count == 1)
{
// Single output with no amount specified anywhere - send all
outputAmount = Money.Satoshis(totalInputAmount);
}
else
{
// Multi-output requires explicit amount
output.Error = "Amount is required.";
model.Errors.Add($"Amount is required for output: {output.Destination}");
continue;
}
}
// Output type is determined by address type:
// - Ark address = VTXO (offchain)
// - Bitcoin address = Onchain
arkOutputs.Add(new ArkTxOut(parseResult.OutputType, outputAmount, parseResult.Destination));
}
if (model.Errors.Any())
{
model.Balances = await GetArkBalances(config.WalletId!, token);
await ReloadSelectedVtxos(model, config.WalletId!, token);
return View("IntentBuilder", model);
}
// Execute the spend with selected coins
// If no outputs specified, SpendingService will send everything as change to self
var txId = await arkadeSpender.Spend(config.WalletId!, selectedCoins.ToArray(), arkOutputs.ToArray(), token);
// Poll for VTXO updates
var activeContracts = await contractStorage.GetContracts(walletIds: [config.WalletId!], isActive: true, cancellationToken: token);
await vtxoSyncService.PollScriptsForVtxos(activeContracts.Select(c => c.Script).ToHashSet(), PostOpVtxoPollSince(), token);
TempData[WellKnownTempData.SuccessMessage] = $"Successfully joined batch. Your VTXOs will be updated in the next round. Transaction ID: {txId}";
return RedirectToAction(nameof(StoreOverview), new { storeId });
}
catch (Exception ex)
{
model.Errors.Add($"Failed to build: {ex.Message}");
model.Balances = await GetArkBalances(config!.WalletId!, token);
await ReloadSelectedVtxos(model, config.WalletId!, token);
return View("IntentBuilder", model);
}
}
private (IDestination? Destination, Money? Amount, ArkTxOutType OutputType) ParseOutputDestination(SpendOutputViewModel output, Network network)
{
var destination = output.Destination.Trim();
// Try direct Ark address -> VTXO output
if (ArkAddress.TryParse(destination, out var arkAddress))
{
return (arkAddress, null, ArkTxOutType.Vtxo);
}
// Try direct Bitcoin address -> Onchain output
try
{
var btcAddress = BitcoinAddress.Create(destination, network);
return (btcAddress, null, ArkTxOutType.Onchain);
}
catch
{
// Not a valid Bitcoin address, continue
}
// Try BIP21 URI
if (Uri.TryCreate(destination, UriKind.Absolute, out var uri) &&
uri.Scheme.Equals("bitcoin", StringComparison.OrdinalIgnoreCase))
{
var host = uri.AbsoluteUri[(uri.Scheme.Length + 1)..].Split('?')[0];
var qs = uri.ParseQueryString();
// Check for ark parameter in query string -> VTXO output
if (qs["ark"] is { } arkQs && ArkAddress.TryParse(arkQs, out var qsArkAddress))
{
var amount = qs["amount"] is { } amountStr && decimal.TryParse(amountStr, System.Globalization.CultureInfo.InvariantCulture, out var amountDec)
? Money.Coins(amountDec)
: null;
return (qsArkAddress, amount, ArkTxOutType.Vtxo);
}
// Try host as Ark address -> VTXO output
if (ArkAddress.TryParse(host, out var hostArkAddress))
{
var amount = qs["amount"] is { } amountStr && decimal.TryParse(amountStr, System.Globalization.CultureInfo.InvariantCulture, out var amountDec)
? Money.Coins(amountDec)
: null;
return (hostArkAddress, amount, ArkTxOutType.Vtxo);
}
// Try host as Bitcoin address -> Onchain output
try
{
var btcAddress = BitcoinAddress.Create(host, network);
var amount = qs["amount"] is { } amountStr && decimal.TryParse(amountStr, System.Globalization.CultureInfo.InvariantCulture, out var amountDec)
? Money.Coins(amountDec)
: null;
return (btcAddress, amount, ArkTxOutType.Onchain);
}
catch
{
// Not a valid Bitcoin address
}
}
return (null, null, ArkTxOutType.Vtxo);
}
private async Task ReloadSelectedVtxos(IntentBuilderViewModel model, string walletId, CancellationToken token)
{
model.SelectedVtxos.Clear();
if (string.IsNullOrEmpty(model.VtxoOutpointsRaw)) return;
var outpointStrings = model.VtxoOutpointsRaw.Split(',', StringSplitOptions.RemoveEmptyEntries);
var parsedOutpoints = ParseOutpoints(outpointStrings);
var selectedVtxos = await vtxoStorage.GetVtxos(
outpoints: parsedOutpoints.ToList(),
walletIds: [walletId],
includeSpent: true,
cancellationToken: token);
foreach (var vtxo in selectedVtxos)
{
model.SelectedVtxos.Add(new SelectedVtxoViewModel
{
Outpoint = $"{vtxo.TransactionId}:{vtxo.TransactionOutputIndex}",
TransactionId = vtxo.TransactionId,
OutputIndex = vtxo.TransactionOutputIndex,
Amount = (long)vtxo.Amount,
ExpiresAt = vtxo.ExpiresAt,
IsRecoverable = vtxo.Swept,
CanSpendOffchain = !vtxo.IsSpent() && !vtxo.Swept
});
}
model.TotalSelectedAmount = model.SelectedVtxos.Sum(v => v.Amount);
}
[HttpPost("stores/{storeId}/estimate-fees")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> EstimateFees(string storeId, [FromBody] FeeEstimateRequest request, CancellationToken token)
{
var (store, config, errorResult) = await ValidateStoreAndConfig(requireOwnedByStore: true);
if (errorResult != null) return BadRequest("Invalid store configuration");
try
{