@karn_lat/protocol-sdk 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +68 -0
  2. package/dist/__tests__/setup.d.ts +14 -0
  3. package/dist/__tests__/setup.d.ts.map +1 -0
  4. package/dist/__tests__/setup.js +44 -0
  5. package/dist/__tests__/setup.js.map +1 -0
  6. package/dist/clients/GovernorClient.d.ts +9 -0
  7. package/dist/clients/GovernorClient.d.ts.map +1 -0
  8. package/dist/clients/GovernorClient.js +18 -0
  9. package/dist/clients/GovernorClient.js.map +1 -0
  10. package/dist/clients/TreasuryClient.d.ts +9 -0
  11. package/dist/clients/TreasuryClient.d.ts.map +1 -0
  12. package/dist/clients/TreasuryClient.js +18 -0
  13. package/dist/clients/TreasuryClient.js.map +1 -0
  14. package/dist/clients/ValocracyClient.d.ts +13 -0
  15. package/dist/clients/ValocracyClient.d.ts.map +1 -0
  16. package/dist/clients/ValocracyClient.js +32 -0
  17. package/dist/clients/ValocracyClient.js.map +1 -0
  18. package/dist/clients/index.d.ts +4 -0
  19. package/dist/clients/index.d.ts.map +1 -0
  20. package/dist/clients/index.js +4 -0
  21. package/dist/clients/index.js.map +1 -0
  22. package/dist/generated/governor/src/index.d.ts +400 -0
  23. package/dist/generated/governor/src/index.d.ts.map +1 -0
  24. package/dist/generated/governor/src/index.js +63 -0
  25. package/dist/generated/governor/src/index.js.map +1 -0
  26. package/dist/generated/treasury/src/index.d.ts +474 -0
  27. package/dist/generated/treasury/src/index.d.ts.map +1 -0
  28. package/dist/generated/treasury/src/index.js +54 -0
  29. package/dist/generated/treasury/src/index.js.map +1 -0
  30. package/dist/generated/valocracy/src/index.d.ts +807 -0
  31. package/dist/generated/valocracy/src/index.d.ts.map +1 -0
  32. package/dist/generated/valocracy/src/index.js +114 -0
  33. package/dist/generated/valocracy/src/index.js.map +1 -0
  34. package/dist/index.d.ts +5 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +5 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/react/hooks/useGovernor.d.ts +24 -0
  39. package/dist/react/hooks/useGovernor.d.ts.map +1 -0
  40. package/dist/react/hooks/useGovernor.js +45 -0
  41. package/dist/react/hooks/useGovernor.js.map +1 -0
  42. package/dist/react/hooks/useMultiWallet.d.ts +35 -0
  43. package/dist/react/hooks/useMultiWallet.d.ts.map +1 -0
  44. package/dist/react/hooks/useMultiWallet.js +87 -0
  45. package/dist/react/hooks/useMultiWallet.js.map +1 -0
  46. package/dist/react/hooks/useTreasury.d.ts +14 -0
  47. package/dist/react/hooks/useTreasury.d.ts.map +1 -0
  48. package/dist/react/hooks/useTreasury.js +45 -0
  49. package/dist/react/hooks/useTreasury.js.map +1 -0
  50. package/dist/react/hooks/useValocracy.d.ts +16 -0
  51. package/dist/react/hooks/useValocracy.d.ts.map +1 -0
  52. package/dist/react/hooks/useValocracy.js +54 -0
  53. package/dist/react/hooks/useValocracy.js.map +1 -0
  54. package/dist/react/hooks/useWallet.d.ts +13 -0
  55. package/dist/react/hooks/useWallet.d.ts.map +1 -0
  56. package/dist/react/hooks/useWallet.js +51 -0
  57. package/dist/react/hooks/useWallet.js.map +1 -0
  58. package/dist/react/index.d.ts +7 -0
  59. package/dist/react/index.d.ts.map +1 -0
  60. package/dist/react/index.js +7 -0
  61. package/dist/react/index.js.map +1 -0
  62. package/dist/react/providers/KarnProvider.d.ts +25 -0
  63. package/dist/react/providers/KarnProvider.d.ts.map +1 -0
  64. package/dist/react/providers/KarnProvider.js +25 -0
  65. package/dist/react/providers/KarnProvider.js.map +1 -0
  66. package/dist/utils/decay.d.ts +19 -0
  67. package/dist/utils/decay.d.ts.map +1 -0
  68. package/dist/utils/decay.js +33 -0
  69. package/dist/utils/decay.js.map +1 -0
  70. package/dist/utils/index.d.ts +4 -0
  71. package/dist/utils/index.d.ts.map +1 -0
  72. package/dist/utils/index.js +4 -0
  73. package/dist/utils/index.js.map +1 -0
  74. package/dist/utils/polling.d.ts +75 -0
  75. package/dist/utils/polling.d.ts.map +1 -0
  76. package/dist/utils/polling.js +104 -0
  77. package/dist/utils/polling.js.map +1 -0
  78. package/dist/utils/simulation.d.ts +67 -0
  79. package/dist/utils/simulation.d.ts.map +1 -0
  80. package/dist/utils/simulation.js +88 -0
  81. package/dist/utils/simulation.js.map +1 -0
  82. package/dist/wallet/WalletManager.d.ts +77 -0
  83. package/dist/wallet/WalletManager.d.ts.map +1 -0
  84. package/dist/wallet/WalletManager.js +268 -0
  85. package/dist/wallet/WalletManager.js.map +1 -0
  86. package/dist/wallet/adapters/AlbedoAdapter.d.ts +47 -0
  87. package/dist/wallet/adapters/AlbedoAdapter.d.ts.map +1 -0
  88. package/dist/wallet/adapters/AlbedoAdapter.js +84 -0
  89. package/dist/wallet/adapters/AlbedoAdapter.js.map +1 -0
  90. package/dist/wallet/adapters/FreighterAdapter.d.ts +42 -0
  91. package/dist/wallet/adapters/FreighterAdapter.d.ts.map +1 -0
  92. package/dist/wallet/adapters/FreighterAdapter.js +107 -0
  93. package/dist/wallet/adapters/FreighterAdapter.js.map +1 -0
  94. package/dist/wallet/adapters/LobstrAdapter.d.ts +34 -0
  95. package/dist/wallet/adapters/LobstrAdapter.d.ts.map +1 -0
  96. package/dist/wallet/adapters/LobstrAdapter.js +89 -0
  97. package/dist/wallet/adapters/LobstrAdapter.js.map +1 -0
  98. package/dist/wallet/adapters/RabetAdapter.d.ts +39 -0
  99. package/dist/wallet/adapters/RabetAdapter.d.ts.map +1 -0
  100. package/dist/wallet/adapters/RabetAdapter.js +104 -0
  101. package/dist/wallet/adapters/RabetAdapter.js.map +1 -0
  102. package/dist/wallet/adapters/xBullAdapter.d.ts +41 -0
  103. package/dist/wallet/adapters/xBullAdapter.d.ts.map +1 -0
  104. package/dist/wallet/adapters/xBullAdapter.js +72 -0
  105. package/dist/wallet/adapters/xBullAdapter.js.map +1 -0
  106. package/dist/wallet/index.d.ts +20 -0
  107. package/dist/wallet/index.d.ts.map +1 -0
  108. package/dist/wallet/index.js +23 -0
  109. package/dist/wallet/index.js.map +1 -0
  110. package/dist/wallet/types.d.ts +165 -0
  111. package/dist/wallet/types.d.ts.map +1 -0
  112. package/dist/wallet/types.js +50 -0
  113. package/dist/wallet/types.js.map +1 -0
  114. package/examples/basic-usage.ts +28 -0
  115. package/jest.config.js +37 -0
  116. package/package.json +58 -0
  117. package/src/__tests__/README.md +364 -0
  118. package/src/__tests__/setup.ts +57 -0
  119. package/src/__tests__/utils/decay.test.ts +331 -0
  120. package/src/__tests__/wallet/WalletManager.test.ts +410 -0
  121. package/src/clients/GovernorClient.ts +23 -0
  122. package/src/clients/TreasuryClient.ts +23 -0
  123. package/src/clients/ValocracyClient.ts +48 -0
  124. package/src/clients/index.ts +3 -0
  125. package/src/generated/governor/README.md +54 -0
  126. package/src/generated/governor/package.json +17 -0
  127. package/src/generated/governor/src/index.ts +428 -0
  128. package/src/generated/governor/tsconfig.json +98 -0
  129. package/src/generated/treasury/README.md +54 -0
  130. package/src/generated/treasury/package.json +17 -0
  131. package/src/generated/treasury/src/index.ts +495 -0
  132. package/src/generated/treasury/tsconfig.json +98 -0
  133. package/src/generated/valocracy/README.md +54 -0
  134. package/src/generated/valocracy/package.json +17 -0
  135. package/src/generated/valocracy/src/index.ts +831 -0
  136. package/src/generated/valocracy/tsconfig.json +98 -0
  137. package/src/index.ts +4 -0
  138. package/src/react/hooks/useGovernor.ts +69 -0
  139. package/src/react/hooks/useMultiWallet.ts +169 -0
  140. package/src/react/hooks/useTreasury.ts +57 -0
  141. package/src/react/hooks/useValocracy.ts +66 -0
  142. package/src/react/hooks/useWallet.ts +60 -0
  143. package/src/react/index.ts +6 -0
  144. package/src/react/providers/KarnProvider.tsx +63 -0
  145. package/src/utils/decay.ts +44 -0
  146. package/src/utils/index.ts +3 -0
  147. package/src/utils/polling.ts +193 -0
  148. package/src/utils/simulation.ts +136 -0
  149. package/src/wallet/WalletManager.ts +360 -0
  150. package/src/wallet/adapters/AlbedoAdapter.ts +140 -0
  151. package/src/wallet/adapters/FreighterAdapter.ts +179 -0
  152. package/src/wallet/adapters/LobstrAdapter.ts +142 -0
  153. package/src/wallet/adapters/RabetAdapter.ts +162 -0
  154. package/src/wallet/adapters/xBullAdapter.ts +123 -0
  155. package/src/wallet/index.ts +37 -0
  156. package/src/wallet/types.ts +204 -0
  157. package/tsconfig.json +40 -0
