btc-wallet 0.5.15-beta → 0.5.16-beta

Sign up to get free protection for your applications and to get access to all the features.
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,52 +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 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
3312
  function getAccountInfo(_0) {
3270
3313
  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) => {
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) => {
3275
3323
  return void 0;
3276
3324
  });
3277
3325
  console.log("get_account accountInfo:", accountInfo);
@@ -3284,9 +3332,8 @@ function getTokenBalance(_0) {
3284
3332
  tokenId,
3285
3333
  env
3286
3334
  }) {
3287
- const network = yield getNetwork();
3288
- const config = yield getConfig(env);
3289
- const nearProvider = getNearProvider({ network });
3335
+ const config = getWalletConfig(env);
3336
+ const nearProvider = getNearProvider({ network: config.network });
3290
3337
  try {
3291
3338
  if (tokenId === config.nearToken) {
3292
3339
  const nearAccount = yield nearProvider.query({
@@ -3297,8 +3344,18 @@ function getTokenBalance(_0) {
3297
3344
  const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
3298
3345
  return { balance, rawBalance: nearAccount.amount };
3299
3346
  } 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;
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;
3302
3359
  const balance = parseFloat(res) / __pow(10, decimals);
3303
3360
  return { balance, rawBalance: res };
3304
3361
  }
@@ -3310,7 +3367,7 @@ function getTokenBalance(_0) {
3310
3367
  }
3311
3368
  function checkGasTokenBalance(csna, minAmount, env) {
3312
3369
  return __async(this, null, function* () {
3313
- const config = yield getConfig(env);
3370
+ const config = getWalletConfig(env);
3314
3371
  const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
3315
3372
  console.log("gas token balance:", rawBalance);
3316
3373
  if (new import_big.default(rawBalance).lt(minAmount)) {
@@ -3323,16 +3380,308 @@ function checkGasTokenBalance(csna, minAmount, env) {
3323
3380
  }
3324
3381
  });
3325
3382
  }
3326
- 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) {
3327
3675
  return __async(this, null, function* () {
3328
3676
  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();
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();
3330
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;
3331
- const hasDebtArrears = new import_big.default(debtAmount).gt(0);
3332
- 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);
3333
3682
  if (!hasDebtArrears && !hasRelayerFeeArrears)
3334
3683
  return;
3335
- const config = yield getConfig(env);
3684
+ const config = getWalletConfig(env);
3336
3685
  const transferAmount = hasDebtArrears ? debtAmount : relayerFeeAmount;
3337
3686
  const action = {
3338
3687
  receiver_id: config.accountContractId,
@@ -3390,7 +3739,7 @@ function getBtcBalance() {
3390
3739
  const estimatedFee = Math.ceil(estimatedTxSize * feeRate);
3391
3740
  console.log("estimatedFee:", estimatedFee);
3392
3741
  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();
3742
+ const availableBalance = new import_big2.default(availableRawBalance).div(__pow(10, btcDecimals)).round(btcDecimals, import_big2.default.roundDown).toNumber();
3394
3743
  return {
3395
3744
  rawBalance,
3396
3745
  balance,
@@ -3415,10 +3764,10 @@ function getDepositAmount(amount, option) {
3415
3764
  var _a;
3416
3765
  const env = (option == null ? void 0 : option.env) || "mainnet";
3417
3766
  const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
3418
- const config = yield getConfig(env);
3767
+ const config = getWalletConfig(env);
3419
3768
  const csna = yield getCsnaAccountId(env);
3420
3769
  const accountInfo = yield getAccountInfo({ csna, env });
3421
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3770
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3422
3771
  const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
3423
3772
  const {
3424
3773
  deposit_bridge_fee: { fee_min, fee_rate },
@@ -3427,7 +3776,7 @@ function getDepositAmount(amount, option) {
3427
3776
  const depositAmount = Math.max(Number(min_deposit_amount), Number(amount));
3428
3777
  const protocolFee = Math.max(Number(fee_min), Number(depositAmount) * fee_rate);
3429
3778
  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();
3779
+ const totalDepositAmount = new import_big2.default(depositAmount).plus(protocolFee).plus(repayAmount).plus(newAccountMinDepositAmount).round(0, import_big2.default.roundDown).toNumber();
3431
3780
  return {
3432
3781
  depositAmount,
3433
3782
  totalDepositAmount,
@@ -3439,7 +3788,7 @@ function getDepositAmount(amount, option) {
3439
3788
  }
3440
3789
  function getCsnaAccountId(env) {
3441
3790
  return __async(this, null, function* () {
3442
- const config = yield getConfig(env);
3791
+ const config = getWalletConfig(env);
3443
3792
  const { getPublicKey } = getBtcProvider();
3444
3793
  const btcPublicKey = yield getPublicKey();
3445
3794
  if (!btcPublicKey) {
@@ -3477,9 +3826,10 @@ function executeBTCDepositAndAction(_0) {
3477
3826
  }) {
3478
3827
  var _a;
3479
3828
  try {
3829
+ console.log("executeBTCDepositAndAction start", amount);
3480
3830
  checkDepositDisabledAddress();
3481
3831
  const { getPublicKey } = getBtcProvider();
3482
- const config = yield getConfig(env);
3832
+ const config = getWalletConfig(env);
3483
3833
  const btcPublicKey = yield getPublicKey();
3484
3834
  if (!btcPublicKey) {
3485
3835
  throw new Error("BTC Public Key is not available.");
@@ -3489,7 +3839,7 @@ function executeBTCDepositAndAction(_0) {
3489
3839
  }
3490
3840
  const csna = yield getCsnaAccountId(env);
3491
3841
  const depositAmount = (_a = action ? action.amount : amount) != null ? _a : "0";
3492
- if (new import_big.default(depositAmount).lt(0)) {
3842
+ if (new import_big2.default(depositAmount).lt(0)) {
3493
3843
  throw new Error("amount must be greater than 0");
3494
3844
  }
3495
3845
  const { totalDepositAmount, protocolFee, repayAmount } = yield getDepositAmount(depositAmount, {
@@ -3498,7 +3848,7 @@ function executeBTCDepositAndAction(_0) {
3498
3848
  });
3499
3849
  const accountInfo = yield getAccountInfo({ csna, env });
3500
3850
  const newActions = [];
3501
- const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
3851
+ const debtAction = yield checkGasTokenDebt(csna, env, false);
3502
3852
  if (debtAction) {
3503
3853
  newActions.push(__spreadProps(__spreadValues({}, debtAction), {
3504
3854
  gas: GAS_LIMIT
@@ -3510,12 +3860,17 @@ function executeBTCDepositAndAction(_0) {
3510
3860
  }));
3511
3861
  }
3512
3862
  const storageDepositMsg = {};
3513
- 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", {
3514
3869
  account_id: csna
3515
3870
  });
3516
3871
  if (!(registerRes == null ? void 0 : registerRes.available)) {
3517
3872
  storageDepositMsg.storage_deposit_msg = {
3518
- contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
3873
+ contract_id: registerContractId,
3519
3874
  deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
3520
3875
  registration_only: true
3521
3876
  };
@@ -3586,7 +3941,7 @@ function checkSatoshiWhitelist(btcAccountId, env = "mainnet") {
3586
3941
  }
3587
3942
  if (!btcAccountId)
3588
3943
  return;
3589
- const config = yield getConfig(env);
3944
+ const config = getWalletConfig(env);
3590
3945
  const whitelist = yield getWhitelist(config.base_url);
3591
3946
  if (!(whitelist == null ? void 0 : whitelist.length))
3592
3947
  return;
@@ -3609,9 +3964,11 @@ function getWithdrawTransaction(_0) {
3609
3964
  feeRate,
3610
3965
  env = "mainnet"
3611
3966
  }) {
3967
+ console.log("=== Start getWithdrawTransaction ===");
3612
3968
  const provider = getBtcProvider();
3613
3969
  const btcAddress = provider.account;
3614
- const config = yield getConfig(env);
3970
+ const config = getWalletConfig(env);
3971
+ const csna = yield getCsnaAccountId(env);
3615
3972
  const brgConfig = yield nearCall(config.bridgeContractId, "get_config", {});
3616
3973
  if (brgConfig.min_withdraw_amount) {
3617
3974
  if (Number(amount) < Number(brgConfig.min_withdraw_amount)) {
@@ -3620,7 +3977,39 @@ function getWithdrawTransaction(_0) {
3620
3977
  }
3621
3978
  const feePercent = Number(brgConfig.withdraw_bridge_fee.fee_rate) * Number(amount);
3622
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);
3623
4011
  const allUTXO = yield nearCall(config.bridgeContractId, "get_utxos_paged", {});
4012
+ console.log("All UTXOs:", allUTXO);
3624
4013
  if (!allUTXO || Object.keys(allUTXO).length === 0) {
3625
4014
  throw new Error("The network is busy, please try again later.");
3626
4015
  }
@@ -3633,42 +4022,48 @@ function getWithdrawTransaction(_0) {
3633
4022
  script: allUTXO[key].script
3634
4023
  };
3635
4024
  });
4025
+ console.log("Formatted UTXOs:", utxos);
3636
4026
  const _feeRate = feeRate || (yield getBtcGasPrice());
3637
- let { inputs, outputs, fee } = (0, import_coinselect.default)(
4027
+ console.log("Fee Rate:", _feeRate);
4028
+ const coinSelectResult = (0, import_coinselect.default)(
3638
4029
  utxos,
3639
- [{ address: btcAddress, value: Number(amount) }],
4030
+ [{ address: btcAddress, value: Number(finalAmount) }],
3640
4031
  Math.ceil(_feeRate)
3641
4032
  );
4033
+ console.log("Coinselect Result:", coinSelectResult);
4034
+ const { inputs, outputs, fee } = coinSelectResult;
3642
4035
  if (!outputs || !inputs) {
3643
4036
  throw new Error("The network is busy, please try again later.");
3644
4037
  }
3645
4038
  const maxBtcFee = Number(brgConfig.max_btc_gas_fee);
3646
4039
  const transactionFee = fee;
3647
- const changeAddress = brgConfig.change_address;
4040
+ console.log("Transaction Fee:", { transactionFee, maxBtcFee });
3648
4041
  if (transactionFee > maxBtcFee) {
3649
4042
  throw new Error("Gas exceeds maximum value");
3650
4043
  }
3651
4044
  let recipientOutput, changeOutput;
3652
4045
  for (let i = 0; i < outputs.length; i++) {
3653
4046
  const output = outputs[i];
3654
- if (output.value.toString() === amount.toString()) {
4047
+ if (output.value.toString() === finalAmount.toString()) {
3655
4048
  recipientOutput = output;
3656
4049
  } else {
3657
4050
  changeOutput = output;
3658
4051
  }
3659
4052
  if (!output.address) {
3660
- output.address = changeAddress;
4053
+ output.address = brgConfig.change_address;
3661
4054
  }
3662
4055
  }
3663
- 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();
3664
4058
  if (changeOutput) {
3665
- 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();
3666
4060
  const remainingInputs = [...inputs];
3667
4061
  let smallestInput = Math.min.apply(
3668
4062
  null,
3669
4063
  remainingInputs.map((input) => input.value)
3670
4064
  );
3671
4065
  let remainingChangeAmount = changeOutput.value;
4066
+ console.log("Initial Change Processing:", { smallestInput, remainingChangeAmount });
3672
4067
  while (remainingChangeAmount >= smallestInput && smallestInput > 0 && remainingInputs.length > 0) {
3673
4068
  remainingChangeAmount -= smallestInput;
3674
4069
  changeOutput.value = remainingChangeAmount;
@@ -3682,30 +4077,50 @@ function getWithdrawTransaction(_0) {
3682
4077
  null,
3683
4078
  remainingInputs.map((input) => input.value)
3684
4079
  );
4080
+ console.log("Change Processing Loop:", {
4081
+ remainingChangeAmount,
4082
+ smallestInput,
4083
+ remainingInputsCount: remainingInputs.length
4084
+ });
3685
4085
  }
3686
4086
  const minChangeAmount = Number(brgConfig.min_change_amount);
3687
4087
  let additionalFee = 0;
4088
+ console.log("Checking minimum change amount:", {
4089
+ changeValue: changeOutput.value,
4090
+ minChangeAmount
4091
+ });
4092
+ let finalOutputs = [...outputs];
3688
4093
  if (changeOutput.value === 0) {
3689
- outputs = outputs.filter((item) => item.value !== 0);
4094
+ finalOutputs = finalOutputs.filter((output) => output.value !== 0);
4095
+ console.log("Removed zero-value change output", finalOutputs);
3690
4096
  } else if (changeOutput.value < minChangeAmount) {
3691
4097
  additionalFee = minChangeAmount - changeOutput.value;
3692
4098
  recipientOutput.value -= additionalFee;
3693
4099
  changeOutput.value = minChangeAmount;
4100
+ console.log("Adjusted for minimum change amount:", {
4101
+ additionalFee,
4102
+ newRecipientValue: recipientOutput.value,
4103
+ newChangeValue: changeOutput.value
4104
+ });
3694
4105
  }
3695
4106
  } else {
3696
4107
  changeOutput = {
3697
- address: changeAddress,
3698
- value: new import_big.default(transactionFee).plus(withdrawFee).toNumber()
4108
+ address: brgConfig.change_address,
4109
+ value: new import_big2.default(transactionFee).plus(withdrawFee).toNumber()
3699
4110
  };
3700
4111
  outputs.push(changeOutput);
4112
+ console.log("Created new change output:", changeOutput);
3701
4113
  }
3702
4114
  const insufficientOutput = outputs.some((item) => item.value < 0);
3703
4115
  if (insufficientOutput) {
4116
+ console.error("Negative output value detected");
3704
4117
  throw new Error("Not enough gas");
3705
4118
  }
3706
4119
  const inputSum = inputs.reduce((sum, cur) => sum + Number(cur.value), 0);
3707
4120
  const outputSum = outputs.reduce((sum, cur) => sum + Number(cur.value), 0);
4121
+ console.log("Balance verification:", { inputSum, outputSum, transactionFee });
3708
4122
  if (transactionFee + outputSum !== inputSum) {
4123
+ console.error("Balance mismatch:", { inputSum, outputSum, transactionFee });
3709
4124
  throw new Error("compute error");
3710
4125
  }
3711
4126
  const network = yield getNetwork();
@@ -3732,6 +4147,7 @@ function getWithdrawTransaction(_0) {
3732
4147
  value: output.value
3733
4148
  });
3734
4149
  });
4150
+ console.log("outputs:", JSON.stringify(outputs));
3735
4151
  const _inputs = inputs.map((item) => {
3736
4152
  return `${item.txid}:${item.vout}`;
3737
4153
  });
@@ -3748,7 +4164,6 @@ function getWithdrawTransaction(_0) {
3748
4164
  output: txOutputs
3749
4165
  }
3750
4166
  };
3751
- const csna = yield getCsnaAccountId(env);
3752
4167
  const transaction = {
3753
4168
  receiverId: config.btcToken,
3754
4169
  signerId: csna,
@@ -3768,6 +4183,7 @@ function getWithdrawTransaction(_0) {
3768
4183
  }
3769
4184
  ]
3770
4185
  };
4186
+ console.log("=== End getWithdrawTransaction ===");
3771
4187
  return transaction;
3772
4188
  });
3773
4189
  }
@@ -4008,86 +4424,7 @@ function updateIframePosition(iframe, buttonRight, buttonBottom, windowWidth, wi
4008
4424
  iframe.style.bottom = `${iframeBottom}px`;
4009
4425
  }
4010
4426
 
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
- };
4427
+ // src/core/setupBTCWallet/index.ts
4091
4428
  var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4092
4429
  metadata,
4093
4430
  options,
@@ -4109,15 +4446,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4109
4446
  calculateGasLimit
4110
4447
  };
4111
4448
  const env = metadata.env || options.network.networkId || "mainnet";
4112
- const currentConfig = walletConfig[env];
4113
- const walletNetwork = ["mainnet", "private_mainnet"].includes(env) ? "mainnet" : "testnet";
4449
+ const currentConfig = getWalletConfig(env);
4114
4450
  yield initBtcContext();
4115
4451
  function validateWalletState() {
4116
- const accountId = state.getAccount();
4117
- const publicKey = state.getPublicKey();
4118
- const btcPublicKey = state.getBtcPublicKey();
4452
+ const accountId = state_default.getAccount();
4453
+ const publicKey = state_default.getPublicKey();
4454
+ const btcPublicKey = state_default.getBtcPublicKey();
4119
4455
  if (!accountId && publicKey || accountId && !publicKey || !publicKey && btcPublicKey) {
4120
- state.clear();
4456
+ state_default.clear();
4121
4457
  return false;
4122
4458
  }
4123
4459
  return true;
@@ -4125,9 +4461,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4125
4461
  function setupBtcContextListeners() {
4126
4462
  return __async(this, null, function* () {
4127
4463
  const handleConnectionUpdate = () => __async(this, null, function* () {
4128
- yield checkBtcNetwork(walletNetwork);
4129
- if (!state.isValid()) {
4130
- state.clear();
4464
+ yield checkBtcNetwork(currentConfig.network);
4465
+ if (!state_default.isValid()) {
4466
+ state_default.clear();
4131
4467
  console.log("setupBtcContextListeners clear");
4132
4468
  }
4133
4469
  validateWalletState();
@@ -4150,7 +4486,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4150
4486
  const context = window.btcContext.getContext();
4151
4487
  context.on("updatePublicKey", (btcPublicKey) => __async(this, null, function* () {
4152
4488
  console.log("updatePublicKey");
4153
- state.clear();
4489
+ state_default.clear();
4154
4490
  console.log("updatePublicKey clear");
4155
4491
  try {
4156
4492
  const { nearAddress, nearPublicKey } = yield getNearAccountByBtcPublicKey(btcPublicKey);
@@ -4169,7 +4505,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4169
4505
  }));
4170
4506
  context.on("btcLogOut", () => __async(this, null, function* () {
4171
4507
  console.log("btcLogOut");
4172
- state.clear();
4508
+ state_default.clear();
4173
4509
  emitter.emit("accountsChanged", { accounts: [] });
4174
4510
  yield handleConnectionUpdate();
4175
4511
  }));
@@ -4213,7 +4549,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4213
4549
  "get_chain_signature_near_account_public_key",
4214
4550
  { btc_public_key: btcPublicKey }
4215
4551
  );
4216
- state.syncSave(csna, nearPublicKey, btcPublicKey);
4552
+ state_default.syncSave(csna, nearPublicKey, btcPublicKey);
4217
4553
  return {
4218
4554
  nearAddress: csna,
4219
4555
  nearPublicKey
@@ -4223,8 +4559,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4223
4559
  function signIn(_02) {
4224
4560
  return __async(this, arguments, function* ({ contractId, methodNames }) {
4225
4561
  const btcContext = window.btcContext;
4226
- state.clear();
4227
- if (!state.getAccount() || !state.getPublicKey()) {
4562
+ state_default.clear();
4563
+ if (!state_default.getAccount() || !state_default.getPublicKey()) {
4228
4564
  yield btcContext.login();
4229
4565
  }
4230
4566
  const btcPublicKey = yield btcContext.getPublicKey();
@@ -4243,8 +4579,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4243
4579
  }
4244
4580
  function signOut() {
4245
4581
  return __async(this, null, function* () {
4246
- const accountId = state.getAccount();
4247
- const publicKey = state.getPublicKey();
4582
+ const accountId = state_default.getAccount();
4583
+ const publicKey = state_default.getPublicKey();
4248
4584
  if (!(accountId && publicKey)) {
4249
4585
  return;
4250
4586
  }
@@ -4252,19 +4588,19 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4252
4588
  if (metadata.syncLogOut) {
4253
4589
  btcContext.logout();
4254
4590
  }
4255
- state.clear();
4591
+ state_default.clear();
4256
4592
  window.localStorage.removeItem("near-wallet-selector:selectedWalletId");
4257
4593
  removeWalletButton();
4258
4594
  });
4259
4595
  }
4260
4596
  function isSignedIn() {
4261
- const accountId = state.getAccount();
4262
- const publicKey = state.getPublicKey();
4597
+ const accountId = state_default.getAccount();
4598
+ const publicKey = state_default.getPublicKey();
4263
4599
  return accountId && publicKey;
4264
4600
  }
4265
4601
  function getAccounts() {
4266
4602
  return __async(this, null, function* () {
4267
- return [{ accountId: state.getAccount() }];
4603
+ return [{ accountId: state_default.getAccount() }];
4268
4604
  });
4269
4605
  }
4270
4606
  function verifyOwner() {
@@ -4294,12 +4630,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4294
4630
  throw new Error("Wallet state is invalid, please reconnect your wallet.");
4295
4631
  }
4296
4632
  const btcContext = window.btcContext;
4297
- const csna = state.getAccount();
4633
+ const csna = state_default.getAccount();
4298
4634
  const accountInfo = yield getAccountInfo({ csna, env });
4299
- yield checkGasTokenDebt(accountInfo, env, true);
4635
+ yield checkGasTokenDebt(csna, env, true);
4300
4636
  const trans = [...params.transactions];
4301
4637
  console.log("signAndSendTransactions raw trans:", trans);
4302
- const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
4638
+ const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy({
4639
+ csna,
4640
+ transactions: trans,
4641
+ env
4642
+ });
4303
4643
  console.log("transferGasTransaction:", transferGasTransaction);
4304
4644
  console.log("useNearPayGas:", useNearPayGas);
4305
4645
  console.log("gasLimit:", gasLimit);
@@ -4309,7 +4649,15 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4309
4649
  }
4310
4650
  console.log("calculateGasStrategy trans:", trans);
4311
4651
  const newTrans = yield Promise.all(
4312
- 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
+ )
4313
4661
  );
4314
4662
  const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
4315
4663
  const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
@@ -4327,7 +4675,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4327
4675
  const signature = yield btcContext.signMessage(strIntention);
4328
4676
  yield receiveTransaction(currentConfig.base_url, {
4329
4677
  sig: signature,
4330
- btcPubKey: state.getBtcPublicKey(),
4678
+ btcPubKey: state_default.getBtcPublicKey(),
4331
4679
  data: toHex(strIntention)
4332
4680
  });
4333
4681
  yield checkBtcTransactionStatus(currentConfig.base_url, signature);
@@ -4337,197 +4685,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
4337
4685
  return result;
4338
4686
  });
4339
4687
  }
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
4688
  function checkBtcNetwork(network) {
4532
4689
  return __async(this, null, function* () {
4533
4690
  const btcContext = window.btcContext;
@@ -4576,7 +4733,7 @@ function setupBTCWallet({
4576
4733
 
4577
4734
  // src/index.ts
4578
4735
  var getVersion = () => {
4579
- return "0.5.15-beta";
4736
+ return "0.5.16-beta";
4580
4737
  };
4581
4738
  if (typeof window !== "undefined") {
4582
4739
  window.__BTC_WALLET_VERSION = getVersion();