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.
@@ -7,5 +7,5 @@ interface RequestOptions<T> extends RequestInit {
7
7
  maxPollingAttempts?: number;
8
8
  shouldStopPolling?: (response: T) => boolean;
9
9
  }
10
- export default function request<T>(url: string, options?: RequestOptions<T>): Promise<T>;
10
+ export default function request<T = any>(url: string, options?: RequestOptions<T>): Promise<T>;
11
11
  export {};
package/esm/index.js CHANGED
@@ -270,7 +270,7 @@ var _network, _event;
270
270
  var XverseConnector = class extends BaseConnector {
271
271
  constructor() {
272
272
  super();
273
- __privateAdd(this, _network, "Mainnet");
273
+ __privateAdd(this, _network, "Testnet");
274
274
  __privateAdd(this, _event, new EventEmitter());
275
275
  this.metadata = {
276
276
  id: "xverse",
@@ -470,7 +470,7 @@ var _network2, _event2;
470
470
  var MagicEdenConnector = class extends BaseConnector {
471
471
  constructor() {
472
472
  super();
473
- __privateAdd(this, _network2, "Mainnet");
473
+ __privateAdd(this, _network2, "Testnet");
474
474
  __privateAdd(this, _event2, new EventEmitter2());
475
475
  this.metadata = {
476
476
  id: "magicEden",
@@ -690,7 +690,16 @@ var useAccounts = () => {
690
690
  // src/hooks/useBTCProvider.ts
691
691
  import { useCallback } from "react";
692
692
  var useBTCProvider = () => {
693
- const { connector, provider, accounts, getPublicKey, signMessage, getNetwork, switchNetwork, sendBitcoin: sendBitcoin2 } = useConnectProvider();
693
+ const {
694
+ connector,
695
+ provider,
696
+ accounts,
697
+ getPublicKey,
698
+ signMessage,
699
+ getNetwork: getNetwork2,
700
+ switchNetwork,
701
+ sendBitcoin: sendBitcoin2
702
+ } = useConnectProvider();
694
703
  const sendInscription = useCallback(
695
704
  (address, inscriptionId, options) => __async(void 0, null, function* () {
696
705
  if (!connector) {
@@ -701,7 +710,17 @@ var useBTCProvider = () => {
701
710
  }),
702
711
  [connector]
703
712
  );
704
- return { provider, accounts, getPublicKey, signMessage, getNetwork, switchNetwork, sendBitcoin: sendBitcoin2, sendInscription, connector };
713
+ return {
714
+ provider,
715
+ accounts,
716
+ getPublicKey,
717
+ signMessage,
718
+ getNetwork: getNetwork2,
719
+ switchNetwork,
720
+ sendBitcoin: sendBitcoin2,
721
+ sendInscription,
722
+ connector
723
+ };
705
724
  };
706
725
 
707
726
  // src/hooks/useConnectModal.ts
@@ -2069,7 +2088,7 @@ var ConnectProvider = ({
2069
2088
  }),
2070
2089
  [connector]
2071
2090
  );
2072
- const getNetwork = useCallback7(() => __async(void 0, null, function* () {
2091
+ const getNetwork2 = useCallback7(() => __async(void 0, null, function* () {
2073
2092
  if (!connector) {
2074
2093
  throw new Error("Wallet not connected!");
2075
2094
  }
@@ -2253,7 +2272,7 @@ var ConnectProvider = ({
2253
2272
  signMessage,
2254
2273
  evmAccount,
2255
2274
  smartAccount,
2256
- getNetwork,
2275
+ getNetwork: getNetwork2,
2257
2276
  switchNetwork,
2258
2277
  sendBitcoin: sendBitcoin2,
2259
2278
  accountContract,
@@ -2407,21 +2426,18 @@ function InitBtcWalletSelectorContext() {
2407
2426
  }
2408
2427
  function useBtcWalletSelector() {
2409
2428
  const { openConnectModal, openConnectModalAsync, disconnect, requestDirectAccount } = useConnectModal();
2410
- const { accounts, sendBitcoin: sendBitcoin2, getPublicKey, provider, signMessage, connector } = useBTCProvider();
2429
+ const { accounts, sendBitcoin: sendBitcoin2, getPublicKey, provider, signMessage, connector, getNetwork: getNetwork2 } = useBTCProvider();
2411
2430
  const publicKey = useRef(null);
2412
2431
  const signMessageFn = useRef(null);
2413
2432
  const connectorRef = useRef(null);
2414
- const providerRef = useRef(null);
2415
- const [updater, setUpdater] = useState8(1);
2416
2433
  const context = useContext2(WalletSelectorContext);
2417
2434
  useEffect6(() => {
2418
2435
  if (provider) {
2419
2436
  getPublicKey().then((res) => {
2420
2437
  publicKey.current = res;
2421
2438
  });
2422
- providerRef.current = provider;
2423
2439
  }
2424
- }, [provider, updater]);
2440
+ }, [provider]);
2425
2441
  useEffect6(() => {
2426
2442
  signMessageFn.current = signMessage;
2427
2443
  }, [signMessage]);
@@ -2444,67 +2460,53 @@ function useBtcWalletSelector() {
2444
2460
  }
2445
2461
  };
2446
2462
  }, [connector]);
2447
- return {
2448
- login: () => __async(this, null, function* () {
2449
- const account = accounts && accounts.length ? accounts[0] : null;
2450
- if (account) {
2451
- return account;
2452
- }
2453
- setUpdater(updater + 1);
2454
- if (openConnectModal) {
2455
- yield openConnectModal();
2456
- }
2457
- return null;
2458
- }),
2459
- autoConnect: () => __async(this, null, function* () {
2460
- let times = 0;
2461
- while (!connectorRef.current) {
2462
- yield delay(500);
2463
- if (times++ > 10) {
2464
- return null;
2463
+ const hook = useMemo6(() => {
2464
+ return {
2465
+ login: () => __async(this, null, function* () {
2466
+ const account = accounts && accounts.length ? accounts[0] : null;
2467
+ if (account) {
2468
+ return account;
2465
2469
  }
2466
- }
2467
- requestDirectAccount(connectorRef.current).catch((e) => {
2468
- context.emit("btcLoginError");
2469
- });
2470
- }),
2471
- logout: () => {
2472
- const accountId = accounts && accounts.length ? accounts[0] : null;
2473
- if (!accountId)
2474
- return;
2475
- disconnect == null ? void 0 : disconnect();
2476
- context.emit("btcLogOut");
2477
- },
2478
- account: accounts && accounts.length ? accounts[0] : null,
2479
- getPublicKey: () => __async(this, null, function* () {
2480
- let times = 0;
2481
- while (!publicKey.current) {
2482
- yield delay(1e3);
2483
- if (times++ > 10) {
2484
- return null;
2470
+ if (openConnectModal) {
2471
+ yield openConnectModal();
2485
2472
  }
2486
- }
2487
- return publicKey.current;
2488
- }),
2489
- signMessage: (msg) => {
2490
- return signMessageFn.current(msg);
2491
- },
2492
- getContext: () => {
2493
- return context;
2494
- },
2495
- getBalance: () => __async(this, null, function* () {
2496
- let times = 0;
2497
- while (!providerRef.current) {
2498
- yield delay(500);
2499
- if (times++ > 10) {
2500
- return null;
2501
- }
2502
- }
2503
- const { total } = yield providerRef.current.getBalance();
2504
- return total;
2505
- }),
2506
- sendBitcoin: sendBitcoin2
2507
- };
2473
+ return null;
2474
+ }),
2475
+ autoConnect: () => __async(this, null, function* () {
2476
+ requestDirectAccount(connectorRef.current).catch((e) => {
2477
+ context.emit("btcLoginError");
2478
+ });
2479
+ }),
2480
+ logout: () => {
2481
+ const accountId = accounts && accounts.length ? accounts[0] : null;
2482
+ if (!accountId)
2483
+ return;
2484
+ disconnect == null ? void 0 : disconnect();
2485
+ context.emit("btcLogOut");
2486
+ },
2487
+ account: accounts && accounts.length ? accounts[0] : null,
2488
+ getPublicKey: () => {
2489
+ return publicKey.current;
2490
+ },
2491
+ signMessage: (msg) => {
2492
+ return signMessageFn.current(msg);
2493
+ },
2494
+ getContext: () => {
2495
+ return context;
2496
+ },
2497
+ getNetwork: getNetwork2,
2498
+ sendBitcoin: sendBitcoin2
2499
+ };
2500
+ }, [
2501
+ accounts,
2502
+ context,
2503
+ disconnect,
2504
+ getNetwork2,
2505
+ openConnectModal,
2506
+ requestDirectAccount,
2507
+ sendBitcoin2
2508
+ ]);
2509
+ return hook;
2508
2510
  }
2509
2511
 
2510
2512
  // src/core/setupBTCWallet.ts
@@ -2727,7 +2729,7 @@ function request(url, options) {
2727
2729
  body,
2728
2730
  method
2729
2731
  });
2730
- const retryCount = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2732
+ const retryCount2 = (_a = options == null ? void 0 : options.retryCount) != null ? _a : 1;
2731
2733
  const controller = new AbortController();
2732
2734
  const timeout = (options == null ? void 0 : options.timeout) || 2e4;
2733
2735
  const timeoutId = setTimeout(() => controller.abort(), timeout);
@@ -2750,16 +2752,16 @@ function request(url, options) {
2750
2752
  return data;
2751
2753
  } catch (err) {
2752
2754
  console.error(err);
2753
- if (retryCount > 0) {
2754
- console.log(`Retrying... attempts left: ${retryCount}`);
2755
- return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount - 1 }));
2755
+ if (retryCount2 > 0) {
2756
+ console.log(`Retrying... attempts left: ${retryCount2}`);
2757
+ return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount2 - 1 }));
2756
2758
  } else if ((options == null ? void 0 : options.pollingInterval) && (options == null ? void 0 : options.maxPollingAttempts)) {
2757
2759
  if (options.maxPollingAttempts > 0) {
2758
2760
  console.log(`Polling... attempts left: ${options.maxPollingAttempts}`);
2759
2761
  yield new Promise((resolve) => setTimeout(resolve, options.pollingInterval));
2760
2762
  return request(url, __spreadProps(__spreadValues({}, options), {
2761
2763
  maxPollingAttempts: options.maxPollingAttempts - 1,
2762
- retryCount
2764
+ retryCount: retryCount2
2763
2765
  }));
2764
2766
  }
2765
2767
  }
@@ -3027,18 +3029,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3027
3029
  near_transactions: newTransactions.map((t) => t.txHex),
3028
3030
  gas_token: currentConfig.token,
3029
3031
  gas_limit: "3000",
3030
- use_near_pay_gas: false,
3031
3032
  nonce
3032
3033
  };
3033
- const nearAccount = yield provider.query({
3034
- request_type: "view_account",
3035
- account_id: accountId,
3036
- finality: "final"
3037
- });
3038
- const availableBalance = parseFloat(nearAccount.amount) / __pow(10, 24);
3039
- if (availableBalance > 0.2) {
3040
- intention.use_near_pay_gas = true;
3041
- }
3042
3034
  const strIntention = JSON.stringify(intention);
3043
3035
  const signature = yield btcContext.signMessage(strIntention);
3044
3036
  const result = yield uploadBTCTx(currentConfig.base_url, {
@@ -3061,10 +3053,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3061
3053
  const checkAndSetupWalletButton = () => {
3062
3054
  const accountId = state.getAccount();
3063
3055
  const btcContext = window.btcContext;
3064
- console.log("checkAndSetupWalletButton:", {
3065
- nearAccountId: accountId,
3066
- btcAccountId: btcContext.account
3067
- });
3068
3056
  if (accountId && btcContext.account) {
3069
3057
  setupWalletButton(network, wallet2, btcContext);
3070
3058
  } else {
@@ -3160,11 +3148,31 @@ function pollTransactionStatuses(network, hashes) {
3160
3148
  });
3161
3149
  }
3162
3150
 
3163
- // src/core/bridgeSupplyUtils.ts
3151
+ // src/core/btcUtils.ts
3164
3152
  import { providers as providers2 } from "near-api-js";
3165
3153
  import Big from "big.js";
3166
- function nearViewMethod(contractId, methodName, args, network) {
3154
+ function getBtcProvider() {
3155
+ if (typeof window === "undefined" || !window.btcContext) {
3156
+ throw new Error("BTC Provider is not initialized.");
3157
+ }
3158
+ return window.btcContext;
3159
+ }
3160
+ function getNetwork() {
3167
3161
  return __async(this, null, function* () {
3162
+ const network = yield getBtcProvider().getNetwork();
3163
+ console.log("btc network:", network);
3164
+ return network === "livenet" ? "mainnet" : "testnet";
3165
+ });
3166
+ }
3167
+ function getBtcRpcUrl() {
3168
+ return __async(this, null, function* () {
3169
+ const network = yield getNetwork();
3170
+ return btcRpcUrls[network];
3171
+ });
3172
+ }
3173
+ function nearViewMethod(contractId, methodName, args) {
3174
+ return __async(this, null, function* () {
3175
+ const network = yield getNetwork();
3168
3176
  const nearProvider = new providers2.FailoverRpcProvider(
3169
3177
  nearRpcUrls[network].map(
3170
3178
  (url) => new providers2.JsonRpcProvider({ url })
@@ -3180,41 +3188,16 @@ function nearViewMethod(contractId, methodName, args, network) {
3180
3188
  return JSON.parse(Buffer.from(res.result).toString());
3181
3189
  });
3182
3190
  }
3183
- function getDepositAddress(btcPublicKey, contractId, network) {
3191
+ function getDepositAddress(btcPublicKey, contractId) {
3184
3192
  return __async(this, null, function* () {
3185
- const res = yield nearViewMethod(
3186
- contractId,
3187
- "get_user_dapp_deposit_address",
3188
- {
3189
- deposit_type: {
3190
- BtcPublicKey: { btc_public_key: btcPublicKey, dapp_operation: "Burrowland->Supply" }
3191
- }
3192
- },
3193
- network
3194
- );
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
+ });
3195
3198
  return res;
3196
3199
  });
3197
3200
  }
3198
- function getGasPrice(network) {
3199
- return __async(this, null, function* () {
3200
- const defaultFeeRate = 100;
3201
- try {
3202
- const btcRpcUrl = btcRpcUrls[network];
3203
- const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3204
- const feeRate = res.fastestFee;
3205
- return feeRate || defaultFeeRate;
3206
- } catch (error) {
3207
- return defaultFeeRate;
3208
- }
3209
- });
3210
- }
3211
- function sendBitcoin(btcProvider, address, amount, feeRate) {
3212
- return __async(this, null, function* () {
3213
- const satoshis = new Big(amount).mul(__pow(10, 8)).toNumber();
3214
- const txHash = yield btcProvider.sendBitcoin(address, satoshis, { feeRate });
3215
- return txHash;
3216
- });
3217
- }
3218
3201
  function receiveDepositMsg(_0, _1) {
3219
3202
  return __async(this, arguments, function* (baseUrl, {
3220
3203
  btcPublicKey,
@@ -3239,27 +3222,66 @@ function checkTransactionStatus(baseUrl, txHash) {
3239
3222
  return res;
3240
3223
  });
3241
3224
  }
3225
+ function getBtcGasPrice() {
3226
+ return __async(this, null, function* () {
3227
+ const defaultFeeRate = 100;
3228
+ try {
3229
+ const btcRpcUrl = yield getBtcRpcUrl();
3230
+ const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3231
+ const feeRate = res.fastestFee;
3232
+ return feeRate || defaultFeeRate;
3233
+ } catch (error) {
3234
+ return defaultFeeRate;
3235
+ }
3236
+ });
3237
+ }
3238
+ var retryCount = 0;
3239
+ function getBtcBalance() {
3240
+ return __async(this, null, function* () {
3241
+ const { account } = getBtcProvider();
3242
+ 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();
3249
+ }
3250
+ retryCount = 0;
3251
+ const btcRpcUrl = yield getBtcRpcUrl();
3252
+ const res = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res2) => res2.json());
3253
+ const rawBalance = res.reduce((acc, cur) => acc + cur.value, 0);
3254
+ const balance = rawBalance / __pow(10, 8);
3255
+ console.log("btc balance:", balance);
3256
+ return { rawBalance, balance };
3257
+ });
3258
+ }
3259
+ function sendBitcoin(address, amount, feeRate) {
3260
+ return __async(this, null, function* () {
3261
+ const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
3262
+ const satoshis = new Big(amount).mul(__pow(10, 8)).toNumber();
3263
+ const txHash = yield sendBitcoin2(address, satoshis, { feeRate });
3264
+ return txHash;
3265
+ });
3266
+ }
3242
3267
  function executeBurrowSupply(_0) {
3243
3268
  return __async(this, arguments, function* ({
3244
3269
  amount,
3245
3270
  feeRate,
3246
- environment = "mainnet"
3271
+ isDev = false
3247
3272
  }) {
3248
3273
  try {
3249
- if (typeof window === "undefined" || !window.btcContext) {
3250
- throw new Error("BTC Provider is not initialized.");
3251
- }
3252
- const btcProvider = window.btcContext;
3253
- const network = environment === "dev" ? "testnet" : environment;
3254
- const config = walletConfig[environment];
3255
- const btcPublicKey = yield btcProvider.getPublicKey();
3274
+ const { getPublicKey } = getBtcProvider();
3275
+ const network = yield getNetwork();
3276
+ const config = walletConfig[isDev ? "dev" : network];
3277
+ const btcPublicKey = yield getPublicKey();
3256
3278
  if (!btcPublicKey) {
3257
3279
  throw new Error("BTC Public Key is not available.");
3258
3280
  }
3259
- const address = yield getDepositAddress(btcPublicKey, config.contractId, network);
3260
- const _feeRate = feeRate || (yield getGasPrice(network));
3281
+ const address = yield getDepositAddress(btcPublicKey, config.contractId);
3282
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3261
3283
  console.log("feeRate", _feeRate);
3262
- const txHash = yield sendBitcoin(btcProvider, address, amount, _feeRate);
3284
+ const txHash = yield sendBitcoin(address, amount, _feeRate);
3263
3285
  const receiveDepositMsgRes = yield receiveDepositMsg(config.base_url, { btcPublicKey, txHash });
3264
3286
  console.log("receiveDepositMsg resp:", receiveDepositMsgRes);
3265
3287
  const checkTransactionStatusRes = yield checkTransactionStatus(config.base_url, txHash);
@@ -3272,7 +3294,7 @@ function executeBurrowSupply(_0) {
3272
3294
 
3273
3295
  // src/index.ts
3274
3296
  var getVersion = () => {
3275
- return "0.3.2";
3297
+ return "0.3.4";
3276
3298
  };
3277
3299
  if (typeof window !== "undefined") {
3278
3300
  window.__PARTICLE_BTC_CONNECT_VERSION = getVersion();
@@ -3291,7 +3313,10 @@ export {
3291
3313
  WizzConnector,
3292
3314
  XverseConnector,
3293
3315
  executeBurrowSupply,
3316
+ getBtcBalance,
3317
+ getBtcGasPrice,
3294
3318
  getVersion,
3319
+ sendBitcoin,
3295
3320
  setupBTCWallet,
3296
3321
  useAccountContract,
3297
3322
  useAccounts,