btc-wallet 0.5.15-beta → 0.5.17-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.
package/esm/index.js CHANGED
@@ -2821,15 +2821,6 @@ function useBtcWalletSelector() {
2821
2821
  return hook;
2822
2822
  }
2823
2823
 
2824
- // src/core/setupBTCWallet.ts
2825
- import { transactions } from "near-api-js";
2826
- import { actionCreators } from "@near-js/transactions";
2827
- import { PublicKey } from "near-api-js/lib/utils/key_pair";
2828
- import { encodeTransaction } from "near-api-js/lib/transaction";
2829
- import { baseDecode } from "@near-js/utils";
2830
- import bs58 from "bs58";
2831
- import { sha256 } from "js-sha256";
2832
-
2833
2824
  // src/config.ts
2834
2825
  var walletConfig = {
2835
2826
  dev: {
@@ -2877,6 +2868,13 @@ var walletConfig = {
2877
2868
  bridgeUrl: "https://ramp.satos.network"
2878
2869
  }
2879
2870
  };
2871
+ function getWalletConfig(env) {
2872
+ const config = walletConfig[env];
2873
+ const network = env === "mainnet" || env === "private_mainnet" ? "mainnet" : "testnet";
2874
+ return __spreadProps(__spreadValues({}, config), {
2875
+ network
2876
+ });
2877
+ }
2880
2878
  var nearRpcUrls = {
2881
2879
  mainnet: [
2882
2880
  "https://near.lava.build",
@@ -2892,7 +2890,7 @@ var btcRpcUrls = {
2892
2890
  };
2893
2891
 
2894
2892
  // src/core/btcUtils.ts
2895
- import Big from "big.js";
2893
+ import Big2 from "big.js";
2896
2894
 
2897
2895
  // src/utils/nearUtils.ts
2898
2896
  import { providers } from "near-api-js";
@@ -2999,7 +2997,7 @@ function nearCallFunction(_0, _1, _2) {
2999
2997
  return withCache(
3000
2998
  cacheKey,
3001
2999
  () => executeNearCall(contractId, methodName, args, options),
3002
- options.cacheTimeout
3000
+ options.cacheTimeout || 5e3
3003
3001
  );
3004
3002
  }
3005
3003
  return executeNearCall(contractId, methodName, args, options);
@@ -3061,6 +3059,95 @@ function pollTransactionStatuses(network, hashes) {
3061
3059
  });
3062
3060
  }
3063
3061
 
3062
+ // src/utils/satoshi.ts
3063
+ import { actionCreators } from "@near-js/transactions";
3064
+ import { PublicKey } from "near-api-js/lib/utils/key_pair";
3065
+ import { encodeTransaction } from "near-api-js/lib/transaction";
3066
+ import { baseDecode } from "@near-js/utils";
3067
+ import bs58 from "bs58";
3068
+ import { sha256 } from "js-sha256";
3069
+ import { transactions } from "near-api-js";
3070
+ import Big from "big.js";
3071
+
3072
+ // src/core/setupBTCWallet/state.ts
3073
+ var STORAGE_KEYS = {
3074
+ ACCOUNT: "btc-wallet-account",
3075
+ PUBLIC_KEY: "btc-wallet-publickey",
3076
+ BTC_PUBLIC_KEY: "btc-wallet-btc-publickey"
3077
+ };
3078
+ var state_default = {
3079
+ saveAccount(account) {
3080
+ if (!account) {
3081
+ this.removeAccount();
3082
+ return;
3083
+ }
3084
+ window.localStorage.setItem(STORAGE_KEYS.ACCOUNT, account);
3085
+ },
3086
+ removeAccount() {
3087
+ window.localStorage.removeItem(STORAGE_KEYS.ACCOUNT);
3088
+ },
3089
+ savePublicKey(publicKey) {
3090
+ if (!publicKey) {
3091
+ this.removePublicKey();
3092
+ return;
3093
+ }
3094
+ window.localStorage.setItem(STORAGE_KEYS.PUBLIC_KEY, publicKey);
3095
+ },
3096
+ removePublicKey() {
3097
+ window.localStorage.removeItem(STORAGE_KEYS.PUBLIC_KEY);
3098
+ },
3099
+ saveBtcPublicKey(publicKey) {
3100
+ if (!publicKey) {
3101
+ this.removeBtcPublicKey();
3102
+ return;
3103
+ }
3104
+ window.localStorage.setItem(STORAGE_KEYS.BTC_PUBLIC_KEY, publicKey);
3105
+ },
3106
+ removeBtcPublicKey() {
3107
+ window.localStorage.removeItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
3108
+ },
3109
+ clear() {
3110
+ this.removeAccount();
3111
+ this.removePublicKey();
3112
+ this.removeBtcPublicKey();
3113
+ },
3114
+ save(account, publicKey) {
3115
+ if (!account || !publicKey) {
3116
+ this.clear();
3117
+ return;
3118
+ }
3119
+ this.saveAccount(account);
3120
+ this.savePublicKey(publicKey);
3121
+ },
3122
+ getAccount() {
3123
+ return window.localStorage.getItem(STORAGE_KEYS.ACCOUNT) || "";
3124
+ },
3125
+ getPublicKey() {
3126
+ return window.localStorage.getItem(STORAGE_KEYS.PUBLIC_KEY) || "";
3127
+ },
3128
+ getBtcPublicKey() {
3129
+ return window.localStorage.getItem(STORAGE_KEYS.BTC_PUBLIC_KEY) || "";
3130
+ },
3131
+ isValid() {
3132
+ const account = this.getAccount();
3133
+ const publicKey = this.getPublicKey();
3134
+ const btcPublicKey = this.getBtcPublicKey();
3135
+ const allEmpty = !account && !publicKey && !btcPublicKey;
3136
+ const allExist = account && publicKey && btcPublicKey;
3137
+ return allEmpty || allExist;
3138
+ },
3139
+ syncSave(account, publicKey, btcPublicKey) {
3140
+ if (!account || !publicKey || !btcPublicKey) {
3141
+ this.clear();
3142
+ return;
3143
+ }
3144
+ this.clear();
3145
+ this.savePublicKey(publicKey);
3146
+ this.saveBtcPublicKey(btcPublicKey);
3147
+ this.saveAccount(account);
3148
+ }
3149
+ };
3150
+
3064
3151
  // src/utils/satoshi.ts
3065
3152
  function getNonce(url, accountId) {
3066
3153
  return __async(this, null, function* () {
@@ -3176,52 +3263,17 @@ function getWhitelist(url) {
3176
3263
  return data;
3177
3264
  });
3178
3265
  }
3179
-
3180
- // src/core/btcUtils.ts
3181
- import bitcoin from "bitcoinjs-lib";
3182
- import * as ecc from "@bitcoinerlab/secp256k1";
3183
- import coinselect from "coinselect";
3184
- bitcoin.initEccLib(ecc);
3185
- var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
3186
- var NBTC_STORAGE_DEPOSIT_AMOUNT = "3000";
3187
- var GAS_LIMIT = "50000000000000";
3188
- var NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT = "1000";
3189
- function getBtcProvider() {
3190
- if (typeof window === "undefined" || !window.btcContext) {
3191
- throw new Error("BTC Provider is not initialized.");
3192
- }
3193
- return window.btcContext;
3194
- }
3195
- function getNetwork() {
3196
- return __async(this, null, function* () {
3197
- const network = yield getBtcProvider().getNetwork();
3198
- console.log("btc network:", network);
3199
- return network === "livenet" ? "mainnet" : "testnet";
3200
- });
3201
- }
3202
- function getBtcRpcUrl() {
3203
- return __async(this, null, function* () {
3204
- const network = yield getNetwork();
3205
- return btcRpcUrls[network];
3206
- });
3207
- }
3208
- function getConfig(env) {
3209
- return __async(this, null, function* () {
3210
- return walletConfig[env];
3211
- });
3212
- }
3213
- function nearCall(contractId, methodName, args) {
3214
- return __async(this, null, function* () {
3215
- const network = yield getNetwork();
3216
- return nearCallFunction(contractId, methodName, args, { network });
3217
- });
3218
- }
3219
3266
  function getAccountInfo(_0) {
3220
3267
  return __async(this, arguments, function* ({ csna, env }) {
3221
- const config = yield getConfig(env);
3222
- const accountInfo = yield nearCall(config.accountContractId, "get_account", {
3223
- account_id: csna
3224
- }).catch((error) => {
3268
+ const config = getWalletConfig(env);
3269
+ const accountInfo = yield nearCallFunction(
3270
+ config.accountContractId,
3271
+ "get_account",
3272
+ {
3273
+ account_id: csna
3274
+ },
3275
+ { network: config.network }
3276
+ ).catch((error) => {
3225
3277
  return void 0;
3226
3278
  });
3227
3279
  console.log("get_account accountInfo:", accountInfo);
@@ -3234,9 +3286,8 @@ function getTokenBalance(_0) {
3234
3286
  tokenId,
3235
3287
  env
3236
3288
  }) {
3237
- const network = yield getNetwork();
3238
- const config = yield getConfig(env);
3239
- const nearProvider = getNearProvider({ network });
3289
+ const config = getWalletConfig(env);
3290
+ const nearProvider = getNearProvider({ network: config.network });
3240
3291
  try {
3241
3292
  if (tokenId === config.nearToken) {
3242
3293
  const nearAccount = yield nearProvider.query({
@@ -3247,8 +3298,18 @@ function getTokenBalance(_0) {
3247
3298
  const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
3248
3299
  return { balance, rawBalance: nearAccount.amount };
3249
3300
  } else {
3250
- const res = yield nearCall(tokenId, "ft_balance_of", { account_id: csna });
3251
- const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCall(tokenId, "ft_metadata", {})).decimals;
3301
+ const res = yield nearCallFunction(
3302
+ tokenId,
3303
+ "ft_balance_of",
3304
+ { account_id: csna },
3305
+ { network: config.network }
3306
+ );
3307
+ const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCallFunction(
3308
+ tokenId,
3309
+ "ft_metadata",
3310
+ {},
3311
+ { network: config.network }
3312
+ )).decimals;
3252
3313
  const balance = parseFloat(res) / __pow(10, decimals);
3253
3314
  return { balance, rawBalance: res };
3254
3315
  }
@@ -3260,7 +3321,7 @@ function getTokenBalance(_0) {
3260
3321
  }
3261
3322
  function checkGasTokenBalance(csna, minAmount, env) {
3262
3323
  return __async(this, null, function* () {
3263
- const config = yield getConfig(env);
3324
+ const config = getWalletConfig(env);
3264
3325
  const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
3265
3326
  console.log("gas token balance:", rawBalance);
3266
3327
  if (new Big(rawBalance).lt(minAmount)) {
@@ -3273,16 +3334,308 @@ function checkGasTokenBalance(csna, minAmount, env) {
3273
3334
  }
3274
3335
  });
3275
3336
  }
3276
- function checkGasTokenDebt(accountInfo, env, autoDeposit) {
3337
+ var { functionCall, transfer } = actionCreators;
3338
+ function convertTransactionToTxHex(_0) {
3339
+ return __async(this, arguments, function* ({
3340
+ transaction,
3341
+ accountId,
3342
+ publicKey,
3343
+ env,
3344
+ index = 0
3345
+ }) {
3346
+ const publicKeyFormat = PublicKey.from(publicKey);
3347
+ const currentConfig = getWalletConfig(env);
3348
+ const provider = getNearProvider({ network: currentConfig.network });
3349
+ const { header } = yield provider.block({
3350
+ finality: "final"
3351
+ });
3352
+ const rawAccessKey = yield provider.query({
3353
+ request_type: "view_access_key",
3354
+ account_id: accountId,
3355
+ public_key: publicKey,
3356
+ finality: "final"
3357
+ }).catch((e) => {
3358
+ console.log("view_access_key error:", e);
3359
+ return void 0;
3360
+ });
3361
+ const accessKey = __spreadProps(__spreadValues({}, rawAccessKey), {
3362
+ nonce: BigInt((rawAccessKey == null ? void 0 : rawAccessKey.nonce) || 0)
3363
+ });
3364
+ const nearNonceFromApi = yield getNearNonce(currentConfig.base_url, accountId);
3365
+ let nearNonceNumber = accessKey.nonce + BigInt(1);
3366
+ if (nearNonceFromApi) {
3367
+ nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
3368
+ }
3369
+ const newActions = transaction.actions.map((action) => {
3370
+ switch (action.type) {
3371
+ case "FunctionCall":
3372
+ return functionCall(
3373
+ action.params.methodName,
3374
+ action.params.args,
3375
+ BigInt(action.params.gas),
3376
+ BigInt(action.params.deposit)
3377
+ );
3378
+ case "Transfer":
3379
+ return transfer(BigInt(action.params.deposit));
3380
+ }
3381
+ }).filter(Boolean);
3382
+ const _transaction = transactions.createTransaction(
3383
+ accountId,
3384
+ publicKeyFormat,
3385
+ transaction.receiverId,
3386
+ BigInt(nearNonceNumber) + BigInt(index),
3387
+ newActions,
3388
+ baseDecode(header.hash)
3389
+ );
3390
+ const txBytes = encodeTransaction(_transaction);
3391
+ const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
3392
+ ""
3393
+ );
3394
+ const hash = bs58.encode(new Uint8Array(sha256.array(txBytes)));
3395
+ return { txBytes, txHex, hash };
3396
+ });
3397
+ }
3398
+ function calculateGasLimit(params) {
3399
+ return __async(this, null, function* () {
3400
+ const trans = [...params.transactions];
3401
+ console.log("raw trans:", trans);
3402
+ const { gasLimit } = yield calculateGasStrategy(params);
3403
+ return gasLimit;
3404
+ });
3405
+ }
3406
+ function calculateGasStrategy(_0) {
3407
+ return __async(this, arguments, function* ({
3408
+ csna,
3409
+ transactions: transactions2,
3410
+ env
3411
+ }) {
3412
+ var _a;
3413
+ const currentConfig = getWalletConfig(env);
3414
+ const accountInfo = yield getAccountInfo({ csna, env });
3415
+ const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
3416
+ const { balance: nearBalance } = yield getTokenBalance({
3417
+ csna,
3418
+ tokenId: currentConfig.nearToken,
3419
+ env
3420
+ });
3421
+ const transferAmount = transactions2.reduce(
3422
+ (acc, tx) => {
3423
+ tx.actions.forEach((action) => {
3424
+ if (action.params.deposit) {
3425
+ const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
3426
+ console.log("near deposit amount:", amount);
3427
+ acc.near = acc.near.plus(amount);
3428
+ }
3429
+ if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
3430
+ const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
3431
+ console.log("btc transfer amount:", amount);
3432
+ acc.btc = acc.btc.plus(amount);
3433
+ }
3434
+ });
3435
+ return acc;
3436
+ },
3437
+ { near: new Big(0), btc: new Big(0) }
3438
+ );
3439
+ const nearAvailableBalance = new Big(nearBalance).minus(transferAmount.near).toNumber();
3440
+ console.log("available near balance:", nearAvailableBalance);
3441
+ console.log("available gas token balance:", gasTokenBalance);
3442
+ const convertTx = yield Promise.all(
3443
+ transactions2.map(
3444
+ (transaction, index) => convertTransactionToTxHex({
3445
+ transaction,
3446
+ accountId: state_default.getAccount(),
3447
+ publicKey: state_default.getPublicKey(),
3448
+ index,
3449
+ env
3450
+ })
3451
+ )
3452
+ );
3453
+ if (nearAvailableBalance > 0.5) {
3454
+ console.log("near balance is enough, get the protocol fee of each transaction");
3455
+ const gasTokens = yield nearCallFunction(
3456
+ currentConfig.accountContractId,
3457
+ "list_gas_token",
3458
+ { token_ids: [currentConfig.btcToken] },
3459
+ { network: currentConfig.network }
3460
+ );
3461
+ console.log("list_gas_token gas tokens:", gasTokens);
3462
+ const perTxFee = Math.max(
3463
+ Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
3464
+ 100
3465
+ );
3466
+ console.log("perTxFee:", perTxFee);
3467
+ const protocolFee = new Big(perTxFee || "0").mul(convertTx.length).toFixed(0);
3468
+ console.log("protocolFee:", protocolFee);
3469
+ if (new Big(gasTokenBalance).gte(protocolFee)) {
3470
+ console.log("use near pay gas and enough gas token balance");
3471
+ return { useNearPayGas: true, gasLimit: protocolFee };
3472
+ } else {
3473
+ console.log("use near pay gas and not enough gas token balance");
3474
+ const transferTx = yield createGasTokenTransfer({ csna, amount: protocolFee, env });
3475
+ return recalculateGasWithTransfer({
3476
+ csna,
3477
+ transferTx,
3478
+ transactions: convertTx,
3479
+ useNearPayGas: true,
3480
+ perTxFee: perTxFee.toString(),
3481
+ env
3482
+ });
3483
+ }
3484
+ } else {
3485
+ console.log("near balance is not enough, predict the gas token amount required");
3486
+ const adjustedGas = yield getPredictedGasAmount({
3487
+ accountContractId: currentConfig.accountContractId,
3488
+ tokenId: currentConfig.btcToken,
3489
+ transactions: convertTx.map((t) => t.txHex),
3490
+ env
3491
+ });
3492
+ if (new Big(gasTokenBalance).gte(adjustedGas)) {
3493
+ console.log("use gas token and gas token balance is enough");
3494
+ return { useNearPayGas: false, gasLimit: adjustedGas };
3495
+ } else {
3496
+ console.log("use gas token and gas token balance is not enough, need to transfer");
3497
+ const transferTx = yield createGasTokenTransfer({ csna, amount: adjustedGas, env });
3498
+ return recalculateGasWithTransfer({
3499
+ csna,
3500
+ transferTx,
3501
+ transactions: convertTx,
3502
+ useNearPayGas: false,
3503
+ env
3504
+ });
3505
+ }
3506
+ }
3507
+ });
3508
+ }
3509
+ function createGasTokenTransfer(_0) {
3510
+ return __async(this, arguments, function* ({
3511
+ csna,
3512
+ amount,
3513
+ env
3514
+ }) {
3515
+ const currentConfig = getWalletConfig(env);
3516
+ return {
3517
+ signerId: csna,
3518
+ receiverId: currentConfig.btcToken,
3519
+ actions: [
3520
+ {
3521
+ type: "FunctionCall",
3522
+ params: {
3523
+ methodName: "ft_transfer_call",
3524
+ args: {
3525
+ receiver_id: currentConfig.accountContractId,
3526
+ amount,
3527
+ msg: JSON.stringify("Repay")
3528
+ },
3529
+ gas: new Big(50).mul(__pow(10, 12)).toFixed(0),
3530
+ deposit: "1"
3531
+ }
3532
+ }
3533
+ ]
3534
+ };
3535
+ });
3536
+ }
3537
+ function recalculateGasWithTransfer(_0) {
3538
+ return __async(this, arguments, function* ({
3539
+ csna,
3540
+ transferTx,
3541
+ transactions: transactions2,
3542
+ useNearPayGas,
3543
+ perTxFee,
3544
+ env
3545
+ }) {
3546
+ const currentConfig = getWalletConfig(env);
3547
+ const { txHex: transferTxHex } = yield convertTransactionToTxHex({
3548
+ transaction: transferTx,
3549
+ accountId: state_default.getAccount(),
3550
+ publicKey: state_default.getPublicKey(),
3551
+ index: 0,
3552
+ env
3553
+ });
3554
+ let newGasLimit;
3555
+ if (useNearPayGas && perTxFee) {
3556
+ newGasLimit = new Big(perTxFee).mul(transactions2.length + 1).toFixed(0);
3557
+ } else {
3558
+ newGasLimit = yield getPredictedGasAmount({
3559
+ accountContractId: currentConfig.accountContractId,
3560
+ tokenId: currentConfig.btcToken,
3561
+ transactions: [transferTxHex, ...transactions2.map((t) => t.txHex)],
3562
+ env
3563
+ });
3564
+ }
3565
+ transferTx.actions[0].params.args.amount = newGasLimit;
3566
+ return { transferGasTransaction: transferTx, useNearPayGas, gasLimit: newGasLimit };
3567
+ });
3568
+ }
3569
+ function getPredictedGasAmount(_0) {
3570
+ return __async(this, arguments, function* ({
3571
+ accountContractId,
3572
+ tokenId,
3573
+ transactions: transactions2,
3574
+ env
3575
+ }) {
3576
+ const currentConfig = getWalletConfig(env);
3577
+ const predictedGas = yield nearCallFunction(
3578
+ accountContractId,
3579
+ "predict_txs_gas_token_amount",
3580
+ {
3581
+ gas_token_id: tokenId,
3582
+ near_transactions: transactions2
3583
+ },
3584
+ { network: currentConfig.network }
3585
+ );
3586
+ const predictedGasAmount = new Big(predictedGas).mul(1.2).toFixed(0);
3587
+ const miniGasAmount = 200 * transactions2.length;
3588
+ const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
3589
+ console.log("predictedGas:", predictedGasAmount);
3590
+ return gasAmount.toString();
3591
+ });
3592
+ }
3593
+
3594
+ // src/core/btcUtils.ts
3595
+ import bitcoin from "bitcoinjs-lib";
3596
+ import * as ecc from "@bitcoinerlab/secp256k1";
3597
+ import coinselect from "coinselect";
3598
+ bitcoin.initEccLib(ecc);
3599
+ var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
3600
+ var NBTC_STORAGE_DEPOSIT_AMOUNT = "3000";
3601
+ var GAS_LIMIT = "50000000000000";
3602
+ var NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT = "1000";
3603
+ function getBtcProvider() {
3604
+ if (typeof window === "undefined" || !window.btcContext) {
3605
+ throw new Error("BTC Provider is not initialized.");
3606
+ }
3607
+ return window.btcContext;
3608
+ }
3609
+ function getNetwork() {
3610
+ return __async(this, null, function* () {
3611
+ const network = yield getBtcProvider().getNetwork();
3612
+ console.log("btc network:", network);
3613
+ return network === "livenet" ? "mainnet" : "testnet";
3614
+ });
3615
+ }
3616
+ function getBtcRpcUrl() {
3617
+ return __async(this, null, function* () {
3618
+ const network = yield getNetwork();
3619
+ return btcRpcUrls[network];
3620
+ });
3621
+ }
3622
+ function nearCall(contractId, methodName, args) {
3623
+ return __async(this, null, function* () {
3624
+ const network = yield getNetwork();
3625
+ return nearCallFunction(contractId, methodName, args, { network });
3626
+ });
3627
+ }
3628
+ function checkGasTokenDebt(csna, env, autoDeposit) {
3277
3629
  return __async(this, null, function* () {
3278
3630
  var _a, _b, _c;
3279
- const debtAmount = new Big(((_a = accountInfo == null ? void 0 : accountInfo.debt_info) == null ? void 0 : _a.near_gas_debt_amount) || 0).plus(((_b = accountInfo == null ? void 0 : accountInfo.debt_info) == null ? void 0 : _b.protocol_fee_debt_amount) || 0).toString();
3631
+ const accountInfo = yield getAccountInfo({ csna, env });
3632
+ const debtAmount = new Big2(((_a = accountInfo == null ? void 0 : accountInfo.debt_info) == null ? void 0 : _a.near_gas_debt_amount) || 0).plus(((_b = accountInfo == null ? void 0 : accountInfo.debt_info) == null ? void 0 : _b.protocol_fee_debt_amount) || 0).toString();
3280
3633
  const relayerFeeAmount = !(accountInfo == null ? void 0 : accountInfo.nonce) ? NBTC_STORAGE_DEPOSIT_AMOUNT : ((_c = accountInfo == null ? void 0 : accountInfo.relayer_fee) == null ? void 0 : _c.amount) || 0;
3281
- const hasDebtArrears = new Big(debtAmount).gt(0);
3282
- const hasRelayerFeeArrears = new Big(relayerFeeAmount).gt(0);
3634
+ const hasDebtArrears = new Big2(debtAmount).gt(0);
3635
+ const hasRelayerFeeArrears = new Big2(relayerFeeAmount).gt(0);
3283
3636
  if (!hasDebtArrears && !hasRelayerFeeArrears)
3284
3637
  return;
3285
- const config = yield getConfig(env);
3638
+ const config = getWalletConfig(env);
3286
3639
  const transferAmount = hasDebtArrears ? debtAmount : relayerFeeAmount;
3287
3640
  const action = {
3288
3641
  receiver_id: config.accountContractId,
@@ -3340,7 +3693,7 @@ function getBtcBalance() {
3340
3693
  const estimatedFee = Math.ceil(estimatedTxSize * feeRate);
3341
3694
  console.log("estimatedFee:", estimatedFee);
3342
3695
  const availableRawBalance = (rawBalance - estimatedFee).toFixed(0);
3343
- const availableBalance = new Big(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, Big.roundDown).toNumber();
3696
+ const availableBalance = new Big2(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, Big2.roundDown).toNumber();
3344
3697
  return {
3345
3698
  rawBalance,
3346
3699
  balance,
@@ -3365,10 +3718,10 @@ function getDepositAmount(amount, option) {
3365
3718
  var _a;
3366
3719
  const env = (option == null ? void 0 : option.env) || "mainnet";
3367
3720
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3368
- const config = yield getConfig(env);
3721
+ const config = getWalletConfig(env);
3369
3722
  const csna = yield getCsnaAccountId(env);
3370
3723
  const accountInfo = yield getAccountInfo({ csna, env });
3371
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3724
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3372
3725
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
3373
3726
  const {
3374
3727
  deposit_bridge_fee: { fee_min, fee_rate },
@@ -3377,7 +3730,7 @@ function getDepositAmount(amount, option) {
3377
3730
  const depositAmount = Math.max(Number(min_deposit_amount), Number(amount));
3378
3731
  const protocolFee = Math.max(Number(fee_min), Number(depositAmount) * fee_rate);
3379
3732
  const newAccountMinDepositAmount = !(accountInfo == null ? void 0 : accountInfo.nonce) && _newAccountMinDepositAmount ? NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT : 0;
3380
- const totalDepositAmount = new Big(depositAmount).plus(protocolFee).plus(repayAmount).plus(newAccountMinDepositAmount).round(0, Big.roundDown).toNumber();
3733
+ const totalDepositAmount = new Big2(depositAmount).plus(protocolFee).plus(repayAmount).plus(newAccountMinDepositAmount).round(0, Big2.roundDown).toNumber();
3381
3734
  return {
3382
3735
  depositAmount,
3383
3736
  totalDepositAmount,
@@ -3389,7 +3742,7 @@ function getDepositAmount(amount, option) {
3389
3742
  }
3390
3743
  function getCsnaAccountId(env) {
3391
3744
  return __async(this, null, function* () {
3392
- const config = yield getConfig(env);
3745
+ const config = getWalletConfig(env);
3393
3746
  const { getPublicKey } = getBtcProvider();
3394
3747
  const btcPublicKey = yield getPublicKey();
3395
3748
  if (!btcPublicKey) {
@@ -3427,9 +3780,10 @@ function executeBTCDepositAndAction(_0) {
3427
3780
  }) {
3428
3781
  var _a;
3429
3782
  try {
3783
+ console.log("executeBTCDepositAndAction start", amount);
3430
3784
  checkDepositDisabledAddress();
3431
3785
  const { getPublicKey } = getBtcProvider();
3432
- const config = yield getConfig(env);
3786
+ const config = getWalletConfig(env);
3433
3787
  const btcPublicKey = yield getPublicKey();
3434
3788
  if (!btcPublicKey) {
3435
3789
  throw new Error("BTC Public Key is not available.");
@@ -3439,7 +3793,7 @@ function executeBTCDepositAndAction(_0) {
3439
3793
  }
3440
3794
  const csna = yield getCsnaAccountId(env);
3441
3795
  const depositAmount = (_a = action ? action.amount : amount) != null ? _a : "0";
3442
- if (new Big(depositAmount).lt(0)) {
3796
+ if (new Big2(depositAmount).lt(0)) {
3443
3797
  throw new Error("amount must be greater than 0");
3444
3798
  }
3445
3799
  const { totalDepositAmount, protocolFee, repayAmount } = yield getDepositAmount(depositAmount, {
@@ -3448,7 +3802,7 @@ function executeBTCDepositAndAction(_0) {
3448
3802
  });
3449
3803
  const accountInfo = yield getAccountInfo({ csna, env });
3450
3804
  const newActions = [];
3451
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3805
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3452
3806
  if (debtAction) {
3453
3807
  newActions.push(__spreadProps(__spreadValues({}, debtAction), {
3454
3808
  gas: GAS_LIMIT
@@ -3460,12 +3814,17 @@ function executeBTCDepositAndAction(_0) {
3460
3814
  }));
3461
3815
  }
3462
3816
  const storageDepositMsg = {};
3463
- const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.btcToken, "storage_balance_of", {
3817
+ const registerContractId = ((action == null ? void 0 : action.receiver_id) || config.btcToken).replace(
3818
+ config.accountContractId,
3819
+ config.btcToken
3820
+ );
3821
+ console.log("executeBTCDepositAndAction registerContractId", registerContractId);
3822
+ const registerRes = yield nearCall(registerContractId, "storage_balance_of", {
3464
3823
  account_id: csna
3465
3824
  });
3466
3825
  if (!(registerRes == null ? void 0 : registerRes.available)) {
3467
3826
  storageDepositMsg.storage_deposit_msg = {
3468
- contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
3827
+ contract_id: registerContractId,
3469
3828
  deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
3470
3829
  registration_only: true
3471
3830
  };
@@ -3536,7 +3895,7 @@ function checkSatoshiWhitelist(btcAccountId, env = "mainnet") {
3536
3895
  }
3537
3896
  if (!btcAccountId)
3538
3897
  return;
3539
- const config = yield getConfig(env);
3898
+ const config = getWalletConfig(env);
3540
3899
  const whitelist = yield getWhitelist(config.base_url);
3541
3900
  if (!(whitelist == null ? void 0 : whitelist.length))
3542
3901
  return;
@@ -3559,9 +3918,11 @@ function getWithdrawTransaction(_0) {
3559
3918
  feeRate,
3560
3919
  env = "mainnet"
3561
3920
  }) {
3921
+ console.log("=== Start getWithdrawTransaction ===");
3562
3922
  const provider = getBtcProvider();
3563
3923
  const btcAddress = provider.account;
3564
- const config = yield getConfig(env);
3924
+ const config = getWalletConfig(env);
3925
+ const csna = yield getCsnaAccountId(env);
3565
3926
  const brgConfig = yield nearCall(config.bridgeContractId, "get_config", {});
3566
3927
  if (brgConfig.min_withdraw_amount) {
3567
3928
  if (Number(amount) < Number(brgConfig.min_withdraw_amount)) {
@@ -3570,7 +3931,39 @@ function getWithdrawTransaction(_0) {
3570
3931
  }
3571
3932
  const feePercent = Number(brgConfig.withdraw_bridge_fee.fee_rate) * Number(amount);
3572
3933
  const withdrawFee = feePercent > Number(brgConfig.withdraw_bridge_fee.fee_min) ? feePercent : Number(brgConfig.withdraw_bridge_fee.fee_min);
3934
+ console.log("Withdrawal Fee:", {
3935
+ feePercent,
3936
+ withdrawFee,
3937
+ minFee: brgConfig.withdraw_bridge_fee.fee_min
3938
+ });
3939
+ const gasLimit = yield calculateGasLimit({
3940
+ csna,
3941
+ transactions: [
3942
+ {
3943
+ signerId: "",
3944
+ receiverId: config.btcToken,
3945
+ actions: [
3946
+ {
3947
+ type: "FunctionCall",
3948
+ params: {
3949
+ methodName: "ft_transfer_call",
3950
+ args: {
3951
+ receiver_id: config.btcToken,
3952
+ amount: "100",
3953
+ msg: ""
3954
+ },
3955
+ gas: "300000000000000",
3956
+ deposit: "1"
3957
+ }
3958
+ }
3959
+ ]
3960
+ }
3961
+ ],
3962
+ env
3963
+ });
3964
+ const finalAmount = Number(gasLimit) > 0 ? Number(amount) - Number(gasLimit) : Number(amount);
3573
3965
  const allUTXO = yield nearCall(config.bridgeContractId, "get_utxos_paged", {});
3966
+ console.log("All UTXOs:", allUTXO);
3574
3967
  if (!allUTXO || Object.keys(allUTXO).length === 0) {
3575
3968
  throw new Error("The network is busy, please try again later.");
3576
3969
  }
@@ -3583,42 +3976,48 @@ function getWithdrawTransaction(_0) {
3583
3976
  script: allUTXO[key].script
3584
3977
  };
3585
3978
  });
3979
+ console.log("Formatted UTXOs:", utxos);
3586
3980
  const _feeRate = feeRate || (yield getBtcGasPrice());
3587
- let { inputs, outputs, fee } = coinselect(
3981
+ console.log("Fee Rate:", _feeRate);
3982
+ const coinSelectResult = coinselect(
3588
3983
  utxos,
3589
- [{ address: btcAddress, value: Number(amount) }],
3984
+ [{ address: btcAddress, value: Number(finalAmount) }],
3590
3985
  Math.ceil(_feeRate)
3591
3986
  );
3987
+ console.log("Coinselect Result:", coinSelectResult);
3988
+ const { inputs, outputs, fee } = coinSelectResult;
3592
3989
  if (!outputs || !inputs) {
3593
3990
  throw new Error("The network is busy, please try again later.");
3594
3991
  }
3595
3992
  const maxBtcFee = Number(brgConfig.max_btc_gas_fee);
3596
3993
  const transactionFee = fee;
3597
- const changeAddress = brgConfig.change_address;
3994
+ console.log("Transaction Fee:", { transactionFee, maxBtcFee });
3598
3995
  if (transactionFee > maxBtcFee) {
3599
3996
  throw new Error("Gas exceeds maximum value");
3600
3997
  }
3601
3998
  let recipientOutput, changeOutput;
3602
3999
  for (let i = 0; i < outputs.length; i++) {
3603
4000
  const output = outputs[i];
3604
- if (output.value.toString() === amount.toString()) {
4001
+ if (output.value.toString() === finalAmount.toString()) {
3605
4002
  recipientOutput = output;
3606
4003
  } else {
3607
4004
  changeOutput = output;
3608
4005
  }
3609
4006
  if (!output.address) {
3610
- output.address = changeAddress;
4007
+ output.address = brgConfig.change_address;
3611
4008
  }
3612
4009
  }
3613
- recipientOutput.value = new Big(recipientOutput.value).minus(transactionFee).minus(withdrawFee).toNumber();
4010
+ console.log("Initial Outputs:", { recipientOutput, changeOutput });
4011
+ recipientOutput.value = new Big2(recipientOutput.value).minus(transactionFee).minus(withdrawFee).toNumber();
3614
4012
  if (changeOutput) {
3615
- changeOutput.value = new Big(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
4013
+ changeOutput.value = new Big2(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
3616
4014
  const remainingInputs = [...inputs];
3617
4015
  let smallestInput = Math.min.apply(
3618
4016
  null,
3619
4017
  remainingInputs.map((input) => input.value)
3620
4018
  );
3621
4019
  let remainingChangeAmount = changeOutput.value;
4020
+ console.log("Initial Change Processing:", { smallestInput, remainingChangeAmount });
3622
4021
  while (remainingChangeAmount >= smallestInput && smallestInput > 0 && remainingInputs.length > 0) {
3623
4022
  remainingChangeAmount -= smallestInput;
3624
4023
  changeOutput.value = remainingChangeAmount;
@@ -3632,30 +4031,50 @@ function getWithdrawTransaction(_0) {
3632
4031
  null,
3633
4032
  remainingInputs.map((input) => input.value)
3634
4033
  );
4034
+ console.log("Change Processing Loop:", {
4035
+ remainingChangeAmount,
4036
+ smallestInput,
4037
+ remainingInputsCount: remainingInputs.length
4038
+ });
3635
4039
  }
3636
4040
  const minChangeAmount = Number(brgConfig.min_change_amount);
3637
4041
  let additionalFee = 0;
4042
+ console.log("Checking minimum change amount:", {
4043
+ changeValue: changeOutput.value,
4044
+ minChangeAmount
4045
+ });
4046
+ let finalOutputs = [...outputs];
3638
4047
  if (changeOutput.value === 0) {
3639
- outputs = outputs.filter((item) => item.value !== 0);
4048
+ finalOutputs = finalOutputs.filter((output) => output.value !== 0);
4049
+ console.log("Removed zero-value change output", finalOutputs);
3640
4050
  } else if (changeOutput.value < minChangeAmount) {
3641
4051
  additionalFee = minChangeAmount - changeOutput.value;
3642
4052
  recipientOutput.value -= additionalFee;
3643
4053
  changeOutput.value = minChangeAmount;
4054
+ console.log("Adjusted for minimum change amount:", {
4055
+ additionalFee,
4056
+ newRecipientValue: recipientOutput.value,
4057
+ newChangeValue: changeOutput.value
4058
+ });
3644
4059
  }
3645
4060
  } else {
3646
4061
  changeOutput = {
3647
- address: changeAddress,
3648
- value: new Big(transactionFee).plus(withdrawFee).toNumber()
4062
+ address: brgConfig.change_address,
4063
+ value: new Big2(transactionFee).plus(withdrawFee).toNumber()
3649
4064
  };
3650
4065
  outputs.push(changeOutput);
4066
+ console.log("Created new change output:", changeOutput);
3651
4067
  }
3652
4068
  const insufficientOutput = outputs.some((item) => item.value < 0);
3653
4069
  if (insufficientOutput) {
4070
+ console.error("Negative output value detected");
3654
4071
  throw new Error("Not enough gas");
3655
4072
  }
3656
4073
  const inputSum = inputs.reduce((sum, cur) => sum + Number(cur.value), 0);
3657
4074
  const outputSum = outputs.reduce((sum, cur) => sum + Number(cur.value), 0);
4075
+ console.log("Balance verification:", { inputSum, outputSum, transactionFee });
3658
4076
  if (transactionFee + outputSum !== inputSum) {
4077
+ console.error("Balance mismatch:", { inputSum, outputSum, transactionFee });
3659
4078
  throw new Error("compute error");
3660
4079
  }
3661
4080
  const network = yield getNetwork();
@@ -3682,6 +4101,7 @@ function getWithdrawTransaction(_0) {
3682
4101
  value: output.value
3683
4102
  });
3684
4103
  });
4104
+ console.log("outputs:", JSON.stringify(outputs));
3685
4105
  const _inputs = inputs.map((item) => {
3686
4106
  return `${item.txid}:${item.vout}`;
3687
4107
  });
@@ -3698,7 +4118,6 @@ function getWithdrawTransaction(_0) {
3698
4118
  output: txOutputs
3699
4119
  }
3700
4120
  };
3701
- const csna = yield getCsnaAccountId(env);
3702
4121
  const transaction = {
3703
4122
  receiverId: config.btcToken,
3704
4123
  signerId: csna,
@@ -3718,6 +4137,7 @@ function getWithdrawTransaction(_0) {
3718
4137
  }
3719
4138
  ]
3720
4139
  };
4140
+ console.log("=== End getWithdrawTransaction ===");
3721
4141
  return transaction;
3722
4142
  });
3723
4143
  }
@@ -3958,86 +4378,7 @@ function updateIframePosition(iframe, buttonRight, buttonBottom, windowWidth, wi
3958
4378
  iframe.style.bottom = `${iframeBottom}px`;
3959
4379
  }
3960
4380
 
3961
- // src/core/setupBTCWallet.ts
3962
- import Big2 from "big.js";
3963
- var { transfer, functionCall } = actionCreators;
3964
- var STORAGE_KEYS = {
3965
- ACCOUNT: "btc-wallet-account",
3966
- PUBLIC_KEY: "btc-wallet-publickey",
3967
- BTC_PUBLIC_KEY: "btc-wallet-btc-publickey"
3968
- };
3969
- var state = {
3970
- saveAccount(account) {
3971
- if (!account) {
3972
- this.removeAccount();
3973
- return;
3974
- }
3975
- window.localStorage.setItem(STORAGE_KEYS.ACCOUNT, account);
3976
- },
3977
- removeAccount() {
3978
- window.localStorage.removeItem(STORAGE_KEYS.ACCOUNT);
3979
- },
3980
- savePublicKey(publicKey) {
3981
- if (!publicKey) {
3982
- this.removePublicKey();
3983
- return;
3984
- }
3985
- window.localStorage.setItem(STORAGE_KEYS.PUBLIC_KEY, publicKey);
3986
- },
3987
- removePublicKey() {
3988
- window.localStorage.removeItem(STORAGE_KEYS.PUBLIC_KEY);
3989
- },
3990
- saveBtcPublicKey(publicKey) {
3991
- if (!publicKey) {
3992
- this.removeBtcPublicKey();
3993
- return;
3994
- }
3995
- window.localStorage.setItem(STORAGE_KEYS.BTC_PUBLIC_KEY, publicKey);
3996
- },
3997
- removeBtcPublicKey() {
3998
- window.localStorage.removeItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
3999
- },
4000
- clear() {
4001
- this.removeAccount();
4002
- this.removePublicKey();
4003
- this.removeBtcPublicKey();
4004
- },
4005
- save(account, publicKey) {
4006
- if (!account || !publicKey) {
4007
- this.clear();
4008
- return;
4009
- }
4010
- this.saveAccount(account);
4011
- this.savePublicKey(publicKey);
4012
- },
4013
- getAccount() {
4014
- return window.localStorage.getItem(STORAGE_KEYS.ACCOUNT);
4015
- },
4016
- getPublicKey() {
4017
- return window.localStorage.getItem(STORAGE_KEYS.PUBLIC_KEY);
4018
- },
4019
- getBtcPublicKey() {
4020
- return window.localStorage.getItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
4021
- },
4022
- isValid() {
4023
- const account = this.getAccount();
4024
- const publicKey = this.getPublicKey();
4025
- const btcPublicKey = this.getBtcPublicKey();
4026
- const allEmpty = !account && !publicKey && !btcPublicKey;
4027
- const allExist = account && publicKey && btcPublicKey;
4028
- return allEmpty || allExist;
4029
- },
4030
- syncSave(account, publicKey, btcPublicKey) {
4031
- if (!account || !publicKey || !btcPublicKey) {
4032
- this.clear();
4033
- return;
4034
- }
4035
- this.clear();
4036
- this.savePublicKey(publicKey);
4037
- this.saveBtcPublicKey(btcPublicKey);
4038
- this.saveAccount(account);
4039
- }
4040
- };
4381
+ // src/core/setupBTCWallet/index.ts
4041
4382
  var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4042
4383
  metadata,
4043
4384
  options,
@@ -4059,15 +4400,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4059
4400
  calculateGasLimit
4060
4401
  };
4061
4402
  const env = metadata.env || options.network.networkId || "mainnet";
4062
- const currentConfig = walletConfig[env];
4063
- const walletNetwork = ["mainnet", "private_mainnet"].includes(env) ? "mainnet" : "testnet";
4403
+ const currentConfig = getWalletConfig(env);
4064
4404
  yield initBtcContext();
4065
4405
  function validateWalletState() {
4066
- const accountId = state.getAccount();
4067
- const publicKey = state.getPublicKey();
4068
- const btcPublicKey = state.getBtcPublicKey();
4406
+ const accountId = state_default.getAccount();
4407
+ const publicKey = state_default.getPublicKey();
4408
+ const btcPublicKey = state_default.getBtcPublicKey();
4069
4409
  if (!accountId && publicKey || accountId && !publicKey || !publicKey && btcPublicKey) {
4070
- state.clear();
4410
+ state_default.clear();
4071
4411
  return false;
4072
4412
  }
4073
4413
  return true;
@@ -4075,9 +4415,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4075
4415
  function setupBtcContextListeners() {
4076
4416
  return __async(this, null, function* () {
4077
4417
  const handleConnectionUpdate = () => __async(this, null, function* () {
4078
- yield checkBtcNetwork(walletNetwork);
4079
- if (!state.isValid()) {
4080
- state.clear();
4418
+ yield checkBtcNetwork(currentConfig.network);
4419
+ if (!state_default.isValid()) {
4420
+ state_default.clear();
4081
4421
  console.log("setupBtcContextListeners clear");
4082
4422
  }
4083
4423
  validateWalletState();
@@ -4100,7 +4440,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4100
4440
  const context = window.btcContext.getContext();
4101
4441
  context.on("updatePublicKey", (btcPublicKey) => __async(this, null, function* () {
4102
4442
  console.log("updatePublicKey");
4103
- state.clear();
4443
+ state_default.clear();
4104
4444
  console.log("updatePublicKey clear");
4105
4445
  try {
4106
4446
  const { nearAddress, nearPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
@@ -4119,7 +4459,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4119
4459
  }));
4120
4460
  context.on("btcLogOut", () => __async(this, null, function* () {
4121
4461
  console.log("btcLogOut");
4122
- state.clear();
4462
+ state_default.clear();
4123
4463
  emitter.emit("accountsChanged", { accounts: [] });
4124
4464
  yield handleConnectionUpdate();
4125
4465
  }));
@@ -4163,7 +4503,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4163
4503
  "get_chain_signature_near_account_public_key",
4164
4504
  { btc_public_key: btcPublicKey }
4165
4505
  );
4166
- state.syncSave(csna, nearPublicKey, btcPublicKey);
4506
+ state_default.syncSave(csna, nearPublicKey, btcPublicKey);
4167
4507
  return {
4168
4508
  nearAddress: csna,
4169
4509
  nearPublicKey
@@ -4173,8 +4513,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4173
4513
  function signIn(_02) {
4174
4514
  return __async(this, arguments, function* ({ contractId, methodNames }) {
4175
4515
  const btcContext = window.btcContext;
4176
- state.clear();
4177
- if (!state.getAccount() || !state.getPublicKey()) {
4516
+ state_default.clear();
4517
+ if (!state_default.getAccount() || !state_default.getPublicKey()) {
4178
4518
  yield btcContext.login();
4179
4519
  }
4180
4520
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4193,8 +4533,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4193
4533
  }
4194
4534
  function signOut() {
4195
4535
  return __async(this, null, function* () {
4196
- const accountId = state.getAccount();
4197
- const publicKey = state.getPublicKey();
4536
+ const accountId = state_default.getAccount();
4537
+ const publicKey = state_default.getPublicKey();
4198
4538
  if (!(accountId && publicKey)) {
4199
4539
  return;
4200
4540
  }
@@ -4202,19 +4542,19 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4202
4542
  if (metadata.syncLogOut) {
4203
4543
  btcContext.logout();
4204
4544
  }
4205
- state.clear();
4545
+ state_default.clear();
4206
4546
  window.localStorage.removeItem("near-wallet-selector:selectedWalletId");
4207
4547
  removeWalletButton();
4208
4548
  });
4209
4549
  }
4210
4550
  function isSignedIn() {
4211
- const accountId = state.getAccount();
4212
- const publicKey = state.getPublicKey();
4551
+ const accountId = state_default.getAccount();
4552
+ const publicKey = state_default.getPublicKey();
4213
4553
  return accountId && publicKey;
4214
4554
  }
4215
4555
  function getAccounts() {
4216
4556
  return __async(this, null, function* () {
4217
- return [{ accountId: state.getAccount() }];
4557
+ return [{ accountId: state_default.getAccount() }];
4218
4558
  });
4219
4559
  }
4220
4560
  function verifyOwner() {
@@ -4244,12 +4584,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4244
4584
  throw new Error("Wallet state is invalid, please reconnect your wallet.");
4245
4585
  }
4246
4586
  const btcContext = window.btcContext;
4247
- const csna = state.getAccount();
4587
+ const csna = state_default.getAccount();
4248
4588
  const accountInfo = yield getAccountInfo({ csna, env });
4249
- yield checkGasTokenDebt(accountInfo, env, true);
4589
+ yield checkGasTokenDebt(csna, env, true);
4250
4590
  const trans = [...params.transactions];
4251
4591
  console.log("signAndSendTransactions raw trans:", trans);
4252
- const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
4592
+ const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy({
4593
+ csna,
4594
+ transactions: trans,
4595
+ env
4596
+ });
4253
4597
  console.log("transferGasTransaction:", transferGasTransaction);
4254
4598
  console.log("useNearPayGas:", useNearPayGas);
4255
4599
  console.log("gasLimit:", gasLimit);
@@ -4259,7 +4603,15 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4259
4603
  }
4260
4604
  console.log("calculateGasStrategy trans:", trans);
4261
4605
  const newTrans = yield Promise.all(
4262
- trans.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4606
+ trans.map(
4607
+ (transaction, index) => convertTransactionToTxHex({
4608
+ transaction,
4609
+ accountId: state_default.getAccount(),
4610
+ publicKey: state_default.getPublicKey(),
4611
+ index,
4612
+ env
4613
+ })
4614
+ )
4263
4615
  );
4264
4616
  const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
4265
4617
  const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
@@ -4277,7 +4629,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4277
4629
  const signature = yield btcContext.signMessage(strIntention);
4278
4630
  yield receiveTransaction(currentConfig.base_url, {
4279
4631
  sig: signature,
4280
- btcPubKey: state.getBtcPublicKey(),
4632
+ btcPubKey: state_default.getBtcPublicKey(),
4281
4633
  data: toHex(strIntention)
4282
4634
  });
4283
4635
  yield checkBtcTransactionStatus(currentConfig.base_url, signature);
@@ -4287,197 +4639,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4287
4639
  return result;
4288
4640
  });
4289
4641
  }
4290
- function calculateGasLimit(params) {
4291
- return __async(this, null, function* () {
4292
- const trans = [...params.transactions];
4293
- console.log("raw trans:", trans);
4294
- const { gasLimit } = yield calculateGasStrategy(trans);
4295
- return gasLimit;
4296
- });
4297
- }
4298
- function createGasTokenTransfer(accountId, amount) {
4299
- return __async(this, null, function* () {
4300
- return {
4301
- signerId: accountId,
4302
- receiverId: currentConfig.btcToken,
4303
- actions: [
4304
- {
4305
- type: "FunctionCall",
4306
- params: {
4307
- methodName: "ft_transfer_call",
4308
- args: {
4309
- receiver_id: currentConfig.accountContractId,
4310
- amount,
4311
- msg: JSON.stringify("Repay")
4312
- },
4313
- gas: new Big2(50).mul(__pow(10, 12)).toFixed(0),
4314
- deposit: "1"
4315
- }
4316
- }
4317
- ]
4318
- };
4319
- });
4320
- }
4321
- function recalculateGasWithTransfer(transferTx, transactions2, useNearPayGas, perTxFee) {
4322
- return __async(this, null, function* () {
4323
- const { txHex: transferTxHex } = yield convertTransactionToTxHex(transferTx);
4324
- let newGasLimit;
4325
- if (useNearPayGas && perTxFee) {
4326
- newGasLimit = new Big2(perTxFee).mul(transactions2.length + 1).toFixed(0);
4327
- } else {
4328
- newGasLimit = yield getPredictedGasAmount(
4329
- currentConfig.accountContractId,
4330
- currentConfig.btcToken,
4331
- [transferTxHex, ...transactions2.map((t) => t.txHex)]
4332
- );
4333
- }
4334
- transferTx.actions[0].params.args.amount = newGasLimit;
4335
- return { transferGasTransaction: transferTx, useNearPayGas, gasLimit: newGasLimit };
4336
- });
4337
- }
4338
- function getPredictedGasAmount(accountContractId, tokenId, transactions2) {
4339
- return __async(this, null, function* () {
4340
- const predictedGas = yield nearCall2(accountContractId, "predict_txs_gas_token_amount", {
4341
- gas_token_id: tokenId,
4342
- near_transactions: transactions2
4343
- });
4344
- const predictedGasAmount = new Big2(predictedGas).mul(1.2).toFixed(0);
4345
- const miniGasAmount = 200 * transactions2.length;
4346
- const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
4347
- console.log("predictedGas:", predictedGasAmount);
4348
- return gasAmount.toString();
4349
- });
4350
- }
4351
- function calculateGasStrategy(transactions2) {
4352
- return __async(this, null, function* () {
4353
- var _a;
4354
- const accountId = state.getAccount();
4355
- const accountInfo = yield getAccountInfo({ csna: accountId, env });
4356
- const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
4357
- const { balance: nearBalance } = yield getTokenBalance({
4358
- csna: accountId,
4359
- tokenId: currentConfig.nearToken,
4360
- env
4361
- });
4362
- const transferAmount = transactions2.reduce(
4363
- (acc, tx) => {
4364
- tx.actions.forEach((action) => {
4365
- if (action.params.deposit) {
4366
- const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
4367
- console.log("near deposit amount:", amount);
4368
- acc.near = acc.near.plus(amount);
4369
- }
4370
- if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
4371
- const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
4372
- console.log("btc transfer amount:", amount);
4373
- acc.btc = acc.btc.plus(amount);
4374
- }
4375
- });
4376
- return acc;
4377
- },
4378
- { near: new Big2(0), btc: new Big2(0) }
4379
- );
4380
- const nearAvailableBalance = new Big2(nearBalance).minus(transferAmount.near).toNumber();
4381
- console.log("available near balance:", nearAvailableBalance);
4382
- console.log("available gas token balance:", gasTokenBalance);
4383
- const convertTx = yield Promise.all(
4384
- transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4385
- );
4386
- if (nearAvailableBalance > 0.5) {
4387
- console.log("near balance is enough, get the protocol fee of each transaction");
4388
- const gasTokens = yield nearCall2(
4389
- currentConfig.accountContractId,
4390
- "list_gas_token",
4391
- { token_ids: [currentConfig.btcToken] }
4392
- );
4393
- console.log("list_gas_token gas tokens:", gasTokens);
4394
- const perTxFee = Math.max(
4395
- Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
4396
- 100
4397
- );
4398
- console.log("perTxFee:", perTxFee);
4399
- const protocolFee = new Big2(perTxFee || "0").mul(convertTx.length).toFixed(0);
4400
- console.log("protocolFee:", protocolFee);
4401
- if (new Big2(gasTokenBalance).gte(protocolFee)) {
4402
- console.log("use near pay gas and enough gas token balance");
4403
- return { useNearPayGas: true, gasLimit: protocolFee };
4404
- } else {
4405
- console.log("use near pay gas and not enough gas token balance");
4406
- const transferTx = yield createGasTokenTransfer(accountId, protocolFee);
4407
- return recalculateGasWithTransfer(transferTx, convertTx, true, perTxFee.toString());
4408
- }
4409
- } else {
4410
- console.log("near balance is not enough, predict the gas token amount required");
4411
- const adjustedGas = yield getPredictedGasAmount(
4412
- currentConfig.accountContractId,
4413
- currentConfig.btcToken,
4414
- convertTx.map((t) => t.txHex)
4415
- );
4416
- if (new Big2(gasTokenBalance).gte(adjustedGas)) {
4417
- console.log("use gas token and gas token balance is enough");
4418
- return { useNearPayGas: false, gasLimit: adjustedGas };
4419
- } else {
4420
- console.log("use gas token and gas token balance is not enough, need to transfer");
4421
- const transferTx = yield createGasTokenTransfer(accountId, adjustedGas);
4422
- return recalculateGasWithTransfer(transferTx, convertTx, false);
4423
- }
4424
- }
4425
- });
4426
- }
4427
- function convertTransactionToTxHex(transaction, index = 0) {
4428
- return __async(this, null, function* () {
4429
- const accountId = state.getAccount();
4430
- const publicKey = state.getPublicKey();
4431
- const publicKeyFormat = PublicKey.from(publicKey);
4432
- const { header } = yield provider.block({
4433
- finality: "final"
4434
- });
4435
- const rawAccessKey = yield provider.query({
4436
- request_type: "view_access_key",
4437
- account_id: accountId,
4438
- public_key: publicKey,
4439
- finality: "final"
4440
- }).catch((e) => {
4441
- console.log("view_access_key error:", e);
4442
- return void 0;
4443
- });
4444
- const accessKey = __spreadProps(__spreadValues({}, rawAccessKey), {
4445
- nonce: BigInt((rawAccessKey == null ? void 0 : rawAccessKey.nonce) || 0)
4446
- });
4447
- const nearNonceFromApi = yield getNearNonce(currentConfig.base_url, accountId);
4448
- let nearNonceNumber = accessKey.nonce + BigInt(1);
4449
- if (nearNonceFromApi) {
4450
- nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
4451
- }
4452
- const newActions = transaction.actions.map((action) => {
4453
- switch (action.type) {
4454
- case "FunctionCall":
4455
- return functionCall(
4456
- action.params.methodName,
4457
- action.params.args,
4458
- BigInt(action.params.gas),
4459
- BigInt(action.params.deposit)
4460
- );
4461
- case "Transfer":
4462
- return transfer(BigInt(action.params.deposit));
4463
- }
4464
- }).filter(Boolean);
4465
- const _transaction = transactions.createTransaction(
4466
- accountId,
4467
- publicKeyFormat,
4468
- transaction.receiverId,
4469
- BigInt(nearNonceNumber) + BigInt(index),
4470
- newActions,
4471
- baseDecode(header.hash)
4472
- );
4473
- const txBytes = encodeTransaction(_transaction);
4474
- const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
4475
- ""
4476
- );
4477
- const hash = bs58.encode(new Uint8Array(sha256.array(txBytes)));
4478
- return { txBytes, txHex, hash };
4479
- });
4480
- }
4481
4642
  function checkBtcNetwork(network) {
4482
4643
  return __async(this, null, function* () {
4483
4644
  const btcContext = window.btcContext;
@@ -4526,7 +4687,7 @@ function setupBTCWallet({
4526
4687
 
4527
4688
  // src/index.ts
4528
4689
  var getVersion = () => {
4529
- return "0.5.15-beta";
4690
+ return "0.5.17-beta";
4530
4691
  };
4531
4692
  if (typeof window !== "undefined") {
4532
4693
  window.__BTC_WALLET_VERSION = getVersion();
@@ -4545,20 +4706,19 @@ export {
4545
4706
  UnisatConnector,
4546
4707
  WizzConnector,
4547
4708
  XverseConnector,
4548
- checkGasTokenBalance,
4709
+ btcRpcUrls,
4549
4710
  checkGasTokenDebt,
4550
4711
  checkSatoshiWhitelist,
4551
4712
  estimateDepositAmount,
4552
4713
  executeBTCDepositAndAction,
4553
- getAccountInfo,
4554
4714
  getBtcBalance,
4555
4715
  getBtcGasPrice,
4556
- getConfig,
4557
4716
  getCsnaAccountId,
4558
4717
  getDepositAmount,
4559
- getTokenBalance,
4560
4718
  getVersion,
4719
+ getWalletConfig,
4561
4720
  getWithdrawTransaction,
4721
+ nearRpcUrls,
4562
4722
  sendBitcoin,
4563
4723
  setupBTCWallet,
4564
4724
  useAccountContract,
@@ -4567,6 +4727,7 @@ export {
4567
4727
  useBtcWalletSelector,
4568
4728
  useConnectModal,
4569
4729
  useConnector,
4570
- useETHProvider
4730
+ useETHProvider,
4731
+ walletConfig
4571
4732
  };
4572
4733
  //# sourceMappingURL=index.js.map