btc-wallet 0.3.4 → 0.3.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -5,3 +5,7 @@ export declare const defaultTokenIcon = "https://static.particle.network/token-l
5
5
  export declare const ipfsToSrc: (ipfs: string) => string;
6
6
  export declare const checkBTCVersion: (accountContracts: AAOptions["accountContracts"], accountContractKey: string, version: string) => boolean;
7
7
  export declare const delay: (ms: number) => Promise<unknown>;
8
+ export declare function retryOperation<T>(operation: () => Promise<T> | T, shouldStop: (result: T) => boolean, { maxRetries, delayMs, }?: {
9
+ maxRetries?: number;
10
+ delayMs?: number;
11
+ }): Promise<T>;
@@ -0,0 +1,7 @@
1
+ import type { ProviderService } from '@near-wallet-selector/core/src/lib/services';
2
+ import { providers } from 'near-api-js';
3
+ export declare function nearCallFunction<T>(contractId: string, methodName: string, args: any, options: {
4
+ network?: string;
5
+ provider?: ProviderService;
6
+ }): Promise<T>;
7
+ export declare function pollTransactionStatuses(network: string, hashes: string[]): Promise<(providers.FinalExecutionOutcome | undefined)[]>;
package/esm/index.js CHANGED
@@ -470,7 +470,7 @@ var _network2, _event2;
470
470
  var MagicEdenConnector = class extends BaseConnector {
471
471
  constructor() {
472
472
  super();
473
- __privateAdd(this, _network2, "Testnet");
473
+ __privateAdd(this, _network2, "Mainnet");
474
474
  __privateAdd(this, _event2, new EventEmitter2());
475
475
  this.metadata = {
476
476
  id: "magicEden",
@@ -1309,6 +1309,27 @@ var checkBTCVersion = (accountContracts, accountContractKey, version) => {
1309
1309
  return accountContracts[accountContractKey].some((item) => item.version === version);
1310
1310
  };
1311
1311
  var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1312
+ function retryOperation(_0, _1) {
1313
+ return __async(this, arguments, function* (operation, shouldStop, {
1314
+ maxRetries = 3,
1315
+ delayMs = 1e3
1316
+ } = {}) {
1317
+ let retries = 0;
1318
+ while (retries <= maxRetries) {
1319
+ const result = yield operation();
1320
+ if (shouldStop(result)) {
1321
+ return result;
1322
+ }
1323
+ if (retries === maxRetries) {
1324
+ console.warn("Max retries reached");
1325
+ return result;
1326
+ }
1327
+ retries++;
1328
+ yield delay(delayMs);
1329
+ }
1330
+ throw new Error("Unexpected execution path");
1331
+ });
1332
+ }
1312
1333
 
1313
1334
  // src/utils/ethereumUtils.ts
1314
1335
  import {
@@ -2437,7 +2458,7 @@ function useBtcWalletSelector() {
2437
2458
  publicKey.current = res;
2438
2459
  });
2439
2460
  }
2440
- }, [provider]);
2461
+ }, [getPublicKey, provider]);
2441
2462
  useEffect6(() => {
2442
2463
  signMessageFn.current = signMessage;
2443
2464
  }, [signMessage]);
@@ -2459,18 +2480,15 @@ function useBtcWalletSelector() {
2459
2480
  connector.removeListener("accountsChanged", fn);
2460
2481
  }
2461
2482
  };
