@le-space/browser 0.1.38 → 0.1.42

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.
Files changed (4) hide show
  1. package/README.md +21 -7
  2. package/index.d.ts +77 -1
  3. package/index.js +172 -0
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @le-space/browser
2
2
 
3
- This package is the planned browser/PWA-facing layer for reusable Aleph
3
+ This package is the browser/PWA-facing shared layer for reusable Aleph
4
4
  deployment primitives.
5
5
 
6
6
  It is intended to sit between:
@@ -9,8 +9,8 @@ It is intended to sit between:
9
9
  - `@le-space/rootfs`
10
10
  - browser applications such as deployment PWAs
11
11
 
12
- The package should stay UI-neutral. It should provide browser-safe helpers, but
13
- it should not own app-specific Svelte state, prepaid product logic, or wallet
12
+ The package should stay UI-neutral. It provides browser-safe helpers, but it
13
+ does not own app-specific Svelte state, prepaid enforcement policy, or wallet
14
14
  UX.
15
15
 
16
16
  ## Client Surface
@@ -37,9 +37,16 @@ Lower-level helper functions remain exported too, but new extractions should
37
37
  prefer hanging reusable behavior off the client surface unless there is a good
38
38
  reason to keep them as standalone utilities.
39
39
 
40
+ The package also exports lower-level browser/EVM helpers for:
41
+
42
+ - `ethCall`
43
+ - `sendTransaction`
44
+ - `personalSign`
45
+ - prepaid vault reads and transaction helpers
46
+
40
47
  ## Planned v1 Scope
41
48
 
42
- The first real extraction wave should cover:
49
+ The package currently covers:
43
50
 
44
51
  - `http.ts`
45
52
  - `fetchWithTimeout`
@@ -47,23 +54,30 @@ The first real extraction wave should cover:
47
54
  - balance fetch
48
55
  - CRN fetch
49
56
  - instance listing
50
- - typed browser client factory
51
57
  - Aleph message broadcast helpers
52
58
  - deployment polling and result inspection
53
- - runtime detail inspection
59
+ - scheduler and CRN runtime lookup helpers
60
+ - `client.ts`
61
+ - typed browser client factory
54
62
  - `rootfs.ts`
55
63
  - RootFS manifest load
56
64
  - RootFS existence check
57
65
  - RootFS reference resolution
58
66
  - `pricing.ts`
59
67
  - instance pricing fetch and parse helpers
68
+ - `evm.ts`
69
+ - `ethCall`
70
+ - `sendTransaction`
71
+ - `personalSign`
72
+ - `prepaid.ts`
73
+ - reusable prepaid vault protocol helpers
60
74
 
61
75
  ## Not In Scope Initially
62
76
 
63
77
  These should remain local to apps until the browser package has a stable base:
64
78
 
65
79
  - wallet-provider integrations
66
- - prepaid vault flows
80
+ - prepaid enforcement policy and wallet UX
67
81
  - UI-only formatting helpers
68
82
  - Svelte state orchestration
69
83
 
package/index.d.ts CHANGED
@@ -16,6 +16,33 @@ interface EthereumTransactionRequest {
16
16
  data?: `0x${string}`;
17
17
  value?: bigint;
18
18
  }
19
+ type PaymentChain = 'BASE' | 'AVAX' | 'ETH';
20
+ interface EvmChainConfig {
21
+ alephChain: PaymentChain;
22
+ chainIdHex: `0x${string}`;
23
+ chainName: string;
24
+ rpcUrls: string[];
25
+ blockExplorerUrls: string[];
26
+ nativeCurrency: {
27
+ name: string;
28
+ symbol: string;
29
+ decimals: number;
30
+ };
31
+ }
32
+ interface PrepaidReservation {
33
+ intentHash: string;
34
+ ownerAddress: string;
35
+ reservedAmount: bigint;
36
+ expiresAt: number;
37
+ consumed: boolean;
38
+ expired: boolean;
39
+ }
40
+ interface PrepaidVaultSnapshot {
41
+ totalDeposited: bigint;
42
+ availableBalance: bigint;
43
+ reservedBalance: bigint;
44
+ currentReservation: PrepaidReservation | null;
45
+ }
19
46
  type MessageStatus = 'processed' | 'pending' | 'rejected' | 'unknown';
20
47
  type ReferenceStatus = MessageStatus | 'missing';
21
48
  type AlephSenderChain = 'ETH';
