@gvnrdao/dh-sdk 0.0.172 → 0.0.206

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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -5
  3. package/browser/dist/index.d.ts +3 -4
  4. package/browser/dist/index.d.ts.map +1 -1
  5. package/browser/dist/index.js +4 -3
  6. package/dist/constants/chunks/contract-abis.d.ts +7 -0
  7. package/dist/constants/chunks/deployment-addresses.d.ts +68 -0
  8. package/dist/constants/chunks/encrypted-provider-params.d.ts +21 -0
  9. package/dist/constants/chunks/environment.browser.d.ts +45 -0
  10. package/dist/constants/chunks/environment.d.ts +57 -0
  11. package/dist/constants/chunks/network-configs.d.ts +65 -0
  12. package/dist/constants/chunks/sdk-config.d.ts +33 -0
  13. package/dist/constants/chunks/sdk-limits.d.ts +66 -0
  14. package/dist/constants/index.d.ts +15 -0
  15. package/dist/graphs/client.d.ts +19 -0
  16. package/dist/graphs/diamond-hands.d.ts +248 -0
  17. package/dist/index.d.ts +47 -7319
  18. package/dist/index.js +4439 -16783
  19. package/dist/index.mjs +4452 -16773
  20. package/dist/interfaces/chunks/btc.i.d.ts +36 -0
  21. package/dist/interfaces/chunks/config.i.d.ts +245 -0
  22. package/dist/interfaces/chunks/contract-interactions.i.d.ts +64 -0
  23. package/dist/interfaces/chunks/contract-types.i.d.ts +165 -0
  24. package/dist/interfaces/chunks/lit-actions-results.i.d.ts +165 -0
  25. package/dist/interfaces/chunks/lit-actions.i.d.ts +98 -0
  26. package/dist/interfaces/chunks/loan-operations.i.d.ts +332 -0
  27. package/dist/interfaces/chunks/pkp-integration.i.d.ts +87 -0
  28. package/dist/interfaces/chunks/position-query.i.d.ts +76 -0
  29. package/dist/interfaces/chunks/requests.i.d.ts +55 -0
  30. package/dist/interfaces/chunks/ucd-minting.i.d.ts +34 -0
  31. package/dist/interfaces/chunks/utility.i.d.ts +64 -0
  32. package/dist/interfaces/index.d.ts +17 -0
  33. package/dist/modules/bitcoin/bitcoin-operations.module.d.ts +215 -0
  34. package/dist/modules/cache/cache-manager.module.d.ts +251 -0
  35. package/dist/modules/contract/contract-manager.module.d.ts +136 -0
  36. package/dist/modules/diamond-hands-sdk.d.ts +666 -0
  37. package/dist/modules/loan/loan-creator.module.d.ts +143 -0
  38. package/dist/modules/loan/loan-query.module.d.ts +204 -0
  39. package/dist/modules/mock/mock-token-manager.module.d.ts +83 -0
  40. package/dist/modules/pkp/pkp-manager.module.d.ts +132 -0
  41. package/dist/protocol/protocol-pause.d.ts +19 -0
  42. package/dist/server.d.ts +17 -0
  43. package/dist/server.js +285 -0
  44. package/dist/server.mjs +242 -0
  45. package/dist/types/authorization-params.d.ts +160 -0
  46. package/dist/types/branded/domain-values.d.ts +138 -0
  47. package/dist/types/branded/ids.d.ts +23 -0
  48. package/dist/types/event-types.d.ts +235 -0
  49. package/dist/types/graph-dtos.d.ts +228 -0
  50. package/dist/types/loanStatus.d.ts +10 -0
  51. package/dist/types/result.d.ts +120 -0
  52. package/dist/utils/bitcoin-address-cache.utils.d.ts +87 -0
  53. package/dist/utils/bitcoin-provider.utils.d.ts +48 -0
  54. package/dist/utils/bitcoin-signature.d.ts +20 -0
  55. package/dist/utils/chunks/bitcoin-utils.d.ts +75 -0
  56. package/dist/utils/chunks/eip1559-broadcast.utils.d.ts +24 -0
  57. package/dist/utils/error-handler.d.ts +106 -0
  58. package/dist/utils/ethers-interop.utils.d.ts +146 -0
  59. package/dist/utils/extend-authorization.utils.d.ts +61 -0
  60. package/dist/utils/lit-signature.utils.d.ts +6 -0
  61. package/dist/utils/logger.utils.d.ts +142 -0
  62. package/dist/utils/mint-authorization.utils.d.ts +231 -0
  63. package/dist/utils/quantum-timing.d.ts +75 -0
  64. package/dist/utils/signature-tempering.utils.d.ts +31 -0
  65. package/dist/utils/telegram-messaging.utils.d.ts +188 -0
  66. package/package.json +43 -23
  67. package/browser/dist/20.browser.js +0 -1
  68. package/browser/dist/397.browser.js +0 -2
  69. package/browser/dist/397.browser.js.LICENSE.txt +0 -1
  70. package/browser/dist/833.browser.js +0 -2
  71. package/browser/dist/833.browser.js.LICENSE.txt +0 -1
  72. package/browser/dist/browser.js +0 -14
  73. package/browser/dist/browser.js.LICENSE.txt +0 -90
  74. package/dist/index.d.mts +0 -7320
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Diamond Hands Protocol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -12,6 +12,23 @@ The official TypeScript SDK for the Diamond Hands Protocol, enabling developers
12
12
  npm install @gvnrdao/dh-sdk