2462
- }, [connector]);
2483
+ }, [connector, context, getPublicKey]);
2463
2484
  const hook = useMemo6(() => {
2464
2485
  return {
2465
2486
  login: () => __async(this, null, function* () {
2466
- const account = accounts && accounts.length ? accounts[0] : null;
2467
- if (account) {
2468
- return account;
2487
+ const account = accounts == null ? void 0 : accounts[0];
2488
+ if (!account) {
2489
+ openConnectModal == null ? void 0 : openConnectModal();
2469
2490
  }
2470
- if (openConnectModal) {
2471
- yield openConnectModal();
2472
- }
2473
- return null;
2491
+ return account;
2474
2492
  }),
2475
2493
  autoConnect: () => __async(this, null, function* () {
2476
2494
  requestDirectAccount(connectorRef.current).catch((e) => {
@@ -2478,13 +2496,13 @@ function useBtcWalletSelector() {
2478
2496
  });
2479
2497
  }),
2480
2498
  logout: () => {
2481
- const accountId = accounts && accounts.length ? accounts[0] : null;
2499
+ const accountId = accounts == null ? void 0 : accounts[0];
2482
2500
  if (!accountId)
2483
2501
  return;
2484
2502
  disconnect == null ? void 0 : disconnect();
2485
2503
  context.emit("btcLogOut");
2486
2504
  },
2487
- account: accounts && accounts.length ? accounts[0] : null,
2505
+ account: accounts == null ? void 0 : accounts[0],
2488
2506
  getPublicKey: () => {
2489
2507
  return publicKey.current;
2490
2508
  },
@@ -2510,7 +2528,7 @@ function useBtcWalletSelector() {
2510
2528
  }
2511
2529
 
2512
2530
  // src/core/setupBTCWallet.ts
2513
- import { providers, transactions } from "near-api-js";
2531
+ import { transactions } from "near-api-js";
2514
2532
  import { actionCreators } from "@near-js/transactions";
2515
2533
  import { PublicKey } from "near-api-js/lib/utils/key_pair";
2516
2534
  import { encodeTransaction } from "near-api-js/lib/transaction";
@@ -2665,20 +2683,23 @@ function removeWalletButton() {
2665
2683
  var walletConfig = {
2666
2684
  dev: {
2667
2685
  base_url: "https://api.dev.satoshibridge.top",
2668
- token: "nbtc1-nsp.testnet",
2669
- contractId: "dev1-nsp.testnet",
2686
+ token: "nbtc-dev.testnet",
2687
+ accountContractId: "acc-dev.testnet",
2688
+ bridgeContractId: "brg-dev.testnet",
2670
2689
  walletUrl: "https://wallet-dev.satoshibridge.top"
2671
2690
  },
2672
2691
  testnet: {
2673
2692
  base_url: "https://api.testnet.satoshibridge.top",
2674
2693
  token: "nbtc2-nsp.testnet",
2675
- contractId: "dev2-nsp.testnet",
2694
+ accountContractId: "dev2-nsp.testnet",
2695
+ bridgeContractId: "brg2-nsp.testnet",
2676
2696
  walletUrl: "https://wallet-test.satoshibridge.top"
2677
2697
  },
2678
2698
  mainnet: {
2679
2699
  base_url: "https://api.mainnet.satoshibridge.top",
2680
2700
  token: "",
2681
- contractId: "",
2701
+ accountContractId: "",
2702
+ bridgeContractId: "",
2682
2703
  walletUrl: "https://wallet.satoshibridge.top"
2683
2704
  }
2684
2705
  };
@@ -2690,8 +2711,8 @@ var nearRpcUrls = {
2690
2711
  "https://near.drpc.org"
2691
2712
  ],
2692
2713
  testnet: [
2693
- "https://near-testnet.lava.build",
2694
2714
  "https://rpc.testnet.near.org",
2715
+ "https://near-testnet.lava.build",
2695
2716
  "https://near-testnet.drpc.org"
2696
2717
  ]
2697
2718
  };
@@ -2729,7 +2750,7 @@ function request(url, options) {
2729
2750
  body,
2730
2751
  method
2731
2752
  });
2732
- const retryCount2 = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2753
+ const retryCount = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2733
2754
  const controller = new AbortController();
2734
2755
  const timeout = (options == null ? void 0 : options.timeout) || 2e4;
2735
2756
  const timeoutId = setTimeout(() => controller.abort(), timeout);
@@ -2752,16 +2773,16 @@ function request(url, options) {
2752
2773
  return data;
2753
2774
  } catch (err) {
2754
2775
  console.error(err);
2755
- if (retryCount2 > 0) {
2756
- console.log(`Retrying... attempts left: ${retryCount2}`);
2757
- return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount2 - 1 }));
2776
+ if (retryCount > 0) {
2777
+ console.log(`Retrying... attempts left: ${retryCount}`);
2778
+ return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount - 1 }));
2758
2779
  } else if ((options == null ? void 0 : options.pollingInterval) && (options == null ? void 0 : options.maxPollingAttempts)) {
2759
2780
  if (options.maxPollingAttempts > 0) {
2760
2781
  console.log(`Polling... attempts left: ${options.maxPollingAttempts}`);
2761
2782
  yield new Promise((resolve) => setTimeout(resolve, options.pollingInterval));
2762
2783
  return request(url, __spreadProps(__spreadValues({}, options), {
2763
2784
  maxPollingAttempts: options.maxPollingAttempts - 1,
2764
- retryCount: retryCount2
2785
+ retryCount
2765
2786
  }));
2766
2787
  }
2767
2788
  }
