btc-wallet 0.3.2 → 0.3.4

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.
@@ -0,0 +1,16 @@
1
+ export declare function getBtcGasPrice(): Promise<number>;
2
+ export declare function getBtcBalance(): Promise<{
3
+ rawBalance: any;
4
+ balance: number;
5
+ }>;
6
+ export declare function sendBitcoin(address: string, amount: string, feeRate: number): Promise<string>;
7
+ interface ExecuteBurrowSupplyParams {
8
+ /** btc amount, e.g. 0.01 */
9
+ amount: string;
10
+ /** fee rate, if not provided, will use the recommended fee rate from the btc node */
11
+ feeRate?: number;
12
+ /** is dev environment */
13
+ isDev?: boolean;
14
+ }
15
+ export declare function executeBurrowSupply({ amount, feeRate, isDev, }: ExecuteBurrowSupplyParams): Promise<void>;
16
+ export {};
@@ -5,13 +5,13 @@ export declare function BtcWalletSelectorContextProvider({ children, }: {
5
5
  }): import("react/jsx-runtime").JSX.Element;
6
6
  export declare function useBtcWalletSelector(): {
7
7
  login: () => Promise<string | null>;
8
- autoConnect: () => Promise<null | undefined>;
8
+ autoConnect: () => Promise<void>;
9
9
  logout: () => void;
10
10
  account: string | null;
11
- getPublicKey: () => Promise<any>;
11
+ getPublicKey: () => any;
12
12
  signMessage: (msg: string) => any;
13
13
  getContext: () => any;
14
- getBalance: () => Promise<any>;
14
+ getNetwork: () => Promise<"livenet" | "testnet">;
15
15
  sendBitcoin: (toAddress: string, satoshis: number, options?: {
16
16
  feeRate: number;
17
17
  }) => Promise<string>;
package/dist/index.d.ts CHANGED
@@ -3,5 +3,5 @@ export { ConnectProvider } from './context';
3
3
  export * from './hooks';
4
4
  export * from './core/btcWalletSelectorContext';
5
5
  export * from './core/setupBTCWallet';
6
- export * from './core/bridgeSupplyUtils';
6
+ export * from './core/btcUtils';
7
7
  export declare const getVersion: () => string;
package/dist/index.js CHANGED
@@ -91,7 +91,10 @@ __export(src_exports, {
91
91
  WizzConnector: () => WizzConnector,
92
92
  XverseConnector: () => XverseConnector,
93
93
  executeBurrowSupply: () => executeBurrowSupply,
94
+ getBtcBalance: () => getBtcBalance,
95
+ getBtcGasPrice: () => getBtcGasPrice,
94
96
  getVersion: () => getVersion,
97
+ sendBitcoin: () => sendBitcoin,
95
98
  setupBTCWallet: () => setupBTCWallet,
96
99
  useAccountContract: () => useAccountContract,
97
100
  useAccounts: () => useAccounts,
@@ -320,7 +323,7 @@ var _network, _event;
320
323
  var XverseConnector = class extends BaseConnector {
321
324
  constructor() {
322
325
  super();
323
- __privateAdd(this, _network, "Mainnet");
326
+ __privateAdd(this, _network, "Testnet");
324
327
  __privateAdd(this, _event, new import_events.default());
325
328
  this.metadata = {
326
329
  id: "xverse",
@@ -520,7 +523,7 @@ var _network2, _event2;
520
523
  var MagicEdenConnector = class extends BaseConnector {
521
524
  constructor() {
522
525
  super();
523
- __privateAdd(this, _network2, "Mainnet");
526
+ __privateAdd(this, _network2, "Testnet");
524
527
  __privateAdd(this, _event2, new import_events2.default());
525
528
  this.metadata = {
526
529
  id: "magicEden",
@@ -740,7 +743,16 @@ var useAccounts = () => {
740
743
  // src/hooks/useBTCProvider.ts
741
744
  var import_react = require("react");
742
745
  var useBTCProvider = () => {
743
- const { connector, provider, accounts, getPublicKey, signMessage, getNetwork, switchNetwork, sendBitcoin: sendBitcoin2 } = useConnectProvider();
746
+ const {
747
+ connector,
748
+ provider,
749
+ accounts,
750
+ getPublicKey,
751
+ signMessage,
752
+ getNetwork: getNetwork2,
753
+ switchNetwork,
754
+ sendBitcoin: sendBitcoin2
755
+ } = useConnectProvider();
744
756
  const sendInscription = (0, import_react.useCallback)(
745
757
  (address, inscriptionId, options) => __async(void 0, null, function* () {
746
758
  if (!connector) {
@@ -751,7 +763,17 @@ var useBTCProvider = () => {
751
763
  }),
752
764
  [connector]
753
765
  );
754
- return { provider, accounts, getPublicKey, signMessage, getNetwork, switchNetwork, sendBitcoin: sendBitcoin2, sendInscription, connector };
766
+ return {
767
+ provider,
768
+ accounts,
769
+ getPublicKey,
770
+ signMessage,
771
+ getNetwork: getNetwork2,
772
+ switchNetwork,
773
+ sendBitcoin: sendBitcoin2,
774
+ sendInscription,
775
+ connector
776
+ };
755
777
  };
756
778
 
757
779
  // src/hooks/useConnectModal.ts
@@ -2105,7 +2127,7 @@ var ConnectProvider = ({
2105
2127
  }),
2106
2128
  [connector]
2107
2129
  );
2108
- const getNetwork = (0, import_react10.useCallback)(() => __async(void 0, null, function* () {
2130
+ const getNetwork2 = (0, import_react10.useCallback)(() => __async(void 0, null, function* () {
2109
2131
  if (!connector) {
2110
2132
  throw new Error("Wallet not connected!");
2111
2133
  }
@@ -2289,7 +2311,7 @@ var ConnectProvider = ({
2289
2311
  signMessage,
2290
2312
  evmAccount,
2291
2313
  smartAccount,
2292
- getNetwork,
2314
+ getNetwork: getNetwork2,
2293
2315
  switchNetwork,
2294
2316
  sendBitcoin: sendBitcoin2,
2295
2317
  accountContract,
@@ -2443,21 +2465,18 @@ function InitBtcWalletSelectorContext() {
2443
2465
  }
2444
2466
  function useBtcWalletSelector() {
2445
2467
  const { openConnectModal, openConnectModalAsync, disconnect, requestDirectAccount } = useConnectModal();
2446
- const { accounts, sendBitcoin: sendBitcoin2, getPublicKey, provider, signMessage, connector } = useBTCProvider();
2468
+ const { accounts, sendBitcoin: sendBitcoin2, getPublicKey, provider, signMessage, connector, getNetwork: getNetwork2 } = useBTCProvider();
2447
2469
  const publicKey = (0, import_react11.useRef)(null);
2448
2470
  const signMessageFn = (0, import_react11.useRef)(null);
2449
2471
  const connectorRef = (0, import_react11.useRef)(null);
2450
- const providerRef = (0, import_react11.useRef)(null);
2451
- const [updater, setUpdater] = (0, import_react11.useState)(1);
2452
2472
  const context = (0, import_react11.useContext)(WalletSelectorContext);
2453
2473
  (0, import_react11.useEffect)(() => {
2454
2474
  if (provider) {
2455
2475
  getPublicKey().then((res) => {
2456
2476
  publicKey.current = res;
2457
2477
  });
2458
- providerRef.current = provider;
2459
2478
  }
2460
- }, [provider, updater]);
2479
+ }, [provider]);
2461
2480
  (0, import_react11.useEffect)(() => {
2462
2481
  signMessageFn.current = signMessage;
2463
2482
  }, [signMessage]);
@@ -2480,67 +2499,53 @@ function useBtcWalletSelector() {
2480
2499
  }
2481
2500
  };
2482
2501
  }, [connector]);
2483
- return {
2484
- login: () => __async(this, null, function* () {
2485
- const account = accounts && accounts.length ? accounts[0] : null;
2486
- if (account) {
2487
- return account;
2488
- }
2489
- setUpdater(updater + 1);
2490
- if (openConnectModal) {
2491
- yield openConnectModal();
2492
- }
2493
- return null;
2494
- }),
2495
- autoConnect: () => __async(this, null, function* () {
2496
- let times = 0;
2497
- while (!connectorRef.current) {
2498
- yield delay(500);
2499
- if (times++ > 10) {
2500
- return null;
2502
+ const hook = (0, import_react11.useMemo)(() => {
2503
+ return {
2504
+ login: () => __async(this, null, function* () {
2505
+ const account = accounts && accounts.length ? accounts[0] : null;
2506
+ if (account) {
2507
+ return account;
2501
2508
  }
2502
- }
2503
- requestDirectAccount(connectorRef.current).catch((e) => {
2504
- context.emit("btcLoginError");
2505
- });
2506
- }),
2507
- logout: () => {
2508
- const accountId = accounts && accounts.length ? accounts[0] : null;
2509
- if (!accountId)
2510
- return;
2511
- disconnect == null ? void 0 : disconnect();
2512
- context.emit("btcLogOut");
2513
- },
2514
- account: accounts && accounts.length ? accounts[0] : null,
2515
- getPublicKey: () => __async(this, null, function* () {
2516
- let times = 0;
2517
- while (!publicKey.current) {
2518
- yield delay(1e3);
2519
- if (times++ > 10) {
2520
- return null;
2509
+ if (openConnectModal) {
2510
+ yield openConnectModal();
2521
2511
  }
2522
- }
2523
- return publicKey.current;
2524
- }),
2525
- signMessage: (msg) => {
2526
- return signMessageFn.current(msg);
2527
- },
2528
- getContext: () => {
2529
- return context;
2530
- },
2531
- getBalance: () => __async(this, null, function* () {
2532
- let times = 0;
2533
- while (!providerRef.current) {
2534
- yield delay(500);
2535
- if (times++ > 10) {
2536
- return null;
2537
- }
2538
- }
2539
- const { total } = yield providerRef.current.getBalance();
2540
- return total;
2541
- }),
2542
- sendBitcoin: sendBitcoin2
2543
- };
2512
+ return null;
2513
+ }),
2514
+ autoConnect: () => __async(this, null, function* () {
2515
+ requestDirectAccount(connectorRef.current).catch((e) => {
2516
+ context.emit("btcLoginError");
2517
+ });
2518
+ }),
2519
+ logout: () => {
2520
+ const accountId = accounts && accounts.length ? accounts[0] : null;
2521
+ if (!accountId)
2522
+ return;
2523
+ disconnect == null ? void 0 : disconnect();
2524
+ context.emit("btcLogOut");
2525
+ },
2526
+ account: accounts && accounts.length ? accounts[0] : null,
2527
+ getPublicKey: () => {
2528
+ return publicKey.current;
2529
+ },
2530
+ signMessage: (msg) => {
2531
+ return signMessageFn.current(msg);
2532
+ },
2533
+ getContext: () => {
2534
+ return context;
2535
+ },
2536
+ getNetwork: getNetwork2,
2537
+ sendBitcoin: sendBitcoin2
2538
+ };
2539
+ }, [
2540
+ accounts,
2541
+ context,
2542
+ disconnect,
2543
+ getNetwork2,
2544
+ openConnectModal,
2545
+ requestDirectAccount,
2546
+ sendBitcoin2
2547
+ ]);
2548
+ return hook;
2544
2549
  }
2545
2550
 
2546
2551
  // src/core/setupBTCWallet.ts
@@ -2548,7 +2553,7 @@ var import_near_api_js = require("near-api-js");
2548
2553
  var import_transactions = require("@near-js/transactions");
2549
2554
  var import_key_pair = require("near-api-js/lib/utils/key_pair");
2550
2555
  var import_transaction = require("near-api-js/lib/transaction");
2551
- var import_utils6 = require("@near-js/utils");
2556
+ var import_utils5 = require("@near-js/utils");
2552
2557
  var import_bs58 = __toESM(require("bs58"), 1);
2553
2558
  var import_js_sha256 = require("js-sha256");
2554
2559
 
@@ -2763,7 +2768,7 @@ function request(url, options) {
2763
2768
  body,
2764
2769
  method
2765
2770
  });
2766
- const retryCount = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2771
+ const retryCount2 = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2767
2772
  const controller = new AbortController();
2768
2773
  const timeout = (options == null ? void 0 : options.timeout) || 2e4;
2769
2774
  const timeoutId = setTimeout(() => controller.abort(), timeout);
@@ -2786,16 +2791,16 @@ function request(url, options) {
2786
2791
  return data;
2787
2792
  } catch (err) {
2788
2793
  console.error(err);
2789
- if (retryCount > 0) {
2790
- console.log(`Retrying... attempts left: ${retryCount}`);
2791
- return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount - 1 }));
2794
+ if (retryCount2 > 0) {
2795
+ console.log(`Retrying... attempts left: ${retryCount2}`);
2796
+ return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount2 - 1 }));
2792
2797
  } else if ((options == null ? void 0 : options.pollingInterval) && (options == null ? void 0 : options.maxPollingAttempts)) {
2793
2798
  if (options.maxPollingAttempts > 0) {
2794
2799
  console.log(`Polling... attempts left: ${options.maxPollingAttempts}`);
2795
2800
  yield new Promise((resolve) => setTimeout(resolve, options.pollingInterval));
2796
2801
  return request(url, __spreadProps(__spreadValues({}, options), {
2797
2802
  maxPollingAttempts: options.maxPollingAttempts - 1,
2798
- retryCount
2803
+ retryCount: retryCount2
2799
2804
  }));
2800
2805
  }
2801
2806
  }
@@ -3040,7 +3045,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3040
3045
  transaction.receiverId,
3041
3046
  BigInt(nearNonceNumber) + BigInt(index),
3042
3047
  newActions,
3043
- (0, import_utils6.baseDecode)(header.hash)
3048
+ (0, import_utils5.baseDecode)(header.hash)
3044
3049
  );
3045
3050
  const txBytes = (0, import_transaction.encodeTransaction)(_transaction);
3046
3051
  const txHex = Array.from(
@@ -3063,18 +3068,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3063
3068
  near_transactions: newTransactions.map((t) => t.txHex),
3064
3069
  gas_token: currentConfig.token,
3065
3070
  gas_limit: "3000",
3066
- use_near_pay_gas: false,
3067
3071
  nonce
3068
3072
  };
3069
- const nearAccount = yield provider.query({
3070
- request_type: "view_account",
3071
- account_id: accountId,
3072
- finality: "final"
3073
- });
3074
- const availableBalance = parseFloat(nearAccount.amount) / __pow(10, 24);
3075
- if (availableBalance > 0.2) {
3076
- intention.use_near_pay_gas = true;
3077
- }
3078
3073
  const strIntention = JSON.stringify(intention);
3079
3074
  const signature = yield btcContext.signMessage(strIntention);
3080
3075
  const result = yield uploadBTCTx(currentConfig.base_url, {
@@ -3097,10 +3092,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3097
3092
  const checkAndSetupWalletButton = () => {
3098
3093
  const accountId = state.getAccount();
3099
3094
  const btcContext = window.btcContext;
3100
- console.log("checkAndSetupWalletButton:", {
3101
- nearAccountId: accountId,
3102
- btcAccountId: btcContext.account
3103
- });
3104
3095
  if (accountId && btcContext.account) {
3105
3096
  setupWalletButton(network, wallet2, btcContext);
3106
3097
  } else {
@@ -3196,11 +3187,31 @@ function pollTransactionStatuses(network, hashes) {
3196
3187
  });
3197
3188
  }
3198
3189
 
3199
- // src/core/bridgeSupplyUtils.ts
3190
+ // src/core/btcUtils.ts
3200
3191
  var import_near_api_js2 = require("near-api-js");
3201
3192
  var import_big = __toESM(require("big.js"), 1);
3202
- function nearViewMethod(contractId, methodName, args, network) {
3193
+ function getBtcProvider() {
3194
+ if (typeof window === "undefined" || !window.btcContext) {
3195
+ throw new Error("BTC Provider is not initialized.");
3196
+ }
3197
+ return window.btcContext;
3198
+ }
3199
+ function getNetwork() {
3203
3200
  return __async(this, null, function* () {
3201
+ const network = yield getBtcProvider().getNetwork();
3202
+ console.log("btc network:", network);
3203
+ return network === "livenet" ? "mainnet" : "testnet";
3204
+ });
3205
+ }
3206
+ function getBtcRpcUrl() {
3207
+ return __async(this, null, function* () {
3208
+ const network = yield getNetwork();
3209
+ return btcRpcUrls[network];
3210
+ });
3211
+ }
3212
+ function nearViewMethod(contractId, methodName, args) {
3213
+ return __async(this, null, function* () {
3214
+ const network = yield getNetwork();
3204
3215
  const nearProvider = new import_near_api_js2.providers.FailoverRpcProvider(
3205
3216
  nearRpcUrls[network].map(
3206
3217
  (url) => new import_near_api_js2.providers.JsonRpcProvider({ url })
@@ -3216,41 +3227,16 @@ function nearViewMethod(contractId, methodName, args, network) {
3216
3227
  return JSON.parse(Buffer.from(res.result).toString());
3217
3228
  });
3218
3229
  }
3219
- function getDepositAddress(btcPublicKey, contractId, network) {
3230
+ function getDepositAddress(btcPublicKey, contractId) {
3220
3231
  return __async(this, null, function* () {
3221
- const res = yield nearViewMethod(
3222
- contractId,
3223
- "get_user_dapp_deposit_address",
3224
- {
3225
- deposit_type: {
3226
- BtcPublicKey: { btc_public_key: btcPublicKey, dapp_operation: "Burrowland->Supply" }
3227
- }
3228
- },
3229
- network
3230
- );
3232
+ const res = yield nearViewMethod(contractId, "get_user_dapp_deposit_address", {
3233
+ deposit_type: {
3234
+ BtcPublicKey: { btc_public_key: btcPublicKey, dapp_operation: "Burrowland->Supply" }
3235
+ }
3236
+ });
3231
3237
  return res;
3232
3238
  });
3233
3239
  }
3234
- function getGasPrice(network) {
3235
- return __async(this, null, function* () {
3236
- const defaultFeeRate = 100;
3237
- try {
3238
- const btcRpcUrl = btcRpcUrls[network];
3239
- const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3240
- const feeRate = res.fastestFee;
3241
- return feeRate || defaultFeeRate;
3242
- } catch (error) {
3243
- return defaultFeeRate;
3244
- }
3245
- });
3246
- }
3247
- function sendBitcoin(btcProvider, address, amount, feeRate) {
3248
- return __async(this, null, function* () {
3249
- const satoshis = new import_big.default(amount).mul(__pow(10, 8)).toNumber();
3250
- const txHash = yield btcProvider.sendBitcoin(address, satoshis, { feeRate });
3251
- return txHash;
3252
- });
3253
- }
3254
3240
  function receiveDepositMsg(_0, _1) {
3255
3241
  return __async(this, arguments, function* (baseUrl, {
3256
3242
  btcPublicKey,
@@ -3275,27 +3261,66 @@ function checkTransactionStatus(baseUrl, txHash) {
3275
3261
  return res;
3276
3262
  });
3277
3263
  }
3264
+ function getBtcGasPrice() {
3265
+ return __async(this, null, function* () {
3266
+ const defaultFeeRate = 100;
3267
+ try {
3268
+ const btcRpcUrl = yield getBtcRpcUrl();
3269
+ const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3270
+ const feeRate = res.fastestFee;
3271
+ return feeRate || defaultFeeRate;
3272
+ } catch (error) {
3273
+ return defaultFeeRate;
3274
+ }
3275
+ });
3276
+ }
3277
+ var retryCount = 0;
3278
+ function getBtcBalance() {
3279
+ return __async(this, null, function* () {
3280
+ const { account } = getBtcProvider();
3281
+ if (!account) {
3282
+ retryCount++;
3283
+ if (retryCount > 3) {
3284
+ throw new Error("BTC Account is not available.");
3285
+ }
3286
+ yield delay(1e3);
3287
+ return getBtcBalance();
3288
+ }
3289
+ retryCount = 0;
3290
+ const btcRpcUrl = yield getBtcRpcUrl();
3291
+ const res = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res2) => res2.json());
3292
+ const rawBalance = res.reduce((acc, cur) => acc + cur.value, 0);
3293
+ const balance = rawBalance / __pow(10, 8);
3294
+ console.log("btc balance:", balance);
3295
+ return { rawBalance, balance };
3296
+ });
3297
+ }
3298
+ function sendBitcoin(address, amount, feeRate) {
3299
+ return __async(this, null, function* () {
3300
+ const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
3301
+ const satoshis = new import_big.default(amount).mul(__pow(10, 8)).toNumber();
3302
+ const txHash = yield sendBitcoin2(address, satoshis, { feeRate });
3303
+ return txHash;
3304
+ });
3305
+ }
3278
3306
  function executeBurrowSupply(_0) {
3279
3307
  return __async(this, arguments, function* ({
3280
3308
  amount,
3281
3309
  feeRate,
3282
- environment = "mainnet"
3310
+ isDev = false
3283
3311
  }) {
3284
3312
  try {
3285
- if (typeof window === "undefined" || !window.btcContext) {
3286
- throw new Error("BTC Provider is not initialized.");
3287
- }
3288
- const btcProvider = window.btcContext;
3289
- const network = environment === "dev" ? "testnet" : environment;
3290
- const config = walletConfig[environment];
3291
- const btcPublicKey = yield btcProvider.getPublicKey();
3313
+ const { getPublicKey } = getBtcProvider();
3314
+ const network = yield getNetwork();
3315
+ const config = walletConfig[isDev ? "dev" : network];
3316
+ const btcPublicKey = yield getPublicKey();
3292
3317
  if (!btcPublicKey) {
3293
3318
  throw new Error("BTC Public Key is not available.");
3294
3319
  }
3295
- const address = yield getDepositAddress(btcPublicKey, config.contractId, network);
3296
- const _feeRate = feeRate || (yield getGasPrice(network));
3320
+ const address = yield getDepositAddress(btcPublicKey, config.contractId);
3321
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3297
3322
  console.log("feeRate", _feeRate);
3298
- const txHash = yield sendBitcoin(btcProvider, address, amount, _feeRate);
3323
+ const txHash = yield sendBitcoin(address, amount, _feeRate);
3299
3324
  const receiveDepositMsgRes = yield receiveDepositMsg(config.base_url, { btcPublicKey, txHash });
3300
3325
  console.log("receiveDepositMsg resp:", receiveDepositMsgRes);
3301
3326
  const checkTransactionStatusRes = yield checkTransactionStatus(config.base_url, txHash);
@@ -3308,7 +3333,7 @@ function executeBurrowSupply(_0) {
3308
3333
 
3309
3334
  // src/index.ts
3310
3335
  var getVersion = () => {
3311
- return "0.3.2";
3336
+ return "0.3.4";
3312
3337
  };
3313
3338
  if (typeof window !== "undefined") {
3314
3339
  window.__PARTICLE_BTC_CONNECT_VERSION = getVersion();