btc-wallet 0.5.14-beta → 0.5.16-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,50 +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 coinselect from "coinselect";
3183
- var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
3184
- var NBTC_STORAGE_DEPOSIT_AMOUNT = "3000";
3185
- var GAS_LIMIT = "50000000000000";
3186
- var NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT = "1000";
3187
- function getBtcProvider() {
3188
- if (typeof window === "undefined" || !window.btcContext) {
3189
- throw new Error("BTC Provider is not initialized.");
3190
- }
3191
- return window.btcContext;
3192
- }
3193
- function getNetwork() {
3194
- return __async(this, null, function* () {
3195
- const network = yield getBtcProvider().getNetwork();
3196
- console.log("btc network:", network);
3197
- return network === "livenet" ? "mainnet" : "testnet";
3198
- });
3199
- }
3200
- function getBtcRpcUrl() {
3201
- return __async(this, null, function* () {
3202
- const network = yield getNetwork();
3203
- return btcRpcUrls[network];
3204
- });
3205
- }
3206
- function getConfig(env) {
3207
- return __async(this, null, function* () {
3208
- return walletConfig[env];
3209
- });
3210
- }
3211
- function nearCall(contractId, methodName, args) {
3212
- return __async(this, null, function* () {
3213
- const network = yield getNetwork();
3214
- return nearCallFunction(contractId, methodName, args, { network });
3215
- });
3216
- }
3217
3266
  function getAccountInfo(_0) {
3218
3267
  return __async(this, arguments, function* ({ csna, env }) {
3219
- const config = yield getConfig(env);
3220
- const accountInfo = yield nearCall(config.accountContractId, "get_account", {
3221
- account_id: csna
3222
- }).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) => {
3223
3277
  return void 0;
3224
3278
  });
3225
3279
  console.log("get_account accountInfo:", accountInfo);
@@ -3232,9 +3286,8 @@ function getTokenBalance(_0) {
3232
3286
  tokenId,
3233
3287
  env
3234
3288
  }) {
3235
- const network = yield getNetwork();
3236
- const config = yield getConfig(env);
3237
- const nearProvider = getNearProvider({ network });
3289
+ const config = getWalletConfig(env);
3290
+ const nearProvider = getNearProvider({ network: config.network });
3238
3291
  try {
3239
3292
  if (tokenId === config.nearToken) {
3240
3293
  const nearAccount = yield nearProvider.query({
@@ -3245,8 +3298,18 @@ function getTokenBalance(_0) {
3245
3298
  const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
3246
3299
  return { balance, rawBalance: nearAccount.amount };
3247
3300
  } 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;
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;
3250
3313
  const balance = parseFloat(res) / __pow(10, decimals);
3251
3314
  return { balance, rawBalance: res };
3252
3315
  }
@@ -3258,7 +3321,7 @@ function getTokenBalance(_0) {
3258
3321
  }
3259
3322
  function checkGasTokenBalance(csna, minAmount, env) {
3260
3323
  return __async(this, null, function* () {
3261
- const config = yield getConfig(env);
3324
+ const config = getWalletConfig(env);
3262
3325
  const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
3263
3326
  console.log("gas token balance:", rawBalance);
3264
3327
  if (new Big(rawBalance).lt(minAmount)) {
@@ -3271,16 +3334,308 @@ function checkGasTokenBalance(csna, minAmount, env) {
3271
3334
  }
3272
3335
  });
3273
3336
  }
3274
- 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) {
3275
3629
  return __async(this, null, function* () {
3276
3630
  var _a, _b, _c;
3277
- 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();
3278
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;
3279
- const hasDebtArrears = new Big(debtAmount).gt(0);
3280
- const hasRelayerFeeArrears = new Big(relayerFeeAmount).gt(0);
3634
+ const hasDebtArrears = new Big2(debtAmount).gt(0);
3635
+ const hasRelayerFeeArrears = new Big2(relayerFeeAmount).gt(0);
3281
3636
  if (!hasDebtArrears && !hasRelayerFeeArrears)
3282
3637
  return;
3283
- const config = yield getConfig(env);
3638
+ const config = getWalletConfig(env);
3284
3639
  const transferAmount = hasDebtArrears ? debtAmount : relayerFeeAmount;
3285
3640
  const action = {
3286
3641
  receiver_id: config.accountContractId,
@@ -3338,7 +3693,7 @@ function getBtcBalance() {
3338
3693
  const estimatedFee = Math.ceil(estimatedTxSize * feeRate);
3339
3694
  console.log("estimatedFee:", estimatedFee);
3340
3695
  const availableRawBalance = (rawBalance - estimatedFee).toFixed(0);
3341
- 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();
3342
3697
  return {
3343
3698
  rawBalance,
3344
3699
  balance,
@@ -3363,10 +3718,10 @@ function getDepositAmount(amount, option) {
3363
3718
  var _a;
3364
3719
  const env = (option == null ? void 0 : option.env) || "mainnet";
3365
3720
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3366
- const config = yield getConfig(env);
3721
+ const config = getWalletConfig(env);
3367
3722
  const csna = yield getCsnaAccountId(env);
3368
3723
  const accountInfo = yield getAccountInfo({ csna, env });
3369
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3724
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3370
3725
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
3371
3726
  const {
3372
3727
  deposit_bridge_fee: { fee_min, fee_rate },
@@ -3375,7 +3730,7 @@ function getDepositAmount(amount, option) {
3375
3730
  const depositAmount = Math.max(Number(min_deposit_amount), Number(amount));
3376
3731
  const protocolFee = Math.max(Number(fee_min), Number(depositAmount) * fee_rate);
3377
3732
  const newAccountMinDepositAmount = !(accountInfo == null ? void 0 : accountInfo.nonce) && _newAccountMinDepositAmount ? NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT : 0;
3378
- 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();
3379
3734
  return {
3380
3735
  depositAmount,
3381
3736
  totalDepositAmount,
@@ -3387,7 +3742,7 @@ function getDepositAmount(amount, option) {
3387
3742
  }
3388
3743
  function getCsnaAccountId(env) {
3389
3744
  return __async(this, null, function* () {
3390
- const config = yield getConfig(env);
3745
+ const config = getWalletConfig(env);
3391
3746
  const { getPublicKey } = getBtcProvider();
3392
3747
  const btcPublicKey = yield getPublicKey();
3393
3748
  if (!btcPublicKey) {
@@ -3425,9 +3780,10 @@ function executeBTCDepositAndAction(_0) {
3425
3780
  }) {
3426
3781
  var _a;
3427
3782
  try {
3783
+ console.log("executeBTCDepositAndAction start", amount);
3428
3784
  checkDepositDisabledAddress();
3429
3785
  const { getPublicKey } = getBtcProvider();
3430
- const config = yield getConfig(env);
3786
+ const config = getWalletConfig(env);
3431
3787
  const btcPublicKey = yield getPublicKey();
3432
3788
  if (!btcPublicKey) {
3433
3789
  throw new Error("BTC Public Key is not available.");
@@ -3437,7 +3793,7 @@ function executeBTCDepositAndAction(_0) {
3437
3793
  }
3438
3794
  const csna = yield getCsnaAccountId(env);
3439
3795
  const depositAmount = (_a = action ? action.amount : amount) != null ? _a : "0";
3440
- if (new Big(depositAmount).lt(0)) {
3796
+ if (new Big2(depositAmount).lt(0)) {
3441
3797
  throw new Error("amount must be greater than 0");
3442
3798
  }
3443
3799
  const { totalDepositAmount, protocolFee, repayAmount } = yield getDepositAmount(depositAmount, {
@@ -3446,7 +3802,7 @@ function executeBTCDepositAndAction(_0) {
3446
3802
  });
3447
3803
  const accountInfo = yield getAccountInfo({ csna, env });
3448
3804
  const newActions = [];
3449
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3805
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3450
3806
  if (debtAction) {
3451
3807
  newActions.push(__spreadProps(__spreadValues({}, debtAction), {
3452
3808
  gas: GAS_LIMIT
@@ -3458,12 +3814,17 @@ function executeBTCDepositAndAction(_0) {
3458
3814
  }));
3459
3815
  }
3460
3816
  const storageDepositMsg = {};
3461
- 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", {
3462
3823
  account_id: csna
3463
3824
  });
3464
3825
  if (!(registerRes == null ? void 0 : registerRes.available)) {
3465
3826
  storageDepositMsg.storage_deposit_msg = {
3466
- contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
3827
+ contract_id: registerContractId,
3467
3828
  deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
3468
3829
  registration_only: true
3469
3830
  };
@@ -3534,7 +3895,7 @@ function checkSatoshiWhitelist(btcAccountId, env = "mainnet") {
3534
3895
  }
3535
3896
  if (!btcAccountId)
3536
3897
  return;
3537
- const config = yield getConfig(env);
3898
+ const config = getWalletConfig(env);
3538
3899
  const whitelist = yield getWhitelist(config.base_url);
3539
3900
  if (!(whitelist == null ? void 0 : whitelist.length))
3540
3901
  return;
@@ -3557,9 +3918,11 @@ function getWithdrawTransaction(_0) {
3557
3918
  feeRate,
3558
3919
  env = "mainnet"
3559
3920
  }) {
3921
+ console.log("=== Start getWithdrawTransaction ===");
3560
3922
  const provider = getBtcProvider();
3561
3923
  const btcAddress = provider.account;
3562
- const config = yield getConfig(env);
3924
+ const config = getWalletConfig(env);
3925
+ const csna = yield getCsnaAccountId(env);
3563
3926
  const brgConfig = yield nearCall(config.bridgeContractId, "get_config", {});
3564
3927
  if (brgConfig.min_withdraw_amount) {
3565
3928
  if (Number(amount) < Number(brgConfig.min_withdraw_amount)) {
@@ -3568,7 +3931,39 @@ function getWithdrawTransaction(_0) {
3568
3931
  }
3569
3932
  const feePercent = Number(brgConfig.withdraw_bridge_fee.fee_rate) * Number(amount);
3570
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);
3571
3965
  const allUTXO = yield nearCall(config.bridgeContractId, "get_utxos_paged", {});
3966
+ console.log("All UTXOs:", allUTXO);
3572
3967
  if (!allUTXO || Object.keys(allUTXO).length === 0) {
3573
3968
  throw new Error("The network is busy, please try again later.");
3574
3969
  }
@@ -3581,42 +3976,48 @@ function getWithdrawTransaction(_0) {
3581
3976
  script: allUTXO[key].script
3582
3977
  };
3583
3978
  });
3979
+ console.log("Formatted UTXOs:", utxos);
3584
3980
  const _feeRate = feeRate || (yield getBtcGasPrice());
3585
- let { inputs, outputs, fee } = coinselect(
3981
+ console.log("Fee Rate:", _feeRate);
3982
+ const coinSelectResult = coinselect(
3586
3983
  utxos,
3587
- [{ address: btcAddress, value: Number(amount) }],
3984
+ [{ address: btcAddress, value: Number(finalAmount) }],
3588
3985
  Math.ceil(_feeRate)
3589
3986
  );
3987
+ console.log("Coinselect Result:", coinSelectResult);
3988
+ const { inputs, outputs, fee } = coinSelectResult;
3590
3989
  if (!outputs || !inputs) {
3591
3990
  throw new Error("The network is busy, please try again later.");
3592
3991
  }
3593
3992
  const maxBtcFee = Number(brgConfig.max_btc_gas_fee);
3594
3993
  const transactionFee = fee;
3595
- const changeAddress = brgConfig.change_address;
3994
+ console.log("Transaction Fee:", { transactionFee, maxBtcFee });
3596
3995
  if (transactionFee > maxBtcFee) {
3597
3996
  throw new Error("Gas exceeds maximum value");
3598
3997
  }
3599
3998
  let recipientOutput, changeOutput;
3600
3999
  for (let i = 0; i < outputs.length; i++) {
3601
4000
  const output = outputs[i];
3602
- if (output.value.toString() === amount.toString()) {
4001
+ if (output.value.toString() === finalAmount.toString()) {
3603
4002
  recipientOutput = output;
3604
4003
  } else {
3605
4004
  changeOutput = output;
3606
4005
  }
3607
4006
  if (!output.address) {
3608
- output.address = changeAddress;
4007
+ output.address = brgConfig.change_address;
3609
4008
  }
3610
4009
  }
3611
- 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();
3612
4012
  if (changeOutput) {
3613
- changeOutput.value = new Big(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
4013
+ changeOutput.value = new Big2(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
3614
4014
  const remainingInputs = [...inputs];
3615
4015
  let smallestInput = Math.min.apply(
3616
4016
  null,
3617
4017
  remainingInputs.map((input) => input.value)
3618
4018
  );
3619
4019
  let remainingChangeAmount = changeOutput.value;
4020
+ console.log("Initial Change Processing:", { smallestInput, remainingChangeAmount });
3620
4021
  while (remainingChangeAmount >= smallestInput && smallestInput > 0 && remainingInputs.length > 0) {
3621
4022
  remainingChangeAmount -= smallestInput;
3622
4023
  changeOutput.value = remainingChangeAmount;
@@ -3630,30 +4031,50 @@ function getWithdrawTransaction(_0) {
3630
4031
  null,
3631
4032
  remainingInputs.map((input) => input.value)
3632
4033
  );
4034
+ console.log("Change Processing Loop:", {
4035
+ remainingChangeAmount,
4036
+ smallestInput,
4037
+ remainingInputsCount: remainingInputs.length
4038
+ });
3633
4039
  }
3634
4040
  const minChangeAmount = Number(brgConfig.min_change_amount);
3635
4041
  let additionalFee = 0;
4042
+ console.log("Checking minimum change amount:", {
4043
+ changeValue: changeOutput.value,
4044
+ minChangeAmount
4045
+ });
4046
+ let finalOutputs = [...outputs];
3636
4047
  if (changeOutput.value === 0) {
3637
- outputs = outputs.filter((item) => item.value !== 0);
4048
+ finalOutputs = finalOutputs.filter((output) => output.value !== 0);
4049
+ console.log("Removed zero-value change output", finalOutputs);
3638
4050
  } else if (changeOutput.value < minChangeAmount) {
3639
4051
  additionalFee = minChangeAmount - changeOutput.value;
3640
4052
  recipientOutput.value -= additionalFee;
3641
4053
  changeOutput.value = minChangeAmount;
4054
+ console.log("Adjusted for minimum change amount:", {
4055
+ additionalFee,
4056
+ newRecipientValue: recipientOutput.value,
4057
+ newChangeValue: changeOutput.value
4058
+ });
3642
4059
  }
3643
4060
  } else {
3644
4061
  changeOutput = {
3645
- address: changeAddress,
3646
- value: new Big(transactionFee).plus(withdrawFee).toNumber()
4062
+ address: brgConfig.change_address,
4063
+ value: new Big2(transactionFee).plus(withdrawFee).toNumber()
3647
4064
  };
3648
4065
  outputs.push(changeOutput);
4066
+ console.log("Created new change output:", changeOutput);
3649
4067
  }
3650
4068
  const insufficientOutput = outputs.some((item) => item.value < 0);
3651
4069
  if (insufficientOutput) {
4070
+ console.error("Negative output value detected");
3652
4071
  throw new Error("Not enough gas");
3653
4072
  }
3654
4073
  const inputSum = inputs.reduce((sum, cur) => sum + Number(cur.value), 0);
3655
4074
  const outputSum = outputs.reduce((sum, cur) => sum + Number(cur.value), 0);
4075
+ console.log("Balance verification:", { inputSum, outputSum, transactionFee });
3656
4076
  if (transactionFee + outputSum !== inputSum) {
4077
+ console.error("Balance mismatch:", { inputSum, outputSum, transactionFee });
3657
4078
  throw new Error("compute error");
3658
4079
  }
3659
4080
  const network = yield getNetwork();
@@ -3680,6 +4101,7 @@ function getWithdrawTransaction(_0) {
3680
4101
  value: output.value
3681
4102
  });
3682
4103
  });
4104
+ console.log("outputs:", JSON.stringify(outputs));
3683
4105
  const _inputs = inputs.map((item) => {
3684
4106
  return `${item.txid}:${item.vout}`;
3685
4107
  });
@@ -3696,7 +4118,6 @@ function getWithdrawTransaction(_0) {
3696
4118
  output: txOutputs
3697
4119
  }
3698
4120
  };
3699
- const csna = yield getCsnaAccountId(env);
3700
4121
  const transaction = {
3701
4122
  receiverId: config.btcToken,
3702
4123
  signerId: csna,
@@ -3716,6 +4137,7 @@ function getWithdrawTransaction(_0) {
3716
4137
  }
3717
4138
  ]
3718
4139
  };
4140
+ console.log("=== End getWithdrawTransaction ===");
3719
4141
  return transaction;
3720
4142
  });
3721
4143
  }
@@ -3956,86 +4378,7 @@ function updateIframePosition(iframe, buttonRight, buttonBottom, windowWidth, wi
3956
4378
  iframe.style.bottom = `${iframeBottom}px`;
3957
4379
  }
3958
4380
 
3959
- // src/core/setupBTCWallet.ts
3960
- import Big2 from "big.js";
3961
- var { transfer, functionCall } = actionCreators;
3962
- var STORAGE_KEYS = {
3963
- ACCOUNT: "btc-wallet-account",
3964
- PUBLIC_KEY: "btc-wallet-publickey",
3965
- BTC_PUBLIC_KEY: "btc-wallet-btc-publickey"
3966
- };
3967
- var state = {
3968
- saveAccount(account) {
3969
- if (!account) {
3970
- this.removeAccount();
3971
- return;
3972
- }
3973
- window.localStorage.setItem(STORAGE_KEYS.ACCOUNT, account);
3974
- },
3975
- removeAccount() {
3976
- window.localStorage.removeItem(STORAGE_KEYS.ACCOUNT);
3977
- },
3978
- savePublicKey(publicKey) {
3979
- if (!publicKey) {
3980
- this.removePublicKey();
3981
- return;
3982
- }
3983
- window.localStorage.setItem(STORAGE_KEYS.PUBLIC_KEY, publicKey);
3984
- },
3985
- removePublicKey() {
3986
- window.localStorage.removeItem(STORAGE_KEYS.PUBLIC_KEY);
3987
- },
3988
- saveBtcPublicKey(publicKey) {
3989
- if (!publicKey) {
3990
- this.removeBtcPublicKey();
3991
- return;
3992
- }
3993
- window.localStorage.setItem(STORAGE_KEYS.BTC_PUBLIC_KEY, publicKey);
3994
- },
3995
- removeBtcPublicKey() {
3996
- window.localStorage.removeItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
3997
- },
3998
- clear() {
3999
- this.removeAccount();
4000
- this.removePublicKey();
4001
- this.removeBtcPublicKey();
4002
- },
4003
- save(account, publicKey) {
4004
- if (!account || !publicKey) {
4005
- this.clear();
4006
- return;
4007
- }
4008
- this.saveAccount(account);
4009
- this.savePublicKey(publicKey);
4010
- },
4011
- getAccount() {
4012
- return window.localStorage.getItem(STORAGE_KEYS.ACCOUNT);
4013
- },
4014
- getPublicKey() {
4015
- return window.localStorage.getItem(STORAGE_KEYS.PUBLIC_KEY);
4016
- },
4017
- getBtcPublicKey() {
4018
- return window.localStorage.getItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
4019
- },
4020
- isValid() {
4021
- const account = this.getAccount();
4022
- const publicKey = this.getPublicKey();
4023
- const btcPublicKey = this.getBtcPublicKey();
4024
- const allEmpty = !account && !publicKey && !btcPublicKey;
4025
- const allExist = account && publicKey && btcPublicKey;
4026
- return allEmpty || allExist;
4027
- },
4028
- syncSave(account, publicKey, btcPublicKey) {
4029
- if (!account || !publicKey || !btcPublicKey) {
4030
- this.clear();
4031
- return;
4032
- }
4033
- this.clear();
4034
- this.savePublicKey(publicKey);
4035
- this.saveBtcPublicKey(btcPublicKey);
4036
- this.saveAccount(account);
4037
- }
4038
- };
4381
+ // src/core/setupBTCWallet/index.ts
4039
4382
  var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4040
4383
  metadata,
4041
4384
  options,
@@ -4057,15 +4400,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4057
4400
  calculateGasLimit
4058
4401
  };
4059
4402
  const env = metadata.env || options.network.networkId || "mainnet";
4060
- const currentConfig = walletConfig[env];
4061
- const walletNetwork = ["mainnet", "private_mainnet"].includes(env) ? "mainnet" : "testnet";
4403
+ const currentConfig = getWalletConfig(env);
4062
4404
  yield initBtcContext();
4063
4405
  function validateWalletState() {
4064
- const accountId = state.getAccount();
4065
- const publicKey = state.getPublicKey();
4066
- const btcPublicKey = state.getBtcPublicKey();
4406
+ const accountId = state_default.getAccount();
4407
+ const publicKey = state_default.getPublicKey();
4408
+ const btcPublicKey = state_default.getBtcPublicKey();
4067
4409
  if (!accountId && publicKey || accountId && !publicKey || !publicKey && btcPublicKey) {
4068
- state.clear();
4410
+ state_default.clear();
4069
4411
  return false;
4070
4412
  }
4071
4413
  return true;
@@ -4073,9 +4415,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4073
4415
  function setupBtcContextListeners() {
4074
4416
  return __async(this, null, function* () {
4075
4417
  const handleConnectionUpdate = () => __async(this, null, function* () {
4076
- yield checkBtcNetwork(walletNetwork);
4077
- if (!state.isValid()) {
4078
- state.clear();
4418
+ yield checkBtcNetwork(currentConfig.network);
4419
+ if (!state_default.isValid()) {
4420
+ state_default.clear();
4079
4421
  console.log("setupBtcContextListeners clear");
4080
4422
  }
4081
4423
  validateWalletState();
@@ -4098,7 +4440,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4098
4440
  const context = window.btcContext.getContext();
4099
4441
  context.on("updatePublicKey", (btcPublicKey) => __async(this, null, function* () {
4100
4442
  console.log("updatePublicKey");
4101
- state.clear();
4443
+ state_default.clear();
4102
4444
  console.log("updatePublicKey clear");
4103
4445
  try {
4104
4446
  const { nearAddress, nearPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
@@ -4117,7 +4459,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4117
4459
  }));
4118
4460
  context.on("btcLogOut", () => __async(this, null, function* () {
4119
4461
  console.log("btcLogOut");
4120
- state.clear();
4462
+ state_default.clear();
4121
4463
  emitter.emit("accountsChanged", { accounts: [] });
4122
4464
  yield handleConnectionUpdate();
4123
4465
  }));
@@ -4161,7 +4503,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4161
4503
  "get_chain_signature_near_account_public_key",
4162
4504
  { btc_public_key: btcPublicKey }
4163
4505
  );
4164
- state.syncSave(csna, nearPublicKey, btcPublicKey);
4506
+ state_default.syncSave(csna, nearPublicKey, btcPublicKey);
4165
4507
  return {
4166
4508
  nearAddress: csna,
4167
4509
  nearPublicKey
@@ -4171,8 +4513,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4171
4513
  function signIn(_02) {
4172
4514
  return __async(this, arguments, function* ({ contractId, methodNames }) {
4173
4515
  const btcContext = window.btcContext;
4174
- state.clear();
4175
- if (!state.getAccount() || !state.getPublicKey()) {
4516
+ state_default.clear();
4517
+ if (!state_default.getAccount() || !state_default.getPublicKey()) {
4176
4518
  yield btcContext.login();
4177
4519
  }
4178
4520
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4191,8 +4533,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4191
4533
  }
4192
4534
  function signOut() {
4193
4535
  return __async(this, null, function* () {
4194
- const accountId = state.getAccount();
4195
- const publicKey = state.getPublicKey();
4536
+ const accountId = state_default.getAccount();
4537
+ const publicKey = state_default.getPublicKey();
4196
4538
  if (!(accountId && publicKey)) {
4197
4539
  return;
4198
4540
  }
@@ -4200,19 +4542,19 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4200
4542
  if (metadata.syncLogOut) {
4201
4543
  btcContext.logout();
4202
4544
  }
4203
- state.clear();
4545
+ state_default.clear();
4204
4546
  window.localStorage.removeItem("near-wallet-selector:selectedWalletId");
4205
4547
  removeWalletButton();
4206
4548
  });
4207
4549
  }
4208
4550
  function isSignedIn() {
4209
- const accountId = state.getAccount();
4210
- const publicKey = state.getPublicKey();
4551
+ const accountId = state_default.getAccount();
4552
+ const publicKey = state_default.getPublicKey();
4211
4553
  return accountId && publicKey;
4212
4554
  }
4213
4555
  function getAccounts() {
4214
4556
  return __async(this, null, function* () {
4215
- return [{ accountId: state.getAccount() }];
4557
+ return [{ accountId: state_default.getAccount() }];
4216
4558
  });
4217
4559
  }
4218
4560
  function verifyOwner() {
@@ -4242,12 +4584,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4242
4584
  throw new Error("Wallet state is invalid, please reconnect your wallet.");
4243
4585
  }
4244
4586
  const btcContext = window.btcContext;
4245
- const csna = state.getAccount();
4587
+ const csna = state_default.getAccount();
4246
4588
  const accountInfo = yield getAccountInfo({ csna, env });
4247
- yield checkGasTokenDebt(accountInfo, env, true);
4589
+ yield checkGasTokenDebt(csna, env, true);
4248
4590
  const trans = [...params.transactions];
4249
4591
  console.log("signAndSendTransactions raw trans:", trans);
4250
- const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
4592
+ const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy({
4593
+ csna,
4594
+ transactions: trans,
4595
+ env
4596
+ });
4251
4597
  console.log("transferGasTransaction:", transferGasTransaction);
4252
4598
  console.log("useNearPayGas:", useNearPayGas);
4253
4599
  console.log("gasLimit:", gasLimit);
@@ -4257,7 +4603,15 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4257
4603
  }
4258
4604
  console.log("calculateGasStrategy trans:", trans);
4259
4605
  const newTrans = yield Promise.all(
4260
- 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
+ )
4261
4615
  );
4262
4616
  const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
4263
4617
  const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
@@ -4275,7 +4629,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4275
4629
  const signature = yield btcContext.signMessage(strIntention);
4276
4630
  yield receiveTransaction(currentConfig.base_url, {
4277
4631
  sig: signature,
4278
- btcPubKey: state.getBtcPublicKey(),
4632
+ btcPubKey: state_default.getBtcPublicKey(),
4279
4633
  data: toHex(strIntention)
4280
4634
  });
4281
4635
  yield checkBtcTransactionStatus(currentConfig.base_url, signature);
@@ -4285,197 +4639,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4285
4639
  return result;
4286
4640
  });
4287
4641
  }
4288
- function calculateGasLimit(params) {
4289
- return __async(this, null, function* () {
4290
- const trans = [...params.transactions];
4291
- console.log("raw trans:", trans);
4292
- const { gasLimit } = yield calculateGasStrategy(trans);
4293
- return gasLimit;
4294
- });
4295
- }
4296
- function createGasTokenTransfer(accountId, amount) {
4297
- return __async(this, null, function* () {
4298
- return {
4299
- signerId: accountId,
4300
- receiverId: currentConfig.btcToken,
4301
- actions: [
4302
- {
4303
- type: "FunctionCall",
4304
- params: {
4305
- methodName: "ft_transfer_call",
4306
- args: {
4307
- receiver_id: currentConfig.accountContractId,
4308
- amount,
4309
- msg: JSON.stringify("Repay")
4310
- },
4311
- gas: new Big2(50).mul(__pow(10, 12)).toFixed(0),
4312
- deposit: "1"
4313
- }
4314
- }
4315
- ]
4316
- };
4317
- });
4318
- }
4319
- function recalculateGasWithTransfer(transferTx, transactions2, useNearPayGas, perTxFee) {
4320
- return __async(this, null, function* () {
4321
- const { txHex: transferTxHex } = yield convertTransactionToTxHex(transferTx);
4322
- let newGasLimit;
4323
- if (useNearPayGas && perTxFee) {
4324
- newGasLimit = new Big2(perTxFee).mul(transactions2.length + 1).toFixed(0);
4325
- } else {
4326
- newGasLimit = yield getPredictedGasAmount(
4327
- currentConfig.accountContractId,
4328
- currentConfig.btcToken,
4329
- [transferTxHex, ...transactions2.map((t) => t.txHex)]
4330
- );
4331
- }
4332
- transferTx.actions[0].params.args.amount = newGasLimit;
4333
- return { transferGasTransaction: transferTx, useNearPayGas, gasLimit: newGasLimit };
4334
- });
4335
- }
4336
- function getPredictedGasAmount(accountContractId, tokenId, transactions2) {
4337
- return __async(this, null, function* () {
4338
- const predictedGas = yield nearCall2(accountContractId, "predict_txs_gas_token_amount", {
4339
- gas_token_id: tokenId,
4340
- near_transactions: transactions2
4341
- });
4342
- const predictedGasAmount = new Big2(predictedGas).mul(1.2).toFixed(0);
4343
- const miniGasAmount = 200 * transactions2.length;
4344
- const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
4345
- console.log("predictedGas:", predictedGasAmount);
4346
- return gasAmount.toString();
4347
- });
4348
- }
4349
- function calculateGasStrategy(transactions2) {
4350
- return __async(this, null, function* () {
4351
- var _a;
4352
- const accountId = state.getAccount();
4353
- const accountInfo = yield getAccountInfo({ csna: accountId, env });
4354
- const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
4355
- const { balance: nearBalance } = yield getTokenBalance({
4356
- csna: accountId,
4357
- tokenId: currentConfig.nearToken,
4358
- env
4359
- });
4360
- const transferAmount = transactions2.reduce(
4361
- (acc, tx) => {
4362
- tx.actions.forEach((action) => {
4363
- if (action.params.deposit) {
4364
- const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
4365
- console.log("near deposit amount:", amount);
4366
- acc.near = acc.near.plus(amount);
4367
- }
4368
- if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
4369
- const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
4370
- console.log("btc transfer amount:", amount);
4371
- acc.btc = acc.btc.plus(amount);
4372
- }
4373
- });
4374
- return acc;
4375
- },
4376
- { near: new Big2(0), btc: new Big2(0) }
4377
- );
4378
- const nearAvailableBalance = new Big2(nearBalance).minus(transferAmount.near).toNumber();
4379
- console.log("available near balance:", nearAvailableBalance);
4380
- console.log("available gas token balance:", gasTokenBalance);
4381
- const convertTx = yield Promise.all(
4382
- transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4383
- );
4384
- if (nearAvailableBalance > 0.5) {
4385
- console.log("near balance is enough, get the protocol fee of each transaction");
4386
- const gasTokens = yield nearCall2(
4387
- currentConfig.accountContractId,
4388
- "list_gas_token",
4389
- { token_ids: [currentConfig.btcToken] }
4390
- );
4391
- console.log("list_gas_token gas tokens:", gasTokens);
4392
- const perTxFee = Math.max(
4393
- Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
4394
- 100
4395
- );
4396
- console.log("perTxFee:", perTxFee);
4397
- const protocolFee = new Big2(perTxFee || "0").mul(convertTx.length).toFixed(0);
4398
- console.log("protocolFee:", protocolFee);
4399
- if (new Big2(gasTokenBalance).gte(protocolFee)) {
4400
- console.log("use near pay gas and enough gas token balance");
4401
- return { useNearPayGas: true, gasLimit: protocolFee };
4402
- } else {
4403
- console.log("use near pay gas and not enough gas token balance");
4404
- const transferTx = yield createGasTokenTransfer(accountId, protocolFee);
4405
- return recalculateGasWithTransfer(transferTx, convertTx, true, perTxFee.toString());
4406
- }
4407
- } else {
4408
- console.log("near balance is not enough, predict the gas token amount required");
4409
- const adjustedGas = yield getPredictedGasAmount(
4410
- currentConfig.accountContractId,
4411
- currentConfig.btcToken,
4412
- convertTx.map((t) => t.txHex)
4413
- );
4414
- if (new Big2(gasTokenBalance).gte(adjustedGas)) {
4415
- console.log("use gas token and gas token balance is enough");
4416
- return { useNearPayGas: false, gasLimit: adjustedGas };
4417
- } else {
4418
- console.log("use gas token and gas token balance is not enough, need to transfer");
4419
- const transferTx = yield createGasTokenTransfer(accountId, adjustedGas);
4420
- return recalculateGasWithTransfer(transferTx, convertTx, false);
4421
- }
4422
- }
4423
- });
4424
- }
4425
- function convertTransactionToTxHex(transaction, index = 0) {
4426
- return __async(this, null, function* () {
4427
- const accountId = state.getAccount();
4428
- const publicKey = state.getPublicKey();
4429
- const publicKeyFormat = PublicKey.from(publicKey);
4430
- const { header } = yield provider.block({
4431
- finality: "final"
4432
- });
4433
- const rawAccessKey = yield provider.query({
4434
- request_type: "view_access_key",
4435
- account_id: accountId,
4436
- public_key: publicKey,
4437
- finality: "final"
4438
- }).catch((e) => {
4439
- console.log("view_access_key error:", e);
4440
- return void 0;
4441
- });
4442
- const accessKey = __spreadProps(__spreadValues({}, rawAccessKey), {
4443
- nonce: BigInt((rawAccessKey == null ? void 0 : rawAccessKey.nonce) || 0)
4444
- });
4445
- const nearNonceFromApi = yield getNearNonce(currentConfig.base_url, accountId);
4446
- let nearNonceNumber = accessKey.nonce + BigInt(1);
4447
- if (nearNonceFromApi) {
4448
- nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
4449
- }
4450
- const newActions = transaction.actions.map((action) => {
4451
- switch (action.type) {
4452
- case "FunctionCall":
4453
- return functionCall(
4454
- action.params.methodName,
4455
- action.params.args,
4456
- BigInt(action.params.gas),
4457
- BigInt(action.params.deposit)
4458
- );
4459
- case "Transfer":
4460
- return transfer(BigInt(action.params.deposit));
4461
- }
4462
- }).filter(Boolean);
4463
- const _transaction = transactions.createTransaction(
4464
- accountId,
4465
- publicKeyFormat,
4466
- transaction.receiverId,
4467
- BigInt(nearNonceNumber) + BigInt(index),
4468
- newActions,
4469
- baseDecode(header.hash)
4470
- );
4471
- const txBytes = encodeTransaction(_transaction);
4472
- const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
4473
- ""
4474
- );
4475
- const hash = bs58.encode(new Uint8Array(sha256.array(txBytes)));
4476
- return { txBytes, txHex, hash };
4477
- });
4478
- }
4479
4642
  function checkBtcNetwork(network) {
4480
4643
  return __async(this, null, function* () {
4481
4644
  const btcContext = window.btcContext;
@@ -4524,7 +4687,7 @@ function setupBTCWallet({
4524
4687
 
4525
4688
  // src/index.ts
4526
4689
  var getVersion = () => {
4527
- return "0.5.14-beta";
4690
+ return "0.5.16-beta";
4528
4691
  };
4529
4692
  if (typeof window !== "undefined") {
4530
4693
  window.__BTC_WALLET_VERSION = getVersion();
@@ -4543,18 +4706,14 @@ export {
4543
4706
  UnisatConnector,
4544
4707
  WizzConnector,
4545
4708
  XverseConnector,
4546
- checkGasTokenBalance,
4547
4709
  checkGasTokenDebt,
4548
4710
  checkSatoshiWhitelist,
4549
4711
  estimateDepositAmount,
4550
4712
  executeBTCDepositAndAction,
4551
- getAccountInfo,
4552
4713
  getBtcBalance,
4553
4714
  getBtcGasPrice,
4554
- getConfig,
4555
4715
  getCsnaAccountId,
4556
4716
  getDepositAmount,
4557
- getTokenBalance,
4558
4717
  getVersion,
4559
4718
  getWithdrawTransaction,
4560
4719
  sendBitcoin,