@@ -2770,6 +2791,58 @@ function request(url, options) {
2770
2791
  });
2771
2792
  }
2772
2793
 
2794
+ // src/utils/nearUtils.ts
2795
+ import { providers } from "near-api-js";
2796
+ function nearCallFunction(contractId, methodName, args, options) {
2797
+ return __async(this, null, function* () {
2798
+ const nearProvider = (options == null ? void 0 : options.provider) || new providers.FailoverRpcProvider(
2799
+ nearRpcUrls[options == null ? void 0 : options.network].map(
2800
+ (url) => new providers.JsonRpcProvider({ url })
2801
+ )
2802
+ );
2803
+ const res = yield nearProvider.query({
2804
+ request_type: "call_function",
2805
+ account_id: contractId,
2806
+ method_name: methodName,
2807
+ args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
2808
+ finality: "final"
2809
+ });
2810
+ return JSON.parse(Buffer.from(res.result).toString());
2811
+ });
2812
+ }
2813
+ function pollTransactionStatuses(network, hashes) {
2814
+ return __async(this, null, function* () {
2815
+ const provider = new providers.FailoverRpcProvider(
2816
+ Object.values(nearRpcUrls[network]).map(
2817
+ (url) => new providers.JsonRpcProvider({ url })
2818
+ )
2819
+ );
2820
+ const maxAttempts = 3;
2821
+ const pollStatus = (hash) => __async(this, null, function* () {
2822
+ let attempt = 0;
2823
+ while (attempt < maxAttempts) {
2824
+ attempt++;
2825
+ try {
2826
+ const result = yield provider.txStatus(hash, "unused", "FINAL");
2827
+ if (result && result.status) {
2828
+ console.log(`Transaction ${hash} result:`, result);
2829
+ return result;
2830
+ }
2831
+ } catch (error) {
2832
+ console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
2833
+ }
2834
+ if (attempt === maxAttempts) {
2835
+ throw new Error(`Transaction not found after max attempts: ${hash}`);
2836
+ }
2837
+ yield delay(1e4);
2838
+ console.log(`RPC request failed for ${hash}, retrying ${maxAttempts - attempt} more times`);
2839
+ }
2840
+ });
2841
+ const results = yield Promise.all(hashes.map((hash) => pollStatus(hash)));
2842
+ return results;
2843
+ });
2844
+ }
2845
+
2773
2846
  // src/core/setupBTCWallet.ts
2774
2847
  var { transfer, functionCall } = actionCreators;
2775
2848
  var state = {
@@ -2867,28 +2940,23 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
2867
2940
  }
2868
2941
  }), 500);
2869
2942
  }
