-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathassets.component.ts
More file actions
719 lines (614 loc) · 24.9 KB
/
assets.component.ts
File metadata and controls
719 lines (614 loc) · 24.9 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
import { Component, OnInit, OnDestroy, ChangeDetectorRef, ViewChild } from '@angular/core';
import { QubicAsset, AssetTransfer } from "../services/api.model";
import { ApiService } from "../services/api.service";
import { FormControl, FormGroup, Validators, FormBuilder, ValidatorFn, AbstractControl, ValidationErrors } from "@angular/forms";
import { WalletService } from '../services/wallet.service';
import { QubicTransferAssetPayload } from '@qubic-lib/qubic-ts-library/dist/qubic-types/transacion-payloads/QubicTransferAssetPayload';
import { QubicTransaction } from '@qubic-lib/qubic-ts-library/dist/qubic-types/QubicTransaction';
import { QubicDefinitions } from '@qubic-lib/qubic-ts-library/dist/QubicDefinitions';
import { lastValueFrom, Subject, combineLatest } from 'rxjs';
import { takeUntil, filter, distinctUntilChanged } from 'rxjs/operators';
import { MatDialog } from "@angular/material/dialog";
import { UpdaterService } from "../services/updater-service";
import { UnLockComponent } from '../lock/unlock/unlock.component';
import { TransactionService } from '../services/transaction.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TranslocoService } from '@ngneat/transloco';
import { PublicKey } from '@qubic-lib/qubic-ts-library/dist/qubic-types/PublicKey';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
import { Router } from '@angular/router';
import { DecimalPipe } from '@angular/common';
import { ApiLiveService } from '../services/apis/live/api.live.service';
import { shortenAddress } from '../utils/address.utils';
import { ExplorerUrlHelper } from '../services/explorer-url.helper';
import { QubicStaticService } from '../services/apis/static/qubic-static.service';
import { StaticSmartContract } from '../services/apis/static/qubic-static.model';
import { ASSET_TRANSFER_FEE, TRANSFER_SHARE_MANAGEMENT_RIGHTS_PROCEDURE } from '../constants/qubic.constants';
// Interfaces for asset grouping
interface GroupedAsset {
publicId: string;
assetName: string;
issuerIdentity: string;
totalAmount: number;
managingContracts: ManagingContract[];
}
import { QUBIC_ADDRESS_LENGTH } from '../constants/qubic.constants';
interface ManagingContract {
contractName: string;
contractIndex: number;
asset: QubicAsset;
}
/**
* Validator to check if the address is all uppercase
* Qubic addresses must be uppercase letters only
*/
function uppercaseValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null; // Don't validate empty values (required validator handles that)
}
const value = control.value as string;
const isUppercase = value === value.toUpperCase();
return isUppercase ? null : { notUppercase: true };
};
}
@Component({
selector: 'app-assets',
templateUrl: './assets.component.html',
styleUrls: ['./assets.component.scss']
})
export class AssetsComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
shortenAddress = shortenAddress;
displayedColumns: string[] = ['publicId', 'ownedAmount', 'managedBy', 'tick', 'actions'];
public assets: QubicAsset[] = [];
public groupedAssets: GroupedAsset[] = [];
public isExpanded: Map<string, boolean> = new Map();
public currentTick = 0;
public tickOverwrite = false;
// Asset transfer fee constant
public readonly assetTransferFee = ASSET_TRANSFER_FEE;
// Cache for smart contract lookups to avoid repeated array searches
private smartContractsMap: Map<number, StaticSmartContract> = new Map();
// Track whether smart contracts data has been loaded to prevent flickering
public smartContractsLoaded: boolean = false;
sendForm: FormGroup;
isAssetsLoading: boolean = false;
isSending: boolean = false;
showSendForm: boolean = false;
isTable: boolean = false;
public selectedAccountId = false;
private selectedDestinationId: any;
private destinationValidators = [Validators.required, uppercaseValidator(), Validators.minLength(QUBIC_ADDRESS_LENGTH), Validators.maxLength(QUBIC_ADDRESS_LENGTH)];
// Template transaction data for repeating transactions
private txTemplate: any;
private txAssetData: AssetTransfer | null = null;
private txSourceId: string | null = null;
private txDestId: string | null = null;
@ViewChild('selectedDestinationId', {
static: false
}) set selectedDestinationIdContent(content: any) {
if (content) { // initially setter gets called with undefined
this.selectedDestinationId = content;
}
}
constructor(
private apiService: ApiService,
public walletService: WalletService,
public transactionService: TransactionService,
private updaterService: UpdaterService,
private t: TranslocoService,
private _snackBar: MatSnackBar,
private dialog: MatDialog,
private router: Router,
private decimalPipe: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private apiLiveService: ApiLiveService,
private qubicStaticService: QubicStaticService
) {
if (!this.walletService.isWalletReady) {
this.router.navigate(['/public']); // Redirect to public page if not authenticated
}
var dashBoardStyle = localStorage.getItem("asset-grid");
this.isTable = dashBoardStyle == '0' ? true : false;
// Check if we're repeating an asset transfer transaction
const state = this.router.getCurrentNavigation()?.extras.state;
if (state && state['template']) {
// We have a template transaction to repeat
this.txTemplate = state['template'];
this.txAssetData = state['assetData'];
this.txSourceId = state['sourceId'];
this.txDestId = state['destId'];
}
this.sendForm = new FormGroup({
destinationAddress: new FormControl('', this.destinationValidators),
selectedDestinationId: new FormControl(''),
amount: new FormControl('', Validators.required),
tick: new FormControl('', Validators.required),
assetSelect: new FormControl('', Validators.required),
});
// Use combineLatest to wait for BOTH smart contracts AND wallet config
combineLatest([
this.qubicStaticService.smartContracts$.pipe(
filter(contracts => contracts !== null && contracts.length > 0)
),
this.walletService.onConfig
])
.pipe(takeUntil(this.destroy$))
.subscribe(([contracts, config]) => {
// Build smart contracts lookup map (only once per update)
this.smartContractsMap.clear();
contracts!.forEach(contract => {
this.smartContractsMap.set(contract.contractIndex, contract);
});
this.smartContractsLoaded = true;
// Update assets from wallet
const seeds = this.walletService.getSeeds().filter(p => !p.isOnlyWatch);
this.assets = seeds
.flatMap(m => m.assets)
.filter(f => f)
.map(m => <QubicAsset>m);
// Compute grouped assets only ONCE when both are ready
this.computeGroupedAssets();
});
// const amountControl = this.sendForm.get('amount');
const assetSelectControl = this.sendForm.get('assetSelect');
// todo: check, this causes a max stack call loop
// why is this needed?
// if (amountControl) {
// amountControl.valueChanges.subscribe(() => {
// // this.updateAmountValidator();
// });
// }
if (assetSelectControl) {
assetSelectControl.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.updateAmountValidator();
});
}
}
ngOnInit() {
this.loadAssets();
this.updaterService.currentTick
.pipe(takeUntil(this.destroy$))
.subscribe(tick => {
this.currentTick = tick;
this.sendForm.controls['tick'].addValidators(Validators.min(tick));
if (!this.tickOverwrite) {
this.sendForm.controls['tick'].setValue(tick + this.walletService.getSettings().tickAddition);
}
});
this.sendForm.get('assetSelect')?.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(s => {
if (s) {
if (this.sendForm.get('selectedDestinationId') == this.sendForm.get('assetSelect')) {
this.sendForm.controls['selectedDestinationId'].setValue(null);
}
}
});
this.sendForm.get('selectedDestinationId')?.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(s => {
if (s) {
if (!this.selectedAccountId) {
this.sendForm.controls['destinationAddress'].setValue(null);
} else {
this.sendForm.controls['destinationAddress'].setValue(s);
}
}
});
// Handle template transaction for repeating asset transfers
if (this.txTemplate) {
this.handleRepeatTransaction();
}
}
toggleTableView(event: MatSlideToggleChange) {
this.isTable = event.checked;
localStorage.setItem("asset-grid", this.isTable ? '0' : '1');
}
updateAmountValidator(): void {
const assetSelectControl = this.sendForm.get('assetSelect');
const amountControl = this.sendForm.get('amount');
if (assetSelectControl && amountControl) {
const selectedAsset = assetSelectControl.value;
const maxAmount = selectedAsset ? selectedAsset.ownedAmount : 0;
amountControl.setValidators([
Validators.required,
Validators.min(1),
Validators.max(maxAmount)
]);
amountControl.updateValueAndValidity();
}
}
refreshData(): void {
this.loadAssets(true);
}
loadAssets(force: boolean = false) {
if (force || this.assets.length <= 0) {
this.isAssetsLoading = true;
this.updaterService.forceLoadAssets((r) => {
this.isAssetsLoading = false;
});
// timeout because of unpropper handling in forceLoadAssets :()
window.setTimeout(() => {
this.isAssetsLoading = false;
}, 5000);
}
}
handleTickEdit(): void {
const currentTickValue = this.sendForm.controls['tick'].value;
if (currentTickValue < this.currentTick) {
this.sendForm.controls['tick'].setValue(this.currentTick + this.walletService.getSettings().tickAddition);
}
this.tickOverwrite = !this.tickOverwrite;
}
getSeedAlias(publicId: string) {
return this.walletService.getSeed(publicId)?.alias;
}
openIssuerIdentity(issuerIdentity: string): void {
window.open(ExplorerUrlHelper.getAddressUrl(issuerIdentity), '_blank');
}
getBalanceAfterFees(): number {
var balanceOfSelectedId = this.walletService.getSeed((<QubicAsset>this.sendForm.controls['assetSelect']?.value)?.publicId)?.balance ?? 0;
const balanceAfterFees = BigInt(balanceOfSelectedId) - BigInt(this.assetTransferFee);
return Number(balanceAfterFees);
}
openSendForm(selectedAsset?: QubicAsset): void {
this.showSendForm = true;
this.tickOverwrite = false;
this.sendForm.controls['tick'].setValue(this.currentTick + this.walletService.getSettings().tickAddition);
const assetSelectControl = this.sendForm.get('assetSelect');
if (assetSelectControl) {
if (selectedAsset) {
assetSelectControl.setValue(selectedAsset);
} else if (this.assets.length > 0) {
assetSelectControl.setValue(this.assets[0]);
}
this.updateAmountValidator();
}
}
/**
* Handle repeating an asset transfer transaction
* Pre-fills the send form with data from the template transaction
*/
handleRepeatTransaction(): void {
if (!this.txAssetData) {
// If we don't have parsed asset data (for non-archiver transactions),
// just open the form and let user fill it manually
this.openSendForm();
return;
}
// Find the matching asset from the user's assets
const assetName = this.txAssetData.assetName;
const sourceId = this.txSourceId;
const matchingAsset = this.assets.find(asset =>
asset.assetName === assetName && asset.publicId === sourceId
);
if (!matchingAsset) {
// Asset not found, show error message
this._snackBar.open(
this.t.translate('assetsComponent.messages.assetNotFound'),
this.t.translate('general.close'),
{ duration: 5000, panelClass: 'error' }
);
return;
}
// Open the send form with the matching asset
this.openSendForm(matchingAsset);
// Pre-fill the destination address and amount
if (this.txDestId) {
// Check if destination is one of the wallet's addresses
const destinationSeed = this.walletService.getSeeds().find(s => s.publicId === this.txDestId);
if (destinationSeed) {
// Destination is in the wallet - use address book mode
this.selectedAccountId = true;
this.sendForm.controls['selectedDestinationId'].addValidators([Validators.required]);
this.sendForm.controls['destinationAddress'].clearValidators();
this.sendForm.controls['destinationAddress'].updateValueAndValidity();
this.sendForm.controls['selectedDestinationId'].setValue(this.txDestId);
this.sendForm.controls['selectedDestinationId'].updateValueAndValidity();
} else {
// Destination is external - use manual entry mode
this.sendForm.controls['destinationAddress'].setValue(this.txDestId);
}
}
if (this.txAssetData.units) {
this.sendForm.controls['amount'].setValue(parseInt(this.txAssetData.units));
}
}
async onSubmitSendForm() {
if (this.sendForm.valid) {
// logic
this.isSending = true;
try {
await this.sendAsset();
} catch (er) {
console.error(er);
}
finally {
this.isSending = false;
}
}
}
cancelSendForm(): void {
this.showSendForm = false;
this.tickOverwrite = false;
this.sendForm.reset();
}
async sendAsset() {
// todo: form/input validation
// todo: create central transaction service to send transactions!!!!
// sample send asset function
const assetSelectControl = this.sendForm.get('assetSelect');
const amountControl = this.sendForm.get('amount');
const destinationAddressControl = this.sendForm.get('destinationAddress');
if (!assetSelectControl || !amountControl || !destinationAddressControl) {
// todo: error handling
return;
}
const sourceAsset = <QubicAsset>assetSelectControl.value;
const sourcePublicKey = sourceAsset.publicId; // must be the sender/owner of th easset
const assetName = sourceAsset.assetName; // must be the name of the asset to be transfered
const numberOfUnits = amountControl.value; // must be the number of units to be transfered
const targetAddress = new PublicKey(destinationAddressControl.value);
// verify target address
if (!(await targetAddress.verifyIdentity())) {
destinationAddressControl.setErrors({ invalidAddress: true });
this.isSending = false;
return;
}
let targetTick = this.sendForm.get("tick")?.value ?? 0;
// todo: think about if we want to let the user set a custom target tick
if (!this.tickOverwrite || targetTick == 0) {
const tickInfo = (await lastValueFrom(this.apiLiveService.getTickInfo())).tickInfo;
targetTick = tickInfo.tick + this.walletService.getSettings().tickAddition; // set tick to send tx
}
// load the seed from wallet service
const signSeed = await this.walletService.revealSeed(sourcePublicKey); // must be the seed to sign the transaction
const assetTransfer = new QubicTransferAssetPayload()
.setIssuer(sourceAsset.issuerIdentity)
.setNewOwnerAndPossessor(targetAddress)
.setAssetName(assetName)
.setNumberOfUnits(numberOfUnits);
// build and sign tx
const tx = new QubicTransaction().setSourcePublicKey(sourcePublicKey)
.setDestinationPublicKey(QubicDefinitions.QX_ADDRESS) // a transfer should go the QX SC
.setAmount(QubicDefinitions.QX_TRANSFER_ASSET_FEE)
.setTick(targetTick) // just a fake tick
.setInputType(QubicDefinitions.QX_TRANSFER_ASSET_INPUT_TYPE)
.setPayload(assetTransfer);
await tx.build(signSeed);
const publishResult = await this.transactionService.publishTransaction(tx);
if (publishResult && publishResult.success) {
this._snackBar.open(this.t.translate('paymentComponent.messages.storedForPropagation', { tick: this.decimalPipe.transform(tx.tick, '1.0-0') }), this.t.translate('general.close'), {
duration: 0,
});
this.showSendForm = false;
}
else {
this._snackBar.open(publishResult.message ?? this.t.translate('paymentComponent.messages.failedToSend'), this.t.translate('general.close'), {
duration: 10000,
panelClass: "error"
});
}
}
loadKey() {
const dialogRef = this.dialog.open(UnLockComponent, { restoreFocus: false });
}
getSeeds(isDestination = false) {
return this.walletService.getSeeds().filter(f => !f.isOnlyWatch && (!isDestination || f.publicId != this.sendForm.get('assetSelect')?.value?.publicId));
}
/**
* Compare function for mat-select to properly match assets by identity
* instead of object reference
*/
compareAssets(asset1: QubicAsset, asset2: QubicAsset): boolean {
return asset1 && asset2 && asset1.assetName === asset2.assetName && asset1.publicId === asset2.publicId;
}
getSelectedDestinationSeed() {
const publicId = this.sendForm.controls['selectedDestinationId'].value;
return this.getSeeds(true).find(s => s.publicId === publicId);
}
getSelectedAsset() {
return this.sendForm.controls['assetSelect'].value;
}
toggleDestinationSelect() {
this.selectedAccountId = !this.selectedAccountId;
this.changeDetectorRef?.detectChanges();
if (this.selectedAccountId) {
this.selectedDestinationId.open();
this.sendForm.get('selectedDestinationId')?.addValidators([Validators.required]);
this.sendForm.get('destinationAddress')?.clearValidators();
this.sendForm.get('destinationAddress')?.updateValueAndValidity();
this.sendForm.get('selectedDestinationId')?.updateValueAndValidity();
} else {
this.sendForm.get('destinationAddress')?.addValidators(this.destinationValidators);
this.sendForm.get('selectedDestinationId')?.clearAsyncValidators();
this.sendForm.get('destinationAddress')?.updateValueAndValidity();
this.sendForm.get('selectedDestinationId')?.updateValueAndValidity();
}
this.changeDetectorRef?.detectChanges();
}
/**
* Compute grouped assets by publicId + assetName + issuerIdentity
* Optimized with cached smart contract lookups
* Only computes if smart contracts data is loaded to prevent flickering
*/
computeGroupedAssets(): void {
// Wait for smart contracts to load before computing groups to prevent flickering
if (!this.smartContractsLoaded) {
this.groupedAssets = [];
return;
}
const grouped = new Map<string, GroupedAsset>();
this.assets.forEach(asset => {
// Create unique key for grouping: publicId + assetName + issuerIdentity
const key = `${asset.publicId}-${asset.assetName}-${asset.issuerIdentity}`;
if (!grouped.has(key)) {
grouped.set(key, {
publicId: asset.publicId,
assetName: asset.assetName,
issuerIdentity: asset.issuerIdentity,
totalAmount: 0,
managingContracts: []
});
}
const group = grouped.get(key)!;
group.totalAmount += asset.ownedAmount || 0;
// Group by contract - use cached Map lookup instead of array find
const contractIndex = asset.contractIndex || 0;
let managingContract = group.managingContracts.find((c: ManagingContract) => c.contractIndex === contractIndex);
if (!managingContract) {
// Fast O(1) lookup from the cached Map instead of O(n) array search
const smartContract = this.smartContractsMap.get(contractIndex);
// Use contract label if found, otherwise show index to indicate unknown contract
const contractName = smartContract?.label || (contractIndex > 0 ? `Contract ${contractIndex}` : '');
managingContract = {
contractName: contractName,
contractIndex: contractIndex,
asset: asset
};
group.managingContracts.push(managingContract);
}
});
// Sort managing contracts by number of units (highest first)
grouped.forEach(group => {
group.managingContracts.sort((a, b) => b.asset.ownedAmount - a.asset.ownedAmount);
});
this.groupedAssets = Array.from(grouped.values()).sort((a, b) =>
a.assetName.localeCompare(b.assetName, undefined, { sensitivity: 'base' })
);
}
/**
* Toggle the expanded state for a specific grouped asset
*/
toggleExpanded(groupKey: string): void {
const currentState = this.isExpanded.get(groupKey) || false;
this.isExpanded.set(groupKey, !currentState);
}
/**
* Check if a specific grouped asset is expanded
*/
isGroupExpanded(groupKey: string): boolean {
return this.isExpanded.get(groupKey) || false;
}
/**
* Get the unique key for a grouped asset
*/
getGroupKey(group: GroupedAsset): string {
return `${group.publicId}-${group.assetName}-${group.issuerIdentity}`;
}
/**
* Check if any managing contract in the group has a valid contract name
*/
hasContractNames(managingContracts: ManagingContract[]): boolean {
return managingContracts.some(mc => mc.contractName && mc.contractName.trim() !== '');
}
/**
* Calculate total owned amount across all managing contracts for a grouped asset
*/
getTotalOwnedAmount(group: GroupedAsset): number {
let total = 0;
group.managingContracts.forEach((mc: ManagingContract) => {
const asset = mc.asset;
if (asset.ownedAmount !== undefined && asset.ownedAmount !== null) {
total += asset.ownedAmount;
}
});
return total;
}
/**
* Calculate total possessed amount across all managing contracts for a grouped asset
*/
getTotalPossessedAmount(group: GroupedAsset): number {
let total = 0;
group.managingContracts.forEach((mc: ManagingContract) => {
const asset = mc.asset;
if (asset.possessedAmount !== undefined && asset.possessedAmount !== null) {
total += asset.possessedAmount;
}
});
return total;
}
/**
* Check if user can send this asset
* Only QX-managed assets can be transferred
* Balance validation is handled in the send form
*/
canSendAsset(asset: QubicAsset): boolean {
// Find contract by index and check if it's QX by comparing address
const contract = this.smartContractsMap.get(asset.contractIndex);
return contract?.address === QubicDefinitions.QX_ADDRESS;
}
/**
* Get only QX-managed assets that can be sent
*/
getQxAssets(): QubicAsset[] {
return this.assets.filter(asset => this.canSendAsset(asset));
}
/**
* Check if a grouped asset has any sendable assets
* (at least one asset in the group is QX-managed)
*/
canSendGroupedAsset(group: GroupedAsset): boolean {
// Check if any managing contract in this group can be sent
return group.managingContracts.some((mc: ManagingContract) =>
this.canSendAsset(mc.asset)
);
}
/**
* Get the QX-managed asset from a grouped asset
* Returns the asset managed by QX contract, or null if none found
*/
getQxManagedAsset(group: GroupedAsset): QubicAsset | null {
const qxContract = group.managingContracts.find((mc: ManagingContract) => {
const contract = this.smartContractsMap.get(mc.contractIndex);
return contract?.address === QubicDefinitions.QX_ADDRESS;
});
return qxContract?.asset ?? null;
}
/**
* Check if a grouped asset supports transfer rights
* Transfer rights are available for assets with balance > 0 in contracts that support it
* Dynamically checks based on procedure name from backend
*/
canTransferRights(group: GroupedAsset): boolean {
// Check if any managing contract in this group supports transfer rights
return group.managingContracts.some((mc: ManagingContract) => {
const contract = this.smartContractsMap.get(mc.contractIndex);
if (!contract) return false;
// Dynamically check if contract has the transfer rights procedure
const hasProcedure = contract.procedures.some(
p => p.name === TRANSFER_SHARE_MANAGEMENT_RIGHTS_PROCEDURE
);
// Must have procedure and positive balance
return hasProcedure && mc.asset.ownedAmount > 0;
});
}
/**
* Navigate to Transfer Rights form with first managing contract pre-selected
*/
openTransferRightsForm(group: GroupedAsset): void {
// Get the first managing contract
const firstContract = group.managingContracts[0];
if (firstContract) {
this.router.navigate(['/assets-area/transfer-rights'], {
queryParams: {
publicId: group.publicId,
assetName: group.assetName,
issuerIdentity: group.issuerIdentity,
contractIndex: firstContract.contractIndex
}
});
} else {
// Fallback if no managing contracts
this.router.navigate(['/assets-area/transfer-rights']);
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}