btc-wallet 0.5.21-beta → 0.5.23-beta

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.
@@ -71,8 +71,8 @@ export declare function convertTransactionToTxHex({ transaction, accountId, publ
71
71
  env: ENV;
72
72
  index?: number;
73
73
  }): Promise<{
74
- txBytes: Uint8Array;
75
74
  txHex: string;
75
+ txBytes: Uint8Array;
76
76
  hash: string;
77
77
  }>;
78
78
  interface CalculateGasLimitParams {
package/esm/index.js CHANGED
@@ -3364,6 +3364,8 @@ function convertTransactionToTxHex(_0) {
3364
3364
  env,
3365
3365
  index = 0
3366
3366
  }) {
3367
+ if (!publicKey)
3368
+ return { txHex: "", txBytes: new Uint8Array(), hash: "" };
3367
3369
  const publicKeyFormat = PublicKey.from(publicKey);
3368
3370
  const currentConfig = getWalletConfig(env);
3369
3371
  const provider = getNearProvider({ network: currentConfig.network });
@@ -3583,7 +3585,8 @@ function getPredictedGasAmount(_0) {
3583
3585
  env
3584
3586
  }) {
3585
3587
  const currentConfig = getWalletConfig(env);
3586
- const predictedGas = yield nearCallFunction(
3588
+ const isValidTransactions = transactions2.every((tx) => tx.length > 0);
3589
+ const predictedGas = isValidTransactions ? yield nearCallFunction(
3587
3590
  accountContractId,
3588
3591
  "predict_txs_gas_token_amount",
3589
3592
  {
@@ -3591,7 +3594,7 @@ function getPredictedGasAmount(_0) {
3591
3594
  near_transactions: transactions2
3592
3595
  },
3593
3596
  { network: currentConfig.network }
3594
- );
3597
+ ) : "0";
3595
3598
  const predictedGasAmount = new Big(predictedGas).mul(1.2).toFixed(0);
3596
3599
  const miniGasAmount = 200 * transactions2.length;
3597
3600
  const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
@@ -3607,9 +3610,9 @@ function calculateWithdraw(_0) {
3607
3610
  btcAddress,
3608
3611
  env
3609
3612
  }) {
3610
- console.log("calculateWithdraw feeRate:", feeRate);
3611
3613
  try {
3612
3614
  const config = getWalletConfig(env);
3615
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3613
3616
  const gasLimit = yield calculateGasLimit({
3614
3617
  csna,
3615
3618
  transactions: [
@@ -3674,7 +3677,7 @@ function calculateWithdraw(_0) {
3674
3677
  const { inputs, outputs, fee } = coinselect(
3675
3678
  utxos,
3676
3679
  [{ address: btcAddress, value: userSatoshis }],
3677
- Math.ceil(feeRate || 0)
3680
+ Math.ceil(_feeRate)
3678
3681
  );
3679
3682
  const newInputs = inputs;
3680
3683
  let newOutputs = outputs;
@@ -3788,6 +3791,7 @@ function calculateWithdraw(_0) {
3788
3791
 
3789
3792
  // src/core/btcUtils.ts
3790
3793
  import bitcoin from "bitcoinjs-lib";
3794
+ import coinselect2 from "coinselect";
3791
3795
  import * as ecc from "@bitcoinerlab/secp256k1";
3792
3796
  bitcoin.initEccLib(ecc);
3793
3797
  var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
@@ -3802,9 +3806,13 @@ function getBtcProvider() {
3802
3806
  }
3803
3807
  function getNetwork() {
3804
3808
  return __async(this, null, function* () {
3805
- const network = yield getBtcProvider().getNetwork();
3806
- console.log("btc network:", network);
3807
- return network === "livenet" ? "mainnet" : "testnet";
3809
+ try {
3810
+ const network = yield getBtcProvider().getNetwork();
3811
+ console.log("btc network:", network);
3812
+ return network === "livenet" ? "mainnet" : "testnet";
3813
+ } catch (error) {
3814
+ return "mainnet";
3815
+ }
3808
3816
  });
3809
3817
  }
3810
3818
  function getBtcRpcUrl() {
@@ -3867,25 +3875,37 @@ function getBtcGasPrice() {
3867
3875
  }
3868
3876
  });
3869
3877
  }
3870
- function getBtcBalance() {
3878
+ function getBtcUtxos(account) {
3871
3879
  return __async(this, null, function* () {
3872
- const { account } = yield retryOperation(getBtcProvider, (res) => !!res.account);
3873
- if (!account) {
3874
- console.error("BTC Account is not available.");
3875
- return { rawBalance: 0, balance: 0, availableBalance: 0 };
3876
- }
3877
3880
  const btcRpcUrl = yield getBtcRpcUrl();
3878
3881
  const utxos = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res) => res.json());
3882
+ return utxos;
3883
+ });
3884
+ }
3885
+ function calculateGasFee(account, amount, feeRate) {
3886
+ return __async(this, null, function* () {
3887
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3888
+ const utxos = yield getBtcUtxos(account);
3889
+ const { fee } = coinselect2(utxos, [{ address: account, value: amount }], Math.ceil(_feeRate));
3890
+ console.log("calculateGasFee fee:", fee);
3891
+ return fee;
3892
+ });
3893
+ }
3894
+ function getBtcBalance(account) {
3895
+ return __async(this, null, function* () {
3896
+ if (!account) {
3897
+ const res = yield retryOperation(getBtcProvider, (res2) => !!res2.account);
3898
+ if (!res.account) {
3899
+ console.error("BTC Account is not available.");
3900
+ return { rawBalance: 0, balance: 0, availableBalance: 0 };
3901
+ }
3902
+ account = res.account;
3903
+ }
3904
+ const utxos = yield getBtcUtxos(account);
3879
3905
  const btcDecimals = 8;
3880
3906
  const rawBalance = (utxos == null ? void 0 : utxos.reduce((acc, cur) => acc + cur.value, 0)) || 0;
3881
3907
  const balance = rawBalance / __pow(10, btcDecimals);
3882
- const feeRate = yield getBtcGasPrice();
3883
- const inputSize = ((utxos == null ? void 0 : utxos.length) || 0) * 69;
3884
- const outputSize = 33 * 2;
3885
- const overheadSize = 11;
3886
- const estimatedTxSize = inputSize + outputSize + overheadSize;
3887
- const estimatedFee = Math.ceil(estimatedTxSize * feeRate);
3888
- console.log("estimatedFee:", estimatedFee);
3908
+ const estimatedFee = yield calculateGasFee(account, rawBalance);
3889
3909
  const availableRawBalance = (rawBalance - estimatedFee).toFixed(0);
3890
3910
  const availableBalance = new Big2(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, Big2.roundDown).toNumber();
3891
3911
  return {
@@ -3912,7 +3932,7 @@ function getDepositAmount(amount, option) {
3912
3932
  var _a;
3913
3933
  const env = (option == null ? void 0 : option.env) || "mainnet";
3914
3934
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3915
- const csna = yield getCsnaAccountId(env);
3935
+ const csna = (option == null ? void 0 : option.csna) || (yield getCsnaAccountId(env));
3916
3936
  const accountInfo = yield getAccountInfo({ csna, env });
3917
3937
  const debtAction = yield checkGasTokenDebt(csna, env, false);
3918
3938
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
@@ -4109,18 +4129,18 @@ function getWithdrawTransaction(_0) {
4109
4129
  return __async(this, arguments, function* ({
4110
4130
  amount,
4111
4131
  feeRate,
4132
+ csna,
4133
+ btcAddress,
4112
4134
  env = "mainnet"
4113
4135
  }) {
4114
4136
  const config = getWalletConfig(env);
4115
- const provider = getBtcProvider();
4116
- const btcAddress = provider.account;
4117
- const csna = yield getCsnaAccountId(env);
4118
- const _feeRate = feeRate || (yield getBtcGasPrice());
4137
+ const _btcAddress = btcAddress || getBtcProvider().account;
4138
+ const _csna = csna || (yield getCsnaAccountId(env));
4119
4139
  const _a = yield calculateWithdraw({
4120
4140
  amount,
4121
- feeRate: _feeRate,
4122
- csna,
4123
- btcAddress,
4141
+ feeRate,
4142
+ csna: _csna,
4143
+ btcAddress: _btcAddress,
4124
4144
  env
4125
4145
  }), { inputs, outputs, isError, errorMsg } = _a, rest = __objRest(_a, ["inputs", "outputs", "isError", "errorMsg"]);
4126
4146
  if (isError || !inputs || !outputs) {
@@ -4136,7 +4156,7 @@ function getWithdrawTransaction(_0) {
4136
4156
  const btcNetwork = network === "mainnet" ? bitcoin.networks.bitcoin : bitcoin.networks.testnet;
4137
4157
  const psbt = new bitcoin.Psbt({ network: btcNetwork });
4138
4158
  const btcRpcUrl = yield getBtcRpcUrl();
4139
- Promise.all(
4159
+ yield Promise.all(
4140
4160
  inputs.map((input) => __async(this, null, function* () {
4141
4161
  const txData = yield fetch(`${btcRpcUrl}/tx/${input.txid}`).then((res) => res.json());
4142
4162
  const inputOptions = {
@@ -4168,14 +4188,14 @@ function getWithdrawTransaction(_0) {
4168
4188
  });
4169
4189
  const msg = {
4170
4190
  Withdraw: {
4171
- target_btc_address: btcAddress,
4191
+ target_btc_address: _btcAddress,
4172
4192
  input: _inputs,
4173
4193
  output: txOutputs
4174
4194
  }
4175
4195
  };
4176
4196
  const transaction = {
4177
4197
  receiverId: config.btcToken,
4178
- signerId: csna,
4198
+ signerId: _csna,
4179
4199
  actions: [
4180
4200
  {
4181
4201
  type: "FunctionCall",
@@ -4443,6 +4463,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4443
4463
  id,
4444
4464
  provider
4445
4465
  }) {
4466
+ let initializing = false;
4467
+ let connectionUpdateTimeout;
4446
4468
  const wallet = {
4447
4469
  signIn,
4448
4470
  signOut,
@@ -4451,8 +4473,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4451
4473
  signMessage,
4452
4474
  isSignedIn,
4453
4475
  signAndSendTransaction,
4454
- signAndSendTransactions,
4455
- calculateGasLimit
4476
+ signAndSendTransactions
4456
4477
  };
4457
4478
  const env = metadata.env || options.network.networkId || "mainnet";
4458
4479
  const currentConfig = getWalletConfig(env);
@@ -4467,15 +4488,52 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4467
4488
  }
4468
4489
  return true;
4469
4490
  }
4491
+ function initBtcContext() {
4492
+ return __async(this, null, function* () {
4493
+ if (initializing) {
4494
+ console.log("BTC context initialization already in progress");
4495
+ return;
4496
+ }
4497
+ console.log("initBtcContext");
4498
+ try {
4499
+ initializing = true;
4500
+ const btcContext = yield retryOperation(
4501
+ () => __async(this, null, function* () {
4502
+ const ctx = window.btcContext;
4503
+ if (!ctx) {
4504
+ throw new Error("btcContext not found");
4505
+ }
4506
+ return ctx;
4507
+ }),
4508
+ (res) => !!res,
4509
+ {
4510
+ maxRetries: 10,
4511
+ delayMs: 500
4512
+ }
4513
+ );
4514
+ yield setupBtcContextListeners();
4515
+ return btcContext;
4516
+ } finally {
4517
+ initializing = false;
4518
+ }
4519
+ });
4520
+ }
4470
4521
  function setupBtcContextListeners() {
4471
4522
  return __async(this, null, function* () {
4472
4523
  const handleConnectionUpdate = () => __async(this, null, function* () {
4524
+ if (connectionUpdateTimeout) {
4525
+ clearTimeout(connectionUpdateTimeout);
4526
+ }
4473
4527
  yield checkBtcNetwork(currentConfig.network);
4474
4528
  if (!state_default.isValid()) {
4475
4529
  state_default.clear();
4476
4530
  console.log("setupBtcContextListeners clear");
4477
4531
  }
4478
- validateWalletState();
4532
+ const valid = validateWalletState();
4533
+ console.log("setupBtcContextListeners wallet state valid:", valid);
4534
+ if (!valid) {
4535
+ return;
4536
+ }
4479
4537
  const btcContext = window.btcContext;
4480
4538
  if (btcContext.account) {
4481
4539
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4486,7 +4544,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4486
4544
  }
4487
4545
  } else {
4488
4546
  removeWalletButton();
4489
- setTimeout(() => {
4547
+ connectionUpdateTimeout = setTimeout(() => {
4490
4548
  handleConnectionUpdate();
4491
4549
  }, 5e3);
4492
4550
  }
@@ -4523,27 +4581,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4523
4581
  }
4524
4582
  });
4525
4583
  }
4526
- function initBtcContext() {
4527
- return __async(this, null, function* () {
4528
- console.log("initBtcContext");
4529
- const btcContext = yield retryOperation(
4530
- () => __async(this, null, function* () {
4531
- const ctx = window.btcContext;
4532
- if (!ctx) {
4533
- throw new Error("btcContext not found");
4534
- }
4535
- return ctx;
4536
- }),
4537
- (res) => !!res,
4538
- {
4539
- maxRetries: 10,
4540
- delayMs: 500
4541
- }
4542
- );
4543
- yield setupBtcContextListeners();
4544
- return btcContext;
4545
- });
4546
- }
4547
4584
  function nearCall2(contractId, methodName, args) {
4548
4585
  return __async(this, null, function* () {
4549
4586
  return nearCallFunction(contractId, methodName, args, { provider });
@@ -4741,7 +4778,7 @@ function setupBTCWallet({
4741
4778
 
4742
4779
  // src/index.ts
4743
4780
  var getVersion = () => {
4744
- return "0.5.21-beta";
4781
+ return "0.5.23-beta";
4745
4782
  };
4746
4783
  if (typeof window !== "undefined") {
4747
4784
  window.__BTC_WALLET_VERSION = getVersion();
@@ -4761,12 +4798,16 @@ export {
4761
4798
  WizzConnector,
4762
4799
  XverseConnector,
4763
4800
  btcRpcUrls,
4801
+ calculateGasFee,
4802
+ calculateGasLimit,
4803
+ calculateWithdraw,
4764
4804
  checkGasTokenDebt,
4765
4805
  checkSatoshiWhitelist,
4766
4806
  estimateDepositAmount,
4767
4807
  executeBTCDepositAndAction,
4768
4808
  getBtcBalance,
4769
4809
  getBtcGasPrice,
4810
+ getBtcUtxos,
4770
4811
  getCsnaAccountId,
4771
4812
  getDepositAmount,
4772
4813
  getVersion,