2870
- function viewMethod(_02) {
2871
- return __async(this, arguments, function* ({ method, args = {} }) {
2872
- const res = yield provider.query({
2873
- request_type: "call_function",
2874
- account_id: currentConfig.contractId,
2875
- method_name: method,
2876
- args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
2877
- finality: "optimistic"
2878
- });
2879
- return JSON.parse(Buffer.from(res.result).toString());
2943
+ function nearCall2(contractId, methodName, args) {
2944
+ return __async(this, null, function* () {
2945
+ return nearCallFunction(contractId, methodName, args, { provider });
2880
2946
  });
2881
2947
  }
2882
2948
  function getNearAccountByBtcPublicKey(btcPublicKey) {
2883
2949
  return __async(this, null, function* () {
2884
- const nearTempAddress = yield viewMethod({
2885
- method: "get_chain_signature_near_account",
2886
- args: { btc_public_key: btcPublicKey }
2887
- });
2888
- const nearTempPublicKey = yield viewMethod({
2889
- method: "get_chain_signature_near_account_public_key",
2890
- args: { btc_public_key: btcPublicKey }
2891
- });
2950
+ const nearTempAddress = yield nearCall2(
2951
+ currentConfig.accountContractId,
2952
+ "get_chain_signature_near_account_id",
2953
+ { btc_public_key: btcPublicKey }
2954
+ );
2955
+ const nearTempPublicKey = yield nearCall2(
2956
+ currentConfig.accountContractId,
2957
+ "get_chain_signature_near_account_public_key",
2958
+ { btc_public_key: btcPublicKey }
2959
+ );
2892
2960
  state.saveAccount(nearTempAddress);
2893
2961
  state.savePublicKey(nearTempPublicKey);
2894
2962
  state.saveBtcPublicKey(btcPublicKey);
@@ -2912,8 +2980,15 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
2912
2980
  }
2913
2981
  ];
2914
2982
  }
2915
- const btcAccount = yield btcContext.login();
2916
- const btcPublicKey = yield btcContext.getPublicKey();
2983
+ yield btcContext.login();
2984
+ const btcPublicKey = yield retryOperation(btcContext.getPublicKey, (res) => !!res, {
2985
+ maxRetries: 40,
2986
+ delayMs: 3e3
2987
+ });
2988
+ console.log("btcPublicKey:", btcPublicKey);
2989
+ if (!btcPublicKey) {
2990
+ throw new Error("No connected BTC wallet, please connect your BTC wallet first.");
2991
+ }
2917
2992
  const { nearTempAddress, nearTempPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
2918
2993
  return [
2919
2994
  {
@@ -2981,11 +3056,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
2981
3056
  nonce: BigInt(rawAccessKey.nonce || 0)
2982
3057
  });
2983
3058
  const publicKeyFormat = PublicKey.from(publicKey);
2984
- const nearNonceApi = yield getNearNonceFromApi(currentConfig.base_url, accountId);
3059
+ const { result_data: nearNonceFromApi } = yield getNearNonceFromApi(
3060
+ currentConfig.base_url,
3061
+ accountId
3062
+ );
2985
3063
  const newTransactions = params.transactions.map((transaction, index) => {
2986
3064
  let nearNonceNumber = accessKey.nonce + BigInt(1);
2987
- if (nearNonceApi) {
2988
- nearNonceNumber = BigInt(nearNonceApi.result_data) > nearNonceNumber ? BigInt(nearNonceApi.result_data) : nearNonceNumber;
3065
+ if (nearNonceFromApi) {
3066
+ nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
2989
3067
  }
2990
3068
  const newActions = transaction.actions.map((action) => {
2991
3069
  switch (action.type) {
@@ -3017,20 +3095,34 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3017
3095
  const hash = bs58.encode(new Uint8Array(sha256.array(txBytes)));
3018
3096
  return { txBytes, txHex, hash };
3019
3097
  });
3020
- const accountInfo = yield viewMethod({
3021
- method: "get_account",
3022
- args: { account_id: accountId }
3023
- });
3024
- const nonceApi = yield getNonceFromApi(currentConfig.base_url, accountId);
3025
- const nonce = Number(nonceApi == null ? void 0 : nonceApi.result_data) > Number(accountInfo.nonce) ? String(nonceApi == null ? void 0 : nonceApi.result_data) : String(accountInfo.nonce);
3098
+ const accountInfo = yield nearCall2(
3099
+ currentConfig.accountContractId,
3100
+ "get_account",
3101
+ { account_id: accountId }
3102
+ );
3103
+ const { result_data: nonceFromApi } = yield getNonceFromApi(
3104
+ currentConfig.base_url,
3105
+ accountId
3106
+ );
3107
+ const nonce = Number(nonceFromApi) > Number(accountInfo.nonce) ? String(nonceFromApi) : String(accountInfo.nonce);
3026
3108
  const intention = {
3027
3109
  chain_id: "397",
3028
3110
  csna: accountId,
3029
3111
  near_transactions: newTransactions.map((t) => t.txHex),
3030
3112
  gas_token: currentConfig.token,
3031
3113
  gas_limit: "3000",
3114
+ use_near_pay_gas: false,
3032
3115
  nonce
3033
3116
  };
3117
+ const nearAccount = yield provider.query({
3118
+ request_type: "view_account",
3119
+ account_id: accountId,
3120
+ finality: "final"
3121
+ });
3122
+ const availableBalance = parseFloat(nearAccount.amount) / __pow(10, 24);
3123
+ if (availableBalance > 0.2) {
3124
+ intention.use_near_pay_gas = true;
3125
+ }
3034
3126
  const strIntention = JSON.stringify(intention);
3035
3127
  const signature = yield btcContext.signMessage(strIntention);
3036
3128
  const result = yield uploadBTCTx(currentConfig.base_url, {
@@ -3115,41 +3207,8 @@ function toHex(originalString) {
3115
3207
  hexString = hexString.replace(/(^0+)/g, "");
3116
3208
  return hexString;
3117
3209
  }
3118
- function pollTransactionStatuses(network, hashes) {
3119
- return __async(this, null, function* () {
3120
- const provider = new providers.FailoverRpcProvider(
3121
- Object.values(nearRpcUrls[network]).map(
3122
- (url) => new providers.JsonRpcProvider({ url })
3123
- )
3124
- );
3125
- const maxAttempts = 3;
3126
- const pollStatus = (hash) => __async(this, null, function* () {
3127
- let attempt = 0;
3128
- while (attempt < maxAttempts) {
3129
- attempt++;
3130
- try {
3131
- const result = yield provider.txStatus(hash, "unused", "FINAL");
3132
- if (result && result.status) {
3133
- console.log(`Transaction ${hash} result:`, result);
3134
- return result;
3135
- }
3136
- } catch (error) {
3137
- console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
3138
- }
3139
- if (attempt === maxAttempts) {
3140
- throw new Error(`Transaction not found after max attempts: ${hash}`);
3141
- }
3142
- yield delay(1e4);
3143
- console.log(`RPC request failed for ${hash}, retrying ${maxAttempts - attempt} more times`);
3144
- }
3145
- });
3146
- const results = yield Promise.all(hashes.map((hash) => pollStatus(hash)));
3147
- return results;
3148
- });
3149
- }
3150
3210
 
3151
3211
  // src/core/btcUtils.ts
3152
- import { providers as providers2 } from "near-api-js";
3153
3212
  import Big from "big.js";
3154
3213
  function getBtcProvider() {
3155
3214
  if (typeof window === "undefined" || !window.btcContext) {
@@ -3170,55 +3229,39 @@ function getBtcRpcUrl() {
3170
3229
  return btcRpcUrls[network];
3171
3230
  });
3172
3231
  }
3173
- function nearViewMethod(contractId, methodName, args) {
3232
+ function nearCall(contractId, methodName, args) {
3174
3233
  return __async(this, null, function* () {
3175
3234
  const network = yield getNetwork();
3176
- const nearProvider = new providers2.FailoverRpcProvider(
3177
- nearRpcUrls[network].map(
3178
- (url) => new providers2.JsonRpcProvider({ url })
3179
- )
3180
- );
3181
- const res = yield nearProvider.query({
3182
- request_type: "call_function",
3183
- account_id: contractId,
3184
- method_name: methodName,
3185
- args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
3186
- finality: "optimistic"
3187
- });
3188
- return JSON.parse(Buffer.from(res.result).toString());
3189
- });
3190
- }
3191
- function getDepositAddress(btcPublicKey, contractId) {
3192
- return __async(this, null, function* () {
3193
- const res = yield nearViewMethod(contractId, "get_user_dapp_deposit_address", {
3194
- deposit_type: {
3195
- BtcPublicKey: { btc_public_key: btcPublicKey, dapp_operation: "Burrowland->Supply" }
3196
- }
3197
- });
3198
- return res;
3235
+ return nearCallFunction(contractId, methodName, args, { network });
3199
3236
  });
3200
3237
  }
3201
3238
  function receiveDepositMsg(_0, _1) {
3202
3239
  return __async(this, arguments, function* (baseUrl, {
3203
3240
  btcPublicKey,
3204
3241
  txHash,
3205
- depositType = 1
3242
+ depositType = 1,
3243
+ postActions,
3244
+ extraMsg
3206
3245
  }) {
3207
3246
  const res = yield request(`${baseUrl}/v1/receiveDepositMsg`, {
3208
3247
  method: "POST",
3209
- body: { btcPublicKey, txHash, depositType }
3248
+ body: { btcPublicKey, txHash, depositType, postActions, extraMsg }
3210
3249
  });
3250
+ console.log("receiveDepositMsg resp:", res);
3211
3251
  return res;
3212
3252
  });
3213
3253
  }
3214
3254
  function checkTransactionStatus(baseUrl, txHash) {
3215
3255
  return __async(this, null, function* () {
3216
- const res = yield request(`${baseUrl}/v1/bridgeFromTx?fromTxHash=${txHash}`, {
3217
- timeout: 6e4,
3218
- pollingInterval: 5e3,
3219
- maxPollingAttempts: 10,
3220
- shouldStopPolling: (res2) => res2.result_code === 0
3221
- });
3256
+ const res = yield request(
3257
+ `${baseUrl}/v1/bridgeFromTx?fromTxHash=${txHash}&fromChainId=1`,
3258
+ {
3259
+ timeout: 6e4,
3260
+ pollingInterval: 5e3,
3261
+ maxPollingAttempts: 10,
3262
+ shouldStopPolling: (res2) => res2.result_code === 0
3263
+ }
3264
+ );
3222
3265
  return res;
3223
3266
  });
3224
3267
  }
@@ -3235,38 +3278,30 @@ function getBtcGasPrice() {
3235
3278
  }
3236
3279
  });
3237
3280
  }
3238
- var retryCount = 0;
3239
3281
  function getBtcBalance() {
3240
3282
  return __async(this, null, function* () {
3241
- const { account } = getBtcProvider();
3283
+ const { account } = yield retryOperation(getBtcProvider, (res2) => !!res2.account);
3242
3284
  if (!account) {
3243
- retryCount++;
3244
- if (retryCount > 3) {
3245
- throw new Error("BTC Account is not available.");
3246
- }
3247
- yield delay(1e3);
3248
- return getBtcBalance();
3285
+ console.error("BTC Account is not available.");
3286
+ return { rawBalance: 0, balance: 0 };
3249
3287
  }
3250
- retryCount = 0;
3251
3288
  const btcRpcUrl = yield getBtcRpcUrl();
3252
3289
  const res = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res2) => res2.json());
3253
- const rawBalance = res.reduce((acc, cur) => acc + cur.value, 0);
3290
+ const rawBalance = res == null ? void 0 : res.reduce((acc, cur) => acc + cur.value, 0);
3254
3291
  const balance = rawBalance / __pow(10, 8);
3255
- console.log("btc balance:", balance);
3256
3292
  return { rawBalance, balance };
3257
3293
  });
3258
3294
  }
3259
3295
  function sendBitcoin(address, amount, feeRate) {
3260
3296
  return __async(this, null, function* () {
3261
3297
  const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
3262
- const satoshis = new Big(amount).mul(__pow(10, 8)).toNumber();
3263
- const txHash = yield sendBitcoin2(address, satoshis, { feeRate });
3298
+ const txHash = yield sendBitcoin2(address, amount, { feeRate });
3264
3299
  return txHash;
3265
3300
  });
3266
3301
  }
3267
- function executeBurrowSupply(_0) {
3302
+ function executeBTCDepositAndAction(_0) {
3268
3303
  return __async(this, arguments, function* ({
3269
- amount,
3304
+ action,
3270
3305
  feeRate,
3271
3306
  isDev = false
3272
3307
  }) {
@@ -3275,26 +3310,75 @@ function executeBurrowSupply(_0) {
3275
3310
  const network = yield getNetwork();
3276
3311
  const config = walletConfig[isDev ? "dev" : network];
3277
3312
  const btcPublicKey = yield getPublicKey();
3313
+ const _action = Object.assign({}, action);
3278
3314
  if (!btcPublicKey) {
3279
3315
  throw new Error("BTC Public Key is not available.");
3280
3316
  }
3281
- const address = yield getDepositAddress(btcPublicKey, config.contractId);
3317
+ if (!_action.receiver_id) {
3318
+ throw new Error("action.receiver_id is required");
3319
+ }
3320
+ if (!_action.amount || !new Big(_action.amount || 0).gt(0)) {
3321
+ throw new Error("action.amount is required and must be greater than 0");
3322
+ }
3323
+ const csna = yield nearCall(
3324
+ config.accountContractId,
3325
+ "get_chain_signature_near_account_id",
3326
+ {
3327
+ btc_public_key: btcPublicKey
3328
+ }
3329
+ );
3330
+ _action.amount = new Big(_action.amount).toString();
3331
+ _action.gas = new Big(100).mul(__pow(10, 12)).toFixed(0);
3332
+ const depositMsg = {
3333
+ recipient_id: csna,
3334
+ post_actions: [_action]
3335
+ };
3336
+ const registerRes = yield nearCall(action.receiver_id, "storage_balance_of", {
3337
+ account_id: csna
3338
+ });
3339
+ if (!(registerRes == null ? void 0 : registerRes.available)) {
3340
+ const storageDepositMsg = {
3341
+ storage_deposit_msg: {
3342
+ contract_id: action.receiver_id,
3343
+ deposit: new Big(0.25).mul(__pow(10, 24)).toFixed(0),
3344
+ registration_only: true
3345
+ },
3346
+ btc_public_key: btcPublicKey
3347
+ };
3348
+ depositMsg.extra_msg = JSON.stringify(storageDepositMsg);
3349
+ }
3350
+ console.log("depositMsg", depositMsg);
3351
+ const userDepositAddress = yield nearCall(
3352
+ config.bridgeContractId,
3353
+ "get_user_deposit_address",
3354
+ { deposit_msg: depositMsg }
3355
+ );
3356
+ console.log("userDepositAddress", userDepositAddress);
3282
3357
  const _feeRate = feeRate || (yield getBtcGasPrice());
3283
- console.log("feeRate", _feeRate);
3284
- const txHash = yield sendBitcoin(address, amount, _feeRate);
3285
- const receiveDepositMsgRes = yield receiveDepositMsg(config.base_url, { btcPublicKey, txHash });
3286
- console.log("receiveDepositMsg resp:", receiveDepositMsgRes);
3358
+ const txHash = yield sendBitcoin(
3359
+ userDepositAddress,
3360
+ new Big(action.amount).toNumber(),
3361
+ _feeRate
3362
+ );
3363
+ yield receiveDepositMsg(config.base_url, {
3364
+ btcPublicKey,
3365
+ txHash,
3366
+ postActions: JSON.stringify(depositMsg.post_actions),
3367
+ extraMsg: depositMsg.extra_msg || ""
3368
+ });
3287
3369
  const checkTransactionStatusRes = yield checkTransactionStatus(config.base_url, txHash);
3288
3370
  console.log("checkTransactionStatus resp:", checkTransactionStatusRes);
3371
+ return checkTransactionStatusRes.result_code === 0 ? { result: "success" } : { result: "failed", error: checkTransactionStatusRes.result_message };
3289
3372
  } catch (error) {
3290
3373
  console.error("Error executing Bridge+BurrowSupply:", error);
3374
+ return { result: "failed", error: error.message };
3291
3375
  }
3292
3376
  });
3293
3377
  }
3294
3378
 
3295
3379
  // src/index.ts
3296
3380
  var getVersion = () => {
3297
- return "0.3.4";
3381
+ return "0.3.6";
3298
3382
  };
3299
3383
  if (typeof window !== "undefined") {
3300
3384
  window.__PARTICLE_BTC_CONNECT_VERSION = getVersion();
@@ -3312,7 +3396,7 @@ export {
3312
3396
  UnisatConnector,
3313
3397
  WizzConnector,
3314
3398
  XverseConnector,
3315
- executeBurrowSupply,
3399
+ executeBTCDepositAndAction,
3316
3400
  getBtcBalance,
3317
3401
  getBtcGasPrice,
3318
3402
  getVersion,