hyperstack-react 0.3.14 → 0.4.0
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.d.ts +58 -76
- package/dist/index.esm.js +1070 -522
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +1080 -521
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.esm.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { createContext,
|
|
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
|
-
|
|
7569
|
-
return
|
|
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
|
-
|
|
7585
|
-
return
|
|
7650
|
+
use(options) {
|
|
7651
|
+
return createEntityStream(storage, subscriptionRegistry, { view: viewDef.view, ...options });
|
|
7652
|
+
},
|
|
7653
|
+
watch(options) {
|
|
7654
|
+
return createUpdateStream(storage, subscriptionRegistry, { view: viewDef.view, ...options });
|
|
7586
7655
|
},
|
|
7587
|
-
watchRich() {
|
|
7588
|
-
return createRichUpdateStream(storage, subscriptionRegistry, { view: viewDef.view });
|
|
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 [
|
|
7669
|
+
for (const [entityName, viewGroup] of Object.entries(stack.views)) {
|
|
7601
7670
|
const group = viewGroup;
|
|
7602
7671
|
const typedGroup = {};
|
|
7603
|
-
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
|
|
7607
|
-
|
|
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[
|
|
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(
|
|
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
|
-
|
|
7637
|
-
|
|
7638
|
-
|
|
7639
|
-
|
|
7640
|
-
|
|
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,469 @@ class HyperStack {
|
|
|
7684
8266
|
}
|
|
7685
8267
|
}
|
|
7686
8268
|
|
|
8269
|
+
const HyperstackContext = createContext(null);
|
|
8270
|
+
function HyperstackProvider({ children, fallback = null, ...config }) {
|
|
8271
|
+
const clientsRef = useRef(new Map());
|
|
8272
|
+
const connectingRef = useRef(new Map());
|
|
8273
|
+
const getOrCreateClient = useCallback(async (stack, urlOverride) => {
|
|
8274
|
+
const cacheKey = urlOverride ? `${stack.name}:${urlOverride}` : stack.name;
|
|
8275
|
+
const existing = clientsRef.current.get(cacheKey);
|
|
8276
|
+
if (existing) {
|
|
8277
|
+
return existing.client;
|
|
8278
|
+
}
|
|
8279
|
+
const connecting = connectingRef.current.get(cacheKey);
|
|
8280
|
+
if (connecting) {
|
|
8281
|
+
return connecting;
|
|
8282
|
+
}
|
|
8283
|
+
const connectionPromise = HyperStack.connect(stack, {
|
|
8284
|
+
url: urlOverride,
|
|
8285
|
+
autoReconnect: config.autoConnect,
|
|
8286
|
+
reconnectIntervals: config.reconnectIntervals,
|
|
8287
|
+
maxReconnectAttempts: config.maxReconnectAttempts,
|
|
8288
|
+
maxEntriesPerView: config.maxEntriesPerView,
|
|
8289
|
+
}).then((client) => {
|
|
8290
|
+
clientsRef.current.set(cacheKey, {
|
|
8291
|
+
client,
|
|
8292
|
+
disconnect: () => client.disconnect()
|
|
8293
|
+
});
|
|
8294
|
+
connectingRef.current.delete(cacheKey);
|
|
8295
|
+
return client;
|
|
8296
|
+
});
|
|
8297
|
+
connectingRef.current.set(cacheKey, connectionPromise);
|
|
8298
|
+
return connectionPromise;
|
|
8299
|
+
}, [config.autoConnect, config.reconnectIntervals, config.maxReconnectAttempts, config.maxEntriesPerView]);
|
|
8300
|
+
const getClient = useCallback((stack) => {
|
|
8301
|
+
if (!stack)
|
|
8302
|
+
return null;
|
|
8303
|
+
const entry = clientsRef.current.get(stack.name);
|
|
8304
|
+
return entry ? entry.client : null;
|
|
8305
|
+
}, []);
|
|
8306
|
+
useEffect(() => {
|
|
8307
|
+
return () => {
|
|
8308
|
+
clientsRef.current.forEach((entry) => {
|
|
8309
|
+
entry.disconnect();
|
|
8310
|
+
});
|
|
8311
|
+
clientsRef.current.clear();
|
|
8312
|
+
connectingRef.current.clear();
|
|
8313
|
+
};
|
|
8314
|
+
}, []);
|
|
8315
|
+
const value = {
|
|
8316
|
+
getOrCreateClient,
|
|
8317
|
+
getClient,
|
|
8318
|
+
config,
|
|
8319
|
+
};
|
|
8320
|
+
return (React.createElement(HyperstackContext.Provider, { value: value }, children));
|
|
8321
|
+
}
|
|
8322
|
+
function useHyperstackContext() {
|
|
8323
|
+
const context = useContext(HyperstackContext);
|
|
8324
|
+
if (!context) {
|
|
8325
|
+
throw new Error('useHyperstackContext must be used within HyperstackProvider');
|
|
8326
|
+
}
|
|
8327
|
+
return context;
|
|
8328
|
+
}
|
|
8329
|
+
function useConnectionState(stack) {
|
|
8330
|
+
const { getClient } = useHyperstackContext();
|
|
8331
|
+
const client = stack ? getClient(stack) : null;
|
|
8332
|
+
return useSyncExternalStore((callback) => {
|
|
8333
|
+
if (!client)
|
|
8334
|
+
return () => { };
|
|
8335
|
+
return client.onConnectionStateChange(callback);
|
|
8336
|
+
}, () => client?.connectionState ?? 'disconnected');
|
|
8337
|
+
}
|
|
8338
|
+
function useView(stack, viewPath) {
|
|
8339
|
+
const { getClient } = useHyperstackContext();
|
|
8340
|
+
const client = getClient(stack);
|
|
8341
|
+
return useSyncExternalStore((callback) => {
|
|
8342
|
+
if (!client)
|
|
8343
|
+
return () => { };
|
|
8344
|
+
return client.store.onUpdate(callback);
|
|
8345
|
+
}, () => {
|
|
8346
|
+
if (!client)
|
|
8347
|
+
return [];
|
|
8348
|
+
const data = client.store.getAll(viewPath);
|
|
8349
|
+
return data;
|
|
8350
|
+
});
|
|
8351
|
+
}
|
|
8352
|
+
function useEntity(stack, viewPath, key) {
|
|
8353
|
+
const { getClient } = useHyperstackContext();
|
|
8354
|
+
const client = getClient(stack);
|
|
8355
|
+
return useSyncExternalStore((callback) => {
|
|
8356
|
+
if (!client)
|
|
8357
|
+
return () => { };
|
|
8358
|
+
return client.store.onUpdate(callback);
|
|
8359
|
+
}, () => {
|
|
8360
|
+
if (!client)
|
|
8361
|
+
return null;
|
|
8362
|
+
const data = client.store.get(viewPath, key);
|
|
8363
|
+
return data;
|
|
8364
|
+
});
|
|
8365
|
+
}
|
|
8366
|
+
|
|
8367
|
+
function shallowArrayEqual(a, b) {
|
|
8368
|
+
if (a === b)
|
|
8369
|
+
return true;
|
|
8370
|
+
if (!a || !b)
|
|
8371
|
+
return false;
|
|
8372
|
+
if (a.length !== b.length)
|
|
8373
|
+
return false;
|
|
8374
|
+
for (let i = 0; i < a.length; i++) {
|
|
8375
|
+
if (a[i] !== b[i])
|
|
8376
|
+
return false;
|
|
8377
|
+
}
|
|
8378
|
+
return true;
|
|
8379
|
+
}
|
|
8380
|
+
function useStateView(viewDef, client, key, options) {
|
|
8381
|
+
const [isLoading, setIsLoading] = useState(!options?.initialData);
|
|
8382
|
+
const [error, setError] = useState();
|
|
8383
|
+
const clientRef = useRef(client);
|
|
8384
|
+
clientRef.current = client;
|
|
8385
|
+
const cachedSnapshotRef = useRef(undefined);
|
|
8386
|
+
const keyString = key ? Object.values(key)[0] : undefined;
|
|
8387
|
+
const enabled = options?.enabled !== false;
|
|
8388
|
+
useEffect(() => {
|
|
8389
|
+
if (!enabled || !clientRef.current)
|
|
8390
|
+
return undefined;
|
|
8391
|
+
try {
|
|
8392
|
+
const registry = clientRef.current.getSubscriptionRegistry();
|
|
8393
|
+
const unsubscribe = registry.subscribe({ view: viewDef.view, key: keyString });
|
|
8394
|
+
setIsLoading(true);
|
|
8395
|
+
return () => {
|
|
8396
|
+
try {
|
|
8397
|
+
unsubscribe();
|
|
8398
|
+
}
|
|
8399
|
+
catch (err) {
|
|
8400
|
+
console.error('[Hyperstack] Error unsubscribing from view:', err);
|
|
8401
|
+
}
|
|
8402
|
+
};
|
|
8403
|
+
}
|
|
8404
|
+
catch (err) {
|
|
8405
|
+
setError(err instanceof Error ? err : new Error('Subscription failed'));
|
|
8406
|
+
setIsLoading(false);
|
|
8407
|
+
return undefined;
|
|
8408
|
+
}
|
|
8409
|
+
}, [viewDef.view, keyString, enabled, client]);
|
|
8410
|
+
const refresh = useCallback(() => {
|
|
8411
|
+
if (!enabled || !clientRef.current)
|
|
8412
|
+
return;
|
|
8413
|
+
try {
|
|
8414
|
+
const registry = clientRef.current.getSubscriptionRegistry();
|
|
8415
|
+
const unsubscribe = registry.subscribe({ view: viewDef.view, key: keyString });
|
|
8416
|
+
setIsLoading(true);
|
|
8417
|
+
setTimeout(() => {
|
|
8418
|
+
try {
|
|
8419
|
+
unsubscribe();
|
|
8420
|
+
}
|
|
8421
|
+
catch (err) {
|
|
8422
|
+
console.error('[Hyperstack] Error during refresh unsubscribe:', err);
|
|
8423
|
+
}
|
|
8424
|
+
}, 0);
|
|
8425
|
+
}
|
|
8426
|
+
catch (err) {
|
|
8427
|
+
setError(err instanceof Error ? err : new Error('Refresh failed'));
|
|
8428
|
+
setIsLoading(false);
|
|
8429
|
+
}
|
|
8430
|
+
}, [viewDef.view, keyString, enabled]);
|
|
8431
|
+
const subscribe = useCallback((callback) => {
|
|
8432
|
+
if (!clientRef.current)
|
|
8433
|
+
return () => { };
|
|
8434
|
+
return clientRef.current.store.onUpdate(callback);
|
|
8435
|
+
}, [client]);
|
|
8436
|
+
const getSnapshot = useCallback(() => {
|
|
8437
|
+
if (!clientRef.current)
|
|
8438
|
+
return cachedSnapshotRef.current;
|
|
8439
|
+
const entity = keyString
|
|
8440
|
+
? clientRef.current.store.get(viewDef.view, keyString)
|
|
8441
|
+
: clientRef.current.store.getAll(viewDef.view)[0];
|
|
8442
|
+
// Cache the result to return stable reference for useSyncExternalStore
|
|
8443
|
+
if (entity !== cachedSnapshotRef.current) {
|
|
8444
|
+
cachedSnapshotRef.current = entity;
|
|
8445
|
+
}
|
|
8446
|
+
return cachedSnapshotRef.current;
|
|
8447
|
+
}, [viewDef.view, keyString, client]);
|
|
8448
|
+
const data = useSyncExternalStore(subscribe, getSnapshot);
|
|
8449
|
+
useEffect(() => {
|
|
8450
|
+
if (data !== undefined && isLoading) {
|
|
8451
|
+
setIsLoading(false);
|
|
8452
|
+
}
|
|
8453
|
+
}, [data, isLoading]);
|
|
8454
|
+
return {
|
|
8455
|
+
data: (options?.initialData ?? data),
|
|
8456
|
+
isLoading: client === null || isLoading,
|
|
8457
|
+
error,
|
|
8458
|
+
refresh
|
|
8459
|
+
};
|
|
8460
|
+
}
|
|
8461
|
+
function useListView(viewDef, client, params, options) {
|
|
8462
|
+
const [isLoading, setIsLoading] = useState(!options?.initialData);
|
|
8463
|
+
const [error, setError] = useState();
|
|
8464
|
+
const clientRef = useRef(client);
|
|
8465
|
+
clientRef.current = client;
|
|
8466
|
+
const cachedSnapshotRef = useRef(undefined);
|
|
8467
|
+
const enabled = options?.enabled !== false;
|
|
8468
|
+
const key = params?.key;
|
|
8469
|
+
const take = params?.take;
|
|
8470
|
+
const skip = params?.skip;
|
|
8471
|
+
const whereJson = params?.where ? JSON.stringify(params.where) : undefined;
|
|
8472
|
+
const filtersJson = params?.filters ? JSON.stringify(params.filters) : undefined;
|
|
8473
|
+
const limit = params?.limit;
|
|
8474
|
+
useEffect(() => {
|
|
8475
|
+
if (!enabled || !clientRef.current)
|
|
8476
|
+
return undefined;
|
|
8477
|
+
try {
|
|
8478
|
+
const registry = clientRef.current.getSubscriptionRegistry();
|
|
8479
|
+
const unsubscribe = registry.subscribe({
|
|
8480
|
+
view: viewDef.view,
|
|
8481
|
+
key,
|
|
8482
|
+
filters: params?.filters,
|
|
8483
|
+
take,
|
|
8484
|
+
skip
|
|
8485
|
+
});
|
|
8486
|
+
setIsLoading(true);
|
|
8487
|
+
return () => {
|
|
8488
|
+
try {
|
|
8489
|
+
unsubscribe();
|
|
8490
|
+
}
|
|
8491
|
+
catch (err) {
|
|
8492
|
+
console.error('[Hyperstack] Error unsubscribing from list view:', err);
|
|
8493
|
+
}
|
|
8494
|
+
};
|
|
8495
|
+
}
|
|
8496
|
+
catch (err) {
|
|
8497
|
+
setError(err instanceof Error ? err : new Error('Subscription failed'));
|
|
8498
|
+
setIsLoading(false);
|
|
8499
|
+
return undefined;
|
|
8500
|
+
}
|
|
8501
|
+
}, [viewDef.view, enabled, key, filtersJson, take, skip, client]);
|
|
8502
|
+
const refresh = useCallback(() => {
|
|
8503
|
+
if (!enabled || !clientRef.current)
|
|
8504
|
+
return;
|
|
8505
|
+
try {
|
|
8506
|
+
const registry = clientRef.current.getSubscriptionRegistry();
|
|
8507
|
+
const unsubscribe = registry.subscribe({
|
|
8508
|
+
view: viewDef.view,
|
|
8509
|
+
key,
|
|
8510
|
+
filters: params?.filters,
|
|
8511
|
+
take,
|
|
8512
|
+
skip
|
|
8513
|
+
});
|
|
8514
|
+
setIsLoading(true);
|
|
8515
|
+
setTimeout(() => {
|
|
8516
|
+
try {
|
|
8517
|
+
unsubscribe();
|
|
8518
|
+
}
|
|
8519
|
+
catch (err) {
|
|
8520
|
+
console.error('[Hyperstack] Error during list refresh unsubscribe:', err);
|
|
8521
|
+
}
|
|
8522
|
+
}, 0);
|
|
8523
|
+
}
|
|
8524
|
+
catch (err) {
|
|
8525
|
+
setError(err instanceof Error ? err : new Error('Refresh failed'));
|
|
8526
|
+
setIsLoading(false);
|
|
8527
|
+
}
|
|
8528
|
+
}, [viewDef.view, enabled, key, filtersJson, take, skip]);
|
|
8529
|
+
const subscribe = useCallback((callback) => {
|
|
8530
|
+
if (!clientRef.current)
|
|
8531
|
+
return () => { };
|
|
8532
|
+
return clientRef.current.store.onUpdate(callback);
|
|
8533
|
+
}, [client]);
|
|
8534
|
+
const getSnapshot = useCallback(() => {
|
|
8535
|
+
if (!clientRef.current)
|
|
8536
|
+
return cachedSnapshotRef.current;
|
|
8537
|
+
const viewData = clientRef.current.store.getAll(viewDef.view);
|
|
8538
|
+
if (!viewData || viewData.length === 0) {
|
|
8539
|
+
if (cachedSnapshotRef.current !== undefined) {
|
|
8540
|
+
cachedSnapshotRef.current = undefined;
|
|
8541
|
+
}
|
|
8542
|
+
return cachedSnapshotRef.current;
|
|
8543
|
+
}
|
|
8544
|
+
let items = viewData;
|
|
8545
|
+
if (params?.where) {
|
|
8546
|
+
items = items.filter((item) => {
|
|
8547
|
+
return Object.entries(params.where).every(([fieldKey, condition]) => {
|
|
8548
|
+
const value = item[fieldKey];
|
|
8549
|
+
if (typeof condition === 'object' && condition !== null) {
|
|
8550
|
+
const cond = condition;
|
|
8551
|
+
if ('gte' in cond)
|
|
8552
|
+
return value >= cond.gte;
|
|
8553
|
+
if ('lte' in cond)
|
|
8554
|
+
return value <= cond.lte;
|
|
8555
|
+
if ('gt' in cond)
|
|
8556
|
+
return value > cond.gt;
|
|
8557
|
+
if ('lt' in cond)
|
|
8558
|
+
return value < cond.lt;
|
|
8559
|
+
}
|
|
8560
|
+
return value === condition;
|
|
8561
|
+
});
|
|
8562
|
+
});
|
|
8563
|
+
}
|
|
8564
|
+
if (limit) {
|
|
8565
|
+
items = items.slice(0, limit);
|
|
8566
|
+
}
|
|
8567
|
+
const result = items;
|
|
8568
|
+
// Cache the result - only update if data actually changed
|
|
8569
|
+
if (!shallowArrayEqual(cachedSnapshotRef.current, result)) {
|
|
8570
|
+
cachedSnapshotRef.current = result;
|
|
8571
|
+
}
|
|
8572
|
+
return cachedSnapshotRef.current;
|
|
8573
|
+
}, [viewDef.view, whereJson, limit, client]);
|
|
8574
|
+
const data = useSyncExternalStore(subscribe, getSnapshot);
|
|
8575
|
+
useEffect(() => {
|
|
8576
|
+
if (data !== undefined && isLoading) {
|
|
8577
|
+
setIsLoading(false);
|
|
8578
|
+
}
|
|
8579
|
+
}, [data, isLoading]);
|
|
8580
|
+
return {
|
|
8581
|
+
data: (options?.initialData ?? data),
|
|
8582
|
+
isLoading: client === null || isLoading,
|
|
8583
|
+
error,
|
|
8584
|
+
refresh
|
|
8585
|
+
};
|
|
8586
|
+
}
|
|
8587
|
+
function createStateViewHook(viewDef, client) {
|
|
8588
|
+
return {
|
|
8589
|
+
use: (key, options) => {
|
|
8590
|
+
return useStateView(viewDef, client, key, options);
|
|
8591
|
+
}
|
|
8592
|
+
};
|
|
8593
|
+
}
|
|
8594
|
+
function createListViewHook(viewDef, client) {
|
|
8595
|
+
function use(params, options) {
|
|
8596
|
+
const result = useListView(viewDef, client, params, options);
|
|
8597
|
+
if (params?.take === 1) {
|
|
8598
|
+
return {
|
|
8599
|
+
data: result.data?.[0],
|
|
8600
|
+
isLoading: result.isLoading,
|
|
8601
|
+
error: result.error,
|
|
8602
|
+
refresh: result.refresh
|
|
8603
|
+
};
|
|
8604
|
+
}
|
|
8605
|
+
return result;
|
|
8606
|
+
}
|
|
8607
|
+
function useOne(params, options) {
|
|
8608
|
+
const paramsWithTake = params ? { ...params, take: 1 } : { take: 1 };
|
|
8609
|
+
const result = useListView(viewDef, client, paramsWithTake, options);
|
|
8610
|
+
return {
|
|
8611
|
+
data: result.data?.[0],
|
|
8612
|
+
isLoading: result.isLoading,
|
|
8613
|
+
error: result.error,
|
|
8614
|
+
refresh: result.refresh
|
|
8615
|
+
};
|
|
8616
|
+
}
|
|
8617
|
+
return { use, useOne };
|
|
8618
|
+
}
|
|
8619
|
+
|
|
8620
|
+
function useInstructionMutation(execute) {
|
|
8621
|
+
const [status, setStatus] = useState('idle');
|
|
8622
|
+
const [error, setError] = useState(null);
|
|
8623
|
+
const [signature, setSignature] = useState(null);
|
|
8624
|
+
const submit = useCallback(async (args, options) => {
|
|
8625
|
+
setStatus('pending');
|
|
8626
|
+
setError(null);
|
|
8627
|
+
setSignature(null);
|
|
8628
|
+
try {
|
|
8629
|
+
const result = await execute(args, options);
|
|
8630
|
+
setStatus('success');
|
|
8631
|
+
setSignature(result.signature);
|
|
8632
|
+
if (options?.onSuccess) {
|
|
8633
|
+
options.onSuccess(result);
|
|
8634
|
+
}
|
|
8635
|
+
return result;
|
|
8636
|
+
}
|
|
8637
|
+
catch (err) {
|
|
8638
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
8639
|
+
const programError = parseInstructionError(err, []);
|
|
8640
|
+
const displayError = programError
|
|
8641
|
+
? `${programError.name}: ${programError.message}`
|
|
8642
|
+
: errorMessage;
|
|
8643
|
+
setStatus('error');
|
|
8644
|
+
setError(displayError);
|
|
8645
|
+
if (options?.onError && err instanceof Error) {
|
|
8646
|
+
options.onError(err);
|
|
8647
|
+
}
|
|
8648
|
+
throw err;
|
|
8649
|
+
}
|
|
8650
|
+
}, [execute]);
|
|
8651
|
+
const reset = useCallback(() => {
|
|
8652
|
+
setStatus('idle');
|
|
8653
|
+
setError(null);
|
|
8654
|
+
setSignature(null);
|
|
8655
|
+
}, []);
|
|
8656
|
+
return {
|
|
8657
|
+
submit,
|
|
8658
|
+
status,
|
|
8659
|
+
error,
|
|
8660
|
+
signature,
|
|
8661
|
+
isLoading: status === 'pending',
|
|
8662
|
+
reset,
|
|
8663
|
+
};
|
|
8664
|
+
}
|
|
8665
|
+
|
|
8666
|
+
function useHyperstack(stack, options) {
|
|
8667
|
+
const { getOrCreateClient, getClient } = useHyperstackContext();
|
|
8668
|
+
const urlOverride = options?.url;
|
|
8669
|
+
const [client, setClient] = useState(getClient(stack));
|
|
8670
|
+
const [isLoading, setIsLoading] = useState(!client);
|
|
8671
|
+
const [error, setError] = useState(null);
|
|
8672
|
+
useEffect(() => {
|
|
8673
|
+
const existingClient = getClient(stack);
|
|
8674
|
+
if (existingClient && !urlOverride) {
|
|
8675
|
+
setClient(existingClient);
|
|
8676
|
+
setIsLoading(false);
|
|
8677
|
+
return;
|
|
8678
|
+
}
|
|
8679
|
+
setIsLoading(true);
|
|
8680
|
+
setError(null);
|
|
8681
|
+
getOrCreateClient(stack, urlOverride)
|
|
8682
|
+
.then((newClient) => {
|
|
8683
|
+
setClient(newClient);
|
|
8684
|
+
setIsLoading(false);
|
|
8685
|
+
})
|
|
8686
|
+
.catch((err) => {
|
|
8687
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
8688
|
+
setIsLoading(false);
|
|
8689
|
+
});
|
|
8690
|
+
}, [stack, getOrCreateClient, getClient, urlOverride]);
|
|
8691
|
+
const views = useMemo(() => {
|
|
8692
|
+
const result = {};
|
|
8693
|
+
for (const [viewName, viewGroup] of Object.entries(stack.views)) {
|
|
8694
|
+
result[viewName] = {};
|
|
8695
|
+
if (typeof viewGroup === 'object' && viewGroup !== null) {
|
|
8696
|
+
for (const [subViewName, viewDef] of Object.entries(viewGroup)) {
|
|
8697
|
+
if (!viewDef || typeof viewDef !== 'object' || !('mode' in viewDef))
|
|
8698
|
+
continue;
|
|
8699
|
+
if (viewDef.mode === 'state') {
|
|
8700
|
+
result[viewName][subViewName] = createStateViewHook(viewDef, client);
|
|
8701
|
+
}
|
|
8702
|
+
else if (viewDef.mode === 'list') {
|
|
8703
|
+
result[viewName][subViewName] = createListViewHook(viewDef, client);
|
|
8704
|
+
}
|
|
8705
|
+
}
|
|
8706
|
+
}
|
|
8707
|
+
}
|
|
8708
|
+
return result;
|
|
8709
|
+
}, [stack, client]);
|
|
8710
|
+
const instructions = useMemo(() => {
|
|
8711
|
+
const result = {};
|
|
8712
|
+
if (client?.instructions) {
|
|
8713
|
+
for (const [instructionName, executeFn] of Object.entries(client.instructions)) {
|
|
8714
|
+
result[instructionName] = {
|
|
8715
|
+
execute: executeFn,
|
|
8716
|
+
useMutation: () => useInstructionMutation(executeFn)
|
|
8717
|
+
};
|
|
8718
|
+
}
|
|
8719
|
+
}
|
|
8720
|
+
return result;
|
|
8721
|
+
}, [client]);
|
|
8722
|
+
return {
|
|
8723
|
+
views: views,
|
|
8724
|
+
instructions: instructions,
|
|
8725
|
+
zustandStore: client?.store,
|
|
8726
|
+
client: client,
|
|
8727
|
+
isLoading,
|
|
8728
|
+
error
|
|
8729
|
+
};
|
|
8730
|
+
}
|
|
8731
|
+
|
|
7687
8732
|
function getNestedValue(obj, path) {
|
|
7688
8733
|
let current = obj;
|
|
7689
8734
|
for (const segment of path) {
|
|
@@ -7979,502 +9024,5 @@ class ZustandAdapter {
|
|
|
7979
9024
|
}
|
|
7980
9025
|
}
|
|
7981
9026
|
|
|
7982
|
-
|
|
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 };
|
|
9027
|
+
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
9028
|
//# sourceMappingURL=index.esm.js.map
|