13
13
  ```
14
14
 
15
+ ### Browser vs server (PKP mint / `PKP_MINT_PRIVATE_KEY`)
16
+
17
+ - **Default export** (`import { DiamondHandsSDK } from "@gvnrdao/dh-sdk"` and `import { loadSDKConfig } from "@gvnrdao/dh-sdk"` via constants) resolves **browser-safe** environment helpers (`environment.browser`) — suitable for frontends, read-only flows, and user-signed transactions. Do **not** put `PKP_MINT_PRIVATE_KEY` in client bundles.
18
+ - **Server / Node scripts** (lit-ops-server, CI, PKP mint wallets) should import Node env + optional mint key from the dedicated subpath:
19
+
20
+ ```typescript
21
+ import {
22
+ loadSDKConfig,
23
+ validateSDKEnvironment,
24
+ } from "@gvnrdao/dh-sdk/server";
25
+
26
+ validateSDKEnvironment({ requiresPrivateKey: true });
27
+ const cfg = loadSDKConfig(); // may include cfg.pkpMintPrivateKey when env is set
28
+ ```
29
+
30
+ See [`docs/security/SECRETS-POLICY.md`](../docs/security/SECRETS-POLICY.md). The repo enforces that only `src/server.ts` may import Node `environment.ts` (ESLint + `npm run lint:server-boundary`).
31
+
15
32
  ## Usage
16
33
 
17
34
  ### Basic Setup
@@ -19,8 +36,7 @@ npm install @gvnrdao/dh-sdk
19
36
  ```typescript
20
37
  import { DiamondHandsSDK } from "@gvnrdao/dh-sdk";
21
38
 