@@ -392,6 +419,55 @@ declare function ethCall(to: string, data: `0x${string}`, provider: EthereumProv
392
419
  declare function sendTransaction(tx: EthereumTransactionRequest, provider: EthereumProviderLike | null | undefined): Promise<string>;
393
420
  declare function personalSign(address: string, message: string, provider: EthereumProviderLike | null | undefined): Promise<string>;
394
421
 
422
+ declare function paymentChainFromChainId(chainId: string | null, chainConfig: Record<PaymentChain, EvmChainConfig>): PaymentChain | null;
423
+ declare function formatBudgetUnits(value: bigint, decimals?: number): number;
424
+ declare function loadPrepaidReservation(args: {
425
+ ownerAddress: string;
426
+ intentHash: string;
427
+ vaultAddress: string;
428
+ provider: EthereumProviderLike | null | undefined;
429
+ }): Promise<PrepaidReservation | null>;
430
+ declare function loadPrepaidVaultSnapshot(args: {
431
+ ownerAddress: string;
432
+ currentIntentHash?: string | null;
433
+ vaultAddress: string;
434
+ provider: EthereumProviderLike | null | undefined;
435
+ }): Promise<PrepaidVaultSnapshot>;
436
+ declare function approvePrepaidBudget(args: {
437
+ ownerAddress: string;
438
+ amount: bigint;
439
+ tokenAddress: string;
440
+ vaultAddress: string;
441
+ provider: EthereumProviderLike | null | undefined;
442
+ }): Promise<string>;
443
+ declare function depositPrepaidBudget(args: {
444
+ ownerAddress: string;
445
+ amount: bigint;
446
+ vaultAddress: string;
447
+ provider: EthereumProviderLike | null | undefined;
448
+ }): Promise<string>;
449
+ declare function reserveDeploymentBudget(args: {
450
+ ownerAddress: string;
451
+ intentHash: string;
452
+ amount: bigint;
453
+ expiresAt: number;
454
+ vaultAddress: string;
455
+ provider: EthereumProviderLike | null | undefined;
456
+ }): Promise<string>;
457
+ declare function consumeDeploymentReservation(args: {
458
+ ownerAddress: string;
459
+ intentHash: string;
460
+ amount: bigint;
461
+ vaultAddress: string;
462
+ provider: EthereumProviderLike | null | undefined;
463
+ }): Promise<string>;
464
+ declare function refundExpiredReservation(args: {
465
+ ownerAddress: string;
466
+ intentHash: string;
467
+ vaultAddress: string;
468
+ provider: EthereumProviderLike | null | undefined;
469
+ }): Promise<string>;
470
+
395
471
  declare const ITEM_HASH_RE: RegExp;
396
472
  declare const DEFAULT_ROOTFS_MANIFEST_URL = "./rootfs-manifest.json";
397
473
  declare const DEFAULT_IPFS_GATEWAY_BASE_URL = "https://ipfs.aleph.cloud/ipfs/";
@@ -407,4 +483,4 @@ declare const DEFAULT_ALEPH_AGGREGATE_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e
407
483
  declare function parseInstancePricing(payload: unknown): InstancePricing;
408
484
  declare function fetchInstancePricing(apiHost?: string, aggregateAddress?: string): Promise<PricingState>;
409
485
 
410
- export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnLocation, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentMode, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, createAlephBrowserClient, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, inspectDeploymentResult, loadRootfsManifest, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, personalSign, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult };
486
+ export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnLocation, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type EvmChainConfig, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentChain, type PaymentMode, type PrepaidReservation, type PrepaidVaultSnapshot, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, approvePrepaidBudget, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, consumeDeploymentReservation, createAlephBrowserClient, depositPrepaidBudget, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, formatBudgetUnits, inspectDeploymentResult, loadPrepaidReservation, loadPrepaidVaultSnapshot, loadRootfsManifest, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, paymentChainFromChainId, personalSign, refundExpiredReservation, reserveDeploymentBudget, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult };
package/index.js CHANGED
@@ -551,6 +551,169 @@ async function personalSign(address, message, provider) {
551
551
  });
552
552
  }
553
553
 
