btc-wallet 0.3.12 → 0.3.14

Sign up to get free protection for your applications and to get access to all the features.
package/dist/config.d.ts CHANGED
@@ -4,7 +4,6 @@ export declare const walletConfig: Record<string, {
4
4
  accountContractId: string;
5
5
  bridgeContractId: string;
6
6
  walletUrl: string;
7
- gasTokenLimit: string;
8
7
  }>;
9
8
  export declare const nearRpcUrls: {
10
9
  mainnet: string[];
@@ -1,3 +1,20 @@
1
+ export interface DebtInfo {
2
+ gas_token_id: string;
3
+ transfer_amount: string;
4
+ near_gas_debt_amount: string;
5
+ protocol_fee_debt_amount: string;
6
+ }
7
+ export declare function getAccountInfo(csna: string, accountContractId: string): Promise<{
8
+ nonce: string;
9
+ gas_token: Record<string, string>;
10
+ debt_info: DebtInfo;
11
+ }>;
12
+ type CheckGasTokenArrearsReturnType<T extends boolean> = T extends true ? void : {
13
+ receiver_id: string;
14
+ amount: string;
15
+ msg: string;
16
+ } | undefined;
17
+ export declare function checkGasTokenArrears<T extends boolean>(debtInfo: DebtInfo | undefined, isDev: boolean, autoDeposit?: T): Promise<CheckGasTokenArrearsReturnType<T>>;
1
18
  export declare function getBtcGasPrice(): Promise<number>;
2
19
  export declare function getBtcBalance(): Promise<{
3
20
  rawBalance: number;
@@ -12,18 +29,29 @@ export declare function getBtcBalance(): Promise<{
12
29
  }>;
13
30
  export declare function sendBitcoin(address: string, amount: number, feeRate: number): Promise<string>;
14
31
  export declare function estimateDepositAmount(amount: string, option?: {
15
- isDev: boolean;
16
- }): Promise<string>;
32
+ isDev?: boolean;
33
+ }): Promise<number>;
34
+ export declare function getDepositAmount(amount: string, option?: {
35
+ isEstimate?: boolean;
36
+ isDev?: boolean;
37
+ }): Promise<{
38
+ depositAmount: number;
39
+ receiveAmount: number;
40
+ fee: number;
41
+ }>;
17
42
  interface ExecuteBTCDepositAndActionParams {
18
- action: {
43
+ action?: {
19
44
  receiver_id: string;
20
45
  amount: string;
21
46
  msg: string;
22
47
  };
48
+ amount?: string;
23
49
  /** fee rate, if not provided, will use the recommended fee rate from the btc node */
24
50
  feeRate?: number;
51
+ /** fixed amount, if true, in arrears mode, amount is fixed, otherwise it is depositAmount-repayAction.amount */
52
+ fixedAmount?: boolean;
25
53
  /** is dev environment */
26
54
  isDev?: boolean;
27
55
  }
28
- export declare function executeBTCDepositAndAction({ action, feeRate, isDev, }: ExecuteBTCDepositAndActionParams): Promise<any[]>;
56
+ export declare function executeBTCDepositAndAction({ action, amount, feeRate, fixedAmount, isDev, }: ExecuteBTCDepositAndActionParams): Promise<any[]>;
29
57
  export {};
package/dist/index.js CHANGED
@@ -90,10 +90,13 @@ __export(src_exports, {
90
90
  UnisatConnector: () => UnisatConnector,
91
91
  WizzConnector: () => WizzConnector,
92
92
  XverseConnector: () => XverseConnector,
93
+ checkGasTokenArrears: () => checkGasTokenArrears,
93
94
  estimateDepositAmount: () => estimateDepositAmount,
94
95
  executeBTCDepositAndAction: () => executeBTCDepositAndAction,
96
+ getAccountInfo: () => getAccountInfo,
95
97
  getBtcBalance: () => getBtcBalance,
96
98
  getBtcGasPrice: () => getBtcGasPrice,
99
+ getDepositAmount: () => getDepositAmount,
97
100
  getVersion: () => getVersion,
98
101
  sendBitcoin: () => sendBitcoin,
99
102
  setupBTCWallet: () => setupBTCWallet,
@@ -2726,24 +2729,21 @@ var walletConfig = {
2726
2729
  token: "nbtc-dev.testnet",
2727
2730
  accountContractId: "acc-dev.testnet",
2728
2731
  bridgeContractId: "brg-dev.testnet",
2729
- walletUrl: "https://wallet-dev.satoshibridge.top",
2730
- gasTokenLimit: "3000"
2732
+ walletUrl: "https://wallet-dev.satoshibridge.top"
2731
2733
  },
2732
2734
  testnet: {
2733
2735
  base_url: "https://api.testnet.satoshibridge.top",
2734
2736
  token: "nbtc2-nsp.testnet",
2735
2737
  accountContractId: "dev2-nsp.testnet",
2736
2738
  bridgeContractId: "brg2-nsp.testnet",
2737
- walletUrl: "https://wallet-test.satoshibridge.top",
2738
- gasTokenLimit: "3000"
2739
+ walletUrl: "https://wallet-test.satoshibridge.top"
2739
2740
  },
2740
2741
  mainnet: {
2741
2742
  base_url: "https://api.mainnet.satoshibridge.top",
2742
2743
  token: "",
2743
2744
  accountContractId: "",
2744
2745
  bridgeContractId: "",
2745
- walletUrl: "https://wallet.satoshibridge.top",
2746
- gasTokenLimit: "3000"
2746
+ walletUrl: "https://wallet.satoshibridge.top"
2747
2747
  }
2748
2748
  };
2749
2749
  var nearRpcUrls = {
@@ -2753,9 +2753,7 @@ var nearRpcUrls = {
2753
2753
  "https://free.rpc.fastnear.com",
2754
2754
  "https://near.drpc.org"
2755
2755
  ],
2756
- testnet: [
2757
- "https://rpc.testnet.near.org"
2758
- ]
2756
+ testnet: ["https://rpc.testnet.near.org"]
2759
2757
  };
2760
2758
  var btcRpcUrls = {
2761
2759
  mainnet: "https://mempool.space/api",
@@ -2966,14 +2964,14 @@ function checkBridgeTransactionStatus(url, txHash) {
2966
2964
  const { result_code, result_message, result_data } = yield request(`${url}/v1/bridgeFromTx?fromTxHash=${txHash}&fromChainId=1`, {
2967
2965
  timeout: 3e5,
2968
2966
  pollingInterval: 5e3,
2969
- maxPollingAttempts: 30,
2967
+ maxPollingAttempts: 60,
2970
2968
  shouldStopPolling: (res) => {
2971
2969
  var _a;
2972
- return res.result_code === 0 && [4, 102].includes(((_a = res.result_data) == null ? void 0 : _a.status) || 0);
2970
+ return res.result_code === 0 && [4, 102].includes(((_a = res.result_data) == null ? void 0 : _a.Status) || 0);
2973
2971
  }
2974
2972
  });
2975
2973
  console.log("checkTransactionStatus resp:", { result_code, result_message, result_data });
2976
- if ((result_data == null ? void 0 : result_data.status) !== 4) {
2974
+ if ((result_data == null ? void 0 : result_data.Status) !== 4) {
2977
2975
  throw new Error(result_message);
2978
2976
  }
2979
2977
  return result_data;
@@ -2984,201 +2982,20 @@ function checkBtcTransactionStatus(url, sig) {
2984
2982
  const { result_code, result_message, result_data } = yield request(`${url}/v1/btcTx?sig=${sig}`, {
2985
2983
  timeout: 3e5,
2986
2984
  pollingInterval: 5e3,
2987
- maxPollingAttempts: 30,
2985
+ maxPollingAttempts: 60,
2988
2986
  shouldStopPolling: (res) => {
2989
2987
  var _a;
2990
- return res.result_code === 0 && [3, 101, 102].includes(((_a = res.result_data) == null ? void 0 : _a.status) || 0);
2988
+ return res.result_code === 0 && [3, 101, 102].includes(((_a = res.result_data) == null ? void 0 : _a.Status) || 0);
2991
2989
  }
2992
2990
  });
2993
2991
  console.log("checkBtcTransactionStatus resp:", { result_code, result_message, result_data });
2994
- if ((result_data == null ? void 0 : result_data.status) !== 3) {
2992
+ if ((result_data == null ? void 0 : result_data.Status) !== 3) {
2995
2993
  throw new Error(result_message);
2996
2994
  }
2997
2995
  return result_data;
2998
2996
  });
2999
2997
  }
3000
2998
 
3001
- // src/core/btcUtils.ts
3002
- function getBtcProvider() {
3003
- if (typeof window === "undefined" || !window.btcContext) {
3004
- throw new Error("BTC Provider is not initialized.");
3005
- }
3006
- return window.btcContext;
3007
- }
3008
- function getNetwork() {
3009
- return __async(this, null, function* () {
3010
- const network = yield getBtcProvider().getNetwork();
3011
- console.log("btc network:", network);
3012
- return network === "livenet" ? "mainnet" : "testnet";
3013
- });
3014
- }
3015
- function getBtcRpcUrl() {
3016
- return __async(this, null, function* () {
3017
- const network = yield getNetwork();
3018
- return btcRpcUrls[network];
3019
- });
3020
- }
3021
- function getConfig(isDev) {
3022
- return __async(this, null, function* () {
3023
- const network = yield getNetwork();
3024
- return walletConfig[isDev ? "dev" : network];
3025
- });
3026
- }
3027
- function nearCall(contractId, methodName, args) {
3028
- return __async(this, null, function* () {
3029
- const network = yield getNetwork();
3030
- return nearCallFunction(contractId, methodName, args, { network });
3031
- });
3032
- }
3033
- function getBtcGasPrice() {
3034
- return __async(this, null, function* () {
3035
- const defaultFeeRate = 100;
3036
- try {
3037
- const btcRpcUrl = yield getBtcRpcUrl();
3038
- const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3039
- const feeRate = res.fastestFee;
3040
- return feeRate || defaultFeeRate;
3041
- } catch (error) {
3042
- return defaultFeeRate;
3043
- }
3044
- });
3045
- }
3046
- function getBtcBalance() {
3047
- return __async(this, null, function* () {
3048
- const { account } = yield retryOperation(getBtcProvider, (res) => !!res.account);
3049
- if (!account) {
3050
- console.error("BTC Account is not available.");
3051
- return { rawBalance: 0, balance: 0, maxSpendableBalance: 0 };
3052
- }
3053
- const btcRpcUrl = yield getBtcRpcUrl();
3054
- const utxos = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res) => res.json());
3055
- const rawBalance = (utxos == null ? void 0 : utxos.reduce((acc, cur) => acc + cur.value, 0)) || 0;
3056
- const balance = rawBalance / __pow(10, 8);
3057
- const feeRate = yield getBtcGasPrice();
3058
- const inputSize = ((utxos == null ? void 0 : utxos.length) || 0) * 66;
3059
- const outputSize = 34;
3060
- const overheadSize = 10;
3061
- const estimatedTxSize = inputSize + outputSize + overheadSize;
3062
- const estimatedFee = estimatedTxSize * feeRate / __pow(10, 8);
3063
- console.log("estimated fee:", estimatedFee);
3064
- const availableBalance = Math.max(0, balance - estimatedFee);
3065
- return {
3066
- rawBalance,
3067
- balance,
3068
- availableBalance
3069
- };
3070
- });
3071
- }
3072
- function sendBitcoin(address, amount, feeRate) {
3073
- return __async(this, null, function* () {
3074
- const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
3075
- const txHash = yield sendBitcoin2(address, amount, { feeRate });
3076
- return txHash;
3077
- });
3078
- }
3079
- function estimateDepositAmount(amount, option) {
3080
- return __async(this, null, function* () {
3081
- const config = yield getConfig((option == null ? void 0 : option.isDev) || false);
3082
- const {
3083
- deposit_bridge_fee: { fee_min, fee_rate }
3084
- } = yield nearCall(
3085
- config.bridgeContractId,
3086
- "get_config",
3087
- {}
3088
- );
3089
- const fee = Math.max(Number(fee_min), Number(amount) * fee_rate);
3090
- return new import_big.default(amount).minus(fee).toFixed(0);
3091
- });
3092
- }
3093
- function executeBTCDepositAndAction(_0) {
3094
- return __async(this, arguments, function* ({
3095
- action,
3096
- feeRate,
3097
- isDev = false
3098
- }) {
3099
- try {
3100
- const { getPublicKey } = getBtcProvider();
3101
- const config = yield getConfig(isDev);
3102
- const btcPublicKey = yield getPublicKey();
3103
- if (!btcPublicKey) {
3104
- throw new Error("BTC Public Key is not available.");
3105
- }
3106
- if (!action.receiver_id) {
3107
- throw new Error("receiver_id is required");
3108
- }
3109
- if (!action.amount) {
3110
- throw new Error("amount is required");
3111
- }
3112
- const csna = yield nearCall(
3113
- config.accountContractId,
3114
- "get_chain_signature_near_account_id",
3115
- {
3116
- btc_public_key: btcPublicKey
3117
- }
3118
- );
3119
- const depositMsg = {
3120
- recipient_id: csna,
3121
- post_actions: [
3122
- __spreadProps(__spreadValues({}, action), {
3123
- gas: new import_big.default(100).mul(__pow(10, 12)).toFixed(0)
3124
- })
3125
- ]
3126
- };
3127
- const storageDepositMsg = {};
3128
- const accountInfo = yield nearCall(
3129
- config.accountContractId,
3130
- "get_account",
3131
- {
3132
- account_id: csna
3133
- }
3134
- );
3135
- if (!(accountInfo == null ? void 0 : accountInfo.nonce)) {
3136
- storageDepositMsg.btc_public_key = btcPublicKey;
3137
- }
3138
- const registerRes = yield nearCall(action.receiver_id, "storage_balance_of", {
3139
- account_id: csna
3140
- });
3141
- if (!(registerRes == null ? void 0 : registerRes.available)) {
3142
- storageDepositMsg.storage_deposit_msg = {
3143
- contract_id: action.receiver_id,
3144
- deposit: new import_big.default(0.25).mul(__pow(10, 24)).toFixed(0),
3145
- registration_only: true
3146
- };
3147
- }
3148
- if (Object.keys(storageDepositMsg).length > 0) {
3149
- depositMsg.extra_msg = JSON.stringify(storageDepositMsg);
3150
- }
3151
- console.log("get_user_deposit_address params:", { deposit_msg: depositMsg });
3152
- const userDepositAddress = yield nearCall(
3153
- config.bridgeContractId,
3154
- "get_user_deposit_address",
3155
- { deposit_msg: depositMsg }
3156
- );
3157
- const _feeRate = feeRate || (yield getBtcGasPrice());
3158
- const minDepositAmount = 5e3;
3159
- const sendAmount = Math.max(minDepositAmount, new import_big.default(action.amount).toNumber());
3160
- console.log("user deposit address:", userDepositAddress);
3161
- console.log("send amount:", sendAmount);
3162
- console.log("fee rate:", _feeRate);
3163
- const txHash = yield sendBitcoin(userDepositAddress, sendAmount, _feeRate);
3164
- yield receiveDepositMsg(config.base_url, {
3165
- btcPublicKey,
3166
- txHash,
3167
- postActions: JSON.stringify(depositMsg.post_actions),
3168
- extraMsg: depositMsg.extra_msg
3169
- });
3170
- const checkTransactionStatusRes = yield checkBridgeTransactionStatus(config.base_url, txHash);
3171
- console.log("checkBridgeTransactionStatus resp:", checkTransactionStatusRes);
3172
- const network = yield getNetwork();
3173
- const result = yield pollTransactionStatuses(network, [checkTransactionStatusRes.ToTxHash]);
3174
- return result;
3175
- } catch (error) {
3176
- console.error("executeBTCDepositAndAction error:", error);
3177
- throw error;
3178
- }
3179
- });
3180
- }
3181
-
3182
2999
  // src/utils/Dialog.ts
3183
3000
  var Dialog = class {
3184
3001
  static injectStyles() {
@@ -3360,6 +3177,249 @@ Dialog.style = `
3360
3177
  }
3361
3178
  `;
3362
3179
 
3180
+ // src/core/btcUtils.ts
3181
+ function getBtcProvider() {
3182
+ if (typeof window === "undefined" || !window.btcContext) {
3183
+ throw new Error("BTC Provider is not initialized.");
3184
+ }
3185
+ return window.btcContext;
3186
+ }
3187
+ function getNetwork() {
3188
+ return __async(this, null, function* () {
3189
+ const network = yield getBtcProvider().getNetwork();
3190
+ console.log("btc network:", network);
3191
+ return network === "livenet" ? "mainnet" : "testnet";
3192
+ });
3193
+ }
3194
+ function getBtcRpcUrl() {
3195
+ return __async(this, null, function* () {
3196
+ const network = yield getNetwork();
3197
+ return btcRpcUrls[network];
3198
+ });
3199
+ }
3200
+ function getConfig(isDev) {
3201
+ return __async(this, null, function* () {
3202
+ const network = yield getNetwork();
3203
+ return walletConfig[isDev ? "dev" : network];
3204
+ });
3205
+ }
3206
+ function nearCall(contractId, methodName, args) {
3207
+ return __async(this, null, function* () {
3208
+ const network = yield getNetwork();
3209
+ return nearCallFunction(contractId, methodName, args, { network });
3210
+ });
3211
+ }
3212
+ function getAccountInfo(csna, accountContractId) {
3213
+ return __async(this, null, function* () {
3214
+ const accountInfo = yield nearCall(accountContractId, "get_account", { account_id: csna });
3215
+ return accountInfo;
3216
+ });
3217
+ }
3218
+ function checkGasTokenArrears(debtInfo, isDev, autoDeposit) {
3219
+ return __async(this, null, function* () {
3220
+ if (!debtInfo)
3221
+ return;
3222
+ const config = yield getConfig(isDev);
3223
+ const transferAmount = debtInfo.transfer_amount;
3224
+ console.log("get_account debtInfo:", debtInfo);
3225
+ const action = {
3226
+ receiver_id: config.accountContractId,
3227
+ amount: transferAmount,
3228
+ msg: JSON.stringify("Deposit")
3229
+ };
3230
+ if (!autoDeposit)
3231
+ return action;
3232
+ const confirmed = yield Dialog.confirm({
3233
+ title: "Has gas token arrears",
3234
+ message: "You have gas token arrears, please deposit gas token to continue."
3235
+ });
3236
+ if (confirmed) {
3237
+ yield executeBTCDepositAndAction({ action, isDev });
3238
+ yield Dialog.alert({
3239
+ title: "Deposit success",
3240
+ message: "Deposit success, will continue to execute transaction."
3241
+ });
3242
+ } else {
3243
+ throw new Error("Deposit failed, please deposit gas token first.");
3244
+ }
3245
+ });
3246
+ }
3247
+ function getBtcGasPrice() {
3248
+ return __async(this, null, function* () {
3249
+ const network = yield getNetwork();
3250
+ const defaultFeeRate = network === "mainnet" ? 5 : 2500;
3251
+ try {
3252
+ const btcRpcUrl = yield getBtcRpcUrl();
3253
+ const res = yield fetch(`${btcRpcUrl}/v1/fees/recommended`).then((res2) => res2.json());
3254
+ const feeRate = res.fastestFee;
3255
+ return feeRate || defaultFeeRate;
3256
+ } catch (error) {
3257
+ return defaultFeeRate;
3258
+ }
3259
+ });
3260
+ }
3261
+ function getBtcBalance() {
3262
+ return __async(this, null, function* () {
3263
+ const { account } = yield retryOperation(getBtcProvider, (res) => !!res.account);
3264
+ if (!account) {
3265
+ console.error("BTC Account is not available.");
3266
+ return { rawBalance: 0, balance: 0, maxSpendableBalance: 0 };
3267
+ }
3268
+ const btcRpcUrl = yield getBtcRpcUrl();
3269
+ const utxos = yield fetch(`${btcRpcUrl}/address/${account}/utxo`).then((res) => res.json());
3270
+ const rawBalance = (utxos == null ? void 0 : utxos.reduce((acc, cur) => acc + cur.value, 0)) || 0;
3271
+ const balance = rawBalance / __pow(10, 8);
3272
+ const feeRate = yield getBtcGasPrice();
3273
+ const inputSize = ((utxos == null ? void 0 : utxos.length) || 0) * 66;
3274
+ const outputSize = 34;
3275
+ const overheadSize = 10;
3276
+ const estimatedTxSize = inputSize + outputSize + overheadSize;
3277
+ const estimatedFee = estimatedTxSize * feeRate / __pow(10, 8);
3278
+ console.log("estimated fee:", estimatedFee);
3279
+ const availableBalance = Math.max(0, balance - estimatedFee);
3280
+ return {
3281
+ rawBalance,
3282
+ balance,
3283
+ availableBalance
3284
+ };
3285
+ });
3286
+ }
3287
+ function sendBitcoin(address, amount, feeRate) {
3288
+ return __async(this, null, function* () {
3289
+ const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
3290
+ const txHash = yield sendBitcoin2(address, amount, { feeRate });
3291
+ return txHash;
3292
+ });
3293
+ }
3294
+ var MINIMUM_DEPOSIT_AMOUNT = 5e3;
3295
+ var MINIMUM_DEPOSIT_AMOUNT_BASE = 1e3;
3296
+ function estimateDepositAmount(amount, option) {
3297
+ return __async(this, null, function* () {
3298
+ const { receiveAmount } = yield getDepositAmount(amount, __spreadProps(__spreadValues({}, option), { isEstimate: true }));
3299
+ return receiveAmount;
3300
+ });
3301
+ }
3302
+ function getDepositAmount(amount, option) {
3303
+ return __async(this, null, function* () {
3304
+ const config = yield getConfig((option == null ? void 0 : option.isDev) || false);
3305
+ const {
3306
+ deposit_bridge_fee: { fee_min, fee_rate }
3307
+ } = yield nearCall(
3308
+ config.bridgeContractId,
3309
+ "get_config",
3310
+ {}
3311
+ );
3312
+ const depositAmount = (option == null ? void 0 : option.isEstimate) ? Number(amount) : Math.max(MINIMUM_DEPOSIT_AMOUNT + MINIMUM_DEPOSIT_AMOUNT_BASE, Number(amount));
3313
+ const fee = Math.max(Number(fee_min), Number(depositAmount) * fee_rate);
3314
+ const receiveAmount = new import_big.default(depositAmount).minus(fee).round(0, import_big.default.roundDown).toNumber();
3315
+ return {
3316
+ depositAmount,
3317
+ receiveAmount: Math.max(receiveAmount, 0),
3318
+ fee
3319
+ };
3320
+ });
3321
+ }
3322
+ function executeBTCDepositAndAction(_0) {
3323
+ return __async(this, arguments, function* ({
3324
+ action,
3325
+ amount,
3326
+ feeRate,
3327
+ fixedAmount = true,
3328
+ isDev = false
3329
+ }) {
3330
+ var _a;
3331
+ try {
3332
+ const { getPublicKey } = getBtcProvider();
3333
+ const config = yield getConfig(isDev);
3334
+ const btcPublicKey = yield getPublicKey();
3335
+ if (!btcPublicKey) {
3336
+ throw new Error("BTC Public Key is not available.");
3337
+ }
3338
+ if (!amount && !action) {
3339
+ throw new Error("amount or action is required");
3340
+ }
3341
+ const csna = yield nearCall(
3342
+ config.accountContractId,
3343
+ "get_chain_signature_near_account_id",
3344
+ {
3345
+ btc_public_key: btcPublicKey
3346
+ }
3347
+ );
3348
+ const rawDepositAmount = (_a = action ? action.amount : amount) != null ? _a : "0";
3349
+ if (new import_big.default(rawDepositAmount).lt(0)) {
3350
+ throw new Error("amount must be greater than 0");
3351
+ }
3352
+ const { depositAmount, receiveAmount } = yield getDepositAmount(rawDepositAmount, {
3353
+ isDev
3354
+ });
3355
+ const accountInfo = yield getAccountInfo(csna, config.accountContractId);
3356
+ const newActions = [];
3357
+ const gasLimit = new import_big.default(50).mul(__pow(10, 12)).toFixed(0);
3358
+ const repayAction = yield checkGasTokenArrears(accountInfo.debt_info, isDev, false);
3359
+ if (repayAction) {
3360
+ newActions.push(__spreadProps(__spreadValues({}, repayAction), {
3361
+ gas: gasLimit
3362
+ }));
3363
+ }
3364
+ if (action) {
3365
+ newActions.push(__spreadProps(__spreadValues({}, action), {
3366
+ amount: (repayAction == null ? void 0 : repayAction.amount) && !fixedAmount ? new import_big.default(receiveAmount).minus(repayAction.amount).toString() : receiveAmount.toString(),
3367
+ gas: gasLimit
3368
+ }));
3369
+ }
3370
+ const depositMsg = {
3371
+ recipient_id: csna,
3372
+ post_actions: newActions.length > 0 ? newActions : void 0
3373
+ };
3374
+ const storageDepositMsg = {};
3375
+ if (!(accountInfo == null ? void 0 : accountInfo.nonce)) {
3376
+ storageDepositMsg.btc_public_key = btcPublicKey;
3377
+ }
3378
+ const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.token, "storage_balance_of", {
3379
+ account_id: csna
3380
+ });
3381
+ if (!(registerRes == null ? void 0 : registerRes.available)) {
3382
+ storageDepositMsg.storage_deposit_msg = {
3383
+ contract_id: (action == null ? void 0 : action.receiver_id) || config.token,
3384
+ deposit: new import_big.default(0.25).mul(__pow(10, 24)).toFixed(0),
3385
+ registration_only: true
3386
+ };
3387
+ }
3388
+ if (Object.keys(storageDepositMsg).length > 0) {
3389
+ depositMsg.extra_msg = JSON.stringify(storageDepositMsg);
3390
+ }
3391
+ console.log("get_user_deposit_address params:", { deposit_msg: depositMsg });
3392
+ const userDepositAddress = yield nearCall(
3393
+ config.bridgeContractId,
3394
+ "get_user_deposit_address",
3395
+ { deposit_msg: depositMsg }
3396
+ );
3397
+ const _feeRate = feeRate || (yield getBtcGasPrice());
3398
+ const sendAmount = (repayAction == null ? void 0 : repayAction.amount) && fixedAmount ? new import_big.default(depositAmount).plus((repayAction == null ? void 0 : repayAction.amount) || 0).toString() : depositAmount;
3399
+ console.log("user deposit address:", userDepositAddress);
3400
+ console.log("send amount:", sendAmount);
3401
+ console.log("fee rate:", _feeRate);
3402
+ const txHash = yield sendBitcoin(userDepositAddress, Number(sendAmount), _feeRate);
3403
+ const postActionsStr = newActions.length > 0 ? JSON.stringify(newActions) : void 0;
3404
+ yield receiveDepositMsg(config.base_url, {
3405
+ btcPublicKey,
3406
+ txHash,
3407
+ depositType: postActionsStr || depositMsg.extra_msg ? 1 : 0,
3408
+ postActions: postActionsStr,
3409
+ extraMsg: depositMsg.extra_msg
3410
+ });
3411
+ const checkTransactionStatusRes = yield checkBridgeTransactionStatus(config.base_url, txHash);
3412
+ console.log("checkBridgeTransactionStatus resp:", checkTransactionStatusRes);
3413
+ const network = yield getNetwork();
3414
+ const result = yield pollTransactionStatuses(network, [checkTransactionStatusRes.ToTxHash]);
3415
+ return result;
3416
+ } catch (error) {
3417
+ console.error("executeBTCDepositAndAction error:", error);
3418
+ throw error;
3419
+ }
3420
+ });
3421
+ }
3422
+
3363
3423
  // src/core/setupBTCWallet.ts
3364
3424
  var { transfer, functionCall } = import_transactions.actionCreators;
3365
3425
  var state = {
@@ -3563,8 +3623,8 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3563
3623
  return __async(this, null, function* () {
3564
3624
  const btcContext = window.btcContext;
3565
3625
  const accountId = state.getAccount();
3566
- const accountInfo = yield getAccountInfo();
3567
- yield checkGasTokenArrears(accountInfo.debt_info);
3626
+ const accountInfo = yield getAccountInfo(accountId, currentConfig.accountContractId);
3627
+ yield checkGasTokenArrears(accountInfo.debt_info, isDev, true);
3568
3628
  const trans = [...params.transactions];
3569
3629
  console.log("raw trans:", trans);
3570
3630
  const gasTokenBalance = accountInfo.gas_token[currentConfig.token] || "0";
@@ -3607,39 +3667,6 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3607
3667
  return result;
3608
3668
  });
3609
3669
  }
3610
- function checkGasTokenArrears(debtInfo) {
3611
- return __async(this, null, function* () {
3612
- const transferAmount = (debtInfo == null ? void 0 : debtInfo.transfer_amount) || "0";
3613
- console.log("get_account debtInfo:", debtInfo);
3614
- if (transferAmount === "0")
3615
- return;
3616
- const confirmed = yield Dialog.confirm({
3617
- title: "Has gas token arrears",
3618
- message: "You have gas token arrears, please deposit gas token to continue."
3619
- });
3620
- if (confirmed) {
3621
- const action = {
3622
- receiver_id: currentConfig.token,
3623
- amount: transferAmount,
3624
- msg: JSON.stringify("Deposit")
3625
- };
3626
- yield executeBTCDepositAndAction({ action, isDev });
3627
- yield Dialog.alert({
3628
- title: "Deposit success",
3629
- message: "Deposit success, will continue to execute transaction."
3630
- });
3631
- } else {
3632
- throw new Error("Deposit failed, please deposit gas token first.");
3633
- }
3634
- });
3635
- }
3636
- function getAccountInfo() {
3637
- return __async(this, null, function* () {
3638
- const accountId = state.getAccount();
3639
- const accountInfo = yield nearCall2(currentConfig.accountContractId, "get_account", { account_id: accountId });
3640
- return accountInfo;
3641
- });
3642
- }
3643
3670
  function createGasTokenTransfer(accountId, amount) {
3644
3671
  return __async(this, null, function* () {
3645
3672
  return {
@@ -3707,6 +3734,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
3707
3734
  transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
3708
3735
  );
3709
3736
  if (availableBalance > 0.2) {
3737
+ console.log("near balance is enough, get the protocol fee of each transaction");
3710
3738
  const gasTokens = yield nearCall2(
3711
3739
  currentConfig.accountContractId,
3712
3740
  "list_gas_token",
@@ -3855,7 +3883,7 @@ function setupBTCWallet({
3855
3883
 
3856
3884
  // src/index.ts
3857
3885
  var getVersion = () => {
3858
- return "0.3.12";
3886
+ return "0.3.14";
3859
3887
  };
3860
3888
  if (typeof window !== "undefined") {
3861
3889
  window.__PARTICLE_BTC_CONNECT_VERSION = getVersion();