btc-wallet 0.3.17 → 0.3.19

Sign up to get free protection for your applications and to get access to all the features.
@@ -11,8 +11,8 @@ export declare abstract class BaseConnector {
11
11
  abstract getAccounts(): Promise<string[]>;
12
12
  abstract getPublicKey(): Promise<string>;
13
13
  abstract signMessage(signStr: string, type?: 'ecdsa' | 'bip322-simple'): Promise<string>;
14
- abstract on(event: string, handler: (data?: unknown) => void): void;
15
- abstract removeListener(event: string, handler: (data?: unknown) => void): void;
14
+ abstract on(event: string, handler: (data?: any) => void): void;
15
+ abstract removeListener(event: string, handler: (data?: any) => void): void;
16
16
  [key: string]: any;
17
17
  abstract getProvider(): any;
18
18
  abstract getNetwork(): Promise<'livenet' | 'testnet'>;
@@ -9,7 +9,7 @@ export declare function getAccountInfo(csna: string, accountContractId: string):
9
9
  gas_token: Record<string, string>;
10
10
  debt_info?: DebtInfo;
11
11
  } | undefined>;
12
- export declare function checkGasTokenBalance(csna: string, gasToken: string, isDev: boolean): Promise<void>;
12
+ export declare function checkGasTokenBalance(csna: string, gasToken: string, minAmount: string, isDev: boolean): Promise<void>;
13
13
  type CheckGasTokenArrearsReturnType<T extends boolean> = T extends true ? void : {
14
14
  receiver_id: string;
15
15
  amount: string;
@@ -4,7 +4,7 @@ export declare function BtcWalletSelectorContextProvider({ children, }: {
4
4
  autoConnect?: boolean;
5
5
  }): import("react/jsx-runtime").JSX.Element;
6
6
  export declare function useBtcWalletSelector(): {
7
- login: () => Promise<string>;
7
+ login: () => Promise<string | null>;
8
8
  autoConnect: () => Promise<void>;
9
9
  logout: () => void;
10
10
  account: string;
@@ -12,6 +12,7 @@ export declare function useBtcWalletSelector(): {
12
12
  signMessage: (msg: string) => any;
13
13
  getContext: () => any;
14
14
  getNetwork: () => Promise<"livenet" | "testnet">;
15
+ switchNetwork: (network: "livenet" | "testnet") => Promise<void>;
15
16
  sendBitcoin: (toAddress: string, satoshis: number, options?: {
16
17
  feeRate: number;
17
18
  }) => Promise<string>;
package/dist/index.js CHANGED
@@ -143,6 +143,7 @@ var InjectedConnector = class extends BaseConnector {
143
143
  requestAccounts() {
144
144
  return __async(this, null, function* () {
145
145
  const accounts = yield this.getProviderOrThrow().requestAccounts();
146
+ console.log("network:", yield this.getNetwork());
146
147
  console.log("\u{1F680} ~ InjectedConnector ~ requestAccounts ~ accounts:", accounts);
147
148
  return accounts;
148
149
  });
@@ -328,7 +329,7 @@ var _network, _event;
328
329
  var XverseConnector = class extends BaseConnector {
329
330
  constructor() {
330
331
  super();
331
- __privateAdd(this, _network, "Testnet");
332
+ __privateAdd(this, _network, "Mainnet");
332
333
  __privateAdd(this, _event, new import_events.default());
333
334
  this.metadata = {
334
335
  id: "xverse",
@@ -504,6 +505,7 @@ var XverseConnector = class extends BaseConnector {
504
505
  });
505
506
  }
506
507
  };
508
+ console.log("\u{1F680} ~ XverseConnector ~ sendBitcoin ~ sendBtcOptions:", sendBtcOptions);
507
509
  sendBtcTransaction(sendBtcOptions).catch((e) => reject(e));
508
510
  });
509
511
  return result;
@@ -2490,12 +2492,22 @@ function InitBtcWalletSelectorContext() {
2490
2492
  return null;
2491
2493
  }
2492
2494
  function useBtcWalletSelector() {
2493
- const { openConnectModal, openConnectModalAsync, disconnect, requestDirectAccount } = useConnectModal();
2494
- const { accounts, sendBitcoin: sendBitcoin2, getPublicKey, provider, signMessage, connector, getNetwork: getNetwork2 } = useBTCProvider();
2495
+ const { openConnectModal, disconnect, requestDirectAccount } = useConnectModal();
2496
+ const {
2497
+ accounts,
2498
+ sendBitcoin: sendBitcoin2,
2499
+ getPublicKey,
2500
+ provider,
2501
+ signMessage,
2502
+ connector,
2503
+ getNetwork: getNetwork2,
2504
+ switchNetwork
2505
+ } = useBTCProvider();
2495
2506
  const publicKey = (0, import_react11.useRef)(null);
2496
2507
  const signMessageFn = (0, import_react11.useRef)(null);
2497
2508
  const connectorRef = (0, import_react11.useRef)(null);
2498
2509
  const context = (0, import_react11.useContext)(WalletSelectorContext);
2510
+ const isLoggingIn = (0, import_react11.useRef)(false);
2499
2511
  (0, import_react11.useEffect)(() => {
2500
2512
  if (provider) {
2501
2513
  getPublicKey().then((res) => {
@@ -2530,7 +2542,27 @@ function useBtcWalletSelector() {
2530
2542
  login: () => __async(this, null, function* () {
2531
2543
  const account = accounts == null ? void 0 : accounts[0];
2532
2544
  if (!account) {
2533
- openConnectModal == null ? void 0 : openConnectModal();
2545
+ if (isLoggingIn.current) {
2546
+ return null;
2547
+ }
2548
+ try {
2549
+ isLoggingIn.current = true;
2550
+ openConnectModal == null ? void 0 : openConnectModal();
2551
+ const account1 = yield retryOperation(
2552
+ () => window.btcContext.account,
2553
+ (res) => !!res,
2554
+ {
2555
+ maxRetries: 100,
2556
+ delayMs: 1e3
2557
+ }
2558
+ );
2559
+ if (!account1) {
2560
+ throw new Error("Failed to get account");
2561
+ }
2562
+ return account1;
2563
+ } finally {
2564
+ isLoggingIn.current = false;
2565
+ }
2534
2566
  }
2535
2567
  return account;
2536
2568
  }),
@@ -2557,16 +2589,18 @@ function useBtcWalletSelector() {
2557
2589
  return context;
2558
2590
  },
2559
2591
  getNetwork: getNetwork2,
2592
+ switchNetwork,
2560
2593
  sendBitcoin: sendBitcoin2
2561
2594
  };
2562
2595
  }, [
2563
2596
  accounts,
2564
- context,
2565
- disconnect,
2566
2597
  getNetwork2,
2598
+ switchNetwork,
2599
+ sendBitcoin2,
2567
2600
  openConnectModal,
2568
2601
  requestDirectAccount,
2569
- sendBitcoin2
2602
+ context,
2603
+ disconnect
2570
2604
  ]);
2571
2605
  return hook;
2572
2606
  }
@@ -2576,7 +2610,7 @@ var import_near_api_js2 = require("near-api-js");
2576
2610
  var import_transactions = require("@near-js/transactions");
2577
2611
  var import_key_pair = require("near-api-js/lib/utils/key_pair");
2578
2612
  var import_transaction = require("near-api-js/lib/transaction");
2579
- var import_utils6 = require("@near-js/utils");
2613
+ var import_utils7 = require("@near-js/utils");
2580
2614
  var import_bs58 = __toESM(require("bs58"), 1);
2581
2615
  var import_js_sha256 = require("js-sha256");
2582
2616
 
@@ -3228,11 +3262,11 @@ function getAccountInfo(csna, accountContractId) {
3228
3262
  return accountInfo;
3229
3263
  });
3230
3264
  }
3231
- function checkGasTokenBalance(csna, gasToken, isDev) {
3265
+ function checkGasTokenBalance(csna, gasToken, minAmount, isDev) {
3232
3266
  return __async(this, null, function* () {
3233
3267
  const amount = yield nearCall(gasToken, "ft_balance_of", { account_id: csna });
3234
3268
  console.log("gas token balance:", amount);
3235
- if (new import_big.default(amount).lte(MINIMUM_DEPOSIT_AMOUNT_BASE)) {
3269
+ if (new import_big.default(amount).lt(minAmount)) {
3236
3270
  yield Dialog.confirm({
3237
3271
  title: "Gas token balance is insufficient",
3238
3272
  message: "Please deposit gas token to continue, will open bridge website."
@@ -3488,7 +3522,6 @@ var state = {
3488
3522
  return window.localStorage.getItem("btc-wallet-btc-publickey");
3489
3523
  }
3490
3524
  };
3491
- var inter = null;
3492
3525
  var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3493
3526
  metadata,
3494
3527
  options,
@@ -3505,47 +3538,74 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3505
3538
  getAccounts,
3506
3539
  verifyOwner,
3507
3540
  signMessage,
3541
+ isSignedIn,
3508
3542
  signAndSendTransaction,
3509
3543
  signAndSendTransactions
3510
3544
  };
3511
3545
  const isDev = (_a = "isDev" in metadata && metadata.isDev) != null ? _a : false;
3512
3546
  const currentConfig = isDev ? walletConfig.dev : walletConfig[options.network.networkId];
3513
3547
  const walletNetwork = isDev ? "dev" : options.network.networkId;
3514
- initWalletButton(walletNetwork, wallet);
3515
- if (!inter) {
3516
- inter = setInterval(() => __async(void 0, null, function* () {
3517
- const btcContext = window.btcContext;
3518
- if (btcContext) {
3519
- clearInterval(inter);
3520
- const context = btcContext.getContext();
3521
- context.on("updatePublicKey", (btcPublicKey) => __async(void 0, null, function* () {
3522
- const { nearTempAddress } = yield getNearAccountByBtcPublicKey(btcPublicKey);
3548
+ yield initBtcContext();
3549
+ function setupBtcContextListeners() {
3550
+ return __async(this, null, function* () {
3551
+ const handleConnectionUpdate = () => __async(this, null, function* () {
3552
+ yield checkBtcNetwork(walletNetwork);
3553
+ const accountId = state.getAccount();
3554
+ const btcContext = window.btcContext;
3555
+ if (accountId && btcContext.account) {
3556
+ setupWalletButton(walletNetwork, wallet, btcContext);
3557
+ } else {
3523
3558
  removeWalletButton();
3524
- initWalletButton(walletNetwork, wallet);
3525
- emitter.emit("accountsChanged", {
3526
- accounts: [
3527
- {
3528
- accountId: nearTempAddress
3529
- }
3530
- ]
3531
- });
3532
- }));
3533
- context.on("btcLoginError", (e) => __async(void 0, null, function* () {
3534
- emitter.emit("accountsChanged", {
3535
- accounts: []
3536
- });
3537
- }));
3538
- context.on("btcLogOut", (e) => __async(void 0, null, function* () {
3539
- emitter.emit("accountsChanged", {
3540
- accounts: []
3541
- });
3542
- }));
3543
- if ("autoConnect" in metadata && metadata.autoConnect && localStorage.getItem("near-wallet-selector:selectedWalletId") === '"btc-wallet"') {
3544
- yield btcContext.autoConnect();
3559
+ setTimeout(() => {
3560
+ handleConnectionUpdate();
3561
+ }, 5e3);
3545
3562
  }
3546
- clearInterval(inter);
3563
+ });
3564
+ const context = window.btcContext.getContext();
3565
+ context.on("updatePublicKey", (btcPublicKey) => __async(this, null, function* () {
3566
+ console.log("updatePublicKey");
3567
+ const { nearAddress } = yield getNearAccountByBtcPublicKey(btcPublicKey);
3568
+ emitter.emit("accountsChanged", {
3569
+ accounts: [{ accountId: nearAddress }]
3570
+ });
3571
+ yield handleConnectionUpdate();
3572
+ }));
3573
+ context.on("btcLoginError", () => __async(this, null, function* () {
3574
+ console.log("btcLoginError");
3575
+ emitter.emit("accountsChanged", { accounts: [] });
3576
+ yield handleConnectionUpdate();
3577
+ }));
3578
+ context.on("btcLogOut", () => __async(this, null, function* () {
3579
+ console.log("btcLogOut");
3580
+ emitter.emit("accountsChanged", { accounts: [] });
3581
+ yield handleConnectionUpdate();
3582
+ }));
3583
+ yield handleConnectionUpdate();
3584
+ if ("autoConnect" in metadata && metadata.autoConnect && localStorage.getItem("near-wallet-selector:selectedWalletId") === '"btc-wallet"') {
3585
+ yield window.btcContext.autoConnect();
3547
3586
  }
3548
- }), 500);
3587
+ });
3588
+ }
3589
+ function initBtcContext() {
3590
+ return __async(this, null, function* () {
3591
+ console.log("initBtcContext");
3592
+ const btcContext = yield retryOperation(
3593
+ () => __async(this, null, function* () {
3594
+ const ctx = window.btcContext;
3595
+ if (!ctx) {
3596
+ throw new Error("btcContext not found");
3597
+ }
3598
+ return ctx;
3599
+ }),
3600
+ (res) => !!res,
3601
+ {
3602
+ maxRetries: 10,
3603
+ delayMs: 500
3604
+ }
3605
+ );
3606
+ yield setupBtcContextListeners();
3607
+ return btcContext;
3608
+ });
3549
3609
  }
3550
3610
  function nearCall2(contractId, methodName, args) {
3551
3611
  return __async(this, null, function* () {
@@ -3554,53 +3614,44 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3554
3614
  }
3555
3615
  function getNearAccountByBtcPublicKey(btcPublicKey) {
3556
3616
  return __async(this, null, function* () {
3557
- const nearTempAddress = yield nearCall2(
3617
+ const nearAddress = yield nearCall2(
3558
3618
  currentConfig.accountContractId,
3559
3619
  "get_chain_signature_near_account_id",
3560
3620
  { btc_public_key: btcPublicKey }
3561
3621
  );
3562
- const nearTempPublicKey = yield nearCall2(
3622
+ const nearPublicKey = yield nearCall2(
3563
3623
  currentConfig.accountContractId,
3564
3624
  "get_chain_signature_near_account_public_key",
3565
3625
  { btc_public_key: btcPublicKey }
3566
3626
  );
3567
- state.saveAccount(nearTempAddress);
3568
- state.savePublicKey(nearTempPublicKey);
3627
+ state.saveAccount(nearAddress);
3628
+ state.savePublicKey(nearPublicKey);
3569
3629
  state.saveBtcPublicKey(btcPublicKey);
3570
3630
  return {
3571
- nearTempAddress,
3572
- nearTempPublicKey
3631
+ nearAddress,
3632
+ nearPublicKey
3573
3633
  };
3574
3634
  });
3575
3635
  }
3576
3636
  function signIn(_02) {
3577
3637
  return __async(this, arguments, function* ({ contractId, methodNames }) {
3638
+ const btcContext = window.btcContext;
3578
3639
  const accountId = state.getAccount();
3579
3640
  const publicKey = state.getPublicKey();
3580
- const btcContext = window.btcContext;
3581
- initWalletButton(walletNetwork, wallet);
3582
- if (accountId && publicKey) {
3583
- return [
3584
- {
3585
- accountId,
3586
- publicKey
3587
- }
3588
- ];
3641
+ console.log("isLogin:", accountId && publicKey);
3642
+ if (!accountId || !publicKey) {
3643
+ yield btcContext.login();
3589
3644
  }
3590
- yield btcContext.login();
3591
- const btcPublicKey = yield retryOperation(btcContext.getPublicKey, (res) => !!res, {
3592
- maxRetries: 40,
3593
- delayMs: 3e3
3594
- });
3645
+ const btcPublicKey = yield btcContext.getPublicKey();
3595
3646
  console.log("btcPublicKey:", btcPublicKey);
3596
3647
  if (!btcPublicKey) {
3597
3648
  throw new Error("No connected BTC wallet, please connect your BTC wallet first.");
3598
3649
  }
3599
- const { nearTempAddress, nearTempPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
3650
+ const { nearAddress, nearPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
3600
3651
  return [
3601
3652
  {
3602
- accountId: nearTempAddress,
3603
- publicKey: nearTempPublicKey
3653
+ accountId: nearAddress,
3654
+ publicKey: nearPublicKey
3604
3655
  }
3605
3656
  ];
3606
3657
  });
@@ -3621,6 +3672,11 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3621
3672
  removeWalletButton();
3622
3673
  });
3623
3674
  }
3675
+ function isSignedIn() {
3676
+ const accountId = state.getAccount();
3677
+ const publicKey = state.getPublicKey();
3678
+ return accountId && publicKey;
3679
+ }
3624
3680
  function getAccounts() {
3625
3681
  return __async(this, null, function* () {
3626
3682
  return [{ accountId: state.getAccount() }];
@@ -3652,7 +3708,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3652
3708
  const btcContext = window.btcContext;
3653
3709
  const accountId = state.getAccount();
3654
3710
  const accountInfo = yield getAccountInfo(accountId, currentConfig.accountContractId);
3655
- yield checkGasTokenBalance(accountId, currentConfig.token, isDev);
3656
3711
  yield checkGasTokenArrears(accountInfo == null ? void 0 : accountInfo.debt_info, isDev, true);
3657
3712
  const trans = [...params.transactions];
3658
3713
  console.log("raw trans:", trans);
@@ -3664,6 +3719,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3664
3719
  console.log("transferGasTransaction:", transferGasTransaction);
3665
3720
  console.log("useNearPayGas:", useNearPayGas);
3666
3721
  console.log("gasLimit:", gasLimit);
3722
+ yield checkGasTokenBalance(accountId, currentConfig.token, gasLimit, isDev);
3667
3723
  if (transferGasTransaction) {
3668
3724
  trans.unshift(transferGasTransaction);
3669
3725
  }
@@ -3844,7 +3900,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3844
3900
  transaction.receiverId,
3845
3901
  BigInt(nearNonceNumber) + BigInt(index),
3846
3902
  newActions,
3847
- (0, import_utils6.baseDecode)(header.hash)
3903
+ (0, import_utils7.baseDecode)(header.hash)
3848
3904
  );
3849
3905
  const txBytes = (0, import_transaction.encodeTransaction)(_transaction);
3850
3906
  const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
@@ -3854,22 +3910,18 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3854
3910
  return { txBytes, txHex, hash };
3855
3911
  });
3856
3912
  }
3857
- function initWalletButton(network, wallet2) {
3913
+ function checkBtcNetwork(network) {
3858
3914
  return __async(this, null, function* () {
3859
- const checkAndSetupWalletButton = () => {
3860
- const accountId = state.getAccount();
3861
- const btcContext = window.btcContext;
3862
- if (accountId && btcContext.account) {
3863
- setupWalletButton(network, wallet2, btcContext);
3864
- } else {
3865
- removeWalletButton();
3866
- setTimeout(() => {
3867
- checkAndSetupWalletButton();
3868
- }, 5e3);
3869
- }
3870
- };
3871
- yield delay(1e3);
3872
- checkAndSetupWalletButton();
3915
+ const btcContext = window.btcContext;
3916
+ if (!btcContext.account)
3917
+ return;
3918
+ const btcNetwork = yield btcContext.getNetwork();
3919
+ console.log("btcNetwork:", btcNetwork, network);
3920
+ if (network === "mainnet" && btcNetwork !== "livenet") {
3921
+ yield btcContext.switchNetwork("livenet");
3922
+ } else if (network === "testnet" && btcNetwork !== "testnet") {
3923
+ yield btcContext.switchNetwork("testnet");
3924
+ }
3873
3925
  });
3874
3926
  }
3875
3927
  return wallet;
@@ -3913,7 +3965,7 @@ function setupBTCWallet({
3913
3965
 
3914
3966
  // src/index.ts
3915
3967
  var getVersion = () => {
3916
- return "0.3.17";
3968
+ return "0.3.19";
3917
3969
  };
3918
3970
  if (typeof window !== "undefined") {
3919
3971
  window.__BTC_WALLET_VERSION = getVersion();