btc-wallet 0.5.11-beta → 0.5.12-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.
@@ -1,7 +1,13 @@
1
1
  import type { ProviderService } from '@near-wallet-selector/core/src/lib/services';
2
2
  import { providers } from 'near-api-js';
3
- export declare function nearCallFunction<T>(contractId: string, methodName: string, args: any, options: {
3
+ export declare function getNearProvider(option: {
4
4
  network?: string;
5
5
  provider?: ProviderService;
6
+ }): ProviderService | providers.FailoverRpcProvider;
7
+ export declare function nearCallFunction<T>(contractId: string, methodName: string, args: any, options?: {
8
+ network?: string;
9
+ provider?: ProviderService;
10
+ cacheTimeout?: number;
11
+ skipCache?: boolean;
6
12
  }): Promise<T>;
7
13
  export declare function pollTransactionStatuses(network: string, hashes: string[]): Promise<providers.FinalExecutionOutcome[]>;
@@ -7,5 +7,6 @@ interface RequestOptions<T> extends RequestInit {
7
7
  maxPollingAttempts?: number;
8
8
  shouldStopPolling?: (response: T) => boolean;
9
9
  }
10
+ export declare function withCache<T>(key: string, fetcher: () => Promise<T>, timeout?: number): Promise<T>;
10
11
  export default function request<T>(url: string, options?: RequestOptions<T>): Promise<T>;
11
12
  export {};
package/esm/index.js CHANGED
@@ -368,11 +368,11 @@ var MobileWalletConnect = class {
368
368
  }
369
369
  static redirectToWallet(walletId) {
370
370
  return __async(this, null, function* () {
371
- var _a;
372
371
  if (isMobile()) {
373
372
  const currentUrl = window.location.href;
374
373
  const universalLink = this.getUniversalLink(walletId, currentUrl);
375
- if (!universalLink) {
374
+ const showGuideDialog = () => __async(this, null, function* () {
375
+ var _a;
376
376
  try {
377
377
  yield (_a = navigator.clipboard) == null ? void 0 : _a.writeText(currentUrl);
378
378
  } catch (error) {
@@ -390,9 +390,23 @@ var MobileWalletConnect = class {
390
390
  `,
391
391
  dangerouslyUseHTML: true
392
392
  });
393
+ });
394
+ if (!universalLink) {
395
+ yield showGuideDialog();
393
396
  return false;
394
397
  }
398
+ const openWallet = () => {
399
+ const iframe = document.createElement("iframe");
400
+ iframe.style.display = "none";
401
+ iframe.src = universalLink;
402
+ document.body.appendChild(iframe);
403
+ setTimeout(() => __async(this, null, function* () {
404
+ document.body.removeChild(iframe);
405
+ yield showGuideDialog();
406
+ }), 2e3);
407
+ };
395
408
  window.location.href = universalLink;
409
+ setTimeout(openWallet, 100);
396
410
  return true;
397
411
  }
398
412
  return false;
@@ -2820,7 +2834,10 @@ import { sha256 } from "js-sha256";
2820
2834
  var walletConfig = {
2821
2835
  dev: {
2822
2836
  base_url: "https://api.dev.satoshibridge.top",
2823
- token: "nbtc-dev.testnet",
2837
+ btcToken: "nbtc-dev.testnet",
2838
+ btcTokenDecimals: 8,
2839
+ nearToken: "wrap.testnet",
2840
+ nearTokenDecimals: 24,
2824
2841
  accountContractId: "acc-dev.testnet",
2825
2842
  bridgeContractId: "brg-dev.testnet",
2826
2843
  walletUrl: "https://wallet-dev.satoshibridge.top",
@@ -2828,7 +2845,10 @@ var walletConfig = {
2828
2845
  },
2829
2846
  testnet: {
2830
2847
  base_url: "https://api.testnet.satoshibridge.top",
2831
- token: "nbtc2-nsp.testnet",
2848
+ btcToken: "nbtc2-nsp.testnet",
2849
+ btcTokenDecimals: 8,
2850
+ nearToken: "wrap.testnet",
2851
+ nearTokenDecimals: 24,
2832
2852
  accountContractId: "acc2-nsp.testnet",
2833
2853
  bridgeContractId: "brg2-nsp.testnet",
2834
2854
  walletUrl: "https://wallet-test.satoshibridge.top",
@@ -2836,7 +2856,10 @@ var walletConfig = {
2836
2856
  },
2837
2857
  private_mainnet: {
2838
2858
  base_url: "https://api.stg.satoshibridge.top",
2839
- token: "nbtc.toalice.near",
2859
+ btcToken: "nbtc.toalice.near",
2860
+ btcTokenDecimals: 8,
2861
+ nearToken: "wrap.near",
2862
+ nearTokenDecimals: 24,
2840
2863
  accountContractId: "acc.toalice.near",
2841
2864
  bridgeContractId: "brg.toalice.near",
2842
2865
  walletUrl: "https://wallet-stg.satoshibridge.top",
@@ -2844,7 +2867,10 @@ var walletConfig = {
2844
2867
  },
2845
2868
  mainnet: {
2846
2869
  base_url: "https://api.satos.network",
2847
- token: "nbtc.bridge.near",
2870
+ btcToken: "nbtc.bridge.near",
2871
+ btcTokenDecimals: 8,
2872
+ nearToken: "wrap.near",
2873
+ nearTokenDecimals: 24,
2848
2874
  accountContractId: "acc.ref-labs.near",
2849
2875
  bridgeContractId: "btc-connector.bridge.near",
2850
2876
  walletUrl: "https://wallet.satoshibridge.top",
@@ -2870,69 +2896,24 @@ import Big from "big.js";
2870
2896
 
2871
2897
  // src/utils/nearUtils.ts
2872
2898
  import { providers } from "near-api-js";
2873
- function nearCallFunction(contractId, methodName, args, options) {
2874
- return __async(this, null, function* () {
2875
- const nearProvider = (options == null ? void 0 : options.provider) || new providers.FailoverRpcProvider(
2876
- nearRpcUrls[options == null ? void 0 : options.network].map(
2877
- (url) => new providers.JsonRpcProvider({ url })
2878
- )
2879
- );
2880
- const res = yield nearProvider.query({
2881
- request_type: "call_function",
2882
- account_id: contractId,
2883
- method_name: methodName,
2884
- args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
2885
- finality: "final"
2886
- });
2887
- return JSON.parse(Buffer.from(res.result).toString());
2888
- });
2889
- }
2890
- function pollTransactionStatuses(network, hashes) {
2891
- return __async(this, null, function* () {
2892
- const provider = new providers.FailoverRpcProvider(
2893
- Object.values(nearRpcUrls[network]).map(
2894
- (url) => new providers.JsonRpcProvider({ url })
2895
- )
2896
- );
2897
- const maxAttempts = 30;
2898
- let currentAttempt = 0;
2899
- const pendingHashes = new Set(hashes);
2900
- const results = /* @__PURE__ */ new Map();
2901
- while (pendingHashes.size > 0 && currentAttempt < maxAttempts) {
2902
- currentAttempt++;
2903
- const promises = Array.from(pendingHashes).map((hash) => __async(this, null, function* () {
2904
- try {
2905
- const result2 = yield provider.txStatus(hash, "unused", "FINAL");
2906
- if (result2 && result2.status) {
2907
- console.log(`Transaction ${hash} result:`, result2);
2908
- results.set(hash, result2);
2909
- pendingHashes.delete(hash);
2910
- }
2911
- } catch (error) {
2912
- console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
2913
- }
2914
- }));
2915
- yield Promise.all(promises);
2916
- if (pendingHashes.size > 0) {
2917
- if (currentAttempt === maxAttempts) {
2918
- throw new Error(
2919
- `Transactions not found after max attempts: ${Array.from(pendingHashes).join(", ")}`
2920
- );
2921
- }
2922
- console.log(
2923
- `Waiting for ${pendingHashes.size} transactions, retrying ${maxAttempts - currentAttempt} more times`
2924
- );
2925
- yield delay(1e4);
2926
- }
2927
- }
2928
- const result = hashes.map((hash) => results.get(hash)).filter(Boolean);
2929
- return result;
2930
- });
2931
- }
2932
2899
 
2933
2900
  // src/utils/request.ts
2934
2901
  var cache = /* @__PURE__ */ new Map();
2935
2902
  var defaultCacheTimeout = 3e3;
2903
+ function withCache(key, fetcher, timeout = defaultCacheTimeout) {
2904
+ const cached = cache.get(key);
2905
+ const isCacheValid = cached && Date.now() - cached.timestamp < timeout;
2906
+ if (isCacheValid) {
2907
+ return Promise.resolve(cached.data);
2908
+ }
2909
+ return fetcher().then((data) => {
2910
+ cache.set(key, { timestamp: Date.now(), data });
2911
+ setTimeout(() => {
2912
+ cache.delete(key);
2913
+ }, timeout);
2914
+ return data;
2915
+ });
2916
+ }
2936
2917
  function request(url, options) {
2937
2918
  return __async(this, null, function* () {
2938
2919
  var _a;
@@ -2974,13 +2955,7 @@ function request(url, options) {
2974
2955
  if (options.shouldStopPolling(data)) {
2975
2956
  return data;
2976
2957
  }
2977
- if (options.maxPollingAttempts && options.maxPollingAttempts > 0) {
2978
- yield new Promise((resolve) => setTimeout(resolve, options.pollingInterval));
2979
- return request(url, __spreadProps(__spreadValues({}, options), {
2980
- maxPollingAttempts: options.maxPollingAttempts - 1
2981
- }));
2982
- }
2983
- throw new Error("Polling failed: maximum attempts reached without meeting the condition");
2958
+ throw new Error("Polling should continue");
2984
2959
  }
2985
2960
  if (cacheKey) {
2986
2961
  cache.set(cacheKey, { timestamp: Date.now(), data });
@@ -2990,6 +2965,7 @@ function request(url, options) {
2990
2965
  }
2991
2966
  return data;
2992
2967
  } catch (err) {
2968
+ console.error(err);
2993
2969
  if (retryCount > 0) {
2994
2970
  console.log(`Retrying... attempts left: ${retryCount}`);
2995
2971
  return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount - 1 }));
@@ -3003,8 +2979,85 @@ function request(url, options) {
3003
2979
  }));
3004
2980
  }
3005
2981
  }
3006
- throw err;
2982
+ return Promise.reject(err);
2983
+ }
2984
+ });
2985
+ }
2986
+
2987
+ // src/utils/nearUtils.ts
2988
+ function getNearProvider(option) {
2989
+ return option.provider || new providers.FailoverRpcProvider(
2990
+ nearRpcUrls[option == null ? void 0 : option.network].map(
2991
+ (url) => new providers.JsonRpcProvider({ url })
2992
+ )
2993
+ );
2994
+ }
2995
+ function nearCallFunction(_0, _1, _2) {
2996
+ return __async(this, arguments, function* (contractId, methodName, args, options = {}) {
2997
+ if (!options.skipCache) {
2998
+ const cacheKey = `near:${contractId}:${methodName}:${args ? JSON.stringify(args) : ""}`;
2999
+ return withCache(
3000
+ cacheKey,
3001
+ () => executeNearCall(contractId, methodName, args, options),
3002
+ options.cacheTimeout
3003
+ );
3004
+ }
3005
+ return executeNearCall(contractId, methodName, args, options);
3006
+ });
3007
+ }
3008
+ function executeNearCall(contractId, methodName, args, options) {
3009
+ return __async(this, null, function* () {
3010
+ const nearProvider = getNearProvider(options);
3011
+ const res = yield nearProvider.query({
3012
+ request_type: "call_function",
3013
+ account_id: contractId,
3014
+ method_name: methodName,
3015
+ args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
3016
+ finality: "final"
3017
+ });
3018
+ return JSON.parse(Buffer.from(res.result).toString());
3019
+ });
3020
+ }
3021
+ function pollTransactionStatuses(network, hashes) {
3022
+ return __async(this, null, function* () {
3023
+ const provider = new providers.FailoverRpcProvider(
3024
+ Object.values(nearRpcUrls[network]).map(
3025
+ (url) => new providers.JsonRpcProvider({ url })
3026
+ )
3027
+ );
3028
+ const maxAttempts = 30;
3029
+ let currentAttempt = 0;
3030
+ const pendingHashes = new Set(hashes);
3031
+ const results = /* @__PURE__ */ new Map();
3032
+ while (pendingHashes.size > 0 && currentAttempt < maxAttempts) {
3033
+ currentAttempt++;
3034
+ const promises = Array.from(pendingHashes).map((hash) => __async(this, null, function* () {
3035
+ try {
3036
+ const result2 = yield provider.txStatus(hash, "unused", "FINAL");
3037
+ if (result2 && result2.status) {
3038
+ console.log(`Transaction ${hash} result:`, result2);
3039
+ results.set(hash, result2);
3040
+ pendingHashes.delete(hash);
3041
+ }
3042
+ } catch (error) {
3043
+ console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
3044
+ }
3045
+ }));
3046
+ yield Promise.all(promises);
3047
+ if (pendingHashes.size > 0) {
3048
+ if (currentAttempt === maxAttempts) {
3049
+ throw new Error(
3050
+ `Transactions not found after max attempts: ${Array.from(pendingHashes).join(", ")}`
3051
+ );
3052
+ }
3053
+ console.log(
3054
+ `Waiting for ${pendingHashes.size} transactions, retrying ${maxAttempts - currentAttempt} more times`
3055
+ );
3056
+ yield delay(1e4);
3057
+ }
3007
3058
  }
3059
+ const result = hashes.map((hash) => results.get(hash)).filter(Boolean);
3060
+ return result;
3008
3061
  });
3009
3062
  }
3010
3063
 
@@ -3161,9 +3214,10 @@ function nearCall(contractId, methodName, args) {
3161
3214
  return nearCallFunction(contractId, methodName, args, { network });
3162
3215
  });
3163
3216
  }
3164
- function getAccountInfo(csna, accountContractId) {
3165
- return __async(this, null, function* () {
3166
- const accountInfo = yield nearCall(accountContractId, "get_account", {
3217
+ function getAccountInfo(_0) {
3218
+ return __async(this, arguments, function* ({ csna, env }) {
3219
+ const config = yield getConfig(env);
3220
+ const accountInfo = yield nearCall(config.accountContractId, "get_account", {
3167
3221
  account_id: csna
3168
3222
  }).catch((error) => {
3169
3223
  return void 0;
@@ -3172,16 +3226,46 @@ function getAccountInfo(csna, accountContractId) {
3172
3226
  return accountInfo;
3173
3227
  });
3174
3228
  }
3175
- function checkGasTokenBalance(csna, gasToken, minAmount, env) {
3229
+ function getTokenBalance(_0) {
3230
+ return __async(this, arguments, function* ({
3231
+ csna,
3232
+ tokenId,
3233
+ env
3234
+ }) {
3235
+ const network = yield getNetwork();
3236
+ const config = yield getConfig(env);
3237
+ const nearProvider = getNearProvider({ network });
3238
+ try {
3239
+ if (tokenId === config.nearToken) {
3240
+ const nearAccount = yield nearProvider.query({
3241
+ request_type: "view_account",
3242
+ account_id: csna,
3243
+ finality: "final"
3244
+ });
3245
+ const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
3246
+ return { balance, rawBalance: nearAccount.amount };
3247
+ } else {
3248
+ const res = yield nearCall(tokenId, "ft_balance_of", { account_id: csna });
3249
+ const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCall(tokenId, "ft_metadata", {})).decimals;
3250
+ const balance = parseFloat(res) / __pow(10, decimals);
3251
+ return { balance, rawBalance: res };
3252
+ }
3253
+ } catch (error) {
3254
+ console.error("getTokenBalance error:", error);
3255
+ return { balance: 0, rawBalance: "0" };
3256
+ }
3257
+ });
3258
+ }
3259
+ function checkGasTokenBalance(csna, minAmount, env) {
3176
3260
  return __async(this, null, function* () {
3177
- const amount = yield nearCall(gasToken, "ft_balance_of", { account_id: csna });
3178
- console.log("gas token balance:", amount);
3179
- if (new Big(amount).lt(minAmount)) {
3261
+ const config = yield getConfig(env);
3262
+ const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
3263
+ console.log("gas token balance:", rawBalance);
3264
+ if (new Big(rawBalance).lt(minAmount)) {
3180
3265
  yield Dialog.confirm({
3181
3266
  title: "Gas token balance is insufficient",
3182
3267
  message: "Please deposit gas token to continue, will open bridge website."
3183
3268
  });
3184
- const config = yield getConfig(env);
3185
3269
  window.open(config.bridgeUrl, "_blank");
3186
3270
  throw new Error("Gas token balance is insufficient");
3187
3271
  }
@@ -3262,18 +3346,6 @@ function getBtcBalance() {
3262
3346
  };
3263
3347
  });
3264
3348
  }
3265
- function getNBTCBalance(address, env) {
3266
- return __async(this, null, function* () {
3267
- const config = yield getConfig(env || "mainnet");
3268
- const rawBalance = yield nearCall(config.token, "ft_balance_of", {
3269
- account_id: address
3270
- });
3271
- const balance = new Big(rawBalance).div(__pow(10, 8)).round(8, Big.roundDown).toNumber();
3272
- const rawAvailableBalance = new Big(rawBalance).minus(1e3).toNumber();
3273
- const availableBalance = new Big(rawAvailableBalance).div(__pow(10, 8)).round(8, Big.roundDown).toNumber();
3274
- return { balance, availableBalance, rawBalance, rawAvailableBalance };
3275
- });
3276
- }
3277
3349
  function sendBitcoin(address, amount, feeRate) {
3278
3350
  return __async(this, null, function* () {
3279
3351
  const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
@@ -3293,7 +3365,7 @@ function getDepositAmount(amount, option) {
3293
3365
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3294
3366
  const config = yield getConfig(env);
3295
3367
  const csna = yield getCsnaAccountId(env);
3296
- const accountInfo = yield getAccountInfo(csna, config.accountContractId);
3368
+ const accountInfo = yield getAccountInfo({ csna, env });
3297
3369
  const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3298
3370
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
3299
3371
  const {
@@ -3372,7 +3444,7 @@ function executeBTCDepositAndAction(_0) {
3372
3444
  env,
3373
3445
  newAccountMinDepositAmount
3374
3446
  });
3375
- const accountInfo = yield getAccountInfo(csna, config.accountContractId);
3447
+ const accountInfo = yield getAccountInfo({ csna, env });
3376
3448
  const newActions = [];
3377
3449
  const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3378
3450
  if (debtAction) {
@@ -3386,12 +3458,12 @@ function executeBTCDepositAndAction(_0) {
3386
3458
  }));
3387
3459
  }
3388
3460
  const storageDepositMsg = {};
3389
- const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.token, "storage_balance_of", {
3461
+ const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.btcToken, "storage_balance_of", {
3390
3462
  account_id: csna
3391
3463
  });
3392
3464
  if (!(registerRes == null ? void 0 : registerRes.available)) {
3393
3465
  storageDepositMsg.storage_deposit_msg = {
3394
- contract_id: (action == null ? void 0 : action.receiver_id) || config.token,
3466
+ contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
3395
3467
  deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
3396
3468
  registration_only: true
3397
3469
  };
@@ -3597,7 +3669,7 @@ function getWithdrawTransaction(_0) {
3597
3669
  };
3598
3670
  const csna = yield getCsnaAccountId(env);
3599
3671
  const transaction = {
3600
- receiverId: config.token,
3672
+ receiverId: config.btcToken,
3601
3673
  signerId: csna,
3602
3674
  actions: [
3603
3675
  {
@@ -4141,20 +4213,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4141
4213
  throw new Error("Wallet state is invalid, please reconnect your wallet.");
4142
4214
  }
4143
4215
  const btcContext = window.btcContext;
4144
- const accountId = state.getAccount();
4145
- const accountInfo = yield getAccountInfo(accountId, currentConfig.accountContractId);
4216
+ const csna = state.getAccount();
4217
+ const accountInfo = yield getAccountInfo({ csna, env });
4146
4218
  yield checkGasTokenDebt(accountInfo, env, true);
4147
4219
  const trans = [...params.transactions];
4148
4220
  console.log("signAndSendTransactions raw trans:", trans);
4149
- const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.token]) || "0";
4150
- const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(
4151
- gasTokenBalance,
4152
- trans
4153
- );
4221
+ const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
4154
4222
  console.log("transferGasTransaction:", transferGasTransaction);
4155
4223
  console.log("useNearPayGas:", useNearPayGas);
4156
4224
  console.log("gasLimit:", gasLimit);
4157
- yield checkGasTokenBalance(accountId, currentConfig.token, gasLimit, env);
4225
+ yield checkGasTokenBalance(csna, gasLimit, env);
4158
4226
  if (transferGasTransaction) {
4159
4227
  trans.unshift(transferGasTransaction);
4160
4228
  }
@@ -4162,14 +4230,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4162
4230
  const newTrans = yield Promise.all(
4163
4231
  trans.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4164
4232
  );
4165
- const nonceFromApi = yield getNonce(currentConfig.base_url, accountId);
4233
+ const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
4166
4234
  const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
4167
4235
  const nonce = Number(nonceFromApi) > Number(nonceFromContract) ? String(nonceFromApi) : String(nonceFromContract);
4168
4236
  const intention = {
4169
4237
  chain_id: "397",
4170
- csna: accountId,
4238
+ csna,
4171
4239
  near_transactions: newTrans.map((t) => t.txHex),
4172
- gas_token: currentConfig.token,
4240
+ gas_token: currentConfig.btcToken,
4173
4241
  gas_limit: gasLimit,
4174
4242
  use_near_pay_gas: useNearPayGas,
4175
4243
  nonce
@@ -4182,7 +4250,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4182
4250
  data: toHex(strIntention)
4183
4251
  });
4184
4252
  yield checkBtcTransactionStatus(currentConfig.base_url, signature);
4185
- const hash = newTrans.map((t) => t.hash);
4253
+ const hash = newTrans.slice(1).map((t) => t.hash);
4186
4254
  console.log("txHash:", hash);
4187
4255
  const result = yield pollTransactionStatuses(options.network.networkId, hash);
4188
4256
  return result;
@@ -4190,12 +4258,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4190
4258
  }
4191
4259
  function calculateGasLimit(params) {
4192
4260
  return __async(this, null, function* () {
4193
- const accountId = state.getAccount();
4194
- const accountInfo = yield getAccountInfo(accountId, currentConfig.accountContractId);
4195
4261
  const trans = [...params.transactions];
4196
4262
  console.log("raw trans:", trans);
4197
- const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.token]) || "0";
4198
- const { gasLimit } = yield calculateGasStrategy(gasTokenBalance, trans);
4263
+ const { gasLimit } = yield calculateGasStrategy(trans);
4199
4264
  return gasLimit;
4200
4265
  });
4201
4266
  }
@@ -4203,7 +4268,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4203
4268
  return __async(this, null, function* () {
4204
4269
  return {
4205
4270
  signerId: accountId,
4206
- receiverId: currentConfig.token,
4271
+ receiverId: currentConfig.btcToken,
4207
4272
  actions: [
4208
4273
  {
4209
4274
  type: "FunctionCall",
@@ -4231,7 +4296,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4231
4296
  } else {
4232
4297
  newGasLimit = yield getPredictedGasAmount(
4233
4298
  currentConfig.accountContractId,
4234
- currentConfig.token,
4299
+ currentConfig.btcToken,
4235
4300
  [transferTxHex, ...transactions2.map((t) => t.txHex)]
4236
4301
  );
4237
4302
  }
@@ -4252,31 +4317,61 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4252
4317
  return gasAmount.toString();
4253
4318
  });
4254
4319
  }
4255
- function calculateGasStrategy(gasTokenBalance, transactions2) {
4320
+ function calculateGasStrategy(transactions2) {
4256
4321
  return __async(this, null, function* () {
4257
4322
  var _a;
4258
4323
  const accountId = state.getAccount();
4259
- const nearAccount = yield provider.query({
4260
- request_type: "view_account",
4261
- account_id: accountId,
4262
- finality: "final"
4324
+ const accountInfo = yield getAccountInfo({ csna: accountId, env });
4325
+ const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
4326
+ const { balance: nearBalance } = yield getTokenBalance({
4327
+ csna: accountId,
4328
+ tokenId: currentConfig.nearToken,
4329
+ env
4263
4330
  });
4264
- const availableBalance = parseFloat(nearAccount.amount) / __pow(10, 24);
4265
- console.log("available near balance:", availableBalance);
4331
+ const { balance: btcBalance } = yield getTokenBalance({
4332
+ csna: accountId,
4333
+ tokenId: currentConfig.btcToken,
4334
+ env
4335
+ });
4336
+ const transferAmount = transactions2.reduce(
4337
+ (acc, tx) => {
4338
+ tx.actions.forEach((action) => {
4339
+ if (action.params.deposit) {
4340
+ const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
4341
+ console.log("near deposit amount:", amount);
4342
+ acc.near = acc.near.plus(amount);
4343
+ }
4344
+ if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
4345
+ const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
4346
+ console.log("btc transfer amount:", amount);
4347
+ acc.btc = acc.btc.plus(amount);
4348
+ }
4349
+ });
4350
+ return acc;
4351
+ },
4352
+ { near: new Big2(0), btc: new Big2(0) }
4353
+ );
4354
+ const nearAvailableBalance = new Big2(nearBalance).minus(transferAmount.near).toNumber();
4355
+ const btcAvailableBalance = new Big2(btcBalance).minus(transferAmount.btc).toNumber();
4356
+ if (btcAvailableBalance < 8e-6) {
4357
+ throw new Error("BTC balance is not enough, please deposit more BTC.");
4358
+ }
4359
+ console.log("available near balance:", nearAvailableBalance);
4360
+ console.log("available btc balance:", btcAvailableBalance);
4266
4361
  console.log("available gas token balance:", gasTokenBalance);
4267
4362
  const convertTx = yield Promise.all(
4268
4363
  transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4269
4364
  );
4270
- if (availableBalance > 0.5) {
4365
+ if (nearAvailableBalance > 0.5) {
4271
4366
  console.log("near balance is enough, get the protocol fee of each transaction");
4272
4367
  const gasTokens = yield nearCall2(
4273
4368
  currentConfig.accountContractId,
4274
4369
  "list_gas_token",
4275
- { token_ids: [currentConfig.token] }
4370
+ { token_ids: [currentConfig.btcToken] }
4276
4371
  );
4277
4372
  console.log("list_gas_token gas tokens:", gasTokens);
4278
4373
  const perTxFee = Math.max(
4279
- Number(((_a = gasTokens[currentConfig.token]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
4374
+ Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
4280
4375
  100
4281
4376
  );
4282
4377
  console.log("perTxFee:", perTxFee);
@@ -4294,7 +4389,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4294
4389
  console.log("near balance is not enough, predict the gas token amount required");
4295
4390
  const adjustedGas = yield getPredictedGasAmount(
4296
4391
  currentConfig.accountContractId,
4297
- currentConfig.token,
4392
+ currentConfig.btcToken,
4298
4393
  convertTx.map((t) => t.txHex)
4299
4394
  );
4300
4395
  if (new Big2(gasTokenBalance).gte(adjustedGas)) {
@@ -4410,7 +4505,7 @@ function setupBTCWallet({
4410
4505
 
4411
4506
  // src/index.ts
4412
4507
  var getVersion = () => {
4413
- return "0.5.11-beta";
4508
+ return "0.5.12-beta";
4414
4509
  };
4415
4510
  if (typeof window !== "undefined") {
4416
4511
  window.__BTC_WALLET_VERSION = getVersion();
@@ -4440,7 +4535,7 @@ export {
4440
4535
  getConfig,
4441
4536
  getCsnaAccountId,
4442
4537
  getDepositAmount,
4443
- getNBTCBalance,
4538
+ getTokenBalance,
4444
4539
  getVersion,
4445
4540
  getWithdrawTransaction,
4446
4541
  sendBitcoin,