btc-wallet 0.5.22-beta → 0.5.24-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.
@@ -37,7 +37,7 @@ export interface AccountInfo {
37
37
  export declare function getAccountInfo({ csna, env }: {
38
38
  csna: string;
39
39
  env: ENV;
40
- }): Promise<AccountInfo | undefined>;
40
+ }): Promise<AccountInfo>;
41
41
  export declare function getBridgeConfig({ env }: {
42
42
  env: ENV;
43
43
  }): Promise<{
@@ -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
@@ -3289,7 +3289,8 @@ function getAccountInfo(_0) {
3289
3289
  },
3290
3290
  { network: config.network }
3291
3291
  ).catch((error) => {
3292
- return void 0;
3292
+ console.log(`get_account error, please try again later`, error);
3293
+ throw error;
3293
3294
  });
3294
3295
  return accountInfo;
3295
3296
  });
@@ -3364,6 +3365,8 @@ function convertTransactionToTxHex(_0) {
3364
3365
  env,
3365
3366
  index = 0
3366
3367
  }) {
3368
+ if (!publicKey)
3369
+ return { txHex: "", txBytes: new Uint8Array(), hash: "" };
3367
3370
  const publicKeyFormat = PublicKey.from(publicKey);
3368
3371
  const currentConfig = getWalletConfig(env);
3369
3372
  const provider = getNearProvider({ network: currentConfig.network });
@@ -3583,7 +3586,8 @@ function getPredictedGasAmount(_0) {
3583
3586
  env
3584
3587
  }) {
3585
3588
  const currentConfig = getWalletConfig(env);
3586
- const predictedGas = yield nearCallFunction(
3589
+ const isValidTransactions = transactions2.every((tx) => tx.length > 0);
3590
+ const predictedGas = isValidTransactions ? yield nearCallFunction(
3587
3591
  accountContractId,
3588
3592
  "predict_txs_gas_token_amount",
3589
3593
  {
@@ -3591,7 +3595,7 @@ function getPredictedGasAmount(_0) {
3591
3595
  near_transactions: transactions2
3592
3596
  },
3593
3597
  { network: currentConfig.network }
3594
- );
3598
+ ) : "0";
3595
3599
  const predictedGasAmount = new Big(predictedGas).mul(1.2).toFixed(0);
3596
3600
  const miniGasAmount = 200 * transactions2.length;
3597
3601
  const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
@@ -3607,9 +3611,9 @@ function calculateWithdraw(_0) {
3607
3611
  btcAddress,
3608
3612
  env
3609
3613
  }) {
3610
- console.log("calculateWithdraw feeRate:", feeRate);
3611
3614
  try {
3612
3615
  const config = getWalletConfig(env);
3616
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3613
3617
  const gasLimit = yield calculateGasLimit({
3614
3618
  csna,
3615
3619
  transactions: [
@@ -3646,7 +3650,7 @@ function calculateWithdraw(_0) {
3646
3650
  return {
3647
3651
  withdrawFee: 0,
3648
3652
  isError: true,
3649
- errorMsg: "Mini withdraw amount is " + (Number(brgConfig.min_withdraw_amount) + Number(gasLimit))
3653
+ errorMsg: `Mini withdraw amount is ${Number(brgConfig.min_withdraw_amount) + Number(gasLimit)} sats`
3650
3654
  };
3651
3655
  }
3652
3656
  }
@@ -3674,7 +3678,7 @@ function calculateWithdraw(_0) {
3674
3678
  const { inputs, outputs, fee } = coinselect(
3675
3679
  utxos,
3676
3680
  [{ address: btcAddress, value: userSatoshis }],
3677
- Math.ceil(feeRate || 0)
3681
+ Math.ceil(_feeRate)
3678
3682
  );
3679
3683
  const newInputs = inputs;
3680
3684
  let newOutputs = outputs;
@@ -3788,6 +3792,7 @@ function calculateWithdraw(_0) {
3788
3792
 
3789
3793
  // src/core/btcUtils.ts
3790
3794
  import bitcoin from "bitcoinjs-lib";
3795
+ import coinselect2 from "coinselect";
3791
3796
  import * as ecc from "@bitcoinerlab/secp256k1";
3792
3797
  bitcoin.initEccLib(ecc);
3793
3798
  var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
@@ -3802,9 +3807,13 @@ function getBtcProvider() {
3802
3807
  }
3803
3808
  function getNetwork() {
3804
3809
  return __async(this, null, function* () {
3805
- const network = yield getBtcProvider().getNetwork();
3806
- console.log("btc network:", network);
3807
- return network === "livenet" ? "mainnet" : "testnet";
3810
+ try {
3811
+ const network = yield getBtcProvider().getNetwork();
3812
+ console.log("btc network:", network);
3813
+ return network === "livenet" ? "mainnet" : "testnet";
3814
+ } catch (error) {
3815
+ return "mainnet";
3816
+ }
3808
3817
  });
3809
3818
  }
3810
3819
  function getBtcRpcUrl() {
@@ -3867,25 +3876,37 @@ function getBtcGasPrice() {
3867
3876
  }
3868
3877
  });
3869
3878
  }
3870
- function getBtcBalance() {
3879
+ function getBtcUtxos(account) {
3871
3880
  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
3881
  const btcRpcUrl = yield getBtcRpcUrl();
3878
3882
  const utxos = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res) => res.json());
3883
+ return utxos;
3884
+ });
3885
+ }
3886
+ function calculateGasFee(account, amount, feeRate) {
3887
+ return __async(this, null, function* () {
3888
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3889
+ const utxos = yield getBtcUtxos(account);
3890
+ const { fee } = coinselect2(utxos, [{ address: account, value: amount }], Math.ceil(_feeRate));
3891
+ console.log("calculateGasFee fee:", fee);
3892
+ return fee;
3893
+ });
3894
+ }
3895
+ function getBtcBalance(account) {
3896
+ return __async(this, null, function* () {
3897
+ if (!account) {
3898
+ const res = yield retryOperation(getBtcProvider, (res2) => !!res2.account);
3899
+ if (!res.account) {
3900
+ console.error("BTC Account is not available.");
3901
+ return { rawBalance: 0, balance: 0, availableBalance: 0 };
3902
+ }
3903
+ account = res.account;
3904
+ }
3905
+ const utxos = yield getBtcUtxos(account);
3879
3906
  const btcDecimals = 8;
3880
3907
  const rawBalance = (utxos == null ? void 0 : utxos.reduce((acc, cur) => acc + cur.value, 0)) || 0;
3881
3908
  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);
3909
+ const estimatedFee = yield calculateGasFee(account, rawBalance);
3889
3910
  const availableRawBalance = (rawBalance - estimatedFee).toFixed(0);
3890
3911
  const availableBalance = new Big2(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, Big2.roundDown).toNumber();
3891
3912
  return {
@@ -3912,7 +3933,7 @@ function getDepositAmount(amount, option) {
3912
3933
  var _a;
3913
3934
  const env = (option == null ? void 0 : option.env) || "mainnet";
3914
3935
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3915
- const csna = yield getCsnaAccountId(env);
3936
+ const csna = (option == null ? void 0 : option.csna) || (yield getCsnaAccountId(env));
3916
3937
  const accountInfo = yield getAccountInfo({ csna, env });
3917
3938
  const debtAction = yield checkGasTokenDebt(csna, env, false);
3918
3939
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
@@ -4109,18 +4130,18 @@ function getWithdrawTransaction(_0) {
4109
4130
  return __async(this, arguments, function* ({
4110
4131
  amount,
4111
4132
  feeRate,
4133
+ csna,
4134
+ btcAddress,
4112
4135
  env = "mainnet"
4113
4136
  }) {
4114
4137
  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());
4138
+ const _btcAddress = btcAddress || getBtcProvider().account;
4139
+ const _csna = csna || (yield getCsnaAccountId(env));
4119
4140
  const _a = yield calculateWithdraw({
4120
4141
  amount,
4121
- feeRate: _feeRate,
4122
- csna,
4123
- btcAddress,
4142
+ feeRate,
4143
+ csna: _csna,
4144
+ btcAddress: _btcAddress,
4124
4145
  env
4125
4146
  }), { inputs, outputs, isError, errorMsg } = _a, rest = __objRest(_a, ["inputs", "outputs", "isError", "errorMsg"]);
4126
4147
  if (isError || !inputs || !outputs) {
@@ -4136,7 +4157,7 @@ function getWithdrawTransaction(_0) {
4136
4157
  const btcNetwork = network === "mainnet" ? bitcoin.networks.bitcoin : bitcoin.networks.testnet;
4137
4158
  const psbt = new bitcoin.Psbt({ network: btcNetwork });
4138
4159
  const btcRpcUrl = yield getBtcRpcUrl();
4139
- Promise.all(
4160
+ yield Promise.all(
4140
4161
  inputs.map((input) => __async(this, null, function* () {
4141
4162
  const txData = yield fetch(`${btcRpcUrl}/tx/${input.txid}`).then((res) => res.json());
4142
4163
  const inputOptions = {
@@ -4168,14 +4189,14 @@ function getWithdrawTransaction(_0) {
4168
4189
  });
4169
4190
  const msg = {
4170
4191
  Withdraw: {
4171
- target_btc_address: btcAddress,
4192
+ target_btc_address: _btcAddress,
4172
4193
  input: _inputs,
4173
4194
  output: txOutputs
4174
4195
  }
4175
4196
  };
4176
4197
  const transaction = {
4177
4198
  receiverId: config.btcToken,
4178
- signerId: csna,
4199
+ signerId: _csna,
4179
4200
  actions: [
4180
4201
  {
4181
4202
  type: "FunctionCall",
@@ -4250,7 +4271,6 @@ function createFloatingButtonWithIframe({
4250
4271
  zIndex: "100000",
4251
4272
  width: "60px",
4252
4273
  height: "60px",
4253
- borderRadius: "50%",
4254
4274
  cursor: "grab",
4255
4275
  transition: "transform 0.15s ease",
4256
4276
  userSelect: "none"
@@ -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,
@@ -4466,15 +4488,52 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4466
4488
  }
4467
4489
  return true;
4468
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
+ }
4469
4521
  function setupBtcContextListeners() {
4470
4522
  return __async(this, null, function* () {
4471
4523
  const handleConnectionUpdate = () => __async(this, null, function* () {
4524
+ if (connectionUpdateTimeout) {
4525
+ clearTimeout(connectionUpdateTimeout);
4526
+ }
4472
4527
  yield checkBtcNetwork(currentConfig.network);
4473
4528
  if (!state_default.isValid()) {
4474
4529
  state_default.clear();
4475
4530
  console.log("setupBtcContextListeners clear");
4476
4531
  }
4477
- validateWalletState();
4532
+ const valid = validateWalletState();
4533
+ console.log("setupBtcContextListeners wallet state valid:", valid);
4534
+ if (!valid) {
4535
+ return;
4536
+ }
4478
4537
  const btcContext = window.btcContext;
4479
4538
  if (btcContext.account) {
4480
4539
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4485,7 +4544,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4485
4544
  }
4486
4545
  } else {
4487
4546
  removeWalletButton();
4488
- setTimeout(() => {
4547
+ connectionUpdateTimeout = setTimeout(() => {
4489
4548
  handleConnectionUpdate();
4490
4549
  }, 5e3);
4491
4550
  }
@@ -4522,27 +4581,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4522
4581
  }
4523
4582
  });
4524
4583
  }
4525
- function initBtcContext() {
4526
- return __async(this, null, function* () {
4527
- console.log("initBtcContext");
4528
- const btcContext = yield retryOperation(
4529
- () => __async(this, null, function* () {
4530
- const ctx = window.btcContext;
4531
- if (!ctx) {
4532
- throw new Error("btcContext not found");
4533
- }
4534
- return ctx;
4535
- }),
4536
- (res) => !!res,
4537
- {
4538
- maxRetries: 10,
4539
- delayMs: 500
4540
- }
4541
- );
4542
- yield setupBtcContextListeners();
4543
- return btcContext;
4544
- });
4545
- }
4546
4584
  function nearCall2(contractId, methodName, args) {
4547
4585
  return __async(this, null, function* () {
4548
4586
  return nearCallFunction(contractId, methodName, args, { provider });
@@ -4740,7 +4778,7 @@ function setupBTCWallet({
4740
4778
 
4741
4779
  // src/index.ts
4742
4780
  var getVersion = () => {
4743
- return "0.5.22-beta";
4781
+ return "0.5.24-beta";
4744
4782
  };
4745
4783
  if (typeof window !== "undefined") {
4746
4784
  window.__BTC_WALLET_VERSION = getVersion();
@@ -4760,13 +4798,16 @@ export {
4760
4798
  WizzConnector,
4761
4799
  XverseConnector,
4762
4800
  btcRpcUrls,
4801
+ calculateGasFee,
4763
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,