@gvnrdao/dh-sdk 0.0.130 → 0.0.132

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.mjs CHANGED
@@ -12754,48 +12754,48 @@ var init_deployment_addresses = __esm({
12754
12754
  LOCALHOST_DEPLOYMENT = {
12755
12755
  "network": "localhost",
12756
12756
  "chainId": 31337,
12757
- "timestamp": "2025-12-05T21:33:05.298Z",
12757
+ "timestamp": "2025-12-11T16:44:37.280Z",
12758
12758
  "deployer": "",
12759
12759
  "contracts": {
12760
- "UpgradeValidator": "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
12760
+ "UpgradeValidator": "0x2279B7A0a67DB372996a5FaB50D91eAA73d2eBe6",
12761
12761
  "UCDToken": "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
12762
12762
  "UCDController": "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9",
12763
- "PriceFeedConsumer": "0x0B306BF915C4d645ff596e518fAf3F9669b97016",
12764
- "BTCProofValidator": "0x9A9f2CCfdE556A7E9Ff0848998Aa4a0CFD8863AE",
12765
- "UCDMintingRewards": "0x3Aa5ebB10DC797CAC828524e59A333d0A371443c",
12766
- "PositionManagerCoreModule": "0x59b670e9fA9D0A427751Af201D676719a970857b",
12767
- "TermManagerModule": "0x322813Fd9A801c5507c9de605d63CEA4f2CE6c44",
12768
- "LoanOperationsManagerModule": "0x09635F643e140090A9A8Dcd712eD6285858ceBef",
12769
- "CollateralManagerModule": "0x67d269191c92Caf3cD7723F116c85e6E9bf55933",
12770
- "LiquidationManagerModule": "0xc3e53F4d16Ae77Db1c982e75a937B9f60FE63690",
12771
- "CircuitBreakerModule": "0x4A679253410272dd5232B3Ff7cF5dbB88f295319",
12772
- "CommunityManagerModule": "0x9E545E3C0baAB3E08CdfD552C960A1050f373042",
12773
- "AdminModule": "0x1613beB3B2C4f22Ee086B2b38C1476A3cE7f78E8",
12774
- "PositionManagerViews": "0x851356ae760d987E095750cCeb3bC6014560891C",
12775
- "PositionManager": "0x95401dc811bb5740090279Ba06cfA8fcF6113778",
12776
- "OperationAuthorizationRegistry": "0x5f3f1dBD7B74C6B46e8c44f98792A1dAf8d69154",
12777
- "PKPValidation": "0x82e01223d51Eb87e16A03E24687EDF0F294da6f1"
12763
+ "PriceFeedConsumer": "0x610178dA211FEF7D417bC0e6FeD39F05609AD788",
12764
+ "BTCProofValidator": "0xA51c1fc2f0D1a1b8494Ed1FE312d7C3a78Ed91C0",
12765
+ "UCDMintingRewards": "0x9A676e781A523b5d0C0e43731313A708CB607508",
12766
+ "PositionManagerCoreModule": "0x959922bE3CAee4b8Cd9a407cc3ac1C251C2007B1",
12767
+ "TermManagerModule": "0x68B1D87F95878fE05B998F19b66F4baba5De1aed",
12768
+ "LoanOperationsManagerModule": "0x4ed7c70F96B99c776995fB64377f0d4aB3B0e1C1",
12769
+ "CollateralManagerModule": "0xa85233C63b9Ee964Add6F2cffe00Fd84eb32338f",
12770
+ "LiquidationManagerModule": "0x7a2088a1bFc9d81c55368AE168C2C02570cB814F",
12771
+ "CircuitBreakerModule": "0xc6e7DF5E7b4f2A278906862b61205850344D4e7d",
12772
+ "CommunityManagerModule": "0xc5a5C42992dECbae36851359345FE25997F5C42d",
12773
+ "AdminModule": "0xE6E340D132b5f46d1e472DebcD681B2aBc16e57E",
12774
+ "PositionManagerViews": "0xc3e53F4d16Ae77Db1c982e75a937B9f60FE63690",
12775
+ "PositionManager": "0x9E545E3C0baAB3E08CdfD552C960A1050f373042",
12776
+ "OperationAuthorizationRegistry": "0x5eb3Bc0a489C5A8288765d2336659EbCA68FCd00",
12777
+ "PKPValidation": "0x4c5859f0F772848b2D91F1D83E2Fe57935348029"
12778
12778
  }
12779
12779
  };
12780
12780
  LOCALHOST_CONTRACTS = {
12781
- "UpgradeValidator": "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
12781
+ "UpgradeValidator": "0x2279B7A0a67DB372996a5FaB50D91eAA73d2eBe6",
12782
12782
  "UCDToken": "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
12783
12783
  "UCDController": "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9",
12784
- "PriceFeedConsumer": "0x0B306BF915C4d645ff596e518fAf3F9669b97016",
12785
- "BTCProofValidator": "0x9A9f2CCfdE556A7E9Ff0848998Aa4a0CFD8863AE",
12786
- "UCDMintingRewards": "0x3Aa5ebB10DC797CAC828524e59A333d0A371443c",
12787
- "PositionManagerCoreModule": "0x59b670e9fA9D0A427751Af201D676719a970857b",
12788
- "TermManagerModule": "0x322813Fd9A801c5507c9de605d63CEA4f2CE6c44",
12789
- "LoanOperationsManagerModule": "0x09635F643e140090A9A8Dcd712eD6285858ceBef",
12790
- "CollateralManagerModule": "0x67d269191c92Caf3cD7723F116c85e6E9bf55933",
12791
- "LiquidationManagerModule": "0xc3e53F4d16Ae77Db1c982e75a937B9f60FE63690",
12792
- "CircuitBreakerModule": "0x4A679253410272dd5232B3Ff7cF5dbB88f295319",
12793
- "CommunityManagerModule": "0x9E545E3C0baAB3E08CdfD552C960A1050f373042",
12794
- "AdminModule": "0x1613beB3B2C4f22Ee086B2b38C1476A3cE7f78E8",
12795
- "PositionManagerViews": "0x851356ae760d987E095750cCeb3bC6014560891C",
12796
- "PositionManager": "0x95401dc811bb5740090279Ba06cfA8fcF6113778",
12797
- "OperationAuthorizationRegistry": "0x5f3f1dBD7B74C6B46e8c44f98792A1dAf8d69154",
12798
- "PKPValidation": "0x82e01223d51Eb87e16A03E24687EDF0F294da6f1"
12784
+ "PriceFeedConsumer": "0x610178dA211FEF7D417bC0e6FeD39F05609AD788",
12785
+ "BTCProofValidator": "0xA51c1fc2f0D1a1b8494Ed1FE312d7C3a78Ed91C0",
12786
+ "UCDMintingRewards": "0x9A676e781A523b5d0C0e43731313A708CB607508",
12787
+ "PositionManagerCoreModule": "0x959922bE3CAee4b8Cd9a407cc3ac1C251C2007B1",
12788
+ "TermManagerModule": "0x68B1D87F95878fE05B998F19b66F4baba5De1aed",
12789
+ "LoanOperationsManagerModule": "0x4ed7c70F96B99c776995fB64377f0d4aB3B0e1C1",
12790
+ "CollateralManagerModule": "0xa85233C63b9Ee964Add6F2cffe00Fd84eb32338f",
12791
+ "LiquidationManagerModule": "0x7a2088a1bFc9d81c55368AE168C2C02570cB814F",
12792
+ "CircuitBreakerModule": "0xc6e7DF5E7b4f2A278906862b61205850344D4e7d",
12793
+ "CommunityManagerModule": "0xc5a5C42992dECbae36851359345FE25997F5C42d",
12794
+ "AdminModule": "0xE6E340D132b5f46d1e472DebcD681B2aBc16e57E",
12795
+ "PositionManagerViews": "0xc3e53F4d16Ae77Db1c982e75a937B9f60FE63690",
12796
+ "PositionManager": "0x9E545E3C0baAB3E08CdfD552C960A1050f373042",
12797
+ "OperationAuthorizationRegistry": "0x5eb3Bc0a489C5A8288765d2336659EbCA68FCd00",
12798
+ "PKPValidation": "0x4c5859f0F772848b2D91F1D83E2Fe57935348029"
12799
12799
  };
12800
12800
  ALL_DEPLOYMENTS = {
12801
12801
  sepolia: SEPOLIA_DEPLOYMENT,
@@ -12943,7 +12943,7 @@ function getSepoliaConfig() {
12943
12943
  operationAuthorizationRegistry: SEPOLIA_CONTRACTS.OperationAuthorizationRegistry || ""
12944
12944
  },
12945
12945
  subgraphs: {
12946
- diamondHandsUrl: "https://api.studio.thegraph.com/query/65258/diamond-hands/version/latest"
12946
+ diamondHandsUrl: "https://api.studio.thegraph.com/query/65258/diamond-hands/v0.3.0-1765544881"
12947
12947
  },
12948
12948
  // litNetwork: "datil-test",
12949
12949
  debug: true
@@ -12997,8 +12997,14 @@ function getLocalhostConfig() {
12997
12997
  );
12998
12998
  logNetworkConfig("log", "[NetworkConfig] Localhost contracts:", {
12999
12999
  PositionManager: getAddress3("POSITION_MANAGER_ADDRESS", "PositionManager"),
13000
- PositionManagerCore: getAddress3("POSITION_MANAGER_CORE_ADDRESS", "PositionManagerCoreModule"),
13001
- LoanOperationsManagerModule: getAddress3("LOAN_OPERATIONS_MANAGER_ADDRESS", "LoanOperationsManagerModule"),
13000
+ PositionManagerCore: getAddress3(
13001
+ "POSITION_MANAGER_CORE_ADDRESS",
13002
+ "PositionManagerCoreModule"
13003
+ ),
13004
+ LoanOperationsManagerModule: getAddress3(
13005
+ "LOAN_OPERATIONS_MANAGER_ADDRESS",
13006
+ "LoanOperationsManagerModule"
13007
+ ),
13002
13008
  TermManagerModule: getAddress3("TERM_MANAGER_ADDRESS", "TermManagerModule"),
13003
13009
  UCDToken: getAddress3("UCD_TOKEN_ADDRESS", "UCDToken")
13004
13010
  });
@@ -13009,23 +13015,53 @@ function getLocalhostConfig() {
13009
13015
  name: "localhost",
13010
13016
  rpcUrls: ["http://localhost:8545"],
13011
13017
  contractAddresses: {
13012
- positionManager: getAddress3("POSITION_MANAGER_ADDRESS", "PositionManager"),
13013
- positionManagerCore: getAddress3("POSITION_MANAGER_CORE_ADDRESS", "PositionManagerCoreModule"),
13014
- positionManagerViews: getAddress3("POSITION_MANAGER_VIEWS_ADDRESS", "PositionManagerViews"),
13018
+ positionManager: getAddress3(
13019
+ "POSITION_MANAGER_ADDRESS",
13020
+ "PositionManager"
13021
+ ),
13022
+ positionManagerCore: getAddress3(
13023
+ "POSITION_MANAGER_CORE_ADDRESS",
13024
+ "PositionManagerCoreModule"
13025
+ ),
13026
+ positionManagerViews: getAddress3(
13027
+ "POSITION_MANAGER_VIEWS_ADDRESS",
13028
+ "PositionManagerViews"
13029
+ ),
13015
13030
  simplePsmV2: getAddress3("SIMPLE_PSM_V2_ADDRESS", "SimplePSMV2"),
13016
- loanOperationsManager: getAddress3("LOAN_OPERATIONS_MANAGER_ADDRESS", "LoanOperationsManagerModule"),
13031
+ loanOperationsManager: getAddress3(
13032
+ "LOAN_OPERATIONS_MANAGER_ADDRESS",
13033
+ "LoanOperationsManagerModule"
13034
+ ),
13017
13035
  termManager: getAddress3("TERM_MANAGER_ADDRESS", "TermManagerModule"),
13018
- circuitBreaker: getAddress3("CIRCUIT_BREAKER_ADDRESS", "CircuitBreakerModule"),
13019
- communityManager: getAddress3("COMMUNITY_MANAGER_ADDRESS", "CommunityManagerModule"),
13020
- liquidationManager: getAddress3("LIQUIDATION_MANAGER_ADDRESS", "LiquidationManagerModule"),
13036
+ circuitBreaker: getAddress3(
13037
+ "CIRCUIT_BREAKER_ADDRESS",
13038
+ "CircuitBreakerModule"
13039
+ ),
13040
+ communityManager: getAddress3(
13041
+ "COMMUNITY_MANAGER_ADDRESS",
13042
+ "CommunityManagerModule"
13043
+ ),
13044
+ liquidationManager: getAddress3(
13045
+ "LIQUIDATION_MANAGER_ADDRESS",
13046
+ "LiquidationManagerModule"
13047
+ ),
13021
13048
  ucdToken: getAddress3("UCD_TOKEN_ADDRESS", "UCDToken"),
13022
13049
  ucdController: getAddress3("UCD_CONTROLLER_ADDRESS", "UCDController"),
13023
- btcProofValidator: getAddress3("BTC_PROOF_VALIDATOR_ADDRESS", "BTCProofValidator"),
13024
- priceFeedConsumer: getAddress3("PRICE_FEED_CONSUMER_ADDRESS", "PriceFeedConsumer"),
13025
- operationAuthorizationRegistry: getAddress3("OPERATION_AUTHORIZATION_REGISTRY_ADDRESS", "OperationAuthorizationRegistry")
13050
+ btcProofValidator: getAddress3(
13051
+ "BTC_PROOF_VALIDATOR_ADDRESS",
13052
+ "BTCProofValidator"
13053
+ ),
13054
+ priceFeedConsumer: getAddress3(
13055
+ "PRICE_FEED_CONSUMER_ADDRESS",
13056
+ "PriceFeedConsumer"
13057
+ ),
13058
+ operationAuthorizationRegistry: getAddress3(
13059
+ "OPERATION_AUTHORIZATION_REGISTRY_ADDRESS",
13060
+ "OperationAuthorizationRegistry"
13061
+ )
13026
13062
  },
13027
13063
  subgraphs: {
13028
- diamondHandsUrl: "https://api.studio.thegraph.com/query/65258/diamond-hands/version/latest"
13064
+ diamondHandsUrl: "https://api.studio.thegraph.com/query/65258/diamond-hands/v0.3.0-1765544881"
13029
13065
  },
13030
13066
  litNetwork: "datil",
13031
13067
  debug: true
@@ -41881,38 +41917,86 @@ var ContractManager = class {
41881
41917
  }
41882
41918
  const contractRunner = runner;
41883
41919
  const contracts = {
41884
- positionManager: PositionManager__factory.connect(
41885
- contractAddresses.positionManager,
41886
- contractRunner
41887
- ),
41888
- loanOperationsManager: ILoanOperationsManager__factory.connect(
41889
- contractAddresses.loanOperationsManager || ethers_exports.constants.AddressZero,
41890
- contractRunner
41891
- ),
41892
- ucdController: IUCDController__factory.connect(
41893
- contractAddresses.ucdToken,
41894
- contractRunner
41895
- ),
41896
- priceFeed: IPriceFeedConsumer__factory.connect(
41897
- contractAddresses.priceFeedConsumer,
41898
- contractRunner
41899
- ),
41900
- termManager: ITermManager__factory.connect(
41901
- contractAddresses.termManager || ethers_exports.constants.AddressZero,
41902
- contractRunner
41903
- ),
41904
- circuitBreaker: CircuitBreakerModule__factory.connect(
41905
- contractAddresses.circuitBreaker || ethers_exports.constants.AddressZero,
41906
- contractRunner
41907
- ),
41908
- communityManager: ICommunityManager__factory.connect(
41909
- contractAddresses.communityManager || ethers_exports.constants.AddressZero,
41910
- contractRunner
41911
- ),
41912
- liquidationManager: ILiquidationManager__factory.connect(
41913
- contractAddresses.liquidationManager || ethers_exports.constants.AddressZero,
41914
- contractRunner
41915
- )
41920
+ positionManager: (() => {
41921
+ try {
41922
+ return PositionManager__factory.connect(
41923
+ contractAddresses.positionManager,
41924
+ contractRunner
41925
+ );
41926
+ } catch (error) {
41927
+ throw new Error(`Failed to connect to PositionManager at ${contractAddresses.positionManager}: ${error}`);
41928
+ }
41929
+ })(),
41930
+ loanOperationsManager: (() => {
41931
+ try {
41932
+ return ILoanOperationsManager__factory.connect(
41933
+ contractAddresses.loanOperationsManager || ethers_exports.constants.AddressZero,
41934
+ contractRunner
41935
+ );
41936
+ } catch (error) {
41937
+ throw new Error(`Failed to connect to LoanOperationsManager at ${contractAddresses.loanOperationsManager}: ${error}`);
41938
+ }
41939
+ })(),
41940
+ ucdController: (() => {
41941
+ try {
41942
+ return IUCDController__factory.connect(
41943
+ contractAddresses.ucdToken,
41944
+ contractRunner
41945
+ );
41946
+ } catch (error) {
41947
+ throw new Error(`Failed to connect to UCDController at ${contractAddresses.ucdToken}: ${error}`);
41948
+ }
41949
+ })(),
41950
+ priceFeed: (() => {
41951
+ try {
41952
+ return IPriceFeedConsumer__factory.connect(
41953
+ contractAddresses.priceFeedConsumer,
41954
+ contractRunner
41955
+ );
41956
+ } catch (error) {
41957
+ throw new Error(`Failed to connect to PriceFeed at ${contractAddresses.priceFeedConsumer}: ${error}`);
41958
+ }
41959
+ })(),
41960
+ termManager: (() => {
41961
+ try {
41962
+ return ITermManager__factory.connect(
41963
+ contractAddresses.termManager || ethers_exports.constants.AddressZero,
41964
+ contractRunner
41965
+ );
41966
+ } catch (error) {
41967
+ throw new Error(`Failed to connect to TermManager at ${contractAddresses.termManager}: ${error}`);
41968
+ }
41969
+ })(),
41970
+ circuitBreaker: (() => {
41971
+ try {
41972
+ return CircuitBreakerModule__factory.connect(
41973
+ contractAddresses.circuitBreaker || ethers_exports.constants.AddressZero,
41974
+ contractRunner
41975
+ );
41976
+ } catch (error) {
41977
+ throw new Error(`Failed to connect to CircuitBreaker at ${contractAddresses.circuitBreaker}: ${error}`);
41978
+ }
41979
+ })(),
41980
+ communityManager: (() => {
41981
+ try {
41982
+ return ICommunityManager__factory.connect(
41983
+ contractAddresses.communityManager || ethers_exports.constants.AddressZero,
41984
+ contractRunner
41985
+ );
41986
+ } catch (error) {
41987
+ throw new Error(`Failed to connect to CommunityManager at ${contractAddresses.communityManager}: ${error}`);
41988
+ }
41989
+ })(),
41990
+ liquidationManager: (() => {
41991
+ try {
41992
+ return ILiquidationManager__factory.connect(
41993
+ contractAddresses.liquidationManager || ethers_exports.constants.AddressZero,
41994
+ contractRunner
41995
+ );
41996
+ } catch (error) {
41997
+ throw new Error(`Failed to connect to LiquidationManager at ${contractAddresses.liquidationManager}: ${error}`);
41998
+ }
41999
+ })()
41916
42000
  };
41917
42001
  this.contracts = contracts;
41918
42002
  return success(contracts);
@@ -43592,6 +43676,55 @@ var LoanQuery = class {
43592
43676
  })
43593
43677
  );
43594
43678
  }
43679
+ /**
43680
+ * Get loans with BTC balance data from Bitcoin network
43681
+ *
43682
+ * Same as getLoans but includes actual Bitcoin balance for each position's vault.
43683
+ * Queries BTC balances in parallel for performance.
43684
+ *
43685
+ * @param filters - Query filters
43686
+ * @param pagination - Pagination parameters
43687
+ * @returns Paginated loans response with BTC balance data
43688
+ */
43689
+ async getLoansWithBtc(filters = {}, pagination) {
43690
+ const page = pagination?.page || 0;
43691
+ const pageSize = pagination?.pageSize || this.defaultPageSize;
43692
+ const skip = page * pageSize;
43693
+ if (!filters.borrower) {
43694
+ if (this.config.debug) {
43695
+ log.info("\u26A0\uFE0F getLoansWithBtc only supports borrower filter, falling back to getLoans");
43696
+ }
43697
+ return this.getLoans(filters, pagination);
43698
+ }
43699
+ if (this.config.debug) {
43700
+ log.info("\u{1F50D} Querying loans with BTC balance data", { filters, page, pageSize, skip });
43701
+ }
43702
+ return tryCatchAsync(
43703
+ async () => {
43704
+ const result = await this.config.graphClient.getUserPositionsWithBtc(
43705
+ filters.borrower,
43706
+ pageSize,
43707
+ skip,
43708
+ filters.orderBy || "createdAt",
43709
+ filters.orderDirection || "desc"
43710
+ );
43711
+ const enrichedLoans = await this.enrichLoansWithVaultAddresses(result.positions);
43712
+ return {
43713
+ loans: enrichedLoans,
43714
+ page,
43715
+ maxRows: pageSize,
43716
+ totalLoans: result.total
43717
+ };
43718
+ },
43719
+ (error) => new SDKError({
43720
+ message: "Failed to query loans with BTC balance",
43721
+ category: "SUBGRAPH" /* SUBGRAPH */,
43722
+ severity: "MEDIUM" /* MEDIUM */,
43723
+ originalError: error instanceof Error ? error : new Error(String(error)),
43724
+ context: { filters, page, pageSize }
43725
+ })
43726
+ );
43727
+ }
43595
43728
  /**
43596
43729
  * Enrich loans with vault addresses derived from PKP public keys
43597
43730
  *
@@ -44177,7 +44310,10 @@ async function getBitcoinAddressesFromPkp(pkpPublicKey) {
44177
44310
  var BitcoinUtils = class {
44178
44311
  static validateAddress(address) {
44179
44312
  const base58Pattern = /^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+$/;
44180
- return base58Pattern.test(address) && address.length >= 26 && address.length <= 35;
44313
+ const isBase58 = base58Pattern.test(address) && address.length >= 26 && address.length <= 35;
44314
+ const bech32Pattern = /^(bc1|tb1|bcrt1)[a-z0-9]{39,87}$/;
44315
+ const isBech32 = bech32Pattern.test(address);
44316
+ return isBase58 || isBech32;
44181
44317
  }
44182
44318
  static formatTransaction(hash3, amount, recipient) {
44183
44319
  return {
@@ -45559,7 +45695,8 @@ var MIN_BITCOIN_PROVIDERS_FOR_CONSENSUS = 2;
45559
45695
  var DiamondHandsGraph = class {
45560
45696
  client;
45561
45697
  defaultPageSize;
45562
- constructor(config) {
45698
+ bitcoinOps;
45699
+ constructor(config, bitcoinOps) {
45563
45700
  this.client = new GraphClient({
45564
45701
  endpoint: config.endpoint,
45565
45702
  requestTimeoutMs: config.requestTimeoutMs,
@@ -45567,12 +45704,14 @@ var DiamondHandsGraph = class {
45567
45704
  headers: config.headers
45568
45705
  });
45569
45706
  this.defaultPageSize = config.defaultPageSize ?? 100;
45707
+ this.bitcoinOps = bitcoinOps;
45570
45708
  }
45571
45709
  /**
45572
45710
  * Transform graph position data to LoanData interface
45573
45711
  * Converts flat graph structure to nested LoanData structure
45574
45712
  */
45575
45713
  transformGraphPositionToLoanData(graphPosition) {
45714
+ const ucdDebt = graphPosition.ucdDebt ? Number(graphPosition.ucdDebt) : 0;
45576
45715
  return {
45577
45716
  id: graphPosition.id,
45578
45717
  pkpId: graphPosition.pkpId,
@@ -45585,14 +45724,16 @@ var DiamondHandsGraph = class {
45585
45724
  loan: {
45586
45725
  ucdMinted: graphPosition.ucdMinted ? Number(graphPosition.ucdMinted) : 0,
45587
45726
  ucdPaid: graphPosition.ucdPaid ? Number(graphPosition.ucdPaid) : 0,
45588
- ucdDebt: graphPosition.ucdDebt ? Number(graphPosition.ucdDebt) : 0,
45727
+ ucdDebt,
45589
45728
  selectedTerm: graphPosition.selectedTerm ? Number(graphPosition.selectedTerm) : 0,
45590
45729
  status: graphPosition.status,
45591
45730
  expiryAt: graphPosition.expiryAt ? Number(graphPosition.expiryAt) : 0
45592
45731
  },
45593
45732
  collateral: {
45594
45733
  vaultAddress: graphPosition.vaultAddress || ""
45595
- }
45734
+ },
45735
+ // Backwards compatibility: provide ucdDebt at top level for components expecting flat structure
45736
+ ucdDebt
45596
45737
  };
45597
45738
  }
45598
45739
  /**
@@ -45636,10 +45777,7 @@ var DiamondHandsGraph = class {
45636
45777
  }
45637
45778
  }
45638
45779
  `;
45639
- const result = await this.client.execute(
45640
- query,
45641
- { ...variables, skip }
45642
- );
45780
+ const result = await this.client.execute(query, { ...variables, skip });
45643
45781
  const items = result && result["positions"] || [];
45644
45782
  totalCount += items.length;
45645
45783
  hasMore = items.length === batchSize;
@@ -45691,10 +45829,9 @@ var DiamondHandsGraph = class {
45691
45829
  query,
45692
45830
  variables
45693
45831
  );
45694
- const total = await this.getTotalCountPaginated(
45695
- "{ borrower: $borrower }",
45696
- { borrower: userAddress.toLowerCase() }
45697
- );
45832
+ const total = await this.getTotalCountPaginated("{ borrower: $borrower }", {
45833
+ borrower: userAddress.toLowerCase()
45834
+ });
45698
45835
  let positions = [];
45699
45836
  if (result && result.user && Array.isArray(result.user.positions)) {
45700
45837
  positions = result.user.positions.filter((p) => p != null).map((p) => this.transformGraphPositionToLoanData(p));
@@ -45704,6 +45841,137 @@ var DiamondHandsGraph = class {
45704
45841
  total
45705
45842
  };
45706
45843
  }
45844
+ /**
45845
+ * Get user positions with enriched Bitcoin balance data
45846
+ *
45847
+ * Same as getUserPositions but queries actual BTC balance from Bitcoin network
45848
+ * for each vault address in parallel.
45849
+ *
45850
+ * @param userAddress - User's Ethereum address
45851
+ * @param first - Optional: max number of positions to return (default: 10)
45852
+ * @param skip - Optional: number of positions to skip (default: 0)
45853
+ * @param orderBy - Optional: field to order by (default: "createdAt")
45854
+ * @param orderDirection - Optional: asc or desc (default: "desc" - most recent first)
45855
+ * @returns Positions with actual BTC balances from Bitcoin network
45856
+ */
45857
+ async getUserPositionsWithBtc(userAddress, first = 10, skip = 0, orderBy = "createdAt", orderDirection = "desc") {
45858
+ const result = await this.getUserPositions(
45859
+ userAddress,
45860
+ first,
45861
+ skip,
45862
+ orderBy,
45863
+ orderDirection
45864
+ );
45865
+ if (!this.bitcoinOps) {
45866
+ console.warn(
45867
+ "[DiamondHandsGraph] BitcoinOperations not available - returning positions without BTC balance"
45868
+ );
45869
+ return result;
45870
+ }
45871
+ const positionsWithPkp = result.positions.filter(
45872
+ (p) => p.pkpId && p.pkpId !== ""
45873
+ );
45874
+ if (positionsWithPkp.length === 0) {
45875
+ console.log("[DiamondHandsGraph] No positions with PKP IDs to check");
45876
+ return result;
45877
+ }
45878
+ console.log(
45879
+ `[DiamondHandsGraph] Deriving Bitcoin addresses and querying balances for ${positionsWithPkp.length} positions in parallel...`
45880
+ );
45881
+ const balancePromises = positionsWithPkp.map(async (position) => {
45882
+ try {
45883
+ const pkpPublicKey = await getPKPPublicKeyFromTokenId(position.pkpId);
45884
+ const addressResult = await this.bitcoinOps.deriveAddresses(
45885
+ pkpPublicKey
45886
+ );
45887
+ if (!addressResult.success) {
45888
+ console.warn(
45889
+ `[DiamondHandsGraph] Failed to derive address for PKP public key ${pkpPublicKey}:`,
45890
+ addressResult.error
45891
+ );
45892
+ return {
45893
+ pkpId: position.pkpId,
45894
+ address: null,
45895
+ balance: null,
45896
+ addresses: null
45897
+ };
45898
+ }
45899
+ const addresses = addressResult.value;
45900
+ const btcAddress = addresses.regtest || addresses.testnet || addresses.mainnet;
45901
+ if (!btcAddress) {
45902
+ console.warn(
45903
+ `[DiamondHandsGraph] No Bitcoin address available for PKP ${position.pkpId}`
45904
+ );
45905
+ return {
45906
+ pkpId: position.pkpId,
45907
+ address: null,
45908
+ balance: null,
45909
+ addresses
45910
+ };
45911
+ }
45912
+ const balanceResult = await this.bitcoinOps.getBalance(btcAddress);
45913
+ if (balanceResult.success) {
45914
+ return {
45915
+ pkpId: position.pkpId,
45916
+ address: btcAddress,
45917
+ balance: balanceResult.value,
45918
+ addresses
45919
+ };
45920
+ } else {
45921
+ console.warn(
45922
+ `[DiamondHandsGraph] Failed to get balance for ${btcAddress}:`,
45923
+ balanceResult.error
45924
+ );
45925
+ return {
45926
+ pkpId: position.pkpId,
45927
+ address: btcAddress,
45928
+ balance: null,
45929
+ addresses
45930
+ };
45931
+ }
45932
+ } catch (error) {
45933
+ console.error(
45934
+ `[DiamondHandsGraph] Error processing PKP ${position.pkpId}:`,
45935
+ error
45936
+ );
45937
+ return {
45938
+ pkpId: position.pkpId,
45939
+ address: null,
45940
+ balance: null,
45941
+ addresses: null
45942
+ };
45943
+ }
45944
+ });
45945
+ const balanceResults = await Promise.all(balancePromises);
45946
+ const balanceMap = /* @__PURE__ */ new Map();
45947
+ balanceResults.forEach(({ pkpId, address, balance, addresses }) => {
45948
+ balanceMap.set(pkpId, { address, balance, addresses });
45949
+ });
45950
+ console.log(
45951
+ `[DiamondHandsGraph] Retrieved ${balanceResults.length} BTC balances`
45952
+ );
45953
+ const enrichedPositions = result.positions.map((position) => {
45954
+ if (!position.pkpId) {
45955
+ return position;
45956
+ }
45957
+ const data = balanceMap.get(position.pkpId);
45958
+ if (!data) {
45959
+ return position;
45960
+ }
45961
+ return {
45962
+ ...position,
45963
+ collateral: {
45964
+ ...position.collateral,
45965
+ vaultAddress: data.address || position.collateral?.vaultAddress || ""
45966
+ },
45967
+ btcBalance: data.balance || void 0
45968
+ };
45969
+ });
45970
+ return {
45971
+ positions: enrichedPositions,
45972
+ total: result.total
45973
+ };
45974
+ }
45707
45975
  /**
45708
45976
  * Get position by PKP ID from subgraph
45709
45977
  */
@@ -45806,10 +46074,7 @@ var DiamondHandsGraph = class {
45806
46074
  const variables = {
45807
46075
  pkpId: pkpId.toLowerCase()
45808
46076
  };
45809
- const result = await this.client.execute(
45810
- query,
45811
- variables
45812
- );
46077
+ const result = await this.client.execute(query, variables);
45813
46078
  if (!result || !result.positions) {
45814
46079
  return null;
45815
46080
  }
@@ -45886,10 +46151,7 @@ var DiamondHandsGraph = class {
45886
46151
  const variables = {
45887
46152
  positionId: positionId.toLowerCase()
45888
46153
  };
45889
- const result = await this.client.execute(
45890
- query,
45891
- variables
45892
- );
46154
+ const result = await this.client.execute(query, variables);
45893
46155
  if (!result || !result.positions) {
45894
46156
  return null;
45895
46157
  }
@@ -45962,10 +46224,12 @@ var DiamondHandsGraph = class {
45962
46224
  }
45963
46225
  }
45964
46226
  `;
45965
- const result = await this.client.execute(
45966
- query,
45967
- { first, skip, orderBy, orderDirection }
45968
- );
46227
+ const result = await this.client.execute(query, {
46228
+ first,
46229
+ skip,
46230
+ orderBy,
46231
+ orderDirection
46232
+ });
45969
46233
  const total = await this.getTotalCountPaginated();
45970
46234
  const positions = result && result.positions || [];
45971
46235
  const transformedPositions = positions.map(
@@ -46007,10 +46271,13 @@ var DiamondHandsGraph = class {
46007
46271
  }
46008
46272
  }
46009
46273
  `;
46010
- const result = await this.client.execute(
46011
- query,
46012
- { first, skip, statuses, orderBy, orderDirection }
46013
- );
46274
+ const result = await this.client.execute(query, {
46275
+ first,
46276
+ skip,
46277
+ statuses,
46278
+ orderBy,
46279
+ orderDirection
46280
+ });
46014
46281
  const total = await this.getTotalCountPaginated(
46015
46282
  "{ status_in: $statuses }",
46016
46283
  { statuses }
@@ -46131,7 +46398,10 @@ var DiamondHandsGraph = class {
46131
46398
  `;
46132
46399
  const first = options?.first ?? this.defaultPageSize;
46133
46400
  const skip = options?.skip ?? 0;
46134
- const result = await this.client.execute(query, { first, skip });
46401
+ const result = await this.client.execute(
46402
+ query,
46403
+ { first, skip }
46404
+ );
46135
46405
  return result.loanTerms || [];
46136
46406
  }
46137
46407
  /**
@@ -46153,7 +46423,10 @@ var DiamondHandsGraph = class {
46153
46423
  }
46154
46424
  }
46155
46425
  `;
46156
- const result = await this.client.execute(query, { id: id3 });
46426
+ const result = await this.client.execute(
46427
+ query,
46428
+ { id: id3 }
46429
+ );
46157
46430
  return result.loanTerm || null;
46158
46431
  }
46159
46432
  // ============================================================================
@@ -46270,7 +46543,13 @@ var DiamondHandsGraph = class {
46270
46543
  * Get PSM transactions with filters
46271
46544
  */
46272
46545
  async getPSMTransactions(filters) {
46273
- const { user, stablecoin, type, first = this.defaultPageSize, skip = 0 } = filters || {};
46546
+ const {
46547
+ user,
46548
+ stablecoin,
46549
+ type,
46550
+ first = this.defaultPageSize,
46551
+ skip = 0
46552
+ } = filters || {};
46274
46553
  let whereConditions = [];
46275
46554
  if (user)
46276
46555
  whereConditions.push(`user: "${user.toLowerCase()}"`);
@@ -46330,7 +46609,10 @@ var DiamondHandsGraph = class {
46330
46609
  }
46331
46610
  `;
46332
46611
  const variables = { first };
46333
- const result = await this.client.execute(query, variables);
46612
+ const result = await this.client.execute(
46613
+ query,
46614
+ variables
46615
+ );
46334
46616
  return result.psmDailyMetrics || [];
46335
46617
  }
46336
46618
  // ============================================================================
@@ -46465,19 +46747,21 @@ var DiamondHandsGraph = class {
46465
46747
  orderDirection
46466
46748
  };
46467
46749
  const result = await this.client.execute(query, variables);
46468
- const payments = (result.position?.payments || []).map((p) => ({
46469
- id: p.id,
46470
- positionId,
46471
- payer: p.payer.id,
46472
- amount: p.amount,
46473
- type: p.type,
46474
- transactionHash: p.transactionHash,
46475
- timestamp: p.timestamp,
46476
- blockNumber: p.blockNumber,
46477
- logIndex: p.logIndex,
46478
- newDebt: p.newDebt,
46479
- newCollateralRatio: p.newCollateralRatio
46480
- }));
46750
+ const payments = (result.position?.payments || []).map(
46751
+ (p) => ({
46752
+ id: p.id,
46753
+ positionId,
46754
+ payer: p.payer.id,
46755
+ amount: p.amount,
46756
+ type: p.type,
46757
+ transactionHash: p.transactionHash,
46758
+ timestamp: p.timestamp,
46759
+ blockNumber: p.blockNumber,
46760
+ logIndex: p.logIndex,
46761
+ newDebt: p.newDebt,
46762
+ newCollateralRatio: p.newCollateralRatio
46763
+ })
46764
+ );
46481
46765
  const statusUpdates = (result.position?.statusUpdates || []).map((s) => ({
46482
46766
  id: s.id,
46483
46767
  positionId,
@@ -46679,7 +46963,7 @@ function createMockTokenManager(config) {
46679
46963
  import { LitOps } from "@gvnrdao/dh-lit-ops";
46680
46964
 
46681
46965
  // src/utils/telegram-messaging.utils.ts
46682
- import TelegramBot from "node-telegram-bot-api";
46966
+ var TelegramBot = null;
46683
46967
  async function sendTelegramMessage(chatId, chatToken, message, threadId) {
46684
46968
  try {
46685
46969
  const bot = new TelegramBot(chatToken, { polling: false });
@@ -46822,13 +47106,16 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
46822
47106
  "Diamond Hands subgraph URL is required. Please provide config.subgraphs.diamondHandsUrl"
46823
47107
  );
46824
47108
  }
46825
- this.graphClient = new DiamondHandsGraph({
46826
- endpoint: graphEndpoint,
46827
- requestTimeoutMs: config.graphOptions?.requestTimeoutMs,
46828
- maxRetries: config.graphOptions?.maxRetries,
46829
- defaultPageSize: config.graphOptions?.pageSize,
46830
- headers: config.graphApiKey ? { Authorization: `Bearer ${config.graphApiKey}` } : void 0
46831
- });
47109
+ this.graphClient = new DiamondHandsGraph(
47110
+ {
47111
+ endpoint: graphEndpoint,
47112
+ requestTimeoutMs: config.graphOptions?.requestTimeoutMs,
47113
+ maxRetries: config.graphOptions?.maxRetries,
47114
+ defaultPageSize: config.graphOptions?.pageSize,
47115
+ headers: config.graphApiKey ? { Authorization: `Bearer ${config.graphApiKey}` } : void 0
47116
+ },
47117
+ this.bitcoinOperations
47118
+ );
46832
47119
  const loanQueryResult = createLoanQuery({
46833
47120
  graphClient: this.graphClient,
46834
47121
  bitcoinOperations: this.bitcoinOperations,
@@ -47651,7 +47938,7 @@ var DiamondHandsSDK = class _DiamondHandsSDK {
47651
47938
  validationResponse.timestamp,
47652
47939
  signatureBytes
47653
47940
  );
47654
- const receipt = await tx.wait();
47941
+ const receipt = await tx.wait(1, 3e5);
47655
47942
  let amountMinted;
47656
47943
  let positionId;
47657
47944
  if (receipt && receipt.logs && receipt.logs.length > 0) {