554
+ // src/prepaid.ts
555
+ var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
556
+ var DEPOSIT_SELECTOR = "0xb6b55f25";
557
+ var RESERVE_SELECTOR = "0x7136e76e";
558
+ var CONSUME_SELECTOR = "0x6a2580db";
559
+ var REFUND_SELECTOR = "0xcc3e049b";
560
+ var TOTAL_DEPOSITED_SELECTOR = "0x53055481";
561
+ var AVAILABLE_BALANCE_SELECTOR = "0xa0821be3";
562
+ var RESERVED_BALANCE_SELECTOR = "0xe2c61aeb";
563
+ var RESERVATION_OF_SELECTOR = "0x0c388a74";
564
+ function padWord(value) {
565
+ return value.replace(/^0x/i, "").padStart(64, "0");
566
+ }
567
+ function encodeAddress(address) {
568
+ return padWord(address.toLowerCase().replace(/^0x/, ""));
569
+ }
570
+ function encodeUint256(value) {
571
+ return padWord(value.toString(16));
572
+ }
573
+ function encodeUint64(value) {
574
+ return padWord(BigInt(value).toString(16));
575
+ }
576
+ function encodeBytes32(value) {
577
+ return padWord(value.replace(/^0x/, ""));
578
+ }
579
+ function encodeCall(selectorValue, args) {
580
+ return `${selectorValue}${args.join("")}`;
581
+ }
582
+ function normalizeHex(value) {
583
+ const normalized = value.startsWith("0x") ? value.toLowerCase() : `0x${value.toLowerCase()}`;
584
+ return normalized;
585
+ }
586
+ function parseUint256Hex(value) {
587
+ const normalized = normalizeHex(value);
588
+ if (!/^0x[0-9a-f]+$/i.test(normalized)) {
589
+ throw new Error(`Invalid uint256 hex value: ${value}`);
590
+ }
591
+ return BigInt(normalized);
592
+ }
593
+ function paymentChainFromChainId(chainId, chainConfig) {
594
+ if (!chainId) return null;
595
+ const normalized = chainId.toLowerCase();
596
+ return Object.entries(chainConfig).find(([, config]) => config.chainIdHex.toLowerCase() === normalized)?.[0] ?? null;
597
+ }
598
+ function formatBudgetUnits(value, decimals = 18) {
599
+ const divisor = 10n ** BigInt(decimals);
600
+ const whole = value / divisor;
601
+ const fraction = value % divisor;
602
+ return Number(whole) + Number(fraction) / 10 ** decimals;
603
+ }
604
+ async function loadPrepaidReservation(args) {
605
+ const encoded = encodeCall(RESERVATION_OF_SELECTOR, [encodeAddress(args.ownerAddress), encodeBytes32(args.intentHash)]);
606
+ const raw = await ethCall(args.vaultAddress, encoded, args.provider);
607
+ const normalized = raw.replace(/^0x/, "").padEnd(256, "0");
608
+ if (!normalized || /^0+$/.test(normalized)) return null;
609
+ const reservedAmount = BigInt(`0x${normalized.slice(0, 64)}`);
610
+ const expiresAt = Number(BigInt(`0x${normalized.slice(64, 128)}`));
611
+ const consumed = BigInt(`0x${normalized.slice(128, 192)}`) !== 0n;
612
+ const owner = `0x${normalized.slice(216, 256)}`;
613
+ if (reservedAmount === 0n) return null;
614
+ return {
615
+ intentHash: args.intentHash,
616
+ ownerAddress: owner.toLowerCase() === args.ownerAddress.toLowerCase() ? args.ownerAddress : owner,
617
+ reservedAmount,
618
+ expiresAt,
619
+ consumed,
620
+ expired: expiresAt <= Math.floor(Date.now() / 1e3)
621
+ };
622
+ }
623
+ async function readUint256(args) {
624
+ const encoded = encodeCall(args.selector, [encodeAddress(args.ownerAddress)]);
625
+ const raw = await ethCall(args.vaultAddress, encoded, args.provider);
626
+ return parseUint256Hex(raw);
627
+ }
628
+ async function loadPrepaidVaultSnapshot(args) {
629
+ const [totalDeposited, availableBalance, reservedBalance, currentReservation] = await Promise.all([
630
+ readUint256({
631
+ selector: TOTAL_DEPOSITED_SELECTOR,
632
+ ownerAddress: args.ownerAddress,
633
+ vaultAddress: args.vaultAddress,
634
+ provider: args.provider
635
+ }),
636
+ readUint256({
637
+ selector: AVAILABLE_BALANCE_SELECTOR,
638
+ ownerAddress: args.ownerAddress,
639
+ vaultAddress: args.vaultAddress,
640
+ provider: args.provider
641
+ }),
642
+ readUint256({
643
+ selector: RESERVED_BALANCE_SELECTOR,
644
+ ownerAddress: args.ownerAddress,
645
+ vaultAddress: args.vaultAddress,
646
+ provider: args.provider
647
+ }),
648
+ args.currentIntentHash ? loadPrepaidReservation({
649
+ ownerAddress: args.ownerAddress,
650
+ intentHash: args.currentIntentHash,
651
+ vaultAddress: args.vaultAddress,
652
+ provider: args.provider
653
+ }) : Promise.resolve(null)
654
+ ]);
655
+ return {
656
+ totalDeposited,
657
+ availableBalance,
658
+ reservedBalance,
659
+ currentReservation
660
+ };
661
+ }
662
+ async function approvePrepaidBudget(args) {
663
+ return sendTransaction(
664
+ {
665
+ from: args.ownerAddress,
666
+ to: args.tokenAddress,
667
+ data: encodeCall(ERC20_APPROVE_SELECTOR, [encodeAddress(args.vaultAddress), encodeUint256(args.amount)])
668
+ },
669
+ args.provider
670
+ );
671
+ }
672
+ async function depositPrepaidBudget(args) {
673
+ return sendTransaction(
674
+ {
675
+ from: args.ownerAddress,
676
+ to: args.vaultAddress,
677
+ data: encodeCall(DEPOSIT_SELECTOR, [encodeUint256(args.amount)])
678
+ },
679
+ args.provider
680
+ );
681
+ }
682
+ async function reserveDeploymentBudget(args) {
683
+ return sendTransaction(
684
+ {
685
+ from: args.ownerAddress,
686
+ to: args.vaultAddress,
687
+ data: encodeCall(RESERVE_SELECTOR, [
688
+ encodeBytes32(args.intentHash),
689
+ encodeUint256(args.amount),
690
+ encodeUint64(args.expiresAt)
691
+ ])
692
+ },
693
+ args.provider
694
+ );
695
+ }
696
+ async function consumeDeploymentReservation(args) {
697
+ return sendTransaction(
698
+ {
699
+ from: args.ownerAddress,
700
+ to: args.vaultAddress,
701
+ data: encodeCall(CONSUME_SELECTOR, [encodeBytes32(args.intentHash), encodeUint256(args.amount)])
702
+ },
703
+ args.provider
704
+ );
705
+ }
706
+ async function refundExpiredReservation(args) {
707
+ return sendTransaction(
708
+ {
709
+ from: args.ownerAddress,
710
+ to: args.vaultAddress,
711
+ data: encodeCall(REFUND_SELECTOR, [encodeBytes32(args.intentHash)])
712
+ },
713
+ args.provider
714
+ );
715
+ }
716
+
554
717
  // src/rootfs.ts
