@le-space/browser 0.1.37 → 0.1.39

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 +10 -1
  2. package/index.d.ts +93 -1
  3. package/index.js +221 -1
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -37,6 +37,13 @@ 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
49
  The first real extraction wave should cover:
@@ -57,13 +64,15 @@ The first real extraction wave should cover:
57
64
  - RootFS reference resolution
58
65
  - `pricing.ts`
59
66
  - instance pricing fetch and parse helpers
67
+ - `prepaid.ts`
68
+ - reusable prepaid vault protocol helpers
60
69
 
61
70
  ## Not In Scope Initially
62
71
 
63
72
  These should remain local to apps until the browser package has a stable base:
64
73
 
65
74
  - wallet-provider integrations
66
- - prepaid vault flows
75
+ - prepaid enforcement policy and wallet UX
67
76
  - UI-only formatting helpers
68
77
  - Svelte state orchestration
69
78
 
package/index.d.ts CHANGED
@@ -4,6 +4,45 @@ interface BrowserPackagePlan {
4
4
  modules: string[];
5
5
  }
6
6
  declare const BROWSER_PACKAGE_PLAN: BrowserPackagePlan;
7
+ interface EthereumProviderLike {
8
+ request<T = unknown>(args: {
9
+ method: string;
10
+ params?: unknown[] | Record<string, unknown>;
11
+ }): Promise<T>;
12
+ }
13
+ interface EthereumTransactionRequest {
14
+ from: string;
15
+ to: string;
16
+ data?: `0x${string}`;
17
+ value?: bigint;
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
+ }
7
46
  type MessageStatus = 'processed' | 'pending' | 'rejected' | 'unknown';
8
47
  type ReferenceStatus = MessageStatus | 'missing';
9
48
  type AlephSenderChain = 'ETH';
@@ -376,6 +415,59 @@ interface CreateAlephBrowserClientOptions {
376
415
  }
377
416
  declare function createAlephBrowserClient(options?: CreateAlephBrowserClientOptions): AlephBrowserClient;
378
417
 
418
+ declare function ethCall(to: string, data: `0x${string}`, provider: EthereumProviderLike | null | undefined): Promise<string>;
419
+ declare function sendTransaction(tx: EthereumTransactionRequest, provider: EthereumProviderLike | null | undefined): Promise<string>;
420
+ declare function personalSign(address: string, message: string, provider: EthereumProviderLike | null | undefined): Promise<string>;
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
+
379
471
  declare const ITEM_HASH_RE: RegExp;
380
472
  declare const DEFAULT_ROOTFS_MANIFEST_URL = "./rootfs-manifest.json";
381
473
  declare const DEFAULT_IPFS_GATEWAY_BASE_URL = "https://ipfs.aleph.cloud/ipfs/";
@@ -391,4 +483,4 @@ declare const DEFAULT_ALEPH_AGGREGATE_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e
391
483
  declare function parseInstancePricing(payload: unknown): InstancePricing;
392
484
  declare function fetchInstancePricing(apiHost?: string, aggregateAddress?: string): Promise<PricingState>;
393
485
 
394
- 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 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, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, inspectDeploymentResult, loadRootfsManifest, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, resolveRootfsReference, 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
@@ -1,7 +1,7 @@
1
1
  // src/types.ts
2
2
  var BROWSER_PACKAGE_PLAN = {
3
3
  phase: "scaffolded",
4
- modules: ["http", "aleph-api", "rootfs", "pricing"]
4
+ modules: ["http", "aleph-api", "client", "evm", "rootfs", "pricing"]
5
5
  };
6
6
 
7
7
  // src/http.ts
@@ -506,6 +506,214 @@ function createAlephBrowserClient(options = {}) {
506
506
  };
507
507
  }
508
508
 
509
+ // src/evm.ts
510
+ function ensureHexQuantity(value) {
511
+ return `0x${value.toString(16)}`;
512
+ }
513
+ function assertProvider(provider) {
514
+ if (!provider) {
515
+ throw new Error("MetaMask provider not found.");
516
+ }
517
+ }
518
+ async function ethCall(to, data, provider) {
519
+ assertProvider(provider);
520
+ return provider.request({
521
+ method: "eth_call",
522
+ params: [
523
+ {
524
+ to,
525
+ data
526
+ },
527
+ "latest"
528
+ ]
529
+ });
530
+ }
531
+ async function sendTransaction(tx, provider) {
532
+ assertProvider(provider);
533
+ return provider.request({
534
+ method: "eth_sendTransaction",
535
+ params: [
536
+ {
537
+ from: tx.from,
538
+ to: tx.to,
539
+ data: tx.data,
540
+ value: tx.value != null ? ensureHexQuantity(tx.value) : void 0
541
+ }
542
+ ]
543
+ });
544
+ }
545
+ async function personalSign(address, message, provider) {
546
+ assertProvider(provider);
547
+ const hexMessage = `0x${Array.from(new TextEncoder().encode(message)).map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
548
+ return provider.request({
549
+ method: "personal_sign",
550
+ params: [hexMessage, address]
551
+ });
552
+ }
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
+
509
717
  // src/rootfs.ts
510
718
  var ITEM_HASH_RE = /^[a-fA-F0-9]{64}$/u;
511
719
  var DEFAULT_ROOTFS_MANIFEST_URL = "./rootfs-manifest.json";
@@ -725,10 +933,14 @@ export {
725
933
  DEFAULT_IPFS_GATEWAY_BASE_URL,
726
934
  DEFAULT_ROOTFS_MANIFEST_URL,
727
935
  ITEM_HASH_RE,
936
+ approvePrepaidBudget,
728
937
  broadcastAlephMessage,
729
938
  broadcastInstanceMessage,
730
939
  configureOrbitdbRelaySetup,
940
+ consumeDeploymentReservation,
731
941
  createAlephBrowserClient,
942
+ depositPrepaidBudget,
943
+ ethCall,
732
944
  fetch2n6WebAccessUrl,
733
945
  fetchBalance,
734
946
  fetchCrnExecutionMap,
@@ -738,13 +950,21 @@ export {
738
950
  fetchMessageEnvelope,
739
951
  fetchSchedulerAllocation,
740
952
  fetchWithTimeout,
953
+ formatBudgetUnits,
741
954
  inspectDeploymentResult,
955
+ loadPrepaidReservation,
956
+ loadPrepaidVaultSnapshot,
742
957
  loadRootfsManifest,
743
958
  normalizeExecution,
744
959
  normalizeMessageStatus,
745
960
  notifyCrnAllocation,
746
961
  parseInstancePricing,
962
+ paymentChainFromChainId,
963
+ personalSign,
964
+ refundExpiredReservation,
965
+ reserveDeploymentBudget,
747
966
  resolveRootfsReference,
967
+ sendTransaction,
748
968
  validateRootfsManifest,
749
969
  verifyRootfsExists,
750
970
  waitForDeploymentResult
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/browser",
3
- "version": "0.1.37",
3
+ "version": "0.1.39",
4
4
  "description": "Shared browser-safe Aleph deployment and polling helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",