@@ -0,0 +1,98 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+ /* Projects */
5
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
6
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
7
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
8
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
9
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
10
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
11
+ /* Language and Environment */
12
+ "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
13
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
14
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
15
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
16
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
17
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
18
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
19
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
20
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
21
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
22
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
23
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
24
+ /* Modules */
25
+ "module": "NodeNext", /* Specify what module code is generated. */
26
+ // "rootDir": "./", /* Specify the root folder within your source files. */
27
+ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
28
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
29
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
30
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
31
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
32
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
33
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
34
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
35
+ // "resolveJsonModule": true, /* Enable importing .json files. */
36
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
37
+ /* JavaScript Support */
38
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
39
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
40
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
41
+ /* Emit */
42
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
43
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
44
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
45
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
46
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
47
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
48
+ // "removeComments": true, /* Disable emitting comments. */
49
+ // "noEmit": true, /* Disable emitting files from a compilation. */
50
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
51
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
52
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
53
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
54
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
55
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
56
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
57
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
58
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
59
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
60
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
61
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
62
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
63
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
64
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
65
+ /* Interop Constraints */
66
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
67
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
68
+ // "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
69
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
70
+ // "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
71
+ /* Type Checking */
72
+ // "strict": true, /* Enable all strict type-checking options. */
73
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
74
+ "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
75
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
76
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
77
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
78
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
79
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
80
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
81
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
82
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
83
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
84
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
85
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
86
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
87
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
88
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
89
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
90
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
91
+ /* Completeness */
92
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
93
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
94
+ },
95
+ "include": [
96
+ "src/*"
97
+ ]
98
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './clients/index.js';
2
+ export * from './utils/index.js';
3
+ export * from './react/index.js';
4
+ export * from './wallet/index.js';
@@ -0,0 +1,69 @@
1
+ import { useState, useEffect } from 'react';
2
+ import { useKarn } from '../providers/KarnProvider.js';
3
+
4
+ export interface Proposal {
5
+ id: bigint;
6
+ proposer: string;
7
+ description: string;
8
+ votesFor: bigint;
9
+ votesAgainst: bigint;
10
+ startTime: bigint;
11
+ endTime: bigint;
12
+ executed: boolean;
13
+ // Add other proposal fields as needed
14
+ }
15
+
16
+ export interface UseGovernorResult {
17
+ proposal: Proposal | null;
18
+ isLoading: boolean;
19
+ error: Error | null;
20
+ refetch: () => Promise<void>;
21
+ }
22
+
23
+ /**
24
+ * React hook to fetch Governor contract proposal data
25
+ *
26
+ * @param proposalId - The proposal ID to query (optional)
27
+ * @returns Object containing proposal data, loading state, and refetch function
28
+ */
29
+
30
+
31
+ export function useGovernor(proposalId?: bigint): UseGovernorResult {
32
+ const { governor } = useKarn();
33
+ const [proposal, setProposal] = useState<Proposal | null>(null);
34
+ const [isLoading, setIsLoading] = useState<boolean>(false);
35
+ const [error, setError] = useState<Error | null>(null);
36
+
37
+ const fetchData = async () => {
38
+ if (proposalId === undefined) {
39
+ setProposal(null);
40
+ setError(null);
41
+ return;
42
+ }
43
+
44
+ setIsLoading(true);
45
+ setError(null);
46
+
47
+ try {
48
+ const proposalData = await governor.getProposal(proposalId);
49
+ setProposal(proposalData as Proposal);
50
+ } catch (err) {
51
+ const error = err instanceof Error ? err : new Error('Failed to fetch proposal data');
52
+ setError(error);
53
+ console.error('useGovernor error:', error);
54
+ } finally {
55
+ setIsLoading(false);
56
+ }
57
+ };
58
+
59
+ useEffect(() => {
60
+ fetchData();
61
+ }, [proposalId?.toString()]);
62
+
63
+ return {
64
+ proposal,
65
+ isLoading,
66
+ error,
67
+ refetch: fetchData,
68
+ };
69
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * React hook for multi-wallet support
3
+ *
4
+ * Provides React-friendly interface to WalletManager with automatic state updates
5
+ */
6
+
7
+
8
+
9
+ import { useState, useEffect, useCallback, useRef } from 'react';
10
+ import {
11
+ WalletManager,
12
+ WalletType,
13
+ WalletState,
14
+ WalletMetadata,
15
+ WalletConnection,
16
+ WalletEvent,
17
+ SignTransactionOptions,
18
+ WalletError,
19
+ } from '../../wallet/index.js';
20
+
21
+ export interface UseMultiWalletReturn {
22
+ /** Current wallet state */
23
+ state: WalletState;
24
+
25
+ /** List of available (installed) wallets */
26
+ availableWallets: WalletMetadata[];
27
+
28
+ /** List of all supported wallets (including unavailable) */
29
+ allWallets: WalletMetadata[];
30
+
31
+ /** Connect to a specific wallet */
32
+ connect: (walletType: WalletType) => Promise<WalletConnection>;
33
+
34
+ /** Disconnect from current wallet */
35
+ disconnect: () => Promise<void>;
36
+
37
+ /** Sign a transaction with current wallet */
38
+ signTransaction: (xdr: string, options?: SignTransactionOptions) => Promise<string>;
39
+
40
+ /** Sign a message (if supported) */
41
+ signMessage: (message: string) => Promise<string>;
42
+
43
+ /** Get current network (if supported) */
44
+ getNetwork: () => Promise<string>;
45
+
46
+ /** Get current address */
47
+ getAddress: () => Promise<string | null>;
48
+
49
+ /** Check if connected */
50
+ isConnected: () => Promise<boolean>;
51
+
52
+ /** Wallet manager instance (for advanced usage) */
53
+ manager: WalletManager;
54
+ }
55
+
56
+ /**
57
+ * Hook for multi-wallet support
58
+ */
59
+ export function useMultiWallet(): UseMultiWalletReturn {
60
+
61
+ const managerRef = useRef<WalletManager>();
62
+ if (!managerRef.current) {
63
+ managerRef.current = new WalletManager();
64
+ }
65
+ const manager = managerRef.current;
66
+
67
+ const [state, setState] = useState<WalletState>(manager.getState());
68
+ const [availableWallets, setAvailableWallets] = useState<WalletMetadata[]>([]);
69
+ const [allWallets] = useState<WalletMetadata[]>(manager.getAllWallets());
70
+
71
+
72
+ useEffect(() => {
73
+ const handleConnect = () => setState(manager.getState());
74
+ const handleDisconnect = () => setState(manager.getState());
75
+ const handleAccountChanged = () => setState(manager.getState());
76
+ const handleNetworkChanged = () => setState(manager.getState());
77
+
78
+ manager.on(WalletEvent.CONNECT, handleConnect);
79
+ manager.on(WalletEvent.DISCONNECT, handleDisconnect);
80
+ manager.on(WalletEvent.ACCOUNT_CHANGED, handleAccountChanged);
81
+ manager.on(WalletEvent.NETWORK_CHANGED, handleNetworkChanged);
82
+
83
+ return () => {
84
+ manager.off(WalletEvent.CONNECT, handleConnect);
85
+ manager.off(WalletEvent.DISCONNECT, handleDisconnect);
86
+ manager.off(WalletEvent.ACCOUNT_CHANGED, handleAccountChanged);
87
+ manager.off(WalletEvent.NETWORK_CHANGED, handleNetworkChanged);
88
+ };
89
+ }, [manager]);
90
+
91
+
92
+ useEffect(() => {
93
+ let mounted = true;
94
+
95
+ async function loadAvailableWallets() {
96
+ const wallets = await manager.getAvailableWallets();
97
+ if (mounted) {
98
+ setAvailableWallets(wallets);
99
+ }
100
+ }
101
+
102
+ loadAvailableWallets();
103
+
104
+ return () => {
105
+ mounted = false;
106
+ };
107
+ }, [manager]);
108
+
109
+
110
+ const connect = useCallback(
111
+ async (walletType: WalletType): Promise<WalletConnection> => {
112
+ const connection = await manager.connect(walletType);
113
+ setState(manager.getState());
114
+ return connection;
115
+ },
116
+ [manager]
117
+ );
118
+
119
+
120
+ const disconnect = useCallback(async (): Promise<void> => {
121
+ await manager.disconnect();
122
+ setState(manager.getState());
123
+ }, [manager]);
124
+
125
+
126
+ const signTransaction = useCallback(
127
+ async (xdr: string, options?: SignTransactionOptions): Promise<string> => {
128
+ return await manager.signTransaction(xdr, options);
129
+ },
130
+ [manager]
131
+ );
132
+
133
+
134
+ const signMessage = useCallback(
135
+ async (message: string): Promise<string> => {
136
+ return await manager.signMessage(message);
137
+ },
138
+ [manager]
139
+ );
140
+
141
+
142
+ const getNetwork = useCallback(async (): Promise<string> => {
143
+ return await manager.getNetwork();
144
+ }, [manager]);
145
+
146
+
147
+ const getAddress = useCallback(async (): Promise<string | null> => {
148
+ return await manager.getAddress();
149
+ }, [manager]);
150
+
151
+
152
+ const isConnected = useCallback(async (): Promise<boolean> => {
153
+ return await manager.isConnected();
154
+ }, [manager]);
155
+
156
+ return {
157
+ state,
158
+ availableWallets,
159
+ allWallets,
160
+ connect,
161
+ disconnect,
162
+ signTransaction,
163
+ signMessage,
164
+ getNetwork,
165
+ getAddress,
166
+ isConnected,
167
+ manager,
168
+ };
169
+ }
@@ -0,0 +1,57 @@
1
+ import { useState, useEffect } from 'react';
2
+ import { useKarn } from '../providers/KarnProvider.js';
3
+
4
+ export interface UseTreasuryResult {
5
+ claimableBalance: bigint | null;
6
+ isLoading: boolean;
7
+ error: Error | null;
8
+ refetch: () => Promise<void>;
9
+ }
10
+
11
+ /**
12
+ * React hook to fetch Treasury contract data for a member
13
+ *
14
+ * @param member - The member address to query (optional)
15
+ * @returns Object containing claimable balance, loading state, and refetch function
16
+ */
17
+
18
+
19
+ export function useTreasury(member?: string): UseTreasuryResult {
20
+ const { treasury } = useKarn();
21
+ const [claimableBalance, setClaimableBalance] = useState<bigint | null>(null);
22
+ const [isLoading, setIsLoading] = useState<boolean>(false);
23
+ const [error, setError] = useState<Error | null>(null);
24
+
25
+ const fetchData = async () => {
26
+ if (!member) {
27
+ setClaimableBalance(null);
28
+ setError(null);
29
+ return;
30
+ }
31
+
32
+ setIsLoading(true);
33
+ setError(null);
34
+
35
+ try {
36
+ const balance = await treasury.getClaimableBalance(member);
37
+ setClaimableBalance(balance);
38
+ } catch (err) {
39
+ const error = err instanceof Error ? err : new Error('Failed to fetch treasury data');
40
+ setError(error);
41
+ console.error('useTreasury error:', error);
42
+ } finally {
43
+ setIsLoading(false);
44
+ }
45
+ };
46
+
47
+ useEffect(() => {
48
+ fetchData();
49
+ }, [member]);
50
+
51
+ return {
52
+ claimableBalance,
53
+ isLoading,
54
+ error,
55
+ refetch: fetchData,
56
+ };
57
+ }
@@ -0,0 +1,66 @@
1
+ import { useState, useEffect } from 'react';
2
+ import { useKarn } from '../providers/KarnProvider.js';
3
+
4
+ export interface UseValocracyResult {
5
+ level: number | null;
6
+ mana: number | null;
7
+ isLoading: boolean;
8
+ error: Error | null;
9
+ refetch: () => Promise<void>;
10
+ }
11
+
12
+ /**
13
+ * React hook to fetch Valocracy contract data for an address
14
+ *
15
+ * @param address - The account address to query (optional)
16
+ * @returns Object containing level, mana, loading state, and refetch function
17
+ *
18
+ */
19
+ export function useValocracy(address?: string): UseValocracyResult {
20
+ const { valocracy } = useKarn();
21
+ const [level, setLevel] = useState<number | null>(null);
22
+ const [mana, setMana] = useState<number | null>(null);
23
+ const [isLoading, setIsLoading] = useState<boolean>(false);
24
+ const [error, setError] = useState<Error | null>(null);
25
+
26
+ const fetchData = async () => {
27
+ if (!address) {
28
+ setLevel(null);
29
+ setMana(null);
30
+ setError(null);
31
+ return;
32
+ }
33
+
34
+ setIsLoading(true);
35
+ setError(null);
36
+
37
+ try {
38
+ // Fetch level and mana in parallel
39
+ const [levelResult, manaResult] = await Promise.all([
40
+ valocracy.getLevel(address),
41
+ valocracy.getMana(address),
42
+ ]);
43
+
44
+ setLevel(levelResult);
45
+ setMana(manaResult);
46
+ } catch (err) {
47
+ const error = err instanceof Error ? err : new Error('Failed to fetch Valocracy data');
48
+ setError(error);
49
+ console.error('useValocracy error:', error);
50
+ } finally {
51
+ setIsLoading(false);
52
+ }
53
+ };
54
+
55
+ useEffect(() => {
56
+ fetchData();
57
+ }, [address]);
58
+
59
+ return {
60
+ level,
61
+ mana,
62
+ isLoading,
63
+ error,
64
+ refetch: fetchData,
65
+ };
66
+ }
@@ -0,0 +1,60 @@
1
+ import { useState, useCallback, useEffect } from 'react';
2
+ import * as freighter from '@stellar/freighter-api';
3
+ // @ts-ignore
4
+ const { isConnected, requestAccess, signTransaction } = freighter;
5
+
6
+ interface WalletState {
7
+ isConnected: boolean;
8
+ address: string | null;
9
+ isConnecting: boolean;
10
+ error: string | null;
11
+ }
12
+
13
+ export const useWallet = () => {
14
+ const [state, setState] = useState<WalletState>({
15
+ isConnected: false,
16
+ address: null,
17
+ isConnecting: false,
18
+ error: null,
19
+ });
20
+
21
+ const connect = useCallback(async () => {
22
+ setState(prev => ({ ...prev, isConnecting: true, error: null }));
23
+ try {
24
+ const allowed = await requestAccess();
25
+ if (allowed) {
26
+
27
+ const address = allowed;
28
+ if (address) {
29
+ setState({
30
+ isConnected: true,
31
+ address: address, // Type check: allowed is string
32
+ isConnecting: false,
33
+ error: null,
34
+ });
35
+ } else {
36
+ throw new Error("Access denied");
37
+ }
38
+ } else {
39
+ throw new Error("User denied access");
40
+ }
41
+ } catch (err: any) {
42
+ setState(prev => ({ ...prev, isConnecting: false, error: err.message || "Failed to connect" }));
43
+ }
44
+ }, []);
45
+
46
+ // Check connection on mount
47
+ useEffect(() => {
48
+ isConnected().then(async (connected) => {
49
+ if (connected) {
50
+
51
+ }
52
+ });
53
+ }, []);
54
+
55
+ return {
56
+ ...state,
57
+ connect,
58
+ signTransaction, // Expose freighter sign
59
+ };
60
+ };
@@ -0,0 +1,6 @@
1
+ export * from './providers/KarnProvider.js';
2
+ export * from './hooks/useValocracy.js';
3
+ export * from './hooks/useGovernor.js';
4
+ export * from './hooks/useTreasury.js';
5
+ export * from './hooks/useWallet.js';
6
+ export * from './hooks/useMultiWallet.js';
@@ -0,0 +1,63 @@
1
+ import React, { createContext, useContext, useMemo, ReactNode } from 'react';
2
+ import { ValocracyClient, GovernorClient, TreasuryClient } from '../../clients';
3
+
4
+ export interface KarnConfig {
5
+ networkPassphrase: string;
6
+ rpcUrl: string;
7
+ contracts: {
8
+ valocracy: string;
9
+ governor: string;
10
+ treasury: string;
11
+ };
12
+ }
13
+
14
+ interface KarnContextValue {
15
+ valocracy: ValocracyClient;
16
+ governor: GovernorClient;
17
+ treasury: TreasuryClient;
18
+ config: KarnConfig;
19
+ }
20
+
21
+ const KarnContext = createContext<KarnContextValue | null>(null);
22
+
23
+ export const useKarn = () => {
24
+ const context = useContext(KarnContext);
25
+ if (!context) {
26
+ throw new Error('useKarn must be used within a KarnProvider');
27
+ }
28
+ return context;
29
+ };
30
+
31
+ interface KarnProviderProps {
32
+ config: KarnConfig;
33
+ children: ReactNode;
34
+ }
35
+
36
+ export const KarnProvider: React.FC<KarnProviderProps> = ({ config, children }) => {
37
+ const clients = useMemo(() => {
38
+ return {
39
+ valocracy: new ValocracyClient(
40
+ config.networkPassphrase,
41
+ config.rpcUrl,
42
+ config.contracts.valocracy
43
+ ),
44
+ governor: new GovernorClient(
45
+ config.networkPassphrase,
46
+ config.rpcUrl,
47
+ config.contracts.governor
48
+ ),
49
+ treasury: new TreasuryClient(
50
+ config.networkPassphrase,
51
+ config.rpcUrl,
52
+ config.contracts.treasury
53
+ ),
54
+ };
55
+ }, [config.networkPassphrase, config.rpcUrl, config.contracts.valocracy, config.contracts.governor, config.contracts.treasury]);
56
+
57
+ const value: KarnContextValue = {
58
+ ...clients,
59
+ config,
60
+ };
61
+
62
+ return <KarnContext.Provider value={value}>{children}</KarnContext.Provider>;
63
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Client-side Mana decay calculation
3
+ */
4
+
5
+ const MEMBER_FLOOR = 5;
6
+ const VACANCY_PERIOD = 15552000; // 180 days in seconds
7
+
8
+ /**
9
+ * Calculate current Mana based on level and last activity
10
+ *
11
+ * Formula: Mana = floor + bonus
12
+ * - floor = MEMBER_FLOOR (fixed constant, e.g. 5)
13
+ * - extra_level = level - floor
14
+ * - bonus = (extra_level * time_remaining) / VACANCY_PERIOD
15
+ *
16
+ * @param level Total level (including permanent)
17
+ * @param permanentLevel Permanent level (Founder badge)
18
+ * @param expiry Expiry timestamp (Unix seconds)
19
+ * @param currentTimestamp Current timestamp (Unix seconds)
20
+ * @returns Current Mana
21
+ */
22
+ export function calculateMana(
23
+ level: number,
24
+ permanentLevel: number,
25
+ expiry: number,
26
+ currentTimestamp: number
27
+ ): number {
28
+ // 1. Calculate decaying portion
29
+ const decayingLevel = Math.max(0, level - permanentLevel);
30
+
31
+
32
+ // 2. Calculate time remaining
33
+ const timeRemaining = Math.max(0, expiry - currentTimestamp);
34
+
35
+ // 3. Calculate bonus
36
+ // Use Math.floor to match integer arithmetic
37
+ // bonus = (DecayingLevel * TimeRemaining) / VacancyPeriod
38
+ const bonus = Math.floor((decayingLevel * timeRemaining) / VACANCY_PERIOD);
39
+
40
+ // 4. Default floor logic
41
+ // Contract: Mana = MemberFloor + bonus + PermanentLevel
42
+
43
+ return MEMBER_FLOOR + bonus + permanentLevel;
44
+ }
@@ -0,0 +1,3 @@
1
+ export * from './decay.js';
2
+ export * from './simulation.js';
3
+ export * from './polling.js';