555
718
  var ITEM_HASH_RE = /^[a-fA-F0-9]{64}$/u;
556
719
  var DEFAULT_ROOTFS_MANIFEST_URL = "./rootfs-manifest.json";
@@ -770,10 +933,13 @@ export {
770
933
  DEFAULT_IPFS_GATEWAY_BASE_URL,
771
934
  DEFAULT_ROOTFS_MANIFEST_URL,
772
935
  ITEM_HASH_RE,
936
+ approvePrepaidBudget,
773
937
  broadcastAlephMessage,
774
938
  broadcastInstanceMessage,
775
939
  configureOrbitdbRelaySetup,
940
+ consumeDeploymentReservation,
776
941
  createAlephBrowserClient,
942
+ depositPrepaidBudget,
777
943
  ethCall,
778
944
  fetch2n6WebAccessUrl,
779
945
  fetchBalance,
@@ -784,13 +950,19 @@ export {
784
950
  fetchMessageEnvelope,
785
951
  fetchSchedulerAllocation,
786
952
  fetchWithTimeout,
953
+ formatBudgetUnits,
787
954
  inspectDeploymentResult,
955
+ loadPrepaidReservation,
956
+ loadPrepaidVaultSnapshot,
788
957
  loadRootfsManifest,
789
958
  normalizeExecution,
790
959
  normalizeMessageStatus,
791
960
  notifyCrnAllocation,
792
961
  parseInstancePricing,
962
+ paymentChainFromChainId,
793
963
  personalSign,
964
+ refundExpiredReservation,
965
+ reserveDeploymentBudget,
794
966
  resolveRootfsReference,
795
967
  sendTransaction,
796
968
  validateRootfsManifest,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/browser",
3
- "version": "0.1.38",
3
+ "version": "0.1.42",
4
4
  "description": "Shared browser-safe Aleph deployment and polling helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",