22
- // Initialize SDK
23
- const sdk = new DiamondHandsSDK({
39
+ const sdkResult = await DiamondHandsSDK.create({
24
40
  mode: "service", // or 'standalone'
25
41
  serviceEndpoint: "http://localhost:3001",
26
42
  contractAddresses: {
@@ -29,8 +45,10 @@ const sdk = new DiamondHandsSDK({
29
45
  // ... other contract addresses
30
46
  },
31
47
  });
32
-
33
- await sdk.initialize();
48
+ if (!sdkResult.success) {
49
+ throw sdkResult.error;
50
+ }
51
+ const sdk = sdkResult.value;
34
52
  ```
35
53
 
36
54
  ### Creating a Loan
@@ -50,6 +68,55 @@ if (result.success) {
50
68
  }
51
69
  ```
52
70
 
71
+ ### UCD mint gas (`requestMintUCD`)
72
+
73
+ `mintUCD` can consume very high gas. The SDK runs **`eth_estimateGas`** on the final calldata, adds **25% headroom**, and caps the limit at **10M**. Fees use **`getFeeData()`** when available, with fallbacks. Broadcasting uses **`signer.sendTransaction`** (EIP-1559 type 2), not manual `signDigest` / raw RPC.
74
+
75
+ If **estimateGas** fails but a **static call** succeeds, on **Sepolia (chain ID 11155111)** the SDK **automatically** sends with the **fixed ceiling**; on other chains it throws unless estimation succeeds.
76
+
77
+ ### Smart wallets and same-block limits (`PositionManager`)
78
+
79
+ The on-chain `PositionManager` applies a **flash-loan protection** modifier to **`createPosition`** and **`extendPosition`**: it rate-limits by **`tx.origin`** (the top-level EOA or account that sent the outer transaction), not by `msg.sender`. This is intentional (anti-abuse); it is **not** used for access control.
80
+
81
+ **Implications for integrators:**
82
+
83
+ - **Contract wallets (e.g. Safe)** can create and extend positions: the protocol sees `msg.sender` as the wallet. Ensure you do **not** put **two** guarded calls (`create` **or** `extend`) in **one** outer transaction (e.g. a Safe multicall batch), or the second can revert with `SameBlockInteraction`.
84
+ - At most **one successful** `createPosition` **or** `extendPosition` per **block** per **`tx.origin`**. Split operations across separate transactions/blocks if needed.
85
+ - Flows where **many users** share the **same** outer submitter in the **same block** (e.g. some **account-abstraction / bundler** setups) can **collide** on that limit because they share `tx.origin`. EOA-submitted Safe transactions are typically unaffected.
86
+
87
+ ### Liquidating Positions (MEV-Protected)
88
+
89
+ The SDK provides MEV-protected liquidation using a commit-reveal system:
90
+
91
+ ```typescript
92
+ // MEV-protected liquidation (recommended)
93
+ const liquidationResult = await sdk.liquidatePosition({
94
+ positionId: "0x...",
95
+ forceContractCall: false, // Use LIT action validation
96
+ });
97
+
98
+ // Legacy admin-only liquidation (faster, for testing)
99
+ const adminResult = await sdk.liquidatePositionAdmin({
100
+ positionId: "0x...",
101
+ forceContractCall: true, // Bypass LIT action
102
+ });
103
+ ```
104
+
105
+ #### MEV Protection Features
106
+
107
+ - **Commit-Reveal System**: Prevents front-running by separating intent from execution
108
+ - **Randomized Delays**: 60-300 second delays to avoid predictable timing attacks
109
+ - **Quantum Timestamps**: LIT Protocol signed timestamps prevent replay attacks
110
+ - **Role-Based Access**: Uses LIQUIDATOR_ROLE instead of admin privileges
111
+
112
+ #### Liquidation Process
113
+
114
+ 1. **Commit Phase**: Submit liquidation intent with LIT Action validation
115
+ 2. **MEV Protection**: Wait randomized delay (60-300 seconds)
116
+ 3. **Reveal Phase**: Execute liquidation with deadline enforcement
117
+
118
+ **Note**: The commit-reveal process takes 1-5 minutes due to MEV protection. Use `liquidatePositionAdmin()` for immediate execution during testing or emergency situations.
119
+
53
120
  ## Features
54
121
 
55
122
  - ✅ **Service & Standalone Modes**: Flexible deployment options
@@ -58,6 +125,7 @@ if (result.success) {
58
125
  - ✅ **PKP Integration**: Secure key management with LIT Protocol
59
126
  - ✅ **Smart Contract Integration**: Direct interaction with Diamond Hands contracts
60
127
  - ✅ **Bitcoin Operations**: Support for Bitcoin deposit verification
128
+ - ✅ **MEV-Protected Liquidations**: Commit-reveal system prevents front-running
61
129
  - ✅ **Telegram Notifications**: Optional event notifications (Node.js only)
62
130
 
63
131
  ## API Reference
@@ -67,11 +135,13 @@ if (result.success) {
67
135
  - `initialize()` - Initialize the SDK
68
136
  - `createLoan(request)` - Create a new loan position
69
137
  - `repayLoan(positionId, amount)` - Repay an existing loan
70
- - `liquidatePosition(positionId)` - Liquidate an undercollateralized position
138
+ - `liquidatePosition(request)` - Liquidate an undercollateralized position (MEV-protected)
139
+ - `liquidatePositionAdmin(request)` - Liquidate position using admin-only access (backward compatibility)
71
140
 
72
141
  ### Configuration Options
73
142
 
74
143
  See the full API documentation for detailed configuration options and method signatures.
144
+ - API Reference (TSDoc source): [`src/index.ts`](src/index.ts)
75
145
 
76
146
  ## Telegram Notifications
77
147
 
@@ -109,6 +179,7 @@ The SDK sends notifications for:
109
179
  - UCD minting
110
180
  - Partial payments
111
181
  - Loan renewals
182
+ - Position liquidations
112
183
  - Balance confirmations
113
184
  - BTC withdrawals
114
185
  - Operation failures
@@ -117,6 +188,16 @@ The SDK sends notifications for:
117
188
 
118
189
  Never expose your Telegram bot token in frontend code. If you need notifications from browser applications, use a backend webhook endpoint instead.
119
190
 
191
+ ## Development — TypeChain
192
+
193
+ After changing Solidity contracts that the SDK consumes:
194
+
195
+ 1. `cd contracts && npm run compile` (or from `sdk/`: `npm run sync:typechain`).
196
+ 2. Commit updated `contracts/typechain-types/**` with the contract changes.
197
+ 3. Update [`sdk/src/contracts/typechain-contracts.ts`](src/contracts/typechain-contracts.ts) re-exports if new contracts need SDK-facing types.
198
+
199
+ Full details: [`docs/TYPECHAIN_IMPLEMENTATION.md`](docs/TYPECHAIN_IMPLEMENTATION.md) (regeneration, commit policy, npm publish behavior).
200
+
120
201
  ## License
121
202
 
122
203
  MIT
@@ -1,9 +1,8 @@
1
- import * as SDKModule from "../dist/index.js";
2
- export declare const DiamondHandsSDK: typeof SDKModule.DiamondHandsSDK;
1
+ export declare const DiamondHandsSDK: any;
3
2
  export type CreateLoanRequest = any;
4
3
  export type CreateLoanResult = any;
5
4
  export type DiamondHandsSDKConfig = any;
6
- export * from "../dist/index.js";
7
- declare const _default: typeof SDKModule.DiamondHandsSDK;
5
+ export declare const AuthParamsValidation: any, BPSConversions: any, BitcoinOperations: any, CacheManager: any, ContractManager: any, SDKClass: any, ErrorCategory: any, ErrorSeverity: any, EventHelpers: any, LoanCreator: any, LoanQuery: any, LoanStatus: any, PaymentType: any, PositionStatus: any, SDKError: any, SatoshisConversions: any, UCDConversions: any, WeiConversions: any, createBitcoinOperations: any, createCacheManager: any, createContractManager: any, createLoanCreator: any, createLoanQuery: any, createPKPManager: any, failure: any, success: any, tryCatch: any, tryCatchAsync: any, unwrap: any, unwrapOr: any, validateSDKConfig: any;
6
+ declare const _default: any;
8
7
  export default _default;
9
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,SAAS,MAAM,kBAAkB,CAAC;AAY9C,eAAO,MAAM,eAAe,kCAA4B,CAAC;AAoCzD,MAAM,MAAM,iBAAiB,GAAG,GAAG,CAAC;AACpC,MAAM,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACnC,MAAM,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAOxC,cAAc,kBAAkB,CAAC;;AAOjC,wBAAyC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,eAAe,KAA4B,CAAC;AAgCzD,MAAM,MAAM,iBAAiB,GAAG,GAAG,CAAC;AACpC,MAAM,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACnC,MAAM,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAQxC,eAAO,MACL,oBAAoB,OACpB,cAAc,OACd,iBAAiB,OACjB,YAAY,OACZ,eAAe,OACE,QAAQ,OACzB,aAAa,OACb,aAAa,OACb,YAAY,OACZ,WAAW,OACX,SAAS,OACT,UAAU,OACV,WAAW,OACX,cAAc,OACd,QAAQ,OACR,mBAAmB,OACnB,cAAc,OACd,cAAc,OACd,uBAAuB,OACvB,kBAAkB,OAClB,qBAAqB,OACrB,iBAAiB,OACjB,eAAe,OACf,gBAAgB,OAChB,OAAO,OACP,OAAO,OACP,QAAQ,OACR,aAAa,OACb,MAAM,OACN,QAAQ,OACR,iBAAiB,KACN,CAAC;;AAOd,wBAAyC"}
@@ -1,8 +1,8 @@
1
1
  // Browser ESM entry point for Diamond Hands SDK
2
2
  // Converts CommonJS exports to ES module imports for browser compatibility
3
3
  // Uses the proven wrapper pattern from test-app/src/lib/lit-ops-wrapper.ts
4
- // Import from the original built SDK
5
- import * as SDKModule from "../dist/index.js";
4
+ // Import from the original built SDK (CommonJS module)
5
+ const SDKModule = require("../dist/index.js");
6
6
  // Import lit-ops and lit-actions (using the wrapper pattern)
7
7
  // TODO: Re-enable when these modules have proper ES module builds
8
8
  // import * as LitOpsModule from "../../lit-ops/dist/index.js";
@@ -16,7 +16,8 @@ export const DiamondHandsSDK = SDKModule.DiamondHandsSDK;
16
16
  // RE-EXPORT CORE SDK ONLY
17
17
  // ========================================
18
18
  // Re-export core SDK exports only to avoid conflicts
19
- export * from "../dist/index.js";
19
+ // Note: CommonJS module, so we export specific items
20
+ export const { AuthParamsValidation, BPSConversions, BitcoinOperations, CacheManager, ContractManager, DiamondHandsSDK: SDKClass, ErrorCategory, ErrorSeverity, EventHelpers, LoanCreator, LoanQuery, LoanStatus, PaymentType, PositionStatus, SDKError, SatoshisConversions, UCDConversions, WeiConversions, createBitcoinOperations, createCacheManager, createContractManager, createLoanCreator, createLoanQuery, createPKPManager, failure, success, tryCatch, tryCatchAsync, unwrap, unwrapOr, validateSDKConfig, } = SDKModule;
20
21
  // ========================================
21
22
  // DEFAULT EXPORT
22
23
  // ========================================
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Smart Contract ABIs
3
+ */
4
+ export declare const POSITION_MANAGER_ABI: readonly ["function createPosition(bytes32 pkpId, bytes calldata validatorSignature, address borrower, string calldata vaultAddress, uint256 selectedTermMonths) external returns (bool)", "function getPositionById(bytes32 positionId) external view returns (tuple(bytes32 positionId, bytes32 pkpId, uint256 ucdDebt, string vaultAddress, address borrower, uint40 createdAt, uint40 lastUpdated, uint16 selectedTerm, uint40 expiryAt, uint8 status))", "function getUserPositions(address user) external view returns (bytes32[] memory)", "function calculateCollateralRatio(bytes32 positionId) external view returns (uint256)", "function hasRole(bytes32 role, address account) external view returns (bool)", "function ADMIN_ROLE() external view returns (bytes32)", "function paused() external view returns (bool)", "function mintUCD(bytes32 positionId, uint256 mintAmount, uint256 mintFee, uint256 newDebt, uint256 newCollateral, uint256 btcPrice, bytes32 authorizedSpendsHash, bytes32 ucdDebtHash, bytes32 contractHash, uint256 quantumTimestamp, bytes calldata mintValidatorSignature) external returns (bool)", "function repayPosition(bytes32 positionId, uint256 repaymentAmount) external returns (bool)", "function makePayment(bytes32 positionId, uint256 paymentAmount, uint256 quantumTimestamp, uint256 btcPrice, bytes calldata paymentValidatorSignature) external returns (bool)", "function withdrawBTC(bytes32 positionId, string withdrawalAddress, uint256 networkFee) external returns (bool)", "function extendPosition(bytes32 positionId, uint256 selectedTerm, uint256 quantumTimestamp, uint256 btcPrice, uint256 availableBTCBalance, bytes calldata extensionValidatorSignature) external returns (bool)", "function liquidatePosition(bytes32 positionId) external returns (bool)", "function commitLiquidation(bytes32 positionId, bytes32 commitHash) external", "function revealAndLiquidate(bytes32 positionId, uint256 nonce, uint256 deadline) external returns (bool)", "function getExpiredLoanLiquidationThreshold(bytes32 positionId) external view returns (uint256)", "function isExpiredLoanLiquidatable(bytes32 positionId, uint256 collateralValue, uint256 debtAmount) external view returns (bool)", "event PositionCreated(bytes32 indexed positionId, bytes32 indexed pkpId, address indexed borrower, uint256 requestedCollateralRatio, uint256 selectedTerm, uint256 expiryAt)", "event UCDMinted(bytes32 indexed positionId, uint256 amount, bytes proof)", "event PositionLiquidated(bytes32 indexed positionId, address indexed liquidator, uint256 collateralRatio, uint256 debtRepaid, uint256 collateralValue, bool wasExpired, uint256 timestamp)", "event CollateralRatioUpdated(bytes32 indexed positionId, uint256 oldRatio, uint256 newRatio)", "event PositionUpdated(bytes32 indexed positionId, uint256 oldDebt, uint256 newDebt)"];
5
+ export declare const UCD_TOKEN_ABI: readonly ["function balanceOf(address account) external view returns (uint256)", "function transfer(address to, uint256 amount) external returns (bool)", "function approve(address spender, uint256 amount) external returns (bool)", "function allowance(address owner, address spender) external view returns (uint256)", "function mint(address to, uint256 amount) external", "function burn(uint256 amount) external", "function burnFrom(address account, uint256 amount) external", "event Transfer(address indexed from, address indexed to, uint256 value)", "event Approval(address indexed owner, address indexed spender, uint256 value)"];
6
+ export declare const PRICE_FEED_CONSUMER_ABI: readonly ["function getCurrentPrice() external view returns (uint256)", "function isPriceStale() external view returns (bool)", "function updatePrice() external", "event PriceUpdated(uint256 indexed price, uint256 timestamp)"];
7
+ export declare const PSM_ABI: readonly ["function swap(address stablecoin, uint256 amountIn, uint256 minUcdOut) external returns (uint256 ucdAmount)", "function addSupportedStablecoin(address stablecoin, uint256 exchangeRate, uint256 entryFeeBps, uint256 exitFeeBps, uint8 decimals, uint256 minSwapAmount, uint256 minRedeemAmount) external", "function updateSupportedStablecoin(address stablecoin, uint256 exchangeRate, uint256 entryFeeBps, uint256 exitFeeBps, uint8 decimals, uint256 minSwapAmount, uint256 minRedeemAmount) external", "function removeSupportedStablecoin(address stablecoin) external", "function withdrawStablecoin(address stablecoin, uint256 amount) external", "function pause() external", "function unpause() external", "function redeem(address stablecoin, uint256 ucdAmount, uint256 minStablecoinOut) external returns (uint256 stablecoinAmount)", "function setExitFee(address stablecoin, uint256 fee) external", "function setEntryFee(address stablecoin, uint256 fee) external", "function setExchangeRate(address stablecoin, uint256 rate) external", "function setRedeemEnabled(bool enabled) external", "function addReserves(address stablecoin, uint256 amount) external", "function syncReserves(address stablecoin) external", "function forceSyncReserves(address stablecoin) external", "function getRedemptionQuote(address stablecoin, uint256 ucdAmount) external view returns (uint256 stablecoinOut, uint256 exitFee)", "function getAvailableReserves(address stablecoin) external view returns (uint256)", "function canRedeem(address stablecoin, uint256 ucdAmount) external view returns (bool)", "function version() external pure returns (string memory)", "function supportedStablecoins(address) external view returns (bool)", "function exchangeRates(address) external view returns (uint256)", "function fees(address) external view returns (uint256)", "function exitFees(address) external view returns (uint256)", "function reserves(address) external view returns (uint256)", "function redeemEnabled() external view returns (bool)", "function stablecoinDecimals(address) external view returns (uint8)", "function lastOperationBlock(address) external view returns (uint256)", "function operationCount(address) external view returns (uint256)", "function BASIS_POINTS() external view returns (uint256)", "function EXCHANGE_RATE_SCALE() external view returns (uint256)", "function MAX_EXIT_FEE() external view returns (uint256)", "function MAX_RESERVE_DRIFT() external view returns (uint256)", "event Swap(address indexed user, address indexed stablecoin, uint256 stablecoinAmount, uint256 ucdAmount, uint256 fee, uint256 timestamp)", "event Redeem(address indexed user, address indexed stablecoin, uint256 ucdAmount, uint256 stablecoinAmount, uint256 exitFee, uint256 timestamp)", "event StablecoinAdded(address indexed stablecoin, uint256 exchangeRate, uint256 fee)", "event StablecoinRemoved(address indexed stablecoin)", "event ReserveUpdated(address indexed stablecoin, uint256 oldReserve, uint256 newReserve)", "event ExitFeeUpdated(address indexed stablecoin, uint256 oldFee, uint256 newFee)", "event EntryFeeUpdated(address indexed stablecoin, uint256 oldFee, uint256 newFee)", "event ExchangeRateUpdated(address indexed stablecoin, uint256 oldRate, uint256 newRate)"];
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Auto-generated deployment addresses
3
+ * Generated by scripts/sync-deployments.js
4
+ * Do not edit manually - this file is overwritten during build
5
+ */
6
+ export interface DeploymentLatestEnv {
7
+ [key: string]: string | number | undefined;
8
+ }
9
+ export interface DeploymentContracts {
10
+ PositionManagerProxy?: string;
11
+ PositionManager?: string;
12
+ PositionManagerCoreModule?: string;
13
+ PositionManagerViews?: string;
14
+ SimplePSMV2?: string;
15
+ LoanOperationsManagerModule?: string;
16
+ BTCSpendAuthorizer?: string;
17
+ TermManagerModule?: string;
18
+ CircuitBreakerModule?: string;
19
+ LiquidationManagerModule?: string;
20
+ CollateralManagerModule?: string;
21
+ AdminModule?: string;
22
+ UCDToken?: string;
23
+ UCDController?: string;
24
+ UCDMintingRewards?: string;
25
+ UpgradeValidator?: string;
26
+ BTCProofValidator?: string;
27
+ LITActionValidator?: string;
28
+ BitcoinProviderRegistry?: string;
29
+ PriceFeedConsumer?: string;
30
+ OperationAuthorizationRegistry?: string;
31
+ PKPValidation?: string;
32
+ EmergencyStorageUpdate?: string;
33
+ mockUsdcToken?: string;
34
+ mockUsdcOwner?: string;
35
+ mockUsdtToken?: string;
36
+ mockUsdtOwner?: string;
37
+ [key: string]: string | undefined;
38
+ }
39
+ export interface DeploymentData {
40
+ network: string;
41
+ chainId?: number;
42
+ timestamp: string;
43
+ deployer: string;
44
+ contracts: DeploymentContracts;
45
+ /** Flat assignments from contracts/deployments/full-{network}-latest.env (proxies, impls, validators, etc.) */
46
+ latestEnv?: DeploymentLatestEnv;
47
+ [key: string]: any;
48
+ }
49
+ export declare const SEPOLIA_DEPLOYMENT: DeploymentData;
50
+ export declare const SEPOLIA_CONTRACTS: DeploymentContracts;
51
+ export declare const LOCALHOST_DEPLOYMENT: DeploymentData;
52
+ export declare const LOCALHOST_CONTRACTS: DeploymentContracts;
53
+ export declare const ALL_DEPLOYMENTS: {
54
+ readonly sepolia: DeploymentData;
55
+ readonly localhost: DeploymentData;
56
+ };
57
+ export declare const ALL_CONTRACTS: {
58
+ readonly sepolia: DeploymentContracts;
59
+ readonly localhost: DeploymentContracts;
60
+ };
61
+ /**
62
+ * Get deployment data by network name
63
+ */
64
+ export declare function getDeploymentByNetwork(network: string): DeploymentData | null;
65
+ /**
66
+ * Get contract addresses by network name
67
+ */
68
+ export declare function getContractsByNetwork(network: string): DeploymentContracts | null;
@@ -0,0 +1,21 @@
1
+ export type EncryptedPriceProvider = {
2
+ name: string;
3
+ pkpId: string;
4
+ apiKey: string;
5
+ apiSecret?: string;
6
+ };
7
+ type RegistryProvider = {
8
+ name: string;
9
+ pkpId: string;
10
+ apiKeyEncrypted: string;
11
+ apiSecretEncrypted?: string;
12
+ version: number;
13
+ updatedAt: string;
14
+ };
15
+ type EncryptedParamsRegistry = {
16
+ network: string;
17
+ providers: RegistryProvider[];
18
+ };
19
+ export declare function loadEncryptedProviderRegistry(registryPath?: string): EncryptedParamsRegistry;
20
+ export declare function getEncryptedPriceProviders(providerNames?: string[], registryPath?: string): EncryptedPriceProvider[];
21
+ export {};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Environment Configuration for Diamond Hands SDK - Browser Version
3
+ * Browser-compatible environment handling without Node.js dependencies
4
+ */
5
+ import { LitNetwork } from "@gvnrdao/dh-lit-ops";
6
+ /** SDK environment label — mirrors `LIT_NETWORK` for supported networks. */
7
+ export type EnvironmentName = "chipotle";
8
+ export interface SDKConfig {
9
+ environment: EnvironmentName;
10
+ litNetwork: LitNetwork;
11
+ realLitTesting: boolean;
12
+ debugMode: boolean;
13
+ runRealIntegrationTests: boolean;
14
+ litRelayUrl?: string;
15
+ ethRpcUrl: string;
16
+ polygonRpcUrl: string;
17
+ pkpMintPrivateKey?: string;
18
+ }
19
+ /**
20
+ * Resolved Lit network from `LIT_NETWORK` / `VITE_LIT_NETWORK` (default: production **chipotle**).
21
+ */
22
+ export declare function resolveLitNetworkFromEnv(): LitNetwork;
23
+ /**
24
+ * SDK environment label derived from `LIT_NETWORK` (default **chipotle**).
25
+ */
26
+ export declare function getCurrentEnvironment(): EnvironmentName;
27
+ /**
28
+ * Load and validate SDK configuration from environment
29
+ */
30
+ export declare function loadSDKConfig(): SDKConfig;
31
+ /**
32
+ * Get LIT Network configuration
33
+ */
34
+ export declare function getLitNetworkConfig(networkName: LitNetwork): LitNetwork;
35
+ /**
36
+ * Environment-aware console logging
37
+ */
38
+ export declare function envLog(message: string, ...args: any[]): void;
39
+ /**
40
+ * Validate SDK environment requirements
41
+ */
42
+ export declare function validateSDKEnvironment(requirements: {
43
+ requiresRealLitTesting?: boolean;
44
+ requiresPrivateKey?: boolean;
45
+ }): SDKConfig;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Environment Configuration for Diamond Hands SDK (Node only)
3
+ *
4
+ * Loads and validates environment variables with multi-path `.env` discovery.
5
+ * Used for server-side flows that may read `PKP_MINT_PRIVATE_KEY`.
6
+ *
7
+ * **Do not import this file from browser-oriented modules.** Import via
8
+ * `@gvnrdao/dh-sdk/server` only. Shared / client code should use `environment.browser`.
9
+ *
10
+ * **Observability:** With `DEBUG_SDK=true`, logs once which `.env` paths were attempted
11
+ * and which existing files were merged (later overrides earlier).
12
+ *
13
+ * **Strict merge checks:** Detecting conflicting definitions of the same variable across
14
+ * multiple `.env` files is not implemented; reserved for a future CI-gated workflow once
15
+ * the repo has automated SDK checks in CI.
16
+ */
17
+ import { LitNetwork } from "@gvnrdao/dh-lit-ops";
18
+ /** SDK environment label — mirrors `LIT_NETWORK` for supported networks. */
19
+ export type EnvironmentName = "chipotle";
20
+ export interface SDKConfig {
21
+ environment: EnvironmentName;
22
+ litNetwork: LitNetwork;
23
+ realLitTesting: boolean;
24
+ debugMode: boolean;
25
+ runRealIntegrationTests: boolean;
26
+ litRelayUrl?: string;
27
+ ethRpcUrl: string;
28
+ polygonRpcUrl: string;
29
+ pkpMintPrivateKey?: string;
30
+ }
31
+ /**
32
+ * Resolved Lit network from `LIT_NETWORK` (default: production **chipotle**).
33
+ */
34
+ export declare function resolveLitNetworkFromEnv(): LitNetwork;
35
+ /**
36
+ * SDK environment label derived from `LIT_NETWORK` (default **chipotle**).
37
+ */
38
+ export declare function getCurrentEnvironment(): EnvironmentName;
39
+ /**
40
+ * Load and validate SDK configuration from environment
41
+ */
42
+ export declare function loadSDKConfig(): SDKConfig;
43
+ /**
44
+ * Get LIT Network configuration
45
+ */
46
+ export declare function getLitNetworkConfig(networkName: LitNetwork): LitNetwork;
47
+ /**
48
+ * Environment-aware console logging
49
+ */
50
+ export declare function envLog(message: string, ...args: any[]): void;
51
+ /**
52
+ * Validate SDK environment requirements
53
+ */
54
+ export declare function validateSDKEnvironment(requirements: {
55
+ requiresRealLitTesting?: boolean;
56
+ requiresPrivateKey?: boolean;
57
+ }): SDKConfig;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Network Configuration Constants
3
+ * Automatically loads contract addresses from deployment files
4
+ * Browser-friendly implementation with silent fallbacks
5
+ */
6
+ /**
7
+ * Network Configuration Interface
8
+ */
9
+ export interface NetworkConfig {
10
+ mode: "service" | "standalone";
11
+ serviceEndpoint: string;
12
+ chainId: number;
13
+ name: string;
14
+ rpcUrls: string[];
15
+ contractAddresses: {
16
+ positionManager: string;
17
+ positionManagerCore?: string;
18
+ positionManagerViews?: string;
19
+ simplePsmV2?: string;
20
+ loanOperationsManager?: string;
21
+ termManager?: string;
22
+ circuitBreaker?: string;
23
+ liquidationManager?: string;
24
+ ucdToken: string;
25
+ ucdController?: string;
26
+ priceFeedConsumer: string;
27
+ operationAuthorizationRegistry?: string;
28
+ btcSpendAuthorizer?: string;
29
+ bitcoinProviderRegistry?: string;
30
+ mockUsdcToken?: string;
31
+ mockUsdtToken?: string;
32
+ mockUsdcOwner?: string;
33
+ };
34
+ subgraphs: {
35
+ diamondHandsUrl?: string;
36
+ tokenGvnrUrl?: string;
37
+ };
38
+ litNetwork: string;
39
+ validatorVersion?: number;
40
+ debug: boolean;
41
+ }
42
+ /**
43
+ * Network Configuration Registry
44
+ */
45
+ export declare const NETWORK_CONFIGS: Record<number, NetworkConfig>;
46
+ /**
47
+ * Get network configuration by chain ID
48
+ */
49
+ export declare function getNetworkConfig(chainId: number): NetworkConfig | null;
50
+ /**
51
+ * Get network configuration by human-readable name (e.g., "sepolia")
52
+ */
53
+ export declare function getNetworkConfigByName(name: string): NetworkConfig | null;
54
+ /**
55
+ * Get all supported network configurations
56
+ */
57
+ export declare function getAllNetworkConfigs(): NetworkConfig[];
58
+ /**
59
+ * Check if a network is supported
60
+ */
61
+ export declare function isNetworkSupported(chainId: number): boolean;
62
+ /**
63
+ * Default network fallbacks
64
+ */
65
+ export declare const DEFAULT_NETWORK_CONFIG: Partial<NetworkConfig>;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * SDK Configuration Constants
3
+ */
4
+ import type { LitNetwork } from "@gvnrdao/dh-lit-ops";
5
+ export declare const DEFAULT_NETWORKS: {
6
+ readonly ETHEREUM_MAINNET: "https://eth-mainnet.g.alchemy.com/v2/";
7
+ readonly ETHEREUM_SEPOLIA: "https://eth-sepolia.g.alchemy.com/v2/";
8
+ readonly POLYGON_MAINNET: "https://polygon-mainnet.g.alchemy.com/v2/";
9
+ readonly LOCAL_HARDHAT: "http://localhost:8545";
10
+ };
11
+ export declare const DEFAULT_LIT_NETWORKS: {
12
+ readonly CHIPOTLE: "chipotle";
13
+ };
14
+ /**
15
+ * Default Lit network when `LIT_NETWORK` is unset or config omits `litNetwork`.
16
+ */
17
+ export declare const DEFAULT_LIT_NETWORK: "chipotle";
18
+ /** Supported Lit Protocol networks for this SDK (Chipotle). */
19
+ export declare const VALID_LIT_NETWORKS: readonly LitNetwork[];
20
+ export declare const SDK_DEFAULTS: {
21
+ readonly SESSION_EXPIRATION_MINUTES: 60;
22
+ readonly TRANSACTION_TIMEOUT_MS: 30000;
23
+ readonly RETRY_ATTEMPTS: 3;
24
+ readonly DEBUG: false;
25
+ };
26
+ export declare const SDK_ERROR_MESSAGES: {
27
+ readonly NOT_INITIALIZED: "SDK not initialized. Call initialize() first.";
28
+ readonly INVALID_CONFIG: "Invalid SDK configuration provided.";
29
+ readonly NETWORK_ERROR: "Network connection error occurred.";
30
+ readonly TRANSACTION_FAILED: "Transaction failed to execute.";
31
+ readonly PKP_CREATION_FAILED: "PKP creation failed.";
32
+ readonly SIGNATURE_INVALID: "Invalid signature provided.";
33
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * SDK Limits and Configuration Constants
3
+ * Centralized constants for magic numbers used throughout the SDK
4
+ */
5
+ /**
6
+ * Maximum batch size for The Graph queries
7
+ * The Graph has a hard limit of 1000 items per query
8
+ */
9
+ export declare const THE_GRAPH_MAX_BATCH_SIZE = 1000;
10
+ /**
11
+ * Maximum rows per page for pagination
12
+ * Prevents excessive memory usage and query timeouts
13
+ */
14
+ export declare const MAX_PAGINATION_ROWS = 1000;
15
+ /**
16
+ * Default rows per page for pagination
17
+ */
18
+ export declare const DEFAULT_PAGINATION_ROWS = 10;
19
+ /**
20
+ * Default maximum number of retries for failed operations
21
+ */
22
+ export declare const DEFAULT_MAX_RETRIES = 3;
23
+ /**
24
+ * Default operation timeout in milliseconds
25
+ */
26
+ export declare const DEFAULT_OPERATION_TIMEOUT_MS = 30000;
27
+ /**
28
+ * Default PKP address cache size
29
+ */
30
+ export declare const DEFAULT_PKP_CACHE_SIZE = 500;
31
+ /**
32
+ * Default PKP address cache TTL in milliseconds
33
+ */
34
+ export declare const DEFAULT_PKP_CACHE_TTL_MS = 300000;
35
+ /**
36
+ * Default balance cache size
37
+ */
38
+ export declare const DEFAULT_BALANCE_CACHE_SIZE = 1000;
39
+ /**
40
+ * Default balance cache TTL in milliseconds
41
+ */
42
+ export declare const DEFAULT_BALANCE_CACHE_TTL_MS = 60000;
43
+ /**
44
+ * Default cache cleanup interval in milliseconds
45
+ */
46
+ export declare const DEFAULT_CACHE_CLEANUP_INTERVAL_MS = 300000;
47
+ /**
48
+ * Default number of blocks for PSM rate limit reset period
49
+ */
50
+ export declare const PSM_RATE_LIMIT_RESET_BLOCKS = 100;
51
+ /**
52
+ * Maximum operations per PSM rate limit window
53
+ */
54
+ export declare const PSM_MAX_OPERATIONS_PER_WINDOW = 10;
55
+ /**
56
+ * Default maximum concurrent operations
57
+ */
58
+ export declare const DEFAULT_CONCURRENCY_LIMIT = 10;
59
+ /**
60
+ * Default Bitcoin provider consensus mode
61
+ */
62
+ export declare const DEFAULT_BITCOIN_CONSENSUS_MODE: "majority";
63
+ /**
64
+ * Minimum number of Bitcoin providers for consensus
65
+ */
66
+ export declare const MIN_BITCOIN_PROVIDERS_FOR_CONSENSUS = 2;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Diamond Hands SDK Constants
3
+ * All constants used in the SDK package
4
+ *
5
+ * Following the golden source pattern with organized chunks
6
+ *
7
+ * **Environment:** This barrel exports **browser-safe** `environment.browser` only.
8
+ * For Node-only config including `PKP_MINT_PRIVATE_KEY` / dotenv paths, use
9
+ * `@gvnrdao/dh-sdk/server` (see `src/server.ts`).
10
+ */
11
+ export * from "./chunks/sdk-config";
12
+ export * from "./chunks/network-configs";
13
+ export * from "./chunks/environment.browser";
14
+ export * from "./chunks/contract-abis";
15
+ export * from "./chunks/sdk-limits";
@@ -0,0 +1,19 @@
1
+ export interface GraphClientConfig {
2
+ endpoint: string;
3
+ requestTimeoutMs?: number;
4
+ maxRetries?: number;
5
+ headers?: Record<string, string>;
6
+ }
7
+ export declare class GraphClient {
8
+ private endpoint;
9
+ private requestTimeoutMs;
10
+ private maxRetries;
11
+ private headers?;
12
+ constructor(config: GraphClientConfig);
13
+ execute<T>(query: string, variables?: Record<string, any>): Promise<T>;
14
+ paginate<TItem>(query: string, variables: Record<string, any>, select: (page: any) => TItem[], options?: {
15
+ pageSize?: number;
16
+ maxPages?: number;
17
+ }): Promise<TItem[]>;
18
+ private backoff;
19
+ }