hyperstack-react 0.3.13 → 0.3.15

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.
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import React, { createContext, useMemo, useRef, useEffect, useContext, useSyncExternalStore, useState, useCallback } from 'react';
1
+ import React, { createContext, useRef, useCallback, useEffect, useContext, useSyncExternalStore, useState, useMemo } from 'react';
2
2
  import { create } from 'zustand';
3
3
 
4
4
  /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
@@ -7498,6 +7498,69 @@ function createUpdateStream(storage, subscriptionRegistry, subscription, keyFilt
7498
7498
  },
7499
7499
  };
7500
7500
  }
7501
+ function createEntityStream(storage, subscriptionRegistry, subscription, keyFilter) {
7502
+ return {
7503
+ [Symbol.asyncIterator]() {
7504
+ const queue = [];
7505
+ let waitingResolve = null;
7506
+ let unsubscribeStorage = null;
7507
+ let unsubscribeRegistry = null;
7508
+ let done = false;
7509
+ const handler = (viewPath, key, update) => {
7510
+ if (viewPath !== subscription.view)
7511
+ return;
7512
+ if (keyFilter !== undefined && key !== keyFilter)
7513
+ return;
7514
+ if (update.type === 'deleted')
7515
+ return;
7516
+ const entity = (update.type === 'created' ? update.data : update.after);
7517
+ if (waitingResolve) {
7518
+ const resolve = waitingResolve;
7519
+ waitingResolve = null;
7520
+ resolve({ value: entity, done: false });
7521
+ }
7522
+ else {
7523
+ if (queue.length >= MAX_QUEUE_SIZE) {
7524
+ queue.shift();
7525
+ }
7526
+ queue.push(entity);
7527
+ }
7528
+ };
7529
+ const start = () => {
7530
+ unsubscribeStorage = storage.onRichUpdate(handler);
7531
+ unsubscribeRegistry = subscriptionRegistry.subscribe(subscription);
7532
+ };
7533
+ const cleanup = () => {
7534
+ done = true;
7535
+ unsubscribeStorage?.();
7536
+ unsubscribeRegistry?.();
7537
+ };
7538
+ start();
7539
+ return {
7540
+ async next() {
7541
+ if (done) {
7542
+ return { value: undefined, done: true };
7543
+ }
7544
+ const queued = queue.shift();
7545
+ if (queued) {
7546
+ return { value: queued, done: false };
7547
+ }
7548
+ return new Promise((resolve) => {
7549
+ waitingResolve = resolve;
7550
+ });
7551
+ },
7552
+ async return() {
7553
+ cleanup();
7554
+ return { value: undefined, done: true };
7555
+ },
7556
+ async throw(error) {
7557
+ cleanup();
7558
+ throw error;
7559
+ },
7560
+ };
7561
+ },
7562
+ };
7563
+ }
7501
7564
  function createRichUpdateStream(storage, subscriptionRegistry, subscription, keyFilter) {
7502
7565
  return {
7503
7566
  [Symbol.asyncIterator]() {
@@ -7565,11 +7628,14 @@ function createRichUpdateStream(storage, subscriptionRegistry, subscription, key
7565
7628
 
7566
7629
  function createTypedStateView(viewDef, storage, subscriptionRegistry) {
7567
7630
  return {
7568
- watch(key) {
7569
- return createUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, key }, key);
7631
+ use(key, options) {
7632
+ return createEntityStream(storage, subscriptionRegistry, { view: viewDef.view, key, ...options }, key);
7633
+ },
7634
+ watch(key, options) {
7635
+ return createUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, key, ...options }, key);
7570
7636
  },
7571
- watchRich(key) {
7572
- return createRichUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, key }, key);
7637
+ watchRich(key, options) {
7638
+ return createRichUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, key, ...options }, key);
7573
7639
  },
