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/dist/index.js CHANGED
@@ -91,20 +91,19 @@ __export(src_exports, {
91
91
  UnisatConnector: () => UnisatConnector,
92
92
  WizzConnector: () => WizzConnector,
93
93
  XverseConnector: () => XverseConnector,
94
- checkGasTokenBalance: () => checkGasTokenBalance,
94
+ btcRpcUrls: () => btcRpcUrls,
95
95
  checkGasTokenDebt: () => checkGasTokenDebt,
96
96
  checkSatoshiWhitelist: () => checkSatoshiWhitelist,
97
97
  estimateDepositAmount: () => estimateDepositAmount,
98
98
  executeBTCDepositAndAction: () => executeBTCDepositAndAction,
99
- getAccountInfo: () => getAccountInfo,
100
99
  getBtcBalance: () => getBtcBalance,
101
100
  getBtcGasPrice: () => getBtcGasPrice,
102
- getConfig: () => getConfig,
103
101
  getCsnaAccountId: () => getCsnaAccountId,
104
102
  getDepositAmount: () => getDepositAmount,
105
- getTokenBalance: () => getTokenBalance,
106
103
  getVersion: () => getVersion,
104
+ getWalletConfig: () => getWalletConfig,
107
105
  getWithdrawTransaction: () => getWithdrawTransaction,
106
+ nearRpcUrls: () => nearRpcUrls,
108
107
  sendBitcoin: () => sendBitcoin,
109
108
  setupBTCWallet: () => setupBTCWallet,
110
109
  useAccountContract: () => useAccountContract,
@@ -113,7 +112,8 @@ __export(src_exports, {
113
112
  useBtcWalletSelector: () => useBtcWalletSelector,
114
113
  useConnectModal: () => useConnectModal,
115
114
  useConnector: () => useConnector,
116
- useETHProvider: () => useETHProvider
115
+ useETHProvider: () => useETHProvider,
116
+ walletConfig: () => walletConfig
117
117
  });
118
118
  module.exports = __toCommonJS(src_exports);
119
119
 
@@ -2871,15 +2871,6 @@ function useBtcWalletSelector() {
2871
2871
  return hook;
2872
2872
  }
2873
2873
 
2874
- // src/core/setupBTCWallet.ts
2875
- var import_near_api_js2 = require("near-api-js");
2876
- var import_transactions = require("@near-js/transactions");
2877
- var import_key_pair = require("near-api-js/lib/utils/key_pair");
2878
- var import_transaction = require("near-api-js/lib/transaction");
2879
- var import_utils10 = require("@near-js/utils");
2880
- var import_bs58 = __toESM(require("bs58"), 1);
2881
- var import_js_sha256 = require("js-sha256");
2882
-
2883
2874
  // src/config.ts
2884
2875
  var walletConfig = {
2885
2876
  dev: {
@@ -2927,6 +2918,13 @@ var walletConfig = {
2927
2918
  bridgeUrl: "https://ramp.satos.network"
2928
2919
  }
2929
2920
  };
2921
+ function getWalletConfig(env) {
2922
+ const config = walletConfig[env];
2923
+ const network = env === "mainnet" || env === "private_mainnet" ? "mainnet" : "testnet";
2924
+ return __spreadProps(__spreadValues({}, config), {
2925
+ network
2926
+ });
2927
+ }
2930
2928
  var nearRpcUrls = {
2931
2929
  mainnet: [
2932
2930
  "https://near.lava.build",
@@ -2942,7 +2940,7 @@ var btcRpcUrls = {
2942
2940
  };
2943
2941
 
2944
2942
  // src/core/btcUtils.ts
2945
- var import_big = __toESM(require("big.js"), 1);
2943
+ var import_big2 = __toESM(require("big.js"), 1);
2946
2944
 
2947
2945
  // src/utils/nearUtils.ts
2948
2946
  var import_near_api_js = require("near-api-js");
@@ -3049,7 +3047,7 @@ function nearCallFunction(_0, _1, _2) {
3049
3047
  return withCache(
3050
3048
  cacheKey,
3051
3049
  () => executeNearCall(contractId, methodName, args, options),
3052
- options.cacheTimeout
3050
+ options.cacheTimeout || 5e3
3053
3051
  );
3054
3052
  }
3055
3053
  return executeNearCall(contractId, methodName, args, options);
@@ -3111,6 +3109,95 @@ function pollTransactionStatuses(network, hashes) {
3111
3109
  });
3112
3110
  }
3113
3111
 
3112
+ // src/utils/satoshi.ts
3113
+ var import_transactions = require("@near-js/transactions");
3114
+ var import_key_pair = require("near-api-js/lib/utils/key_pair");
3115
+ var import_transaction = require("near-api-js/lib/transaction");
3116
+ var import_utils9 = require("@near-js/utils");
3117
+ var import_bs58 = __toESM(require("bs58"), 1);
3118
+ var import_js_sha256 = require("js-sha256");
3119
+ var import_near_api_js2 = require("near-api-js");
3120
+ var import_big = __toESM(require("big.js"), 1);
3121
+
3122
+ // src/core/setupBTCWallet/state.ts
3123
+ var STORAGE_KEYS = {
3124
+ ACCOUNT: "btc-wallet-account",
3125
+ PUBLIC_KEY: "btc-wallet-publickey",
3126
+ BTC_PUBLIC_KEY: "btc-wallet-btc-publickey"
3127
+ };
3128
+ var state_default = {
3129
+ saveAccount(account) {
3130
+ if (!account) {
3131
+ this.removeAccount();
3132
+ return;
3133
+ }
3134
+ window.localStorage.setItem(STORAGE_KEYS.ACCOUNT, account);
3135
+ },
3136
+ removeAccount() {
3137
+ window.localStorage.removeItem(STORAGE_KEYS.ACCOUNT);
3138
+ },
3139
+ savePublicKey(publicKey) {
3140
+ if (!publicKey) {
3141
+ this.removePublicKey();
3142
+ return;
3143
+ }
3144
+ window.localStorage.setItem(STORAGE_KEYS.PUBLIC_KEY, publicKey);
3145
+ },
3146
+ removePublicKey() {
3147
+ window.localStorage.removeItem(STORAGE_KEYS.PUBLIC_KEY);
3148
+ },
3149
+ saveBtcPublicKey(publicKey) {
3150
+ if (!publicKey) {
3151
+ this.removeBtcPublicKey();
3152
+ return;
3153
+ }
3154
+ window.localStorage.setItem(STORAGE_KEYS.BTC_PUBLIC_KEY, publicKey);
3155
+ },
3156
+ removeBtcPublicKey() {
3157
+ window.localStorage.removeItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
3158
+ },
3159
+ clear() {
3160
+ this.removeAccount();
3161
+ this.removePublicKey();
3162
+ this.removeBtcPublicKey();
3163
+ },
3164
+ save(account, publicKey) {
3165
+ if (!account || !publicKey) {
3166
+ this.clear();
3167
+ return;
3168
+ }
3169
+ this.saveAccount(account);
3170
+ this.savePublicKey(publicKey);
3171
+ },
3172
+ getAccount() {
3173
+ return window.localStorage.getItem(STORAGE_KEYS.ACCOUNT) || "";
3174
+ },
3175
+ getPublicKey() {
3176
+ return window.localStorage.getItem(STORAGE_KEYS.PUBLIC_KEY) || "";
3177
+ },
3178
+ getBtcPublicKey() {
3179
+ return window.localStorage.getItem(STORAGE_KEYS.BTC_PUBLIC_KEY) || "";
3180
+ },
3181
+ isValid() {
3182
+ const account = this.getAccount();
3183
+ const publicKey = this.getPublicKey();
3184
+ const btcPublicKey = this.getBtcPublicKey();
3185
+ const allEmpty = !account && !publicKey && !btcPublicKey;
3186
+ const allExist = account && publicKey && btcPublicKey;
3187
+ return allEmpty || allExist;
3188
+ },
3189
+ syncSave(account, publicKey, btcPublicKey) {
3190
+ if (!account || !publicKey || !btcPublicKey) {
3191
+ this.clear();
3192
+ return;
3193
+ }
3194
+ this.clear();
3195
+ this.savePublicKey(publicKey);
3196
+ this.saveBtcPublicKey(btcPublicKey);
3197
+ this.saveAccount(account);
3198
+ }
3199
+ };
3200
+
3114
3201
  // src/utils/satoshi.ts
3115
3202
  function getNonce(url, accountId) {
3116
3203
  return __async(this, null, function* () {
@@ -3226,52 +3313,17 @@ function getWhitelist(url) {
3226
3313
  return data;
3227
3314
  });
3228
3315
  }
3229
-
3230
- // src/core/btcUtils.ts
3231
- var import_bitcoinjs_lib = __toESM(require("bitcoinjs-lib"), 1);
3232
- var ecc = __toESM(require("@bitcoinerlab/secp256k1"), 1);
3233
- var import_coinselect = __toESM(require("coinselect"), 1);
3234
- import_bitcoinjs_lib.default.initEccLib(ecc);
3235
- var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
3236
- var NBTC_STORAGE_DEPOSIT_AMOUNT = "3000";
3237
- var GAS_LIMIT = "50000000000000";
3238
- var NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT = "1000";
3239
- function getBtcProvider() {
3240
- if (typeof window === "undefined" || !window.btcContext) {
3241
- throw new Error("BTC Provider is not initialized.");
3242
- }
3243
- return window.btcContext;
3244
- }
3245
- function getNetwork() {
3246
- return __async(this, null, function* () {
3247
- const network = yield getBtcProvider().getNetwork();
3248
- console.log("btc network:", network);
3249
- return network === "livenet" ? "mainnet" : "testnet";
3250
- });
3251
- }
3252
- function getBtcRpcUrl() {
3253
- return __async(this, null, function* () {
3254
- const network = yield getNetwork();
3255
- return btcRpcUrls[network];
3256
- });
3257
- }
3258
- function getConfig(env) {
3259
- return __async(this, null, function* () {
3260
- return walletConfig[env];
3261
- });
3262
- }
3263
- function nearCall(contractId, methodName, args) {
3264
- return __async(this, null, function* () {
3265
- const network = yield getNetwork();
3266
- return nearCallFunction(contractId, methodName, args, { network });
3267
- });
3268
- }
3269
3316
  function getAccountInfo(_0) {
3270
3317
  return __async(this, arguments, function* ({ csna, env }) {
3271
- const config = yield getConfig(env);
3272
- const accountInfo = yield nearCall(config.accountContractId, "get_account", {
3273
- account_id: csna
3274
- }).catch((error) => {
3318
+ const config = getWalletConfig(env);
3319
+ const accountInfo = yield nearCallFunction(
3320
+ config.accountContractId,
3321
+ "get_account",
3322
+ {
3323
+ account_id: csna
3324
+ },
3325
+ { network: config.network }
3326
+ ).catch((error) => {
3275
3327
  return void 0;
3276
3328
  });
3277
3329
  console.log("get_account accountInfo:", accountInfo);
@@ -3284,9 +3336,8 @@ function getTokenBalance(_0) {
3284
3336
  tokenId,
3285
3337
  env
3286
3338
  }) {
3287
- const network = yield getNetwork();
3288
- const config = yield getConfig(env);
3289
- const nearProvider = getNearProvider({ network });
3339
+ const config = getWalletConfig(env);
3340
+ const nearProvider = getNearProvider({ network: config.network });
3290
3341
  try {
3291
3342
  if (tokenId === config.nearToken) {
3292
3343
  const nearAccount = yield nearProvider.query({
@@ -3297,8 +3348,18 @@ function getTokenBalance(_0) {
3297
3348
  const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
3298
3349
  return { balance, rawBalance: nearAccount.amount };
3299
3350
  } else {
3300
- const res = yield nearCall(tokenId, "ft_balance_of", { account_id: csna });
3301
- const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCall(tokenId, "ft_metadata", {})).decimals;
3351
+ const res = yield nearCallFunction(
3352
+ tokenId,
3353
+ "ft_balance_of",
3354
+ { account_id: csna },
3355
+ { network: config.network }
3356
+ );
3357
+ const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCallFunction(
3358
+ tokenId,
3359
+ "ft_metadata",
3360
+ {},
3361
+ { network: config.network }
3362
+ )).decimals;
3302
3363
  const balance = parseFloat(res) / __pow(10, decimals);
3303
3364
  return { balance, rawBalance: res };
3304
3365
  }
@@ -3310,7 +3371,7 @@ function getTokenBalance(_0) {
3310
3371
  }
3311
3372
  function checkGasTokenBalance(csna, minAmount, env) {
3312
3373
  return __async(this, null, function* () {
3313
- const config = yield getConfig(env);
3374
+ const config = getWalletConfig(env);
3314
3375
  const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
3315
3376
  console.log("gas token balance:", rawBalance);
3316
3377
  if (new import_big.default(rawBalance).lt(minAmount)) {
@@ -3323,16 +3384,308 @@ function checkGasTokenBalance(csna, minAmount, env) {
3323
3384
  }
3324
3385
  });
3325
3386
  }
3326
- function checkGasTokenDebt(accountInfo, env, autoDeposit) {
3387
+ var { functionCall, transfer } = import_transactions.actionCreators;
3388
+ function convertTransactionToTxHex(_0) {
3389
+ return __async(this, arguments, function* ({
3390
+ transaction,
3391
+ accountId,
3392
+ publicKey,
3393
+ env,
3394
+ index = 0
3395
+ }) {
3396
+ const publicKeyFormat = import_key_pair.PublicKey.from(publicKey);
3397
+ const currentConfig = getWalletConfig(env);
3398
+ const provider = getNearProvider({ network: currentConfig.network });
3399
+ const { header } = yield provider.block({
3400
+ finality: "final"
3401
+ });
3402
+ const rawAccessKey = yield provider.query({
3403
+ request_type: "view_access_key",
3404
+ account_id: accountId,
3405
+ public_key: publicKey,
3406
+ finality: "final"
3407
+ }).catch((e) => {
3408
+ console.log("view_access_key error:", e);
3409
+ return void 0;
3410
+ });
3411
+ const accessKey = __spreadProps(__spreadValues({}, rawAccessKey), {
3412
+ nonce: BigInt((rawAccessKey == null ? void 0 : rawAccessKey.nonce) || 0)
3413
+ });
3414
+ const nearNonceFromApi = yield getNearNonce(currentConfig.base_url, accountId);
3415
+ let nearNonceNumber = accessKey.nonce + BigInt(1);
3416
+ if (nearNonceFromApi) {
3417
+ nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
3418
+ }
3419
+ const newActions = transaction.actions.map((action) => {
3420
+ switch (action.type) {
3421
+ case "FunctionCall":
3422
+ return functionCall(
3423
+ action.params.methodName,
3424
+ action.params.args,
3425
+ BigInt(action.params.gas),
3426
+ BigInt(action.params.deposit)
3427
+ );
3428
+ case "Transfer":
3429
+ return transfer(BigInt(action.params.deposit));
3430
+ }
3431
+ }).filter(Boolean);
3432
+ const _transaction = import_near_api_js2.transactions.createTransaction(
3433
+ accountId,
3434
+ publicKeyFormat,
3435
+ transaction.receiverId,
3436
+ BigInt(nearNonceNumber) + BigInt(index),
3437
+ newActions,
3438
+ (0, import_utils9.baseDecode)(header.hash)
3439
+ );
3440
+ const txBytes = (0, import_transaction.encodeTransaction)(_transaction);
3441
+ const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
3442
+ ""
3443
+ );
3444
+ const hash = import_bs58.default.encode(new Uint8Array(import_js_sha256.sha256.array(txBytes)));
3445
+ return { txBytes, txHex, hash };
3446
+ });
3447
+ }
3448
+ function calculateGasLimit(params) {
3449
+ return __async(this, null, function* () {
3450
+ const trans = [...params.transactions];
3451
+ console.log("raw trans:", trans);
3452
+ const { gasLimit } = yield calculateGasStrategy(params);
3453
+ return gasLimit;
3454
+ });
3455
+ }
3456
+ function calculateGasStrategy(_0) {
3457
+ return __async(this, arguments, function* ({
3458
+ csna,
3459
+ transactions: transactions2,
3460
+ env
3461
+ }) {
3462
+ var _a;
3463
+ const currentConfig = getWalletConfig(env);
3464
+ const accountInfo = yield getAccountInfo({ csna, env });
3465
+ const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
3466
+ const { balance: nearBalance } = yield getTokenBalance({
3467
+ csna,
3468
+ tokenId: currentConfig.nearToken,
3469
+ env
3470
+ });
3471
+ const transferAmount = transactions2.reduce(
3472
+ (acc, tx) => {
3473
+ tx.actions.forEach((action) => {
3474
+ if (action.params.deposit) {
3475
+ const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
3476
+ console.log("near deposit amount:", amount);
3477
+ acc.near = acc.near.plus(amount);
3478
+ }
3479
+ if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
3480
+ const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
3481
+ console.log("btc transfer amount:", amount);
3482
+ acc.btc = acc.btc.plus(amount);
3483
+ }
3484
+ });
3485
+ return acc;
3486
+ },
3487
+ { near: new import_big.default(0), btc: new import_big.default(0) }
3488
+ );
3489
+ const nearAvailableBalance = new import_big.default(nearBalance).minus(transferAmount.near).toNumber();
3490
+ console.log("available near balance:", nearAvailableBalance);
3491
+ console.log("available gas token balance:", gasTokenBalance);
3492
+ const convertTx = yield Promise.all(
3493
+ transactions2.map(
3494
+ (transaction, index) => convertTransactionToTxHex({
3495
+ transaction,
3496
+ accountId: state_default.getAccount(),
3497
+ publicKey: state_default.getPublicKey(),
3498
+ index,
3499
+ env
3500
+ })
3501
+ )
3502
+ );
3503
+ if (nearAvailableBalance > 0.5) {
3504
+ console.log("near balance is enough, get the protocol fee of each transaction");
3505
+ const gasTokens = yield nearCallFunction(
3506
+ currentConfig.accountContractId,
3507
+ "list_gas_token",
3508
+ { token_ids: [currentConfig.btcToken] },
3509
+ { network: currentConfig.network }
3510
+ );
3511
+ console.log("list_gas_token gas tokens:", gasTokens);
3512
+ const perTxFee = Math.max(
3513
+ Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
3514
+ 100
3515
+ );
3516
+ console.log("perTxFee:", perTxFee);
3517
+ const protocolFee = new import_big.default(perTxFee || "0").mul(convertTx.length).toFixed(0);
3518
+ console.log("protocolFee:", protocolFee);
3519
+ if (new import_big.default(gasTokenBalance).gte(protocolFee)) {
3520
+ console.log("use near pay gas and enough gas token balance");
3521
+ return { useNearPayGas: true, gasLimit: protocolFee };
3522
+ } else {
3523
+ console.log("use near pay gas and not enough gas token balance");
3524
+ const transferTx = yield createGasTokenTransfer({ csna, amount: protocolFee, env });
3525
+ return recalculateGasWithTransfer({
3526
+ csna,
3527
+ transferTx,
3528
+ transactions: convertTx,
3529
+ useNearPayGas: true,
3530
+ perTxFee: perTxFee.toString(),
3531
+ env
3532
+ });
3533
+ }
3534
+ } else {
3535
+ console.log("near balance is not enough, predict the gas token amount required");
3536
+ const adjustedGas = yield getPredictedGasAmount({
3537
+ accountContractId: currentConfig.accountContractId,
3538
+ tokenId: currentConfig.btcToken,
3539
+ transactions: convertTx.map((t) => t.txHex),
3540
+ env
3541
+ });
3542
+ if (new import_big.default(gasTokenBalance).gte(adjustedGas)) {
3543
+ console.log("use gas token and gas token balance is enough");
3544
+ return { useNearPayGas: false, gasLimit: adjustedGas };
3545
+ } else {
3546
+ console.log("use gas token and gas token balance is not enough, need to transfer");
3547
+ const transferTx = yield createGasTokenTransfer({ csna, amount: adjustedGas, env });
3548
+ return recalculateGasWithTransfer({
3549
+ csna,
3550
+ transferTx,
3551
+ transactions: convertTx,
3552
+ useNearPayGas: false,
3553
+ env
3554
+ });
3555
+ }
3556
+ }
3557
+ });
3558
+ }
3559
+ function createGasTokenTransfer(_0) {
3560
+ return __async(this, arguments, function* ({
3561
+ csna,
3562
+ amount,
3563
+ env
3564
+ }) {
3565
+ const currentConfig = getWalletConfig(env);
3566
+ return {
3567
+ signerId: csna,
3568
+ receiverId: currentConfig.btcToken,
3569
+ actions: [
3570
+ {
3571
+ type: "FunctionCall",
3572
+ params: {
3573
+ methodName: "ft_transfer_call",
3574
+ args: {
3575
+ receiver_id: currentConfig.accountContractId,
3576
+ amount,
3577
+ msg: JSON.stringify("Repay")
3578
+ },
3579
+ gas: new import_big.default(50).mul(__pow(10, 12)).toFixed(0),
3580
+ deposit: "1"
3581
+ }
3582
+ }
3583
+ ]
3584
+ };
3585
+ });
3586
+ }
3587
+ function recalculateGasWithTransfer(_0) {
3588
+ return __async(this, arguments, function* ({
3589
+ csna,
3590
+ transferTx,
3591
+ transactions: transactions2,
3592
+ useNearPayGas,
3593
+ perTxFee,
3594
+ env
3595
+ }) {
3596
+ const currentConfig = getWalletConfig(env);
3597
+ const { txHex: transferTxHex } = yield convertTransactionToTxHex({
3598
+ transaction: transferTx,
3599
+ accountId: state_default.getAccount(),
3600
+ publicKey: state_default.getPublicKey(),
3601
+ index: 0,
3602
+ env
3603
+ });
3604
+ let newGasLimit;
3605
+ if (useNearPayGas && perTxFee) {
3606
+ newGasLimit = new import_big.default(perTxFee).mul(transactions2.length + 1).toFixed(0);
3607
+ } else {
3608
+ newGasLimit = yield getPredictedGasAmount({
3609
+ accountContractId: currentConfig.accountContractId,
3610
+ tokenId: currentConfig.btcToken,
3611
+ transactions: [transferTxHex, ...transactions2.map((t) => t.txHex)],
3612
+ env
3613
+ });
3614
+ }
3615
+ transferTx.actions[0].params.args.amount = newGasLimit;
3616
+ return { transferGasTransaction: transferTx, useNearPayGas, gasLimit: newGasLimit };
3617
+ });
3618
+ }
3619
+ function getPredictedGasAmount(_0) {
3620
+ return __async(this, arguments, function* ({
3621
+ accountContractId,
3622
+ tokenId,
3623
+ transactions: transactions2,
3624
+ env
3625
+ }) {
3626
+ const currentConfig = getWalletConfig(env);
3627
+ const predictedGas = yield nearCallFunction(
3628
+ accountContractId,
3629
+ "predict_txs_gas_token_amount",
3630
+ {
3631
+ gas_token_id: tokenId,
3632
+ near_transactions: transactions2
3633
+ },
3634
+ { network: currentConfig.network }
3635
+ );
3636
+ const predictedGasAmount = new import_big.default(predictedGas).mul(1.2).toFixed(0);
3637
+ const miniGasAmount = 200 * transactions2.length;
3638
+ const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
3639
+ console.log("predictedGas:", predictedGasAmount);
3640
+ return gasAmount.toString();
3641
+ });
3642
+ }
3643
+
3644
+ // src/core/btcUtils.ts
3645
+ var import_bitcoinjs_lib = __toESM(require("bitcoinjs-lib"), 1);
3646
+ var ecc = __toESM(require("@bitcoinerlab/secp256k1"), 1);
3647
+ var import_coinselect = __toESM(require("coinselect"), 1);
3648
+ import_bitcoinjs_lib.default.initEccLib(ecc);
3649
+ var NEAR_STORAGE_DEPOSIT_AMOUNT = "1250000000000000000000";
3650
+ var NBTC_STORAGE_DEPOSIT_AMOUNT = "3000";
3651
+ var GAS_LIMIT = "50000000000000";
3652
+ var NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT = "1000";
3653
+ function getBtcProvider() {
3654
+ if (typeof window === "undefined" || !window.btcContext) {
3655
+ throw new Error("BTC Provider is not initialized.");
3656
+ }
3657
+ return window.btcContext;
3658
+ }
3659
+ function getNetwork() {
3660
+ return __async(this, null, function* () {
3661
+ const network = yield getBtcProvider().getNetwork();
3662
+ console.log("btc network:", network);
3663
+ return network === "livenet" ? "mainnet" : "testnet";
3664
+ });
3665
+ }
3666
+ function getBtcRpcUrl() {
3667
+ return __async(this, null, function* () {
3668
+ const network = yield getNetwork();
3669
+ return btcRpcUrls[network];
3670
+ });
3671
+ }
3672
+ function nearCall(contractId, methodName, args) {
3673
+ return __async(this, null, function* () {
3674
+ const network = yield getNetwork();
3675
+ return nearCallFunction(contractId, methodName, args, { network });
3676
+ });
3677
+ }
3678
+ function checkGasTokenDebt(csna, env, autoDeposit) {
3327
3679
  return __async(this, null, function* () {
3328
3680
  var _a, _b, _c;
3329
- const debtAmount = new import_big.default(((_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();
3681
+ const accountInfo = yield getAccountInfo({ csna, env });
3682
+ const debtAmount = new import_big2.default(((_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();
3330
3683
  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;
3331
- const hasDebtArrears = new import_big.default(debtAmount).gt(0);
3332
- const hasRelayerFeeArrears = new import_big.default(relayerFeeAmount).gt(0);
3684
+ const hasDebtArrears = new import_big2.default(debtAmount).gt(0);
3685
+ const hasRelayerFeeArrears = new import_big2.default(relayerFeeAmount).gt(0);
3333
3686
  if (!hasDebtArrears && !hasRelayerFeeArrears)
3334
3687
  return;
3335
- const config = yield getConfig(env);
3688
+ const config = getWalletConfig(env);
3336
3689
  const transferAmount = hasDebtArrears ? debtAmount : relayerFeeAmount;
3337
3690
  const action = {
3338
3691
  receiver_id: config.accountContractId,
@@ -3390,7 +3743,7 @@ function getBtcBalance() {
3390
3743
  const estimatedFee = Math.ceil(estimatedTxSize * feeRate);
3391
3744
  console.log("estimatedFee:", estimatedFee);
3392
3745
  const availableRawBalance = (rawBalance - estimatedFee).toFixed(0);
3393
- const availableBalance = new import_big.default(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, import_big.default.roundDown).toNumber();
3746
+ const availableBalance = new import_big2.default(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, import_big2.default.roundDown).toNumber();
3394
3747
  return {
3395
3748
  rawBalance,
3396
3749
  balance,
@@ -3415,10 +3768,10 @@ function getDepositAmount(amount, option) {
3415
3768
  var _a;
3416
3769
  const env = (option == null ? void 0 : option.env) || "mainnet";
3417
3770
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3418
- const config = yield getConfig(env);
3771
+ const config = getWalletConfig(env);
3419
3772
  const csna = yield getCsnaAccountId(env);
3420
3773
  const accountInfo = yield getAccountInfo({ csna, env });
3421
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3774
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3422
3775
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
3423
3776
  const {
3424
3777
  deposit_bridge_fee: { fee_min, fee_rate },
@@ -3427,7 +3780,7 @@ function getDepositAmount(amount, option) {
3427
3780
  const depositAmount = Math.max(Number(min_deposit_amount), Number(amount));
3428
3781
  const protocolFee = Math.max(Number(fee_min), Number(depositAmount) * fee_rate);
3429
3782
  const newAccountMinDepositAmount = !(accountInfo == null ? void 0 : accountInfo.nonce) && _newAccountMinDepositAmount ? NEW_ACCOUNT_MIN_DEPOSIT_AMOUNT : 0;
3430
- const totalDepositAmount = new import_big.default(depositAmount).plus(protocolFee).plus(repayAmount).plus(newAccountMinDepositAmount).round(0, import_big.default.roundDown).toNumber();
3783
+ const totalDepositAmount = new import_big2.default(depositAmount).plus(protocolFee).plus(repayAmount).plus(newAccountMinDepositAmount).round(0, import_big2.default.roundDown).toNumber();
3431
3784
  return {
3432
3785
  depositAmount,
3433
3786
  totalDepositAmount,
@@ -3439,7 +3792,7 @@ function getDepositAmount(amount, option) {
3439
3792
  }
3440
3793
  function getCsnaAccountId(env) {
3441
3794
  return __async(this, null, function* () {
3442
- const config = yield getConfig(env);
3795
+ const config = getWalletConfig(env);
3443
3796
  const { getPublicKey } = getBtcProvider();
3444
3797
  const btcPublicKey = yield getPublicKey();
3445
3798
  if (!btcPublicKey) {
@@ -3477,9 +3830,10 @@ function executeBTCDepositAndAction(_0) {
3477
3830
  }) {
3478
3831
  var _a;
3479
3832
  try {
3833
+ console.log("executeBTCDepositAndAction start", amount);
3480
3834
  checkDepositDisabledAddress();
3481
3835
  const { getPublicKey } = getBtcProvider();
3482
- const config = yield getConfig(env);
3836
+ const config = getWalletConfig(env);
3483
3837
  const btcPublicKey = yield getPublicKey();
3484
3838
  if (!btcPublicKey) {
3485
3839
  throw new Error("BTC Public Key is not available.");
@@ -3489,7 +3843,7 @@ function executeBTCDepositAndAction(_0) {
3489
3843
  }
3490
3844
  const csna = yield getCsnaAccountId(env);
3491
3845
  const depositAmount = (_a = action ? action.amount : amount) != null ? _a : "0";
3492
- if (new import_big.default(depositAmount).lt(0)) {
3846
+ if (new import_big2.default(depositAmount).lt(0)) {
3493
3847
  throw new Error("amount must be greater than 0");
3494
3848
  }
3495
3849
  const { totalDepositAmount, protocolFee, repayAmount } = yield getDepositAmount(depositAmount, {
@@ -3498,7 +3852,7 @@ function executeBTCDepositAndAction(_0) {
3498
3852
  });
3499
3853
  const accountInfo = yield getAccountInfo({ csna, env });
3500
3854
  const newActions = [];
3501
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3855
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3502
3856
  if (debtAction) {
3503
3857
  newActions.push(__spreadProps(__spreadValues({}, debtAction), {
3504
3858
  gas: GAS_LIMIT
@@ -3510,12 +3864,17 @@ function executeBTCDepositAndAction(_0) {
3510
3864
  }));
3511
3865
  }
3512
3866
  const storageDepositMsg = {};
3513
- const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.btcToken, "storage_balance_of", {
3867
+ const registerContractId = ((action == null ? void 0 : action.receiver_id) || config.btcToken).replace(
3868
+ config.accountContractId,
3869
+ config.btcToken
3870
+ );
3871
+ console.log("executeBTCDepositAndAction registerContractId", registerContractId);
3872
+ const registerRes = yield nearCall(registerContractId, "storage_balance_of", {
3514
3873
  account_id: csna
3515
3874
  });
3516
3875
  if (!(registerRes == null ? void 0 : registerRes.available)) {
3517
3876
  storageDepositMsg.storage_deposit_msg = {
3518
- contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
3877
+ contract_id: registerContractId,
3519
3878
  deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
3520
3879
  registration_only: true
3521
3880
  };
@@ -3586,7 +3945,7 @@ function checkSatoshiWhitelist(btcAccountId, env = "mainnet") {
3586
3945
  }
3587
3946
  if (!btcAccountId)
3588
3947
  return;
3589
- const config = yield getConfig(env);
3948
+ const config = getWalletConfig(env);
3590
3949
  const whitelist = yield getWhitelist(config.base_url);
3591
3950
  if (!(whitelist == null ? void 0 : whitelist.length))
3592
3951
  return;
@@ -3609,9 +3968,11 @@ function getWithdrawTransaction(_0) {
3609
3968
  feeRate,
3610
3969
  env = "mainnet"
3611
3970
  }) {
3971
+ console.log("=== Start getWithdrawTransaction ===");
3612
3972
  const provider = getBtcProvider();
3613
3973
  const btcAddress = provider.account;
3614
- const config = yield getConfig(env);
3974
+ const config = getWalletConfig(env);
3975
+ const csna = yield getCsnaAccountId(env);
3615
3976
  const brgConfig = yield nearCall(config.bridgeContractId, "get_config", {});
3616
3977
  if (brgConfig.min_withdraw_amount) {
3617
3978
  if (Number(amount) < Number(brgConfig.min_withdraw_amount)) {
@@ -3620,7 +3981,39 @@ function getWithdrawTransaction(_0) {
3620
3981
  }
3621
3982
  const feePercent = Number(brgConfig.withdraw_bridge_fee.fee_rate) * Number(amount);
3622
3983
  const withdrawFee = feePercent > Number(brgConfig.withdraw_bridge_fee.fee_min) ? feePercent : Number(brgConfig.withdraw_bridge_fee.fee_min);
3984
+ console.log("Withdrawal Fee:", {
3985
+ feePercent,
3986
+ withdrawFee,
3987
+ minFee: brgConfig.withdraw_bridge_fee.fee_min
3988
+ });
3989
+ const gasLimit = yield calculateGasLimit({
3990
+ csna,
3991
+ transactions: [
3992
+ {
3993
+ signerId: "",
3994
+ receiverId: config.btcToken,
3995
+ actions: [
3996
+ {
3997
+ type: "FunctionCall",
3998
+ params: {
3999
+ methodName: "ft_transfer_call",
4000
+ args: {
4001
+ receiver_id: config.btcToken,
4002
+ amount: "100",
4003
+ msg: ""
4004
+ },
4005
+ gas: "300000000000000",
4006
+ deposit: "1"
4007
+ }
4008
+ }
4009
+ ]
4010
+ }
4011
+ ],
4012
+ env
4013
+ });
4014
+ const finalAmount = Number(gasLimit) > 0 ? Number(amount) - Number(gasLimit) : Number(amount);
3623
4015
  const allUTXO = yield nearCall(config.bridgeContractId, "get_utxos_paged", {});
4016
+ console.log("All UTXOs:", allUTXO);
3624
4017
  if (!allUTXO || Object.keys(allUTXO).length === 0) {
3625
4018
  throw new Error("The network is busy, please try again later.");
3626
4019
  }
@@ -3633,42 +4026,48 @@ function getWithdrawTransaction(_0) {
3633
4026
  script: allUTXO[key].script
3634
4027
  };
3635
4028
  });
4029
+ console.log("Formatted UTXOs:", utxos);
3636
4030
  const _feeRate = feeRate || (yield getBtcGasPrice());
3637
- let { inputs, outputs, fee } = (0, import_coinselect.default)(
4031
+ console.log("Fee Rate:", _feeRate);
4032
+ const coinSelectResult = (0, import_coinselect.default)(
3638
4033
  utxos,
3639
- [{ address: btcAddress, value: Number(amount) }],
4034
+ [{ address: btcAddress, value: Number(finalAmount) }],
3640
4035
  Math.ceil(_feeRate)
3641
4036
  );
4037
+ console.log("Coinselect Result:", coinSelectResult);
4038
+ const { inputs, outputs, fee } = coinSelectResult;
3642
4039
  if (!outputs || !inputs) {
3643
4040
  throw new Error("The network is busy, please try again later.");
3644
4041
  }
3645
4042
  const maxBtcFee = Number(brgConfig.max_btc_gas_fee);
3646
4043
  const transactionFee = fee;
3647
- const changeAddress = brgConfig.change_address;
4044
+ console.log("Transaction Fee:", { transactionFee, maxBtcFee });
3648
4045
  if (transactionFee > maxBtcFee) {
3649
4046
  throw new Error("Gas exceeds maximum value");
3650
4047
  }
3651
4048
  let recipientOutput, changeOutput;
3652
4049
  for (let i = 0; i < outputs.length; i++) {
3653
4050
  const output = outputs[i];
3654
- if (output.value.toString() === amount.toString()) {
4051
+ if (output.value.toString() === finalAmount.toString()) {
3655
4052
  recipientOutput = output;
3656
4053
  } else {
3657
4054
  changeOutput = output;
3658
4055
  }
3659
4056
  if (!output.address) {
3660
- output.address = changeAddress;
4057
+ output.address = brgConfig.change_address;
3661
4058
  }
3662
4059
  }
3663
- recipientOutput.value = new import_big.default(recipientOutput.value).minus(transactionFee).minus(withdrawFee).toNumber();
4060
+ console.log("Initial Outputs:", { recipientOutput, changeOutput });
4061
+ recipientOutput.value = new import_big2.default(recipientOutput.value).minus(transactionFee).minus(withdrawFee).toNumber();
3664
4062
  if (changeOutput) {
3665
- changeOutput.value = new import_big.default(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
4063
+ changeOutput.value = new import_big2.default(changeOutput.value).plus(transactionFee).plus(withdrawFee).toNumber();
3666
4064
  const remainingInputs = [...inputs];
3667
4065
  let smallestInput = Math.min.apply(
3668
4066
  null,
3669
4067
  remainingInputs.map((input) => input.value)
3670
4068
  );
3671
4069
  let remainingChangeAmount = changeOutput.value;
4070
+ console.log("Initial Change Processing:", { smallestInput, remainingChangeAmount });
3672
4071
  while (remainingChangeAmount >= smallestInput && smallestInput > 0 && remainingInputs.length > 0) {
3673
4072
  remainingChangeAmount -= smallestInput;
3674
4073
  changeOutput.value = remainingChangeAmount;
@@ -3682,30 +4081,50 @@ function getWithdrawTransaction(_0) {
3682
4081
  null,
3683
4082
  remainingInputs.map((input) => input.value)
3684
4083
  );
4084
+ console.log("Change Processing Loop:", {
4085
+ remainingChangeAmount,
4086
+ smallestInput,
4087
+ remainingInputsCount: remainingInputs.length
4088
+ });
3685
4089
  }
3686
4090
  const minChangeAmount = Number(brgConfig.min_change_amount);
3687
4091
  let additionalFee = 0;
4092
+ console.log("Checking minimum change amount:", {
4093
+ changeValue: changeOutput.value,
4094
+ minChangeAmount
4095
+ });
4096
+ let finalOutputs = [...outputs];
3688
4097
  if (changeOutput.value === 0) {
3689
- outputs = outputs.filter((item) => item.value !== 0);
4098
+ finalOutputs = finalOutputs.filter((output) => output.value !== 0);
4099
+ console.log("Removed zero-value change output", finalOutputs);
3690
4100
  } else if (changeOutput.value < minChangeAmount) {
3691
4101
  additionalFee = minChangeAmount - changeOutput.value;
3692
4102
  recipientOutput.value -= additionalFee;
3693
4103
  changeOutput.value = minChangeAmount;
4104
+ console.log("Adjusted for minimum change amount:", {
4105
+ additionalFee,
4106
+ newRecipientValue: recipientOutput.value,
4107
+ newChangeValue: changeOutput.value
4108
+ });
3694
4109
  }
3695
4110
  } else {
3696
4111
  changeOutput = {
3697
- address: changeAddress,
3698
- value: new import_big.default(transactionFee).plus(withdrawFee).toNumber()
4112
+ address: brgConfig.change_address,
4113
+ value: new import_big2.default(transactionFee).plus(withdrawFee).toNumber()
3699
4114
  };
3700
4115
  outputs.push(changeOutput);
4116
+ console.log("Created new change output:", changeOutput);
3701
4117
  }
3702
4118
  const insufficientOutput = outputs.some((item) => item.value < 0);
3703
4119
  if (insufficientOutput) {
4120
+ console.error("Negative output value detected");
3704
4121
  throw new Error("Not enough gas");
3705
4122
  }
3706
4123
  const inputSum = inputs.reduce((sum, cur) => sum + Number(cur.value), 0);
3707
4124
  const outputSum = outputs.reduce((sum, cur) => sum + Number(cur.value), 0);
4125
+ console.log("Balance verification:", { inputSum, outputSum, transactionFee });
3708
4126
  if (transactionFee + outputSum !== inputSum) {
4127
+ console.error("Balance mismatch:", { inputSum, outputSum, transactionFee });
3709
4128
  throw new Error("compute error");
3710
4129
  }
3711
4130
  const network = yield getNetwork();
@@ -3732,6 +4151,7 @@ function getWithdrawTransaction(_0) {
3732
4151
  value: output.value
3733
4152
  });
3734
4153
  });
4154
+ console.log("outputs:", JSON.stringify(outputs));
3735
4155
  const _inputs = inputs.map((item) => {
3736
4156
  return `${item.txid}:${item.vout}`;
3737
4157
  });
@@ -3748,7 +4168,6 @@ function getWithdrawTransaction(_0) {
3748
4168
  output: txOutputs
3749
4169
  }
3750
4170
  };
3751
- const csna = yield getCsnaAccountId(env);
3752
4171
  const transaction = {
3753
4172
  receiverId: config.btcToken,
3754
4173
  signerId: csna,
@@ -3768,6 +4187,7 @@ function getWithdrawTransaction(_0) {
3768
4187
  }
3769
4188
  ]
3770
4189
  };
4190
+ console.log("=== End getWithdrawTransaction ===");
3771
4191
  return transaction;
3772
4192
  });
3773
4193
  }
@@ -4008,86 +4428,7 @@ function updateIframePosition(iframe, buttonRight, buttonBottom, windowWidth, wi
4008
4428
  iframe.style.bottom = `${iframeBottom}px`;
4009
4429
  }
4010
4430
 
4011
- // src/core/setupBTCWallet.ts
4012
- var import_big2 = __toESM(require("big.js"), 1);
4013
- var { transfer, functionCall } = import_transactions.actionCreators;
4014
- var STORAGE_KEYS = {
4015
- ACCOUNT: "btc-wallet-account",
4016
- PUBLIC_KEY: "btc-wallet-publickey",
4017
- BTC_PUBLIC_KEY: "btc-wallet-btc-publickey"
4018
- };
4019
- var state = {
4020
- saveAccount(account) {
4021
- if (!account) {
4022
- this.removeAccount();
4023
- return;
4024
- }
4025
- window.localStorage.setItem(STORAGE_KEYS.ACCOUNT, account);
4026
- },
4027
- removeAccount() {
4028
- window.localStorage.removeItem(STORAGE_KEYS.ACCOUNT);
4029
- },
4030
- savePublicKey(publicKey) {
4031
- if (!publicKey) {
4032
- this.removePublicKey();
4033
- return;
4034
- }
4035
- window.localStorage.setItem(STORAGE_KEYS.PUBLIC_KEY, publicKey);
4036
- },
4037
- removePublicKey() {
4038
- window.localStorage.removeItem(STORAGE_KEYS.PUBLIC_KEY);
4039
- },
4040
- saveBtcPublicKey(publicKey) {
4041
- if (!publicKey) {
4042
- this.removeBtcPublicKey();
4043
- return;
4044
- }
4045
- window.localStorage.setItem(STORAGE_KEYS.BTC_PUBLIC_KEY, publicKey);
4046
- },
4047
- removeBtcPublicKey() {
4048
- window.localStorage.removeItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
4049
- },
4050
- clear() {
4051
- this.removeAccount();
4052
- this.removePublicKey();
4053
- this.removeBtcPublicKey();
4054
- },
4055
- save(account, publicKey) {
4056
- if (!account || !publicKey) {
4057
- this.clear();
4058
- return;
4059
- }
4060
- this.saveAccount(account);
4061
- this.savePublicKey(publicKey);
4062
- },
4063
- getAccount() {
4064
- return window.localStorage.getItem(STORAGE_KEYS.ACCOUNT);
4065
- },
4066
- getPublicKey() {
4067
- return window.localStorage.getItem(STORAGE_KEYS.PUBLIC_KEY);
4068
- },
4069
- getBtcPublicKey() {
4070
- return window.localStorage.getItem(STORAGE_KEYS.BTC_PUBLIC_KEY);
4071
- },
4072
- isValid() {
4073
- const account = this.getAccount();
4074
- const publicKey = this.getPublicKey();
4075
- const btcPublicKey = this.getBtcPublicKey();
4076
- const allEmpty = !account && !publicKey && !btcPublicKey;
4077
- const allExist = account && publicKey && btcPublicKey;
4078
- return allEmpty || allExist;
4079
- },
4080
- syncSave(account, publicKey, btcPublicKey) {
4081
- if (!account || !publicKey || !btcPublicKey) {
4082
- this.clear();
4083
- return;
4084
- }
4085
- this.clear();
4086
- this.savePublicKey(publicKey);
4087
- this.saveBtcPublicKey(btcPublicKey);
4088
- this.saveAccount(account);
4089
- }
4090
- };
4431
+ // src/core/setupBTCWallet/index.ts
4091
4432
  var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4092
4433
  metadata,
4093
4434
  options,
@@ -4109,15 +4450,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4109
4450
  calculateGasLimit
4110
4451
  };
4111
4452
  const env = metadata.env || options.network.networkId || "mainnet";
4112
- const currentConfig = walletConfig[env];
4113
- const walletNetwork = ["mainnet", "private_mainnet"].includes(env) ? "mainnet" : "testnet";
4453
+ const currentConfig = getWalletConfig(env);
4114
4454
  yield initBtcContext();
4115
4455
  function validateWalletState() {
4116
- const accountId = state.getAccount();
4117
- const publicKey = state.getPublicKey();
4118
- const btcPublicKey = state.getBtcPublicKey();
4456
+ const accountId = state_default.getAccount();
4457
+ const publicKey = state_default.getPublicKey();
4458
+ const btcPublicKey = state_default.getBtcPublicKey();
4119
4459
  if (!accountId && publicKey || accountId && !publicKey || !publicKey && btcPublicKey) {
4120
- state.clear();
4460
+ state_default.clear();
4121
4461
  return false;
4122
4462
  }
4123
4463
  return true;
@@ -4125,9 +4465,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4125
4465
  function setupBtcContextListeners() {
4126
4466
  return __async(this, null, function* () {
4127
4467
  const handleConnectionUpdate = () => __async(this, null, function* () {
4128
- yield checkBtcNetwork(walletNetwork);
4129
- if (!state.isValid()) {
4130
- state.clear();
4468
+ yield checkBtcNetwork(currentConfig.network);
4469
+ if (!state_default.isValid()) {
4470
+ state_default.clear();
4131
4471
  console.log("setupBtcContextListeners clear");
4132
4472
  }
4133
4473
  validateWalletState();
@@ -4150,7 +4490,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4150
4490
  const context = window.btcContext.getContext();
4151
4491
  context.on("updatePublicKey", (btcPublicKey) => __async(this, null, function* () {
4152
4492
  console.log("updatePublicKey");
4153
- state.clear();
4493
+ state_default.clear();
4154
4494
  console.log("updatePublicKey clear");
4155
4495
  try {
4156
4496
  const { nearAddress, nearPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
@@ -4169,7 +4509,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4169
4509
  }));
4170
4510
  context.on("btcLogOut", () => __async(this, null, function* () {
4171
4511
  console.log("btcLogOut");
4172
- state.clear();
4512
+ state_default.clear();
4173
4513
  emitter.emit("accountsChanged", { accounts: [] });
4174
4514
  yield handleConnectionUpdate();
4175
4515
  }));
@@ -4213,7 +4553,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4213
4553
  "get_chain_signature_near_account_public_key",
4214
4554
  { btc_public_key: btcPublicKey }
4215
4555
  );
4216
- state.syncSave(csna, nearPublicKey, btcPublicKey);
4556
+ state_default.syncSave(csna, nearPublicKey, btcPublicKey);
4217
4557
  return {
4218
4558
  nearAddress: csna,
4219
4559
  nearPublicKey
@@ -4223,8 +4563,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4223
4563
  function signIn(_02) {
4224
4564
  return __async(this, arguments, function* ({ contractId, methodNames }) {
4225
4565
  const btcContext = window.btcContext;
4226
- state.clear();
4227
- if (!state.getAccount() || !state.getPublicKey()) {
4566
+ state_default.clear();
4567
+ if (!state_default.getAccount() || !state_default.getPublicKey()) {
4228
4568
  yield btcContext.login();
4229
4569
  }
4230
4570
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4243,8 +4583,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4243
4583
  }
4244
4584
  function signOut() {
4245
4585
  return __async(this, null, function* () {
4246
- const accountId = state.getAccount();
4247
- const publicKey = state.getPublicKey();
4586
+ const accountId = state_default.getAccount();
4587
+ const publicKey = state_default.getPublicKey();
4248
4588
  if (!(accountId && publicKey)) {
4249
4589
  return;
4250
4590
  }
@@ -4252,19 +4592,19 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4252
4592
  if (metadata.syncLogOut) {
4253
4593
  btcContext.logout();
4254
4594
  }
4255
- state.clear();
4595
+ state_default.clear();
4256
4596
  window.localStorage.removeItem("near-wallet-selector:selectedWalletId");
4257
4597
  removeWalletButton();
4258
4598
  });
4259
4599
  }
4260
4600
  function isSignedIn() {
4261
- const accountId = state.getAccount();
4262
- const publicKey = state.getPublicKey();
4601
+ const accountId = state_default.getAccount();
4602
+ const publicKey = state_default.getPublicKey();
4263
4603
  return accountId && publicKey;
4264
4604
  }
4265
4605
  function getAccounts() {
4266
4606
  return __async(this, null, function* () {
4267
- return [{ accountId: state.getAccount() }];
4607
+ return [{ accountId: state_default.getAccount() }];
4268
4608
  });
4269
4609
  }
4270
4610
  function verifyOwner() {
@@ -4294,12 +4634,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4294
4634
  throw new Error("Wallet state is invalid, please reconnect your wallet.");
4295
4635
  }
4296
4636
  const btcContext = window.btcContext;
4297
- const csna = state.getAccount();
4637
+ const csna = state_default.getAccount();
4298
4638
  const accountInfo = yield getAccountInfo({ csna, env });
4299
- yield checkGasTokenDebt(accountInfo, env, true);
4639
+ yield checkGasTokenDebt(csna, env, true);
4300
4640
  const trans = [...params.transactions];
4301
4641
  console.log("signAndSendTransactions raw trans:", trans);
4302
- const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
4642
+ const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy({
4643
+ csna,
4644
+ transactions: trans,
4645
+ env
4646
+ });
4303
4647
  console.log("transferGasTransaction:", transferGasTransaction);
4304
4648
  console.log("useNearPayGas:", useNearPayGas);
4305
4649
  console.log("gasLimit:", gasLimit);
@@ -4309,7 +4653,15 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4309
4653
  }
4310
4654
  console.log("calculateGasStrategy trans:", trans);
4311
4655
  const newTrans = yield Promise.all(
4312
- trans.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4656
+ trans.map(
4657
+ (transaction, index) => convertTransactionToTxHex({
4658
+ transaction,
4659
+ accountId: state_default.getAccount(),
4660
+ publicKey: state_default.getPublicKey(),
4661
+ index,
4662
+ env
4663
+ })
4664
+ )
4313
4665
  );
4314
4666
  const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
4315
4667
  const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
@@ -4327,7 +4679,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4327
4679
  const signature = yield btcContext.signMessage(strIntention);
4328
4680
  yield receiveTransaction(currentConfig.base_url, {
4329
4681
  sig: signature,
4330
- btcPubKey: state.getBtcPublicKey(),
4682
+ btcPubKey: state_default.getBtcPublicKey(),
4331
4683
  data: toHex(strIntention)
4332
4684
  });
4333
4685
  yield checkBtcTransactionStatus(currentConfig.base_url, signature);
@@ -4337,197 +4689,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4337
4689
  return result;
4338
4690
  });
4339
4691
  }
4340
- function calculateGasLimit(params) {
4341
- return __async(this, null, function* () {
4342
- const trans = [...params.transactions];
4343
- console.log("raw trans:", trans);
4344
- const { gasLimit } = yield calculateGasStrategy(trans);
4345
- return gasLimit;
4346
- });
4347
- }
4348
- function createGasTokenTransfer(accountId, amount) {
4349
- return __async(this, null, function* () {
4350
- return {
4351
- signerId: accountId,
4352
- receiverId: currentConfig.btcToken,
4353
- actions: [
4354
- {
4355
- type: "FunctionCall",
4356
- params: {
4357
- methodName: "ft_transfer_call",
4358
- args: {
4359
- receiver_id: currentConfig.accountContractId,
4360
- amount,
4361
- msg: JSON.stringify("Repay")
4362
- },
4363
- gas: new import_big2.default(50).mul(__pow(10, 12)).toFixed(0),
4364
- deposit: "1"
4365
- }
4366
- }
4367
- ]
4368
- };
4369
- });
4370
- }
4371
- function recalculateGasWithTransfer(transferTx, transactions2, useNearPayGas, perTxFee) {
4372
- return __async(this, null, function* () {
4373
- const { txHex: transferTxHex } = yield convertTransactionToTxHex(transferTx);
4374
- let newGasLimit;
4375
- if (useNearPayGas && perTxFee) {
4376
- newGasLimit = new import_big2.default(perTxFee).mul(transactions2.length + 1).toFixed(0);
4377
- } else {
4378
- newGasLimit = yield getPredictedGasAmount(
4379
- currentConfig.accountContractId,
4380
- currentConfig.btcToken,
4381
- [transferTxHex, ...transactions2.map((t) => t.txHex)]
4382
- );
4383
- }
4384
- transferTx.actions[0].params.args.amount = newGasLimit;
4385
- return { transferGasTransaction: transferTx, useNearPayGas, gasLimit: newGasLimit };
4386
- });
4387
- }
4388
- function getPredictedGasAmount(accountContractId, tokenId, transactions2) {
4389
- return __async(this, null, function* () {
4390
- const predictedGas = yield nearCall2(accountContractId, "predict_txs_gas_token_amount", {
4391
- gas_token_id: tokenId,
4392
- near_transactions: transactions2
4393
- });
4394
- const predictedGasAmount = new import_big2.default(predictedGas).mul(1.2).toFixed(0);
4395
- const miniGasAmount = 200 * transactions2.length;
4396
- const gasAmount = Math.max(Number(predictedGasAmount), miniGasAmount);
4397
- console.log("predictedGas:", predictedGasAmount);
4398
- return gasAmount.toString();
4399
- });
4400
- }
4401
- function calculateGasStrategy(transactions2) {
4402
- return __async(this, null, function* () {
4403
- var _a;
4404
- const accountId = state.getAccount();
4405
- const accountInfo = yield getAccountInfo({ csna: accountId, env });
4406
- const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
4407
- const { balance: nearBalance } = yield getTokenBalance({
4408
- csna: accountId,
4409
- tokenId: currentConfig.nearToken,
4410
- env
4411
- });
4412
- const transferAmount = transactions2.reduce(
4413
- (acc, tx) => {
4414
- tx.actions.forEach((action) => {
4415
- if (action.params.deposit) {
4416
- const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
4417
- console.log("near deposit amount:", amount);
4418
- acc.near = acc.near.plus(amount);
4419
- }
4420
- if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
4421
- const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
4422
- console.log("btc transfer amount:", amount);
4423
- acc.btc = acc.btc.plus(amount);
4424
- }
4425
- });
4426
- return acc;
4427
- },
4428
- { near: new import_big2.default(0), btc: new import_big2.default(0) }
4429
- );
4430
- const nearAvailableBalance = new import_big2.default(nearBalance).minus(transferAmount.near).toNumber();
4431
- console.log("available near balance:", nearAvailableBalance);
4432
- console.log("available gas token balance:", gasTokenBalance);
4433
- const convertTx = yield Promise.all(
4434
- transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
4435
- );
4436
- if (nearAvailableBalance > 0.5) {
4437
- console.log("near balance is enough, get the protocol fee of each transaction");
4438
- const gasTokens = yield nearCall2(
4439
- currentConfig.accountContractId,
4440
- "list_gas_token",
4441
- { token_ids: [currentConfig.btcToken] }
4442
- );
4443
- console.log("list_gas_token gas tokens:", gasTokens);
4444
- const perTxFee = Math.max(
4445
- Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
4446
- 100
4447
- );
4448
- console.log("perTxFee:", perTxFee);
4449
- const protocolFee = new import_big2.default(perTxFee || "0").mul(convertTx.length).toFixed(0);
4450
- console.log("protocolFee:", protocolFee);
4451
- if (new import_big2.default(gasTokenBalance).gte(protocolFee)) {
4452
- console.log("use near pay gas and enough gas token balance");
4453
- return { useNearPayGas: true, gasLimit: protocolFee };
4454
- } else {
4455
- console.log("use near pay gas and not enough gas token balance");
4456
- const transferTx = yield createGasTokenTransfer(accountId, protocolFee);
4457
- return recalculateGasWithTransfer(transferTx, convertTx, true, perTxFee.toString());
4458
- }
4459
- } else {
4460
- console.log("near balance is not enough, predict the gas token amount required");
4461
- const adjustedGas = yield getPredictedGasAmount(
4462
- currentConfig.accountContractId,
4463
- currentConfig.btcToken,
4464
- convertTx.map((t) => t.txHex)
4465
- );
4466
- if (new import_big2.default(gasTokenBalance).gte(adjustedGas)) {
4467
- console.log("use gas token and gas token balance is enough");
4468
- return { useNearPayGas: false, gasLimit: adjustedGas };
4469
- } else {
4470
- console.log("use gas token and gas token balance is not enough, need to transfer");
4471
- const transferTx = yield createGasTokenTransfer(accountId, adjustedGas);
4472
- return recalculateGasWithTransfer(transferTx, convertTx, false);
4473
- }
4474
- }
4475
- });
4476
- }
4477
- function convertTransactionToTxHex(transaction, index = 0) {
4478
- return __async(this, null, function* () {
4479
- const accountId = state.getAccount();
4480
- const publicKey = state.getPublicKey();
4481
- const publicKeyFormat = import_key_pair.PublicKey.from(publicKey);
4482
- const { header } = yield provider.block({
4483
- finality: "final"
4484
- });
4485
- const rawAccessKey = yield provider.query({
4486
- request_type: "view_access_key",
4487
- account_id: accountId,
4488
- public_key: publicKey,
4489
- finality: "final"
4490
- }).catch((e) => {
4491
- console.log("view_access_key error:", e);
4492
- return void 0;
4493
- });
4494
- const accessKey = __spreadProps(__spreadValues({}, rawAccessKey), {
4495
- nonce: BigInt((rawAccessKey == null ? void 0 : rawAccessKey.nonce) || 0)
4496
- });
4497
- const nearNonceFromApi = yield getNearNonce(currentConfig.base_url, accountId);
4498
- let nearNonceNumber = accessKey.nonce + BigInt(1);
4499
- if (nearNonceFromApi) {
4500
- nearNonceNumber = BigInt(nearNonceFromApi) > nearNonceNumber ? BigInt(nearNonceFromApi) : nearNonceNumber;
4501
- }
4502
- const newActions = transaction.actions.map((action) => {
4503
- switch (action.type) {
4504
- case "FunctionCall":
4505
- return functionCall(
4506
- action.params.methodName,
4507
- action.params.args,
4508
- BigInt(action.params.gas),
4509
- BigInt(action.params.deposit)
4510
- );
4511
- case "Transfer":
4512
- return transfer(BigInt(action.params.deposit));
4513
- }
4514
- }).filter(Boolean);
4515
- const _transaction = import_near_api_js2.transactions.createTransaction(
4516
- accountId,
4517
- publicKeyFormat,
4518
- transaction.receiverId,
4519
- BigInt(nearNonceNumber) + BigInt(index),
4520
- newActions,
4521
- (0, import_utils10.baseDecode)(header.hash)
4522
- );
4523
- const txBytes = (0, import_transaction.encodeTransaction)(_transaction);
4524
- const txHex = Array.from(txBytes, (byte) => ("0" + (byte & 255).toString(16)).slice(-2)).join(
4525
- ""
4526
- );
4527
- const hash = import_bs58.default.encode(new Uint8Array(import_js_sha256.sha256.array(txBytes)));
4528
- return { txBytes, txHex, hash };
4529
- });
4530
- }
4531
4692
  function checkBtcNetwork(network) {
4532
4693
  return __async(this, null, function* () {
4533
4694
  const btcContext = window.btcContext;
@@ -4576,7 +4737,7 @@ function setupBTCWallet({
4576
4737
 
4577
4738
  // src/index.ts
4578
4739
  var getVersion = () => {
4579
- return "0.5.15-beta";
4740
+ return "0.5.17-beta";
4580
4741
  };
4581
4742
  if (typeof window !== "undefined") {
4582
4743
  window.__BTC_WALLET_VERSION = getVersion();