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