7574
7640
  async get(key) {
7575
7641
  return storage.get(viewDef.view, key);
@@ -7581,11 +7647,14 @@ function createTypedStateView(viewDef, storage, subscriptionRegistry) {
7581
7647
  }
7582
7648
  function createTypedListView(viewDef, storage, subscriptionRegistry) {
7583
7649
  return {
7584
- watch() {
7585
- return createUpdateStream(storage, subscriptionRegistry, { view: viewDef.view });
7650
+ use(options) {
7651
+ return createEntityStream(storage, subscriptionRegistry, { view: viewDef.view, ...options });
7586
7652
  },
7587
- watchRich() {
7588
- return createRichUpdateStream(storage, subscriptionRegistry, { view: viewDef.view });
7653
+ watch(options) {
7654
+ return createUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, ...options });
7655
+ },
7656
+ watchRich(options) {
7657
+ return createRichUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, ...options });
7589
7658
  },
7590
7659
  async get() {
7591
7660
  return storage.getAll(viewDef.view);
@@ -7597,20 +7666,512 @@ function createTypedListView(viewDef, storage, subscriptionRegistry) {
7597
7666
  }
7598
7667
  function createTypedViews(stack, storage, subscriptionRegistry) {
7599
7668
  const views = {};
7600
- for (const [viewName, viewGroup] of Object.entries(stack.views)) {
7669
+ for (const [entityName, viewGroup] of Object.entries(stack.views)) {
7601
7670
  const group = viewGroup;
7602
7671
  const typedGroup = {};
7603
- if (group.state) {
7604
- typedGroup.state = createTypedStateView(group.state, storage, subscriptionRegistry);
7605
- }
7606
- if (group.list) {
7607
- typedGroup.list = createTypedListView(group.list, storage, subscriptionRegistry);
7672
+ for (const [viewName, viewDef] of Object.entries(group)) {
7673
+ if (viewDef.mode === 'state') {
7674
+ typedGroup[viewName] = createTypedStateView(viewDef, storage, subscriptionRegistry);
7675
+ }
7676
+ else if (viewDef.mode === 'list') {
7677
+ typedGroup[viewName] = createTypedListView(viewDef, storage, subscriptionRegistry);
7678
+ }
7608
7679
  }
7609
- views[viewName] = typedGroup;
7680
+ views[entityName] = typedGroup;
7610
7681
  }
7611
7682
  return views;
7612
7683
  }
7613
7684
 
7685
+ /**
7686
+ * Resolves instruction accounts by categorizing and deriving addresses.
7687
+ *
7688
+ * @param accountMetas - Account metadata from the instruction definition
7689
+ * @param args - Instruction arguments (used for PDA derivation)
7690
+ * @param options - Resolution options including wallet and user-provided accounts
7691
+ * @returns Resolved accounts and any missing required accounts
7692
+ */
7693
+ function resolveAccounts(accountMetas, args, options) {
7694
+ const resolved = [];
7695
+ const missing = [];
7696
+ for (const meta of accountMetas) {
7697
+ const resolvedAccount = resolveSingleAccount(meta, args, options);
7698
+ if (resolvedAccount) {
7699
+ resolved.push(resolvedAccount);
7700
+ }
7701
+ else if (!meta.isOptional) {
7702
+ missing.push(meta.name);
7703
+ }
7704
+ }
7705
+ return {
7706
+ accounts: resolved,
7707
+ missingUserAccounts: missing,
7708
+ };
7709
+ }
7710
+ function resolveSingleAccount(meta, args, options) {
7711
+ switch (meta.category) {
7712
+ case 'signer':
7713
+ return resolveSignerAccount(meta, options.wallet);
7714
+ case 'known':
7715
+ return resolveKnownAccount(meta);
7716
+ case 'pda':
7717
+ return resolvePdaAccount(meta);
7718
+ case 'userProvided':
7719
+ return resolveUserProvidedAccount(meta, options.accounts);
7720
+ default:
7721
+ return null;
7722
+ }
7723
+ }
7724
+ function resolveSignerAccount(meta, wallet) {
7725
+ if (!wallet) {
7726
+ return null;
7727
+ }
7728
+ return {
7729
+ name: meta.name,
7730
+ address: wallet.publicKey,
7731
+ isSigner: true,
7732
+ isWritable: meta.isWritable,
7733
+ };
7734
+ }
7735
+ function resolveKnownAccount(meta) {
7736
+ if (!meta.knownAddress) {
7737
+ return null;
7738
+ }
7739
+ return {
7740
+ name: meta.name,
7741
+ address: meta.knownAddress,
7742
+ isSigner: meta.isSigner,
7743
+ isWritable: meta.isWritable,
7744
+ };
7745
+ }
7746
+ function resolvePdaAccount(meta, args) {
7747
+ if (!meta.pdaConfig) {
7748
+ return null;
7749
+ }
7750
+ // PDA derivation will be implemented in pda.ts
7751
+ // For now, return a placeholder that will be resolved later
7752
+ return {
7753
+ name: meta.name,
7754
+ address: '', // Will be derived
7755
+ isSigner: meta.isSigner,
7756
+ isWritable: meta.isWritable,
7757
+ };
7758
+ }
7759
+ function resolveUserProvidedAccount(meta, accounts) {
7760
+ const address = accounts?.[meta.name];
7761
+ if (!address) {
7762
+ return null;
7763
+ }
7764
+ return {
7765
+ name: meta.name,
7766
+ address,
7767
+ isSigner: meta.isSigner,
7768
+ isWritable: meta.isWritable,
7769
+ };
7770
+ }
7771
+ /**
7772
+ * Validates that all required accounts are present.
7773
+ *
7774
+ * @param result - Account resolution result
7775
+ * @throws Error if any required accounts are missing
7776
+ */
7777
+ function validateAccountResolution(result) {
7778
+ if (result.missingUserAccounts.length > 0) {
7779
+ throw new Error(`Missing required accounts: ${result.missingUserAccounts.join(', ')}`);
7780
+ }
7781
+ }
7782
+
7783
+ /**
7784
+ * Derives a Program-Derived Address (PDA) from seeds and program ID.
7785
+ *
7786
+ * This function implements PDA derivation using the Solana algorithm:
7787
+ * 1. Concatenate all seeds
7788
+ * 2. Hash with SHA-256
7789
+ * 3. Check if result is off-curve (valid PDA)
7790
+ *
7791
+ * Note: This is a placeholder implementation. In production, you would use
7792
+ * the actual Solana web3.js library's PDA derivation.
7793
+ *
7794
+ * @param seeds - Array of seed buffers
7795
+ * @param programId - The program ID (as base58 string)
7796
+ * @returns The derived PDA address (base58 string)
7797
+ */
7798
+ async function derivePda(seeds, programId) {
7799
+ // In production, this would use:
7800
+ // PublicKey.findProgramAddressSync(seeds, new PublicKey(programId))
7801
+ // For now, return a placeholder that will be replaced with actual implementation
7802
+ const combined = Buffer.concat(seeds);
7803
+ // Simulate PDA derivation (this is NOT the actual algorithm)
7804
+ const hash = await simulateHash(combined);
7805
+ // Return base58-encoded address
7806
+ return bs58Encode(hash);
7807
+ }
7808
+ /**
7809
+ * Creates a seed buffer from various input types.
7810
+ *
7811
+ * @param value - The value to convert to a seed
7812
+ * @returns Buffer suitable for PDA derivation
7813
+ */
7814
+ function createSeed(value) {
7815
+ if (Buffer.isBuffer(value)) {
7816
+ return value;
7817
+ }
7818
+ if (value instanceof Uint8Array) {
7819
+ return Buffer.from(value);
7820
+ }
7821
+ if (typeof value === 'string') {
7822
+ return Buffer.from(value, 'utf-8');
7823
+ }
7824
+ if (typeof value === 'bigint') {
7825
+ // Convert bigint to 8-byte buffer (u64)
7826
+ const buffer = Buffer.alloc(8);
7827
+ buffer.writeBigUInt64LE(value);
7828
+ return buffer;
7829
+ }
7830
+ throw new Error(`Cannot create seed from type: ${typeof value}`);
7831
+ }
7832
+ /**
7833
+ * Creates a public key seed from a base58-encoded address.
7834
+ *
7835
+ * @param address - Base58-encoded public key
7836
+ * @returns 32-byte buffer
7837
+ */
7838
+ function createPublicKeySeed(address) {
7839
+ // In production, decode base58 to 32-byte buffer
7840
+ // For now, return placeholder
7841
+ return Buffer.alloc(32);
7842
+ }
7843
+ async function simulateHash(data) {
7844
+ // In production, use actual SHA-256
7845
+ // This is a placeholder
7846
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
7847
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
7848
+ return Buffer.from(hashBuffer);
7849
+ }
7850
+ // Fallback for Node.js
7851
+ return Buffer.alloc(32, 0);
7852
+ }
7853
+ function bs58Encode(buffer) {
7854
+ // In production, use actual base58 encoding
7855
+ // This is a placeholder
7856
+ return 'P' + buffer.toString('hex').slice(0, 31);
7857
+ }
7858
+
7859
+ /**
7860
+ * Borsh-compatible instruction data serializer.
7861
+ *
7862
+ * This module handles serializing instruction arguments into the binary format
7863
+ * expected by Solana programs using Borsh serialization.
7864
+ */
7865
+ /**
7866
+ * Serializes instruction arguments into a Buffer using Borsh encoding.
7867
+ *
7868
+ * @param discriminator - The 8-byte instruction discriminator
7869
+ * @param args - Arguments to serialize
7870
+ * @param schema - Schema defining argument types
7871
+ * @returns Serialized instruction data
7872
+ */
7873
+ function serializeInstructionData(discriminator, args, schema) {
7874
+ const buffers = [Buffer.from(discriminator)];
7875
+ for (const field of schema) {
7876
+ const value = args[field.name];
7877
+ const serialized = serializeValue(value, field.type);
7878
+ buffers.push(serialized);
7879
+ }
7880
+ return Buffer.concat(buffers);
7881
+ }
7882
+ function serializeValue(value, type) {
7883
+ if (typeof type === 'string') {
7884
+ return serializePrimitive(value, type);
7885
+ }
7886
+ if ('vec' in type) {
7887
+ return serializeVec(value, type.vec);
7888
+ }
7889
+ if ('option' in type) {
7890
+ return serializeOption(value, type.option);
7891
+ }
7892
+ if ('array' in type) {
7893
+ return serializeArray(value, type.array[0], type.array[1]);
7894
+ }
7895
+ throw new Error(`Unknown type: ${JSON.stringify(type)}`);
7896
+ }
7897
+ function serializePrimitive(value, type) {
7898
+ switch (type) {
7899
+ case 'u8':
7900
+ return Buffer.from([value]);
7901
+ case 'u16':
7902
+ const u16 = Buffer.alloc(2);
7903
+ u16.writeUInt16LE(value, 0);
7904
+ return u16;
7905
+ case 'u32':
7906
+ const u32 = Buffer.alloc(4);
7907
+ u32.writeUInt32LE(value, 0);
7908
+ return u32;
7909
+ case 'u64':
7910
+ const u64 = Buffer.alloc(8);
7911
+ u64.writeBigUInt64LE(BigInt(value), 0);
7912
+ return u64;
7913
+ case 'u128':
7914
+ // u128 is 16 bytes, little-endian
7915
+ const u128 = Buffer.alloc(16);
7916
+ const bigU128 = BigInt(value);
7917
+ u128.writeBigUInt64LE(bigU128 & BigInt('0xFFFFFFFFFFFFFFFF'), 0);
7918
+ u128.writeBigUInt64LE(bigU128 >> BigInt(64), 8);
7919
+ return u128;
7920
+ case 'i8':
7921
+ return Buffer.from([value]);
7922
+ case 'i16':
7923
+ const i16 = Buffer.alloc(2);
7924
+ i16.writeInt16LE(value, 0);
7925
+ return i16;
7926
+ case 'i32':
7927
+ const i32 = Buffer.alloc(4);
7928
+ i32.writeInt32LE(value, 0);
7929
+ return i32;
7930
+ case 'i64':
7931
+ const i64 = Buffer.alloc(8);
7932
+ i64.writeBigInt64LE(BigInt(value), 0);
7933
+ return i64;
7934
+ case 'i128':
7935
+ const i128 = Buffer.alloc(16);
7936
+ const bigI128 = BigInt(value);
7937
+ i128.writeBigInt64LE(bigI128 & BigInt('0xFFFFFFFFFFFFFFFF'), 0);
7938
+ i128.writeBigInt64LE(bigI128 >> BigInt(64), 8);
7939
+ return i128;
7940
+ case 'bool':
7941
+ return Buffer.from([value ? 1 : 0]);
7942
+ case 'string':
7943
+ const str = value;
7944
+ const strBytes = Buffer.from(str, 'utf-8');
7945
+ const strLen = Buffer.alloc(4);
7946
+ strLen.writeUInt32LE(strBytes.length, 0);
7947
+ return Buffer.concat([strLen, strBytes]);
7948
+ case 'pubkey':
7949
+ // In production, decode base58 to 32 bytes
7950
+ return Buffer.alloc(32, 0);
7951
+ default:
7952
+ throw new Error(`Unknown primitive type: ${type}`);
7953
+ }
7954
+ }
7955
+ function serializeVec(values, elementType) {
7956
+ const len = Buffer.alloc(4);
7957
+ len.writeUInt32LE(values.length, 0);
7958
+ const elementBuffers = values.map(v => serializeValue(v, elementType));
7959
+ return Buffer.concat([len, ...elementBuffers]);
7960
+ }
7961
+ function serializeOption(value, innerType) {
7962
+ if (value === null || value === undefined) {
7963
+ return Buffer.from([0]); // None
7964
+ }
7965
+ const inner = serializeValue(value, innerType);
7966
+ return Buffer.concat([Buffer.from([1]), inner]); // Some
7967
+ }
7968
+ function serializeArray(values, elementType, length) {
7969
+ if (values.length !== length) {
7970
+ throw new Error(`Array length mismatch: expected ${length}, got ${values.length}`);
7971
+ }
7972
+ const elementBuffers = values.map(v => serializeValue(v, elementType));
7973
+ return Buffer.concat(elementBuffers);
7974
+ }
7975
+
7976
+ /**
7977
+ * Waits for transaction confirmation.
7978
+ *
7979
+ * @param signature - Transaction signature
7980
+ * @param level - Desired confirmation level
7981
+ * @param timeout - Maximum wait time in milliseconds
7982
+ * @returns Confirmation result
7983
+ */
7984
+ async function waitForConfirmation(signature, level = 'confirmed', timeout = 60000) {
7985
+ const startTime = Date.now();
7986
+ while (Date.now() - startTime < timeout) {
7987
+ const status = await checkTransactionStatus();
7988
+ if (status.err) {
7989
+ throw new Error(`Transaction failed: ${JSON.stringify(status.err)}`);
7990
+ }
7991
+ if (isConfirmationLevelSufficient(status.confirmations, level)) {
7992
+ return {
7993
+ level,
7994
+ slot: status.slot,
7995
+ };
7996
+ }
7997
+ await sleep(1000);
7998
+ }
7999
+ throw new Error(`Transaction confirmation timeout after ${timeout}ms`);
8000
+ }
8001
+ async function checkTransactionStatus(signature) {
8002
+ // In production, query the Solana RPC
8003
+ return {
8004
+ err: null,
8005
+ confirmations: 32,
8006
+ slot: 123456789,
8007
+ };
8008
+ }
8009
+ function isConfirmationLevelSufficient(confirmations, level) {
8010
+ if (confirmations === null) {
8011
+ return false;
8012
+ }
8013
+ switch (level) {
8014
+ case 'processed':
8015
+ return confirmations >= 0;
8016
+ case 'confirmed':
8017
+ return confirmations >= 1;
8018
+ case 'finalized':
8019
+ return confirmations >= 32;
8020
+ default:
8021
+ return false;
8022
+ }
8023
+ }
8024
+ function sleep(ms) {
8025
+ return new Promise(resolve => setTimeout(resolve, ms));
8026
+ }
8027
+
8028
+ /**
8029
+ * Parses and handles instruction errors.
8030
+ */
8031
+ /**
8032
+ * Parses an error returned from a Solana transaction.
8033
+ *
8034
+ * @param error - The error from the transaction
8035
+ * @param errorMetadata - Error definitions from the IDL
8036
+ * @returns Parsed program error or null if not a program error
8037
+ */
8038
+ function parseInstructionError(error, errorMetadata) {
8039
+ if (!error) {
8040
+ return null;
8041
+ }
8042
+ const errorCode = extractErrorCode(error);
8043
+ if (errorCode === null) {
8044
+ return null;
8045
+ }
8046
+ const metadata = errorMetadata.find(e => e.code === errorCode);
8047
+ if (metadata) {
8048
+ return {
8049
+ code: metadata.code,
8050
+ name: metadata.name,
8051
+ message: metadata.msg,
8052
+ };
8053
+ }
8054
+ return {
8055
+ code: errorCode,
8056
+ name: `CustomError${errorCode}`,
8057
+ message: `Unknown error with code ${errorCode}`,
8058
+ };
8059
+ }
8060
+ function extractErrorCode(error) {
8061
+ if (typeof error !== 'object' || error === null) {
8062
+ return null;
8063
+ }
8064
+ const errorObj = error;
8065
+ // Check for InstructionError format
8066
+ if (errorObj.InstructionError) {
8067
+ const instructionError = errorObj.InstructionError;
8068
+ if (instructionError[1]?.Custom !== undefined) {
8069
+ return instructionError[1].Custom;
8070
+ }
8071
+ }
8072
+ // Check for direct code
8073
+ if (typeof errorObj.code === 'number') {
8074
+ return errorObj.code;
8075
+ }
8076
+ return null;
8077
+ }
8078
+ /**
8079
+ * Formats an error for display.
8080
+ *
8081
+ * @param error - The program error
8082
+ * @returns Human-readable error message
8083
+ */
8084
+ function formatProgramError(error) {
8085
+ return `${error.name} (${error.code}): ${error.message}`;
8086
+ }
8087
+
8088
+ /**
8089
+ * Converts resolved account array to a map for the builder.
8090
+ */
8091
+ function toResolvedAccountsMap(accounts) {
8092
+ const map = {};
8093
+ for (const account of accounts) {
8094
+ map[account.name] = account.address;
8095
+ }
8096
+ return map;
8097
+ }
8098
+ /**
8099
+ * Executes an instruction handler with the given arguments and options.
8100
+ *
8101
+ * This is the main function for executing Solana instructions. It handles:
8102
+ * 1. Account resolution (signer, PDA, user-provided)
8103
+ * 2. Calling the generated build() function
8104
+ * 3. Transaction signing and sending
8105
+ * 4. Confirmation waiting
8106
+ *
8107
+ * @param handler - Instruction handler from generated SDK
8108
+ * @param args - Instruction arguments
8109
+ * @param options - Execution options
8110
+ * @returns Execution result with signature
8111
+ */
8112
+ async function executeInstruction(handler, args, options = {}) {
8113
+ // Step 1: Resolve accounts using handler's account metadata
8114
+ const resolutionOptions = {
8115
+ accounts: options.accounts,
8116
+ wallet: options.wallet,
8117
+ };
8118
+ const resolution = resolveAccounts(handler.accounts, args, resolutionOptions);
8119
+ validateAccountResolution(resolution);
8120
+ // Step 2: Call generated build() function
8121
+ const resolvedAccountsMap = toResolvedAccountsMap(resolution.accounts);
8122
+ const instruction = handler.build(args, resolvedAccountsMap);
8123
+ // Step 3: Build transaction from the built instruction
8124
+ const transaction = buildTransaction(instruction);
8125
+ // Step 4: Sign and send
8126
+ if (!options.wallet) {
8127
+ throw new Error('Wallet required to sign transaction');
8128
+ }
8129
+ const signature = await options.wallet.signAndSend(transaction);
8130
+ // Step 5: Wait for confirmation
8131
+ const confirmationLevel = options.confirmationLevel ?? 'confirmed';
8132
+ const timeout = options.timeout ?? 60000;
8133
+ const confirmation = await waitForConfirmation(signature, confirmationLevel, timeout);
8134
+ return {
8135
+ signature,
8136
+ confirmationLevel: confirmation.level,
8137
+ slot: confirmation.slot,
8138
+ };
8139
+ }
8140
+ /**
8141
+ * Creates a transaction object from a built instruction.
8142
+ *
8143
+ * @param instruction - Built instruction from handler
8144
+ * @returns Transaction object ready for signing
8145
+ */
8146
+ function buildTransaction(instruction) {
8147
+ // This returns a framework-agnostic transaction representation.
8148
+ // The wallet adapter is responsible for converting this to the
8149
+ // appropriate format (@solana/web3.js Transaction, etc.)
8150
+ return {
8151
+ instructions: [{
8152
+ programId: instruction.programId,
8153
+ keys: instruction.keys,
8154
+ data: Array.from(instruction.data),
8155
+ }],
8156
+ };
8157
+ }
8158
+ /**
8159
+ * Creates an instruction executor bound to a specific wallet.
8160
+ *
8161
+ * @param wallet - Wallet adapter
8162
+ * @returns Bound executor function
8163
+ */
8164
+ function createInstructionExecutor(wallet) {
8165
+ return {
8166
+ execute: async (handler, args, options) => {
8167
+ return executeInstruction(handler, args, {
8168
+ ...options,
8169
+ wallet,
8170
+ });
8171
+ },
8172
+ };
8173
+ }
8174
+
7614
8175
  class HyperStack {
7615
8176
  constructor(url, options) {
7616
8177
  this.stack = options.stack;
@@ -7628,16 +8189,34 @@ class HyperStack {
7628
8189
  this.processor.handleFrame(frame);
7629
8190
  });
7630
8191
  this._views = createTypedViews(this.stack, this.storage, this.subscriptionRegistry);
8192
+ this._instructions = this.buildInstructions();
8193
+ }
8194
+ buildInstructions() {
8195
+ const instructions = {};
8196
+ if (this.stack.instructions) {
8197
+ for (const [name, handler] of Object.entries(this.stack.instructions)) {
8198
+ instructions[name] = (args, options) => {
8199
+ return executeInstruction(handler, args, options);
8200
+ };
8201
+ }
8202
+ }
8203
+ return instructions;
7631
8204
  }
7632
- static async connect(url, options) {
8205
+ static async connect(stack, options) {
8206
+ const url = options?.url ?? stack.url;
7633
8207
  if (!url) {
7634
- throw new HyperStackError('URL is required', 'INVALID_CONFIG');
7635
- }
7636
- if (!options.stack) {
7637
- throw new HyperStackError('Stack definition is required', 'INVALID_CONFIG');
7638
- }
7639
- const client = new HyperStack(url, options);
7640
- if (options.autoReconnect !== false) {
8208
+ throw new HyperStackError('URL is required (provide url option or define url in stack)', 'INVALID_CONFIG');
8209
+ }
8210
+ const internalOptions = {
8211
+ stack,
8212
+ storage: options?.storage,
8213
+ maxEntriesPerView: options?.maxEntriesPerView,
8214
+ autoReconnect: options?.autoReconnect,
8215
+ reconnectIntervals: options?.reconnectIntervals,
8216
+ maxReconnectAttempts: options?.maxReconnectAttempts,
8217
+ };
8218
+ const client = new HyperStack(url, internalOptions);
8219
+ if (options?.autoReconnect !== false) {
7641
8220
  await client.connection.connect();
7642
8221
  }
7643
8222
  return client;
@@ -7645,6 +8224,9 @@ class HyperStack {
7645
8224
  get views() {
7646
8225
  return this._views;
7647
8226
  }
8227
+ get instructions() {
8228
+ return this._instructions;
8229
+ }
7648
8230
  get connectionState() {
7649
8231
  return this.connection.getState();
7650
8232
  }
@@ -7684,6 +8266,504 @@ class HyperStack {
7684
8266
  }
7685
8267
  }
7686
8268
 
8269
+ const HyperstackContext = createContext(null);
8270
+ function resolveNetworkConfig(network, websocketUrl) {
8271
+ if (websocketUrl) {
8272
+ return {
8273
+ name: 'custom',
8274
+ websocketUrl
8275
+ };
8276
+ }
8277
+ if (typeof network === 'object') {
8278
+ return network;
8279
+ }
8280
+ if (network === 'mainnet') {
8281
+ return {
8282
+ name: 'mainnet',
8283
+ websocketUrl: 'wss://mainnet.hyperstack.xyz',
8284
+ };
8285
+ }
8286
+ if (network === 'devnet') {
8287
+ return {
8288
+ name: 'devnet',
8289
+ websocketUrl: 'ws://localhost:8080',
8290
+ };
8291
+ }
8292
+ if (network === 'localnet') {
8293
+ return {
8294
+ name: 'localnet',
8295
+ websocketUrl: 'ws://localhost:8080',
8296
+ };
8297
+ }
8298
+ throw new Error('Must provide either network or websocketUrl');
8299
+ }
8300
+ function HyperstackProvider({ children, fallback = null, ...config }) {
8301
+ const networkConfig = resolveNetworkConfig(config.network, config.websocketUrl);
8302
+ const clientsRef = useRef(new Map());
8303
+ const connectingRef = useRef(new Map());
8304
+ const getOrCreateClient = useCallback(async (stack) => {
8305
+ const existing = clientsRef.current.get(stack.name);
8306
+ if (existing) {
8307
+ return existing.client;
8308
+ }
8309
+ const connecting = connectingRef.current.get(stack.name);
8310
+ if (connecting) {
8311
+ return connecting;
8312
+ }
8313
+ const connectionPromise = HyperStack.connect(stack, {
8314
+ url: networkConfig.websocketUrl,
8315
+ autoReconnect: config.autoConnect,
8316
+ reconnectIntervals: config.reconnectIntervals,
8317
+ maxReconnectAttempts: config.maxReconnectAttempts,
8318
+ maxEntriesPerView: config.maxEntriesPerView,
8319
+ }).then((client) => {
8320
+ clientsRef.current.set(stack.name, {
8321
+ client,
8322
+ disconnect: () => client.disconnect()
8323
+ });
8324
+ connectingRef.current.delete(stack.name);
8325
+ return client;
8326
+ });
8327
+ connectingRef.current.set(stack.name, connectionPromise);
8328
+ return connectionPromise;
8329
+ }, [networkConfig.websocketUrl, config.autoConnect, config.reconnectIntervals, config.maxReconnectAttempts, config.maxEntriesPerView]);
8330
+ const getClient = useCallback((stack) => {
8331
+ if (!stack)
8332
+ return null;
8333
+ const entry = clientsRef.current.get(stack.name);
8334
+ return entry ? entry.client : null;
8335
+ }, []);
8336
+ useEffect(() => {
8337
+ return () => {
8338
+ clientsRef.current.forEach((entry) => {
8339
+ entry.disconnect();
8340
+ });
8341
+ clientsRef.current.clear();
8342
+ connectingRef.current.clear();
8343
+ };
8344
+ }, []);
8345
+ const value = {
8346
+ getOrCreateClient,
8347
+ getClient,
8348
+ config: {
8349
+ websocketUrl: networkConfig.websocketUrl,
8350
+ autoConnect: config.autoConnect,
8351
+ reconnectIntervals: config.reconnectIntervals,
8352
+ maxReconnectAttempts: config.maxReconnectAttempts,
8353
+ maxEntriesPerView: config.maxEntriesPerView,
8354
+ }
8355
+ };
8356
+ return (React.createElement(HyperstackContext.Provider, { value: value }, children));
8357
+ }
8358
+ function useHyperstackContext() {
8359
+ const context = useContext(HyperstackContext);
8360
+ if (!context) {
8361
+ throw new Error('useHyperstackContext must be used within HyperstackProvider');
8362
+ }
8363
+ return context;
8364
+ }
8365
+ function useConnectionState(stack) {
8366
+ const { getClient } = useHyperstackContext();
8367
+ const client = stack ? getClient(stack) : null;
8368
+ return useSyncExternalStore((callback) => {
8369
+ if (!client)
8370
+ return () => { };
8371
+ return client.onConnectionStateChange(callback);
8372
+ }, () => client?.connectionState ?? 'disconnected');
8373
+ }
8374
+ function useView(stack, viewPath) {
8375
+ const { getClient } = useHyperstackContext();
8376
+ const client = getClient(stack);
8377
+ return useSyncExternalStore((callback) => {
8378
+ if (!client)
8379
+ return () => { };
8380
+ return client.store.onUpdate(callback);
8381
+ }, () => {
8382
+ if (!client)
8383
+ return [];
8384
+ const data = client.store.getAll(viewPath);
8385
+ return data;
8386
+ });
8387
+ }
8388
+ function useEntity(stack, viewPath, key) {
8389
+ const { getClient } = useHyperstackContext();
8390
+ const client = getClient(stack);
8391
+ return useSyncExternalStore((callback) => {
8392
+ if (!client)
8393
+ return () => { };
8394
+ return client.store.onUpdate(callback);
8395
+ }, () => {
8396
+ if (!client)
8397
+ return null;
8398
+ const data = client.store.get(viewPath, key);
8399
+ return data;
8400
+ });
8401
+ }
8402
+
8403
+ function shallowArrayEqual(a, b) {
8404
+ if (a === b)
8405
+ return true;
8406
+ if (!a || !b)
8407
+ return false;
8408
+ if (a.length !== b.length)
8409
+ return false;
8410
+ for (let i = 0; i < a.length; i++) {
8411
+ if (a[i] !== b[i])
8412
+ return false;
8413
+ }
8414
+ return true;
8415
+ }
8416
+ function useStateView(viewDef, client, key, options) {
8417
+ const [isLoading, setIsLoading] = useState(!options?.initialData);
8418
+ const [error, setError] = useState();
8419
+ const clientRef = useRef(client);
8420
+ clientRef.current = client;
8421
+ const cachedSnapshotRef = useRef(undefined);
8422
+ const keyString = key ? Object.values(key)[0] : undefined;
8423
+ const enabled = options?.enabled !== false;
8424
+ useEffect(() => {
8425
+ if (!enabled || !clientRef.current)
8426
+ return undefined;
8427
+ try {
8428
+ const registry = clientRef.current.getSubscriptionRegistry();
8429
+ const unsubscribe = registry.subscribe({ view: viewDef.view, key: keyString });
8430
+ setIsLoading(true);
8431
+ return () => {
8432
+ try {
8433
+ unsubscribe();
8434
+ }
8435
+ catch (err) {
8436
+ console.error('[Hyperstack] Error unsubscribing from view:', err);
8437
+ }
8438
+ };
8439
+ }
8440
+ catch (err) {
8441
+ setError(err instanceof Error ? err : new Error('Subscription failed'));
8442
+ setIsLoading(false);
8443
+ return undefined;
8444
+ }
8445
+ }, [viewDef.view, keyString, enabled, client]);
8446
+ const refresh = useCallback(() => {
8447
+ if (!enabled || !clientRef.current)
8448
+ return;
8449
+ try {
8450
+ const registry = clientRef.current.getSubscriptionRegistry();
8451
+ const unsubscribe = registry.subscribe({ view: viewDef.view, key: keyString });
8452
+ setIsLoading(true);
8453
+ setTimeout(() => {
8454
+ try {
8455
+ unsubscribe();
8456
+ }
8457
+ catch (err) {
8458
+ console.error('[Hyperstack] Error during refresh unsubscribe:', err);
8459
+ }
8460
+ }, 0);
8461
+ }
8462
+ catch (err) {
8463
+ setError(err instanceof Error ? err : new Error('Refresh failed'));
8464
+ setIsLoading(false);
8465
+ }
8466
+ }, [viewDef.view, keyString, enabled]);
8467
+ const subscribe = useCallback((callback) => {
8468
+ if (!clientRef.current)
8469
+ return () => { };
8470
+ return clientRef.current.store.onUpdate(callback);
8471
+ }, [client]);
8472
+ const getSnapshot = useCallback(() => {
8473
+ if (!clientRef.current)
8474
+ return cachedSnapshotRef.current;
8475
+ const entity = keyString
8476
+ ? clientRef.current.store.get(viewDef.view, keyString)
8477
+ : clientRef.current.store.getAll(viewDef.view)[0];
8478
+ // Cache the result to return stable reference for useSyncExternalStore
8479
+ if (entity !== cachedSnapshotRef.current) {
8480
+ cachedSnapshotRef.current = entity;
8481
+ }
8482
+ return cachedSnapshotRef.current;
8483
+ }, [viewDef.view, keyString, client]);
8484
+ const data = useSyncExternalStore(subscribe, getSnapshot);
8485
+ useEffect(() => {
8486
+ if (data !== undefined && isLoading) {
8487
+ setIsLoading(false);
8488
+ }
8489
+ }, [data, isLoading]);
8490
+ return {
8491
+ data: (options?.initialData ?? data),
8492
+ isLoading: client === null || isLoading,
8493
+ error,
8494
+ refresh
8495
+ };
8496
+ }
8497
+ function useListView(viewDef, client, params, options) {
8498
+ const [isLoading, setIsLoading] = useState(!options?.initialData);
8499
+ const [error, setError] = useState();
8500
+ const clientRef = useRef(client);
8501
+ clientRef.current = client;
8502
+ const cachedSnapshotRef = useRef(undefined);
8503
+ const enabled = options?.enabled !== false;
8504
+ const key = params?.key;
8505
+ const take = params?.take;
8506
+ const skip = params?.skip;
8507
+ const whereJson = params?.where ? JSON.stringify(params.where) : undefined;
8508
+ const filtersJson = params?.filters ? JSON.stringify(params.filters) : undefined;
8509
+ const limit = params?.limit;
8510
+ useEffect(() => {
8511
+ if (!enabled || !clientRef.current)
8512
+ return undefined;
8513
+ try {
8514
+ const registry = clientRef.current.getSubscriptionRegistry();
8515
+ const unsubscribe = registry.subscribe({
8516
+ view: viewDef.view,
8517
+ key,
8518
+ filters: params?.filters,
8519
+ take,
8520
+ skip
8521
+ });
8522
+ setIsLoading(true);
8523
+ return () => {
8524
+ try {
8525
+ unsubscribe();
8526
+ }
8527
+ catch (err) {
8528
+ console.error('[Hyperstack] Error unsubscribing from list view:', err);
8529
+ }
8530
+ };
8531
+ }
8532
+ catch (err) {
8533
+ setError(err instanceof Error ? err : new Error('Subscription failed'));
8534
+ setIsLoading(false);
8535
+ return undefined;
8536
+ }
8537
+ }, [viewDef.view, enabled, key, filtersJson, take, skip, client]);
8538
+ const refresh = useCallback(() => {
8539
+ if (!enabled || !clientRef.current)
8540
+ return;
8541
+ try {
8542
+ const registry = clientRef.current.getSubscriptionRegistry();
8543
+ const unsubscribe = registry.subscribe({
8544
+ view: viewDef.view,
8545
+ key,
8546
+ filters: params?.filters,
8547
+ take,
8548
+ skip
8549
+ });
8550
+ setIsLoading(true);
8551
+ setTimeout(() => {
8552
+ try {
8553
+ unsubscribe();
8554
+ }
8555
+ catch (err) {
8556
+ console.error('[Hyperstack] Error during list refresh unsubscribe:', err);
8557
+ }
8558
+ }, 0);
8559
+ }
8560
+ catch (err) {
8561
+ setError(err instanceof Error ? err : new Error('Refresh failed'));
8562
+ setIsLoading(false);
8563
+ }
8564
+ }, [viewDef.view, enabled, key, filtersJson, take, skip]);
8565
+ const subscribe = useCallback((callback) => {
8566
+ if (!clientRef.current)
8567
+ return () => { };
8568
+ return clientRef.current.store.onUpdate(callback);
8569
+ }, [client]);
8570
+ const getSnapshot = useCallback(() => {
8571
+ if (!clientRef.current)
8572
+ return cachedSnapshotRef.current;
8573
+ const viewData = clientRef.current.store.getAll(viewDef.view);
8574
+ if (!viewData || viewData.length === 0) {
8575
+ if (cachedSnapshotRef.current !== undefined) {
8576
+ cachedSnapshotRef.current = undefined;
8577
+ }
8578
+ return cachedSnapshotRef.current;
8579
+ }
8580
+ let items = viewData;
8581
+ if (params?.where) {
8582
+ items = items.filter((item) => {
8583
+ return Object.entries(params.where).every(([fieldKey, condition]) => {
8584
+ const value = item[fieldKey];
8585
+ if (typeof condition === 'object' && condition !== null) {
8586
+ const cond = condition;
8587
+ if ('gte' in cond)
8588
+ return value >= cond.gte;
8589
+ if ('lte' in cond)
8590
+ return value <= cond.lte;
8591
+ if ('gt' in cond)
8592
+ return value > cond.gt;
8593
+ if ('lt' in cond)
8594
+ return value < cond.lt;
8595
+ }
8596
+ return value === condition;
8597
+ });
8598
+ });
8599
+ }
8600
+ if (limit) {
8601
+ items = items.slice(0, limit);
8602
+ }
8603
+ const result = items;
8604
+ // Cache the result - only update if data actually changed
8605
+ if (!shallowArrayEqual(cachedSnapshotRef.current, result)) {
8606
+ cachedSnapshotRef.current = result;
8607
+ }
8608
+ return cachedSnapshotRef.current;
8609
+ }, [viewDef.view, whereJson, limit, client]);
8610
+ const data = useSyncExternalStore(subscribe, getSnapshot);
8611
+ useEffect(() => {
8612
+ if (data !== undefined && isLoading) {
8613
+ setIsLoading(false);
8614
+ }
8615
+ }, [data, isLoading]);
8616
+ return {
8617
+ data: (options?.initialData ?? data),
8618
+ isLoading: client === null || isLoading,
8619
+ error,
8620
+ refresh
8621
+ };
8622
+ }
8623
+ function createStateViewHook(viewDef, client) {
8624
+ return {
8625
+ use: (key, options) => {
8626
+ return useStateView(viewDef, client, key, options);
8627
+ }
8628
+ };
8629
+ }
8630
+ function createListViewHook(viewDef, client) {
8631
+ function use(params, options) {
8632
+ const result = useListView(viewDef, client, params, options);
8633
+ if (params?.take === 1) {
8634
+ return {
8635
+ data: result.data?.[0],
8636
+ isLoading: result.isLoading,
8637
+ error: result.error,
8638
+ refresh: result.refresh
8639
+ };
8640
+ }
8641
+ return result;
8642
+ }
8643
+ function useOne(params, options) {
8644
+ const paramsWithTake = params ? { ...params, take: 1 } : { take: 1 };
8645
+ const result = useListView(viewDef, client, paramsWithTake, options);
8646
+ return {
8647
+ data: result.data?.[0],
8648
+ isLoading: result.isLoading,
8649
+ error: result.error,
8650
+ refresh: result.refresh
8651
+ };
8652
+ }
8653
+ return { use, useOne };
8654
+ }
8655
+
8656
+ function useInstructionMutation(execute) {
8657
+ const [status, setStatus] = useState('idle');
8658
+ const [error, setError] = useState(null);
8659
+ const [signature, setSignature] = useState(null);
8660
+ const submit = useCallback(async (args, options) => {
8661
+ setStatus('pending');
8662
+ setError(null);
8663
+ setSignature(null);
8664
+ try {
8665
+ const result = await execute(args, options);
8666
+ setStatus('success');
8667
+ setSignature(result.signature);
8668
+ if (options?.onSuccess) {
8669
+ options.onSuccess(result);
8670
+ }
8671
+ return result;
8672
+ }
8673
+ catch (err) {
8674
+ const errorMessage = err instanceof Error ? err.message : String(err);
8675
+ const programError = parseInstructionError(err, []);
8676
+ const displayError = programError
8677
+ ? `${programError.name}: ${programError.message}`
8678
+ : errorMessage;
8679
+ setStatus('error');
8680
+ setError(displayError);
8681
+ if (options?.onError && err instanceof Error) {
8682
+ options.onError(err);
8683
+ }
8684
+ throw err;
8685
+ }
8686
+ }, [execute]);
8687
+ const reset = useCallback(() => {
8688
+ setStatus('idle');
8689
+ setError(null);
8690
+ setSignature(null);
8691
+ }, []);
8692
+ return {
8693
+ submit,
8694
+ status,
8695
+ error,
8696
+ signature,
8697
+ isLoading: status === 'pending',
8698
+ reset,
8699
+ };
8700
+ }
8701
+
8702
+ function useHyperstack(stack) {
8703
+ const { getOrCreateClient, getClient } = useHyperstackContext();
8704
+ const [client, setClient] = useState(getClient(stack));
8705
+ const [isLoading, setIsLoading] = useState(!client);
8706
+ const [error, setError] = useState(null);
8707
+ useEffect(() => {
8708
+ const existingClient = getClient(stack);
8709
+ if (existingClient) {
8710
+ setClient(existingClient);
8711
+ setIsLoading(false);
8712
+ return;
8713
+ }
8714
+ setIsLoading(true);
8715
+ setError(null);
8716
+ getOrCreateClient(stack)
8717
+ .then((newClient) => {
8718
+ setClient(newClient);
8719
+ setIsLoading(false);
8720
+ })
8721
+ .catch((err) => {
8722
+ setError(err instanceof Error ? err : new Error(String(err)));
8723
+ setIsLoading(false);
8724
+ });
8725
+ }, [stack, getOrCreateClient, getClient]);
8726
+ const views = useMemo(() => {
8727
+ const result = {};
8728
+ for (const [viewName, viewGroup] of Object.entries(stack.views)) {
8729
+ result[viewName] = {};
8730
+ if (typeof viewGroup === 'object' && viewGroup !== null) {
8731
+ for (const [subViewName, viewDef] of Object.entries(viewGroup)) {
8732
+ if (!viewDef || typeof viewDef !== 'object' || !('mode' in viewDef))
8733
+ continue;
8734
+ if (viewDef.mode === 'state') {
8735
+ result[viewName][subViewName] = createStateViewHook(viewDef, client);
8736
+ }
8737
+ else if (viewDef.mode === 'list') {
8738
+ result[viewName][subViewName] = createListViewHook(viewDef, client);
8739
+ }
8740
+ }
8741
+ }
8742
+ }
8743
+ return result;
8744
+ }, [stack, client]);
8745
+ const instructions = useMemo(() => {
8746
+ const result = {};
8747
+ if (client?.instructions) {
8748
+ for (const [instructionName, executeFn] of Object.entries(client.instructions)) {
8749
+ result[instructionName] = {
8750
+ execute: executeFn,
8751
+ useMutation: () => useInstructionMutation(executeFn)
8752
+ };
8753
+ }
8754
+ }
8755
+ return result;
8756
+ }, [client]);
8757
+ return {
8758
+ views: views,
8759
+ instructions: instructions,
8760
+ zustandStore: client?.store,
8761
+ client: client,
8762
+ isLoading,
8763
+ error
8764
+ };
8765
+ }
8766
+
7687
8767
  function getNestedValue(obj, path) {
7688
8768
  let current = obj;
7689
8769
  for (const segment of path) {
@@ -7979,502 +9059,5 @@ class ZustandAdapter {
7979
9059
  }
7980
9060
  }
7981
9061
 
7982
- const DEFAULT_FLUSH_INTERVAL_MS = 16;
7983
-
7984
- function createRuntime(config) {
7985
- const adapter = new ZustandAdapter();
7986
- const processor = new FrameProcessor(adapter, {
7987
- maxEntriesPerView: config.maxEntriesPerView,
7988
- flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
7989
- });
7990
- const connection = new ConnectionManager({
7991
- websocketUrl: config.websocketUrl,
7992
- reconnectIntervals: config.reconnectIntervals,
7993
- maxReconnectAttempts: config.maxReconnectAttempts,
7994
- });
7995
- const subscriptionRegistry = new SubscriptionRegistry(connection);
7996
- connection.onFrame((frame) => {
7997
- processor.handleFrame(frame);
7998
- });
7999
- connection.onStateChange((state, error) => {
8000
- adapter.setConnectionState(state, error);
8001
- });
8002
- return {
8003
- zustandStore: adapter.store,
8004
- adapter,
8005
- connection,
8006
- subscriptionRegistry,
8007
- wallet: config.wallet,
8008
- subscribe(view, key, filters, take, skip) {
8009
- const subscription = { view, key, filters, take, skip };
8010
- const unsubscribe = subscriptionRegistry.subscribe(subscription);
8011
- return {
8012
- view,
8013
- key,
8014
- filters,
8015
- take,
8016
- skip,
8017
- unsubscribe,
8018
- };
8019
- },
8020
- unsubscribe(handle) {
8021
- handle.unsubscribe();
8022
- },
8023
- };
8024
- }
8025
-
8026
- const HyperstackContext = createContext(null);
8027
- function resolveNetworkConfig(network, websocketUrl) {
8028
- if (websocketUrl) {
8029
- return {
8030
- name: 'custom',
8031
- websocketUrl
8032
- };
8033
- }
8034
- if (typeof network === 'object') {
8035
- return network;
8036
- }
8037
- if (network === 'mainnet') {
8038
- return {
8039
- name: 'mainnet',
8040
- websocketUrl: 'wss://mainnet.hyperstack.xyz',
8041
- };
8042
- }
8043
- if (network === 'devnet') {
8044
- return {
8045
- name: 'devnet',
8046
- websocketUrl: 'ws://localhost:8080',
8047
- };
8048
- }
8049
- if (network === 'localnet') {
8050
- return {
8051
- name: 'localnet',
8052
- websocketUrl: 'ws://localhost:8080',
8053
- };
8054
- }
8055
- throw new Error('Must provide either network or websocketUrl');
8056
- }
8057
- function HyperstackProvider({ children, ...config }) {
8058
- const networkConfig = useMemo(() => {
8059
- try {
8060
- return resolveNetworkConfig(config.network, config.websocketUrl);
8061
- }
8062
- catch (error) {
8063
- console.error('[Hyperstack] Invalid network configuration:', error);
8064
- throw error;
8065
- }
8066
- }, [config.network, config.websocketUrl]);
8067
- const runtimeRef = useRef(null);
8068
- if (!runtimeRef.current) {
8069
- try {
8070
- runtimeRef.current = createRuntime({
8071
- ...config,
8072
- websocketUrl: networkConfig.websocketUrl,
8073
- network: networkConfig
8074
- });
8075
- }
8076
- catch (error) {
8077
- console.error('[Hyperstack] Failed to create runtime:', error);
8078
- throw error;
8079
- }
8080
- }
8081
- const runtime = runtimeRef.current;
8082
- const isMountedRef = useRef(true);
8083
- useEffect(() => {
8084
- isMountedRef.current = true;
8085
- if (config.autoConnect !== false) {
8086
- try {
8087
- runtime.connection.connect();
8088
- }
8089
- catch (error) {
8090
- console.error('[Hyperstack] Failed to auto-connect:', error);
8091
- }
8092
- }
8093
- return () => {
8094
- isMountedRef.current = false;
8095
- setTimeout(() => {
8096
- if (!isMountedRef.current) {
8097
- try {
8098
- runtime.subscriptionRegistry.clear();
8099
- runtime.connection.disconnect();
8100
- }
8101
- catch (error) {
8102
- console.error('[Hyperstack] Failed to disconnect:', error);
8103
- }
8104
- }
8105
- }, 100);
8106
- };
8107
- }, [runtime, config.autoConnect]);
8108
- const value = {
8109
- runtime,
8110
- config: { ...config, network: networkConfig }
8111
- };
8112
- return (React.createElement(HyperstackContext.Provider, { value: value }, children));
8113
- }
8114
- function useHyperstackContext() {
8115
- const context = useContext(HyperstackContext);
8116
- if (!context) {
8117
- throw new Error('useHyperstackContext must be used within HyperstackProvider');
8118
- }
8119
- return context;
8120
- }
8121
- function useConnectionState() {
8122
- const { runtime } = useHyperstackContext();
8123
- return useSyncExternalStore((callback) => {
8124
- const unsubscribe = runtime.zustandStore.subscribe(callback);
8125
- return unsubscribe;
8126
- }, () => runtime.zustandStore.getState().connectionState);
8127
- }
8128
- function useView(viewPath) {
8129
- const { runtime } = useHyperstackContext();
8130
- return useSyncExternalStore((callback) => runtime.zustandStore.subscribe(callback), () => {
8131
- const viewMap = runtime.zustandStore.getState().entities.get(viewPath);
8132
- if (!viewMap)
8133
- return [];
8134
- return Array.from(viewMap.values());
8135
- });
8136
- }
8137
- function useEntity(viewPath, key) {
8138
- const { runtime } = useHyperstackContext();
8139
- return useSyncExternalStore((callback) => runtime.zustandStore.subscribe(callback), () => {
8140
- const viewMap = runtime.zustandStore.getState().entities.get(viewPath);
8141
- if (!viewMap)
8142
- return null;
8143
- const value = viewMap.get(key);
8144
- return value !== undefined ? value : null;
8145
- });
8146
- }
8147
-
8148
- function createStateViewHook(viewDef, runtime) {
8149
- return {
8150
- use: (key, options) => {
8151
- const [isLoading, setIsLoading] = useState(!options?.initialData);
8152
- const [error, setError] = useState();
8153
- const keyString = key ? Object.values(key)[0] : undefined;
8154
- const enabled = options?.enabled !== false;
8155
- useEffect(() => {
8156
- if (!enabled)
8157
- return undefined;
8158
- try {
8159
- const handle = runtime.subscribe(viewDef.view, keyString);
8160
- setIsLoading(true);
8161
- return () => {
8162
- try {
8163
- handle.unsubscribe();
8164
- }
8165
- catch (err) {
8166
- console.error('[Hyperstack] Error unsubscribing from view:', err);
8167
- }
8168
- };
8169
- }
8170
- catch (err) {
8171
- setError(err instanceof Error ? err : new Error('Subscription failed'));
8172
- setIsLoading(false);
8173
- return undefined;
8174
- }
8175
- }, [keyString, enabled]);
8176
- const refresh = useCallback(() => {
8177
- if (!enabled)
8178
- return;
8179
- try {
8180
- const handle = runtime.subscribe(viewDef.view, keyString);
8181
- setIsLoading(true);
8182
- setTimeout(() => {
8183
- try {
8184
- handle.unsubscribe();
8185
- }
8186
- catch (err) {
8187
- console.error('[Hyperstack] Error during refresh unsubscribe:', err);
8188
- }
8189
- }, 0);
8190
- }
8191
- catch (err) {
8192
- setError(err instanceof Error ? err : new Error('Refresh failed'));
8193
- setIsLoading(false);
8194
- }
8195
- }, [keyString, enabled]);
8196
- const data = useSyncExternalStore((callback) => {
8197
- const unsubscribe = runtime.zustandStore.subscribe(callback);
8198
- return unsubscribe;
8199
- }, () => {
8200
- const viewMap = runtime.zustandStore.getState().entities.get(viewDef.view);
8201
- if (!viewMap)
8202
- return undefined;
8203
- if (keyString) {
8204
- return viewMap.get(keyString);
8205
- }
8206
- const firstEntry = viewMap.values().next();
8207
- return firstEntry.done ? undefined : firstEntry.value;
8208
- });
8209
- useEffect(() => {
8210
- if (data && isLoading) {
8211
- setIsLoading(false);
8212
- }
8213
- }, [data, isLoading]);
8214
- return {
8215
- data: (options?.initialData ?? data),
8216
- isLoading,
8217
- error,
8218
- refresh
8219
- };
8220
- }
8221
- };
8222
- }
8223
- function useListViewInternal(viewDef, runtime, params, options) {
8224
- const [isLoading, setIsLoading] = useState(!options?.initialData);
8225
- const [error, setError] = useState();
8226
- const cachedDataRef = useRef(undefined);
8227
- const lastMapRef = useRef(undefined);
8228
- const lastSortedKeysRef = useRef(undefined);
8229
- const enabled = options?.enabled !== false;
8230
- const key = params?.key;
8231
- const take = params?.take;
8232
- const skip = params?.skip;
8233
- const filtersJson = params?.filters ? JSON.stringify(params.filters) : undefined;
8234
- const filters = useMemo(() => params?.filters, [filtersJson]);
8235
- useEffect(() => {
8236
- if (!enabled)
8237
- return undefined;
8238
- try {
8239
- const handle = runtime.subscribe(viewDef.view, key, filters, take, skip);
8240
- setIsLoading(true);
8241
- return () => {
8242
- try {
8243
- handle.unsubscribe();
8244
- }
8245
- catch (err) {
8246
- console.error('[Hyperstack] Error unsubscribing from list view:', err);
8247
- }
8248
- };
8249
- }
8250
- catch (err) {
8251
- setError(err instanceof Error ? err : new Error('Subscription failed'));
8252
- setIsLoading(false);
8253
- return undefined;
8254
- }
8255
- }, [enabled, key, filtersJson, take, skip]);
8256
- const refresh = useCallback(() => {
8257
- if (!enabled)
8258
- return;
8259
- try {
8260
- const handle = runtime.subscribe(viewDef.view, key, filters, take, skip);
8261
- setIsLoading(true);
8262
- setTimeout(() => {
8263
- try {
8264
- handle.unsubscribe();
8265
- }
8266
- catch (err) {
8267
- console.error('[Hyperstack] Error during list refresh unsubscribe:', err);
8268
- }
8269
- }, 0);
8270
- }
8271
- catch (err) {
8272
- setError(err instanceof Error ? err : new Error('Refresh failed'));
8273
- setIsLoading(false);
8274
- }
8275
- }, [enabled, key, filtersJson, take, skip]);
8276
- const data = useSyncExternalStore((callback) => {
8277
- const unsubscribe = runtime.zustandStore.subscribe(callback);
8278
- return unsubscribe;
8279
- }, () => {
8280
- const state = runtime.zustandStore.getState();
8281
- const baseMap = state.entities.get(viewDef.view);
8282
- const sortedKeys = state.sortedKeys.get(viewDef.view);
8283
- if (!baseMap) {
8284
- if (cachedDataRef.current !== undefined) {
8285
- cachedDataRef.current = undefined;
8286
- lastMapRef.current = undefined;
8287
- lastSortedKeysRef.current = undefined;
8288
- }
8289
- return undefined;
8290
- }
8291
- if (lastMapRef.current === baseMap && lastSortedKeysRef.current === sortedKeys && cachedDataRef.current !== undefined) {
8292
- return cachedDataRef.current;
8293
- }
8294
- let items;
8295
- if (sortedKeys && sortedKeys.length > 0) {
8296
- items = sortedKeys.map(k => baseMap.get(k)).filter(v => v !== undefined);
8297
- }
8298
- else {
8299
- items = Array.from(baseMap.values());
8300
- }
8301
- if (params?.where) {
8302
- items = items.filter((item) => {
8303
- return Object.entries(params.where).every(([fieldKey, condition]) => {
8304
- const value = item[fieldKey];
8305
- if (typeof condition === 'object' && condition !== null) {
8306
- const cond = condition;
8307
- if ('gte' in cond)
8308
- return value >= cond.gte;
8309
- if ('lte' in cond)
8310
- return value <= cond.lte;
8311
- if ('gt' in cond)
8312
- return value > cond.gt;
8313
- if ('lt' in cond)
8314
- return value < cond.lt;
8315
- }
8316
- return value === condition;
8317
- });
8318
- });
8319
- }
8320
- if (params?.limit) {
8321
- items = items.slice(0, params.limit);
8322
- }
8323
- lastMapRef.current = baseMap;
8324
- lastSortedKeysRef.current = sortedKeys;
8325
- cachedDataRef.current = items;
8326
- return items;
8327
- });
8328
- useEffect(() => {
8329
- if (data && isLoading) {
8330
- setIsLoading(false);
8331
- }
8332
- }, [data, isLoading]);
8333
- return {
8334
- data: (options?.initialData ?? data),
8335
- isLoading,
8336
- error,
8337
- refresh
8338
- };
8339
- }
8340
- function createListViewHook(viewDef, runtime) {
8341
- function use(params, options) {
8342
- const result = useListViewInternal(viewDef, runtime, params, options);
8343
- if (params?.take === 1) {
8344
- return {
8345
- data: result.data?.[0],
8346
- isLoading: result.isLoading,
8347
- error: result.error,
8348
- refresh: result.refresh
8349
- };
8350
- }
8351
- return result;
8352
- }
8353
- function useOne(params, options) {
8354
- const paramsWithTake = params ? { ...params, take: 1 } : { take: 1 };
8355
- const result = useListViewInternal(viewDef, runtime, paramsWithTake, options);
8356
- return {
8357
- data: result.data?.[0],
8358
- isLoading: result.isLoading,
8359
- error: result.error,
8360
- refresh: result.refresh
8361
- };
8362
- }
8363
- return { use, useOne };
8364
- }
8365
-
8366
- function createTxMutationHook(runtime, transactions) {
8367
- return function useMutation() {
8368
- const [status, setStatus] = useState('idle');
8369
- const [error, setError] = useState();
8370
- const [signature, setSignature] = useState();
8371
- const submit = async (instructionOrTx) => {
8372
- setStatus('pending');
8373
- setError(undefined);
8374
- setSignature(undefined);
8375
- try {
8376
- if (!instructionOrTx) {
8377
- throw new Error('Transaction instruction or transaction object is required');
8378
- }
8379
- if (!runtime.wallet) {
8380
- throw new Error('Wallet not connected. Please provide a wallet adapter to HyperstackProvider.');
8381
- }
8382
- let txSignature;
8383
- let instructionsToRefresh = [];
8384
- if (Array.isArray(instructionOrTx)) {
8385
- txSignature = await runtime.wallet.signAndSend(instructionOrTx);
8386
- instructionsToRefresh = instructionOrTx.filter(inst => inst && typeof inst === 'object' && inst.instruction && inst.params !== undefined);
8387
- }
8388
- else if (typeof instructionOrTx === 'object' &&
8389
- instructionOrTx.instruction &&
8390
- instructionOrTx.params !== undefined) {
8391
- txSignature = await runtime.wallet.signAndSend(instructionOrTx);
8392
- instructionsToRefresh = [instructionOrTx];
8393
- }
8394
- else {
8395
- txSignature = await runtime.wallet.signAndSend(instructionOrTx);
8396
- }
8397
- setSignature(txSignature);
8398
- setStatus('success');
8399
- if (transactions && instructionsToRefresh.length > 0) {
8400
- for (const inst of instructionsToRefresh) {
8401
- const txDef = transactions[inst.instruction];
8402
- if (txDef?.refresh) {
8403
- for (const refreshTarget of txDef.refresh) {
8404
- try {
8405
- const key = typeof refreshTarget.key === 'function'
8406
- ? refreshTarget.key(inst.params)
8407
- : refreshTarget.key;
8408
- runtime.subscribe(refreshTarget.view, key);
8409
- }
8410
- catch (err) {
8411
- console.error('[Hyperstack] Error refreshing view after transaction:', err);
8412
- }
8413
- }
8414
- }
8415
- }
8416
- }
8417
- return txSignature;
8418
- }
8419
- catch (err) {
8420
- const errorMessage = err instanceof Error ? err.message : 'Transaction failed';
8421
- console.error('[Hyperstack] Transaction error:', errorMessage, err);
8422
- setStatus('error');
8423
- setError(errorMessage);
8424
- throw err;
8425
- }
8426
- };
8427
- const reset = () => {
8428
- setStatus('idle');
8429
- setError(undefined);
8430
- setSignature(undefined);
8431
- };
8432
- return {
8433
- submit,
8434
- status,
8435
- error,
8436
- signature,
8437
- reset
8438
- };
8439
- };
8440
- }
8441
-
8442
- function useHyperstack(stack) {
8443
- if (!stack) {
8444
- throw new Error('[Hyperstack] Stack definition is required');
8445
- }
8446
- const { runtime } = useHyperstackContext();
8447
- const views = {};
8448
- for (const [viewName, viewGroup] of Object.entries(stack.views)) {
8449
- views[viewName] = {};
8450
- if (typeof viewGroup === 'object' && viewGroup !== null) {
8451
- const group = viewGroup;
8452
- for (const [subViewName, viewDef] of Object.entries(group)) {
8453
- if (!viewDef || typeof viewDef !== 'object' || !('mode' in viewDef))
8454
- continue;
8455
- if (viewDef.mode === 'state') {
8456
- views[viewName][subViewName] = createStateViewHook(viewDef, runtime);
8457
- }
8458
- else if (viewDef.mode === 'list') {
8459
- views[viewName][subViewName] = createListViewHook(viewDef, runtime);
8460
- }
8461
- }
8462
- }
8463
- }
8464
- const tx = {};
8465
- if (stack.transactions) {
8466
- for (const [txName, txDef] of Object.entries(stack.transactions)) {
8467
- tx[txName] = txDef.build;
8468
- }
8469
- }
8470
- tx.useMutation = createTxMutationHook(runtime, stack.transactions);
8471
- return {
8472
- views,
8473
- tx,
8474
- zustandStore: runtime.zustandStore,
8475
- runtime
8476
- };
8477
- }
8478
-
8479
- export { ConnectionManager, DEFAULT_CONFIG, DEFAULT_MAX_ENTRIES_PER_VIEW, FrameProcessor, HyperStack, HyperStackError, HyperstackProvider, MemoryAdapter, SubscriptionRegistry, ZustandAdapter, createRuntime, isSnapshotFrame, isValidFrame, parseFrame, parseFrameFromBlob, useConnectionState, useEntity, useHyperstack, useHyperstackContext, useView };
9062
+ export { ConnectionManager, DEFAULT_CONFIG, DEFAULT_MAX_ENTRIES_PER_VIEW, FrameProcessor, HyperStack, HyperStackError, HyperstackProvider, MemoryAdapter, SubscriptionRegistry, ZustandAdapter, createInstructionExecutor, createPublicKeySeed, createSeed, derivePda, executeInstruction, formatProgramError, isSnapshotFrame, isValidFrame, parseFrame, parseFrameFromBlob, parseInstructionError, resolveAccounts, serializeInstructionData, useConnectionState, useEntity, useHyperstack, useHyperstackContext, useInstructionMutation, useView, validateAccountResolution, waitForConfirmation };
8480
9063
  //# sourceMappingURL=index.esm.js.map