btc-wallet 0.5.10-beta → 0.5.12-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/config.d.ts +4 -1
- package/dist/connector/injected.d.ts +0 -1
- package/dist/core/btcUtils.d.ts +17 -9
- package/dist/index.js +227 -158
- package/dist/index.js.map +2 -2
- package/dist/utils/nearUtils.d.ts +7 -1
- package/dist/utils/request.d.ts +1 -0
- package/esm/index.js +227 -158
- package/esm/index.js.map +2 -2
- package/package.json +1 -1
@@ -1,7 +1,13 @@
|
|
1
1
|
import type { ProviderService } from '@near-wallet-selector/core/src/lib/services';
|
2
2
|
import { providers } from 'near-api-js';
|
3
|
-
export declare function
|
3
|
+
export declare function getNearProvider(option: {
|
4
4
|
network?: string;
|
5
5
|
provider?: ProviderService;
|
6
|
+
}): ProviderService | providers.FailoverRpcProvider;
|
7
|
+
export declare function nearCallFunction<T>(contractId: string, methodName: string, args: any, options?: {
|
8
|
+
network?: string;
|
9
|
+
provider?: ProviderService;
|
10
|
+
cacheTimeout?: number;
|
11
|
+
skipCache?: boolean;
|
6
12
|
}): Promise<T>;
|
7
13
|
export declare function pollTransactionStatuses(network: string, hashes: string[]): Promise<providers.FinalExecutionOutcome[]>;
|
package/dist/utils/request.d.ts
CHANGED
@@ -7,5 +7,6 @@ interface RequestOptions<T> extends RequestInit {
|
|
7
7
|
maxPollingAttempts?: number;
|
8
8
|
shouldStopPolling?: (response: T) => boolean;
|
9
9
|
}
|
10
|
+
export declare function withCache<T>(key: string, fetcher: () => Promise<T>, timeout?: number): Promise<T>;
|
10
11
|
export default function request<T>(url: string, options?: RequestOptions<T>): Promise<T>;
|
11
12
|
export {};
|
package/esm/index.js
CHANGED
@@ -368,11 +368,11 @@ var MobileWalletConnect = class {
|
|
368
368
|
}
|
369
369
|
static redirectToWallet(walletId) {
|
370
370
|
return __async(this, null, function* () {
|
371
|
-
var _a;
|
372
371
|
if (isMobile()) {
|
373
372
|
const currentUrl = window.location.href;
|
374
373
|
const universalLink = this.getUniversalLink(walletId, currentUrl);
|
375
|
-
|
374
|
+
const showGuideDialog = () => __async(this, null, function* () {
|
375
|
+
var _a;
|
376
376
|
try {
|
377
377
|
yield (_a = navigator.clipboard) == null ? void 0 : _a.writeText(currentUrl);
|
378
378
|
} catch (error) {
|
@@ -390,9 +390,23 @@ var MobileWalletConnect = class {
|
|
390
390
|
`,
|
391
391
|
dangerouslyUseHTML: true
|
392
392
|
});
|
393
|
+
});
|
394
|
+
if (!universalLink) {
|
395
|
+
yield showGuideDialog();
|
393
396
|
return false;
|
394
397
|
}
|
398
|
+
const openWallet = () => {
|
399
|
+
const iframe = document.createElement("iframe");
|
400
|
+
iframe.style.display = "none";
|
401
|
+
iframe.src = universalLink;
|
402
|
+
document.body.appendChild(iframe);
|
403
|
+
setTimeout(() => __async(this, null, function* () {
|
404
|
+
document.body.removeChild(iframe);
|
405
|
+
yield showGuideDialog();
|
406
|
+
}), 2e3);
|
407
|
+
};
|
395
408
|
window.location.href = universalLink;
|
409
|
+
setTimeout(openWallet, 100);
|
396
410
|
return true;
|
397
411
|
}
|
398
412
|
return false;
|
@@ -441,24 +455,6 @@ var InjectedConnector = class extends BaseConnector {
|
|
441
455
|
return accounts;
|
442
456
|
});
|
443
457
|
}
|
444
|
-
getUniversalLink(url) {
|
445
|
-
url = "https://www.deltatrade.ai/";
|
446
|
-
console.log(this.metadata.id);
|
447
|
-
switch (this.metadata.id) {
|
448
|
-
case "unisat":
|
449
|
-
return `unisat://dapp?url=${encodeURIComponent(url)}`;
|
450
|
-
case "okx":
|
451
|
-
return `okx://wallet/dapp/url?dappUrl=${encodeURIComponent(url)}`;
|
452
|
-
case "bitget":
|
453
|
-
return `https://bkcode.vip?action=dapp&url=${encodeURIComponent(url)}`;
|
454
|
-
case "binance":
|
455
|
-
return `binance://dapp?url=${encodeURIComponent(url)}`;
|
456
|
-
case "xverse":
|
457
|
-
return `https://connect.xverse.app/browser?url=${encodeURIComponent(url)}`;
|
458
|
-
default:
|
459
|
-
return url;
|
460
|
-
}
|
461
|
-
}
|
462
458
|
getAccounts() {
|
463
459
|
return __async(this, null, function* () {
|
464
460
|
const accounts = yield this.getProviderOrThrow().getAccounts();
|
@@ -737,18 +733,10 @@ var XverseConnector = class extends BaseConnector {
|
|
737
733
|
message: signStr,
|
738
734
|
protocol: "ECDSA"
|
739
735
|
});
|
740
|
-
const modifiedSig = Buffer.from(result.signature, "base64");
|
741
736
|
console.log("xverse walletType", address.walletType);
|
742
|
-
console.log("xverse raw sig", result.signature
|
743
|
-
|
744
|
-
|
745
|
-
modifiedSig[0] = 31 + (modifiedSig[0] - 39);
|
746
|
-
} else if (address.addressType === "p2sh") {
|
747
|
-
modifiedSig[0] = 31 + (modifiedSig[0] - 35);
|
748
|
-
}
|
749
|
-
} else {
|
750
|
-
modifiedSig[0] = 31 + (modifiedSig[0] - 31) % 4;
|
751
|
-
}
|
737
|
+
console.log("xverse raw sig", result.signature);
|
738
|
+
const modifiedSig = Buffer.from(result.signature, "base64");
|
739
|
+
modifiedSig[0] = 31 + (modifiedSig[0] - 31) % 4;
|
752
740
|
const sig = modifiedSig.toString("base64");
|
753
741
|
console.log("xverse modified sig", sig);
|
754
742
|
return sig;
|
@@ -2846,7 +2834,10 @@ import { sha256 } from "js-sha256";
|
|
2846
2834
|
var walletConfig = {
|
2847
2835
|
dev: {
|
2848
2836
|
base_url: "https://api.dev.satoshibridge.top",
|
2849
|
-
|
2837
|
+
btcToken: "nbtc-dev.testnet",
|
2838
|
+
btcTokenDecimals: 8,
|
2839
|
+
nearToken: "wrap.testnet",
|
2840
|
+
nearTokenDecimals: 24,
|
2850
2841
|
accountContractId: "acc-dev.testnet",
|
2851
2842
|
bridgeContractId: "brg-dev.testnet",
|
2852
2843
|
walletUrl: "https://wallet-dev.satoshibridge.top",
|
@@ -2854,7 +2845,10 @@ var walletConfig = {
|
|
2854
2845
|
},
|
2855
2846
|
testnet: {
|
2856
2847
|
base_url: "https://api.testnet.satoshibridge.top",
|
2857
|
-
|
2848
|
+
btcToken: "nbtc2-nsp.testnet",
|
2849
|
+
btcTokenDecimals: 8,
|
2850
|
+
nearToken: "wrap.testnet",
|
2851
|
+
nearTokenDecimals: 24,
|
2858
2852
|
accountContractId: "acc2-nsp.testnet",
|
2859
2853
|
bridgeContractId: "brg2-nsp.testnet",
|
2860
2854
|
walletUrl: "https://wallet-test.satoshibridge.top",
|
@@ -2862,7 +2856,10 @@ var walletConfig = {
|
|
2862
2856
|
},
|
2863
2857
|
private_mainnet: {
|
2864
2858
|
base_url: "https://api.stg.satoshibridge.top",
|
2865
|
-
|
2859
|
+
btcToken: "nbtc.toalice.near",
|
2860
|
+
btcTokenDecimals: 8,
|
2861
|
+
nearToken: "wrap.near",
|
2862
|
+
nearTokenDecimals: 24,
|
2866
2863
|
accountContractId: "acc.toalice.near",
|
2867
2864
|
bridgeContractId: "brg.toalice.near",
|
2868
2865
|
walletUrl: "https://wallet-stg.satoshibridge.top",
|
@@ -2870,7 +2867,10 @@ var walletConfig = {
|
|
2870
2867
|
},
|
2871
2868
|
mainnet: {
|
2872
2869
|
base_url: "https://api.satos.network",
|
2873
|
-
|
2870
|
+
btcToken: "nbtc.bridge.near",
|
2871
|
+
btcTokenDecimals: 8,
|
2872
|
+
nearToken: "wrap.near",
|
2873
|
+
nearTokenDecimals: 24,
|
2874
2874
|
accountContractId: "acc.ref-labs.near",
|
2875
2875
|
bridgeContractId: "btc-connector.bridge.near",
|
2876
2876
|
walletUrl: "https://wallet.satoshibridge.top",
|
@@ -2896,69 +2896,24 @@ import Big from "big.js";
|
|
2896
2896
|
|
2897
2897
|
// src/utils/nearUtils.ts
|
2898
2898
|
import { providers } from "near-api-js";
|
2899
|
-
function nearCallFunction(contractId, methodName, args, options) {
|
2900
|
-
return __async(this, null, function* () {
|
2901
|
-
const nearProvider = (options == null ? void 0 : options.provider) || new providers.FailoverRpcProvider(
|
2902
|
-
nearRpcUrls[options == null ? void 0 : options.network].map(
|
2903
|
-
(url) => new providers.JsonRpcProvider({ url })
|
2904
|
-
)
|
2905
|
-
);
|
2906
|
-
const res = yield nearProvider.query({
|
2907
|
-
request_type: "call_function",
|
2908
|
-
account_id: contractId,
|
2909
|
-
method_name: methodName,
|
2910
|
-
args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
|
2911
|
-
finality: "final"
|
2912
|
-
});
|
2913
|
-
return JSON.parse(Buffer.from(res.result).toString());
|
2914
|
-
});
|
2915
|
-
}
|
2916
|
-
function pollTransactionStatuses(network, hashes) {
|
2917
|
-
return __async(this, null, function* () {
|
2918
|
-
const provider = new providers.FailoverRpcProvider(
|
2919
|
-
Object.values(nearRpcUrls[network]).map(
|
2920
|
-
(url) => new providers.JsonRpcProvider({ url })
|
2921
|
-
)
|
2922
|
-
);
|
2923
|
-
const maxAttempts = 30;
|
2924
|
-
let currentAttempt = 0;
|
2925
|
-
const pendingHashes = new Set(hashes);
|
2926
|
-
const results = /* @__PURE__ */ new Map();
|
2927
|
-
while (pendingHashes.size > 0 && currentAttempt < maxAttempts) {
|
2928
|
-
currentAttempt++;
|
2929
|
-
const promises = Array.from(pendingHashes).map((hash) => __async(this, null, function* () {
|
2930
|
-
try {
|
2931
|
-
const result2 = yield provider.txStatus(hash, "unused", "FINAL");
|
2932
|
-
if (result2 && result2.status) {
|
2933
|
-
console.log(`Transaction ${hash} result:`, result2);
|
2934
|
-
results.set(hash, result2);
|
2935
|
-
pendingHashes.delete(hash);
|
2936
|
-
}
|
2937
|
-
} catch (error) {
|
2938
|
-
console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
|
2939
|
-
}
|
2940
|
-
}));
|
2941
|
-
yield Promise.all(promises);
|
2942
|
-
if (pendingHashes.size > 0) {
|
2943
|
-
if (currentAttempt === maxAttempts) {
|
2944
|
-
throw new Error(
|
2945
|
-
`Transactions not found after max attempts: ${Array.from(pendingHashes).join(", ")}`
|
2946
|
-
);
|
2947
|
-
}
|
2948
|
-
console.log(
|
2949
|
-
`Waiting for ${pendingHashes.size} transactions, retrying ${maxAttempts - currentAttempt} more times`
|
2950
|
-
);
|
2951
|
-
yield delay(1e4);
|
2952
|
-
}
|
2953
|
-
}
|
2954
|
-
const result = hashes.map((hash) => results.get(hash)).filter(Boolean);
|
2955
|
-
return result;
|
2956
|
-
});
|
2957
|
-
}
|
2958
2899
|
|
2959
2900
|
// src/utils/request.ts
|
2960
2901
|
var cache = /* @__PURE__ */ new Map();
|
2961
2902
|
var defaultCacheTimeout = 3e3;
|
2903
|
+
function withCache(key, fetcher, timeout = defaultCacheTimeout) {
|
2904
|
+
const cached = cache.get(key);
|
2905
|
+
const isCacheValid = cached && Date.now() - cached.timestamp < timeout;
|
2906
|
+
if (isCacheValid) {
|
2907
|
+
return Promise.resolve(cached.data);
|
2908
|
+
}
|
2909
|
+
return fetcher().then((data) => {
|
2910
|
+
cache.set(key, { timestamp: Date.now(), data });
|
2911
|
+
setTimeout(() => {
|
2912
|
+
cache.delete(key);
|
2913
|
+
}, timeout);
|
2914
|
+
return data;
|
2915
|
+
});
|
2916
|
+
}
|
2962
2917
|
function request(url, options) {
|
2963
2918
|
return __async(this, null, function* () {
|
2964
2919
|
var _a;
|
@@ -3000,13 +2955,7 @@ function request(url, options) {
|
|
3000
2955
|
if (options.shouldStopPolling(data)) {
|
3001
2956
|
return data;
|
3002
2957
|
}
|
3003
|
-
|
3004
|
-
yield new Promise((resolve) => setTimeout(resolve, options.pollingInterval));
|
3005
|
-
return request(url, __spreadProps(__spreadValues({}, options), {
|
3006
|
-
maxPollingAttempts: options.maxPollingAttempts - 1
|
3007
|
-
}));
|
3008
|
-
}
|
3009
|
-
throw new Error("Polling failed: maximum attempts reached without meeting the condition");
|
2958
|
+
throw new Error("Polling should continue");
|
3010
2959
|
}
|
3011
2960
|
if (cacheKey) {
|
3012
2961
|
cache.set(cacheKey, { timestamp: Date.now(), data });
|
@@ -3016,6 +2965,7 @@ function request(url, options) {
|
|
3016
2965
|
}
|
3017
2966
|
return data;
|
3018
2967
|
} catch (err) {
|
2968
|
+
console.error(err);
|
3019
2969
|
if (retryCount > 0) {
|
3020
2970
|
console.log(`Retrying... attempts left: ${retryCount}`);
|
3021
2971
|
return request(url, __spreadProps(__spreadValues({}, options), { retryCount: retryCount - 1 }));
|
@@ -3029,8 +2979,85 @@ function request(url, options) {
|
|
3029
2979
|
}));
|
3030
2980
|
}
|
3031
2981
|
}
|
3032
|
-
|
2982
|
+
return Promise.reject(err);
|
2983
|
+
}
|
2984
|
+
});
|
2985
|
+
}
|
2986
|
+
|
2987
|
+
// src/utils/nearUtils.ts
|
2988
|
+
function getNearProvider(option) {
|
2989
|
+
return option.provider || new providers.FailoverRpcProvider(
|
2990
|
+
nearRpcUrls[option == null ? void 0 : option.network].map(
|
2991
|
+
(url) => new providers.JsonRpcProvider({ url })
|
2992
|
+
)
|
2993
|
+
);
|
2994
|
+
}
|
2995
|
+
function nearCallFunction(_0, _1, _2) {
|
2996
|
+
return __async(this, arguments, function* (contractId, methodName, args, options = {}) {
|
2997
|
+
if (!options.skipCache) {
|
2998
|
+
const cacheKey = `near:${contractId}:${methodName}:${args ? JSON.stringify(args) : ""}`;
|
2999
|
+
return withCache(
|
3000
|
+
cacheKey,
|
3001
|
+
() => executeNearCall(contractId, methodName, args, options),
|
3002
|
+
options.cacheTimeout
|
3003
|
+
);
|
3004
|
+
}
|
3005
|
+
return executeNearCall(contractId, methodName, args, options);
|
3006
|
+
});
|
3007
|
+
}
|
3008
|
+
function executeNearCall(contractId, methodName, args, options) {
|
3009
|
+
return __async(this, null, function* () {
|
3010
|
+
const nearProvider = getNearProvider(options);
|
3011
|
+
const res = yield nearProvider.query({
|
3012
|
+
request_type: "call_function",
|
3013
|
+
account_id: contractId,
|
3014
|
+
method_name: methodName,
|
3015
|
+
args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
|
3016
|
+
finality: "final"
|
3017
|
+
});
|
3018
|
+
return JSON.parse(Buffer.from(res.result).toString());
|
3019
|
+
});
|
3020
|
+
}
|
3021
|
+
function pollTransactionStatuses(network, hashes) {
|
3022
|
+
return __async(this, null, function* () {
|
3023
|
+
const provider = new providers.FailoverRpcProvider(
|
3024
|
+
Object.values(nearRpcUrls[network]).map(
|
3025
|
+
(url) => new providers.JsonRpcProvider({ url })
|
3026
|
+
)
|
3027
|
+
);
|
3028
|
+
const maxAttempts = 30;
|
3029
|
+
let currentAttempt = 0;
|
3030
|
+
const pendingHashes = new Set(hashes);
|
3031
|
+
const results = /* @__PURE__ */ new Map();
|
3032
|
+
while (pendingHashes.size > 0 && currentAttempt < maxAttempts) {
|
3033
|
+
currentAttempt++;
|
3034
|
+
const promises = Array.from(pendingHashes).map((hash) => __async(this, null, function* () {
|
3035
|
+
try {
|
3036
|
+
const result2 = yield provider.txStatus(hash, "unused", "FINAL");
|
3037
|
+
if (result2 && result2.status) {
|
3038
|
+
console.log(`Transaction ${hash} result:`, result2);
|
3039
|
+
results.set(hash, result2);
|
3040
|
+
pendingHashes.delete(hash);
|
3041
|
+
}
|
3042
|
+
} catch (error) {
|
3043
|
+
console.error(`Failed to fetch transaction status for ${hash}: ${error.message}`);
|
3044
|
+
}
|
3045
|
+
}));
|
3046
|
+
yield Promise.all(promises);
|
3047
|
+
if (pendingHashes.size > 0) {
|
3048
|
+
if (currentAttempt === maxAttempts) {
|
3049
|
+
throw new Error(
|
3050
|
+
`Transactions not found after max attempts: ${Array.from(pendingHashes).join(", ")}`
|
3051
|
+
);
|
3052
|
+
}
|
3053
|
+
console.log(
|
3054
|
+
`Waiting for ${pendingHashes.size} transactions, retrying ${maxAttempts - currentAttempt} more times`
|
3055
|
+
);
|
3056
|
+
yield delay(1e4);
|
3057
|
+
}
|
3033
3058
|
}
|
3059
|
+
const result = hashes.map((hash) => results.get(hash)).filter(Boolean);
|
3060
|
+
return result;
|
3034
3061
|
});
|
3035
3062
|
}
|
3036
3063
|
|
@@ -3187,9 +3214,10 @@ function nearCall(contractId, methodName, args) {
|
|
3187
3214
|
return nearCallFunction(contractId, methodName, args, { network });
|
3188
3215
|
});
|
3189
3216
|
}
|
3190
|
-
function getAccountInfo(
|
3191
|
-
return __async(this,
|
3192
|
-
const
|
3217
|
+
function getAccountInfo(_0) {
|
3218
|
+
return __async(this, arguments, function* ({ csna, env }) {
|
3219
|
+
const config = yield getConfig(env);
|
3220
|
+
const accountInfo = yield nearCall(config.accountContractId, "get_account", {
|
3193
3221
|
account_id: csna
|
3194
3222
|
}).catch((error) => {
|
3195
3223
|
return void 0;
|
@@ -3198,16 +3226,46 @@ function getAccountInfo(csna, accountContractId) {
|
|
3198
3226
|
return accountInfo;
|
3199
3227
|
});
|
3200
3228
|
}
|
3201
|
-
function
|
3229
|
+
function getTokenBalance(_0) {
|
3230
|
+
return __async(this, arguments, function* ({
|
3231
|
+
csna,
|
3232
|
+
tokenId,
|
3233
|
+
env
|
3234
|
+
}) {
|
3235
|
+
const network = yield getNetwork();
|
3236
|
+
const config = yield getConfig(env);
|
3237
|
+
const nearProvider = getNearProvider({ network });
|
3238
|
+
try {
|
3239
|
+
if (tokenId === config.nearToken) {
|
3240
|
+
const nearAccount = yield nearProvider.query({
|
3241
|
+
request_type: "view_account",
|
3242
|
+
account_id: csna,
|
3243
|
+
finality: "final"
|
3244
|
+
});
|
3245
|
+
const balance = parseFloat(nearAccount.amount) / __pow(10, config.nearTokenDecimals);
|
3246
|
+
return { balance, rawBalance: nearAccount.amount };
|
3247
|
+
} else {
|
3248
|
+
const res = yield nearCall(tokenId, "ft_balance_of", { account_id: csna });
|
3249
|
+
const decimals = tokenId === config.btcToken ? config.btcTokenDecimals : (yield nearCall(tokenId, "ft_metadata", {})).decimals;
|
3250
|
+
const balance = parseFloat(res) / __pow(10, decimals);
|
3251
|
+
return { balance, rawBalance: res };
|
3252
|
+
}
|
3253
|
+
} catch (error) {
|
3254
|
+
console.error("getTokenBalance error:", error);
|
3255
|
+
return { balance: 0, rawBalance: "0" };
|
3256
|
+
}
|
3257
|
+
});
|
3258
|
+
}
|
3259
|
+
function checkGasTokenBalance(csna, minAmount, env) {
|
3202
3260
|
return __async(this, null, function* () {
|
3203
|
-
const
|
3204
|
-
|
3205
|
-
|
3261
|
+
const config = yield getConfig(env);
|
3262
|
+
const { rawBalance } = yield getTokenBalance({ csna, tokenId: config.btcToken, env });
|
3263
|
+
console.log("gas token balance:", rawBalance);
|
3264
|
+
if (new Big(rawBalance).lt(minAmount)) {
|
3206
3265
|
yield Dialog.confirm({
|
3207
3266
|
title: "Gas token balance is insufficient",
|
3208
3267
|
message: "Please deposit gas token to continue, will open bridge website."
|
3209
3268
|
});
|
3210
|
-
const config = yield getConfig(env);
|
3211
3269
|
window.open(config.bridgeUrl, "_blank");
|
3212
3270
|
throw new Error("Gas token balance is insufficient");
|
3213
3271
|
}
|
@@ -3288,18 +3346,6 @@ function getBtcBalance() {
|
|
3288
3346
|
};
|
3289
3347
|
});
|
3290
3348
|
}
|
3291
|
-
function getNBTCBalance(address, env) {
|
3292
|
-
return __async(this, null, function* () {
|
3293
|
-
const config = yield getConfig(env || "mainnet");
|
3294
|
-
const rawBalance = yield nearCall(config.token, "ft_balance_of", {
|
3295
|
-
account_id: address
|
3296
|
-
});
|
3297
|
-
const balance = new Big(rawBalance).div(__pow(10, 8)).round(8, Big.roundDown).toNumber();
|
3298
|
-
const rawAvailableBalance = new Big(rawBalance).minus(1e3).toNumber();
|
3299
|
-
const availableBalance = new Big(rawAvailableBalance).div(__pow(10, 8)).round(8, Big.roundDown).toNumber();
|
3300
|
-
return { balance, availableBalance, rawBalance, rawAvailableBalance };
|
3301
|
-
});
|
3302
|
-
}
|
3303
3349
|
function sendBitcoin(address, amount, feeRate) {
|
3304
3350
|
return __async(this, null, function* () {
|
3305
3351
|
const { sendBitcoin: sendBitcoin2 } = getBtcProvider();
|
@@ -3319,7 +3365,7 @@ function getDepositAmount(amount, option) {
|
|
3319
3365
|
const _newAccountMinDepositAmount = (_a = option == null ? void 0 : option.newAccountMinDepositAmount) != null ? _a : true;
|
3320
3366
|
const config = yield getConfig(env);
|
3321
3367
|
const csna = yield getCsnaAccountId(env);
|
3322
|
-
const accountInfo = yield getAccountInfo(csna,
|
3368
|
+
const accountInfo = yield getAccountInfo({ csna, env });
|
3323
3369
|
const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
|
3324
3370
|
const repayAmount = (debtAction == null ? void 0 : debtAction.amount) || 0;
|
3325
3371
|
const {
|
@@ -3398,7 +3444,7 @@ function executeBTCDepositAndAction(_0) {
|
|
3398
3444
|
env,
|
3399
3445
|
newAccountMinDepositAmount
|
3400
3446
|
});
|
3401
|
-
const accountInfo = yield getAccountInfo(csna,
|
3447
|
+
const accountInfo = yield getAccountInfo({ csna, env });
|
3402
3448
|
const newActions = [];
|
3403
3449
|
const debtAction = yield checkGasTokenDebt(accountInfo, env, false);
|
3404
3450
|
if (debtAction) {
|
@@ -3412,12 +3458,12 @@ function executeBTCDepositAndAction(_0) {
|
|
3412
3458
|
}));
|
3413
3459
|
}
|
3414
3460
|
const storageDepositMsg = {};
|
3415
|
-
const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.
|
3461
|
+
const registerRes = yield nearCall((action == null ? void 0 : action.receiver_id) || config.btcToken, "storage_balance_of", {
|
3416
3462
|
account_id: csna
|
3417
3463
|
});
|
3418
3464
|
if (!(registerRes == null ? void 0 : registerRes.available)) {
|
3419
3465
|
storageDepositMsg.storage_deposit_msg = {
|
3420
|
-
contract_id: (action == null ? void 0 : action.receiver_id) || config.
|
3466
|
+
contract_id: (action == null ? void 0 : action.receiver_id) || config.btcToken,
|
3421
3467
|
deposit: registerDeposit || NEAR_STORAGE_DEPOSIT_AMOUNT,
|
3422
3468
|
registration_only: true
|
3423
3469
|
};
|
@@ -3623,7 +3669,7 @@ function getWithdrawTransaction(_0) {
|
|
3623
3669
|
};
|
3624
3670
|
const csna = yield getCsnaAccountId(env);
|
3625
3671
|
const transaction = {
|
3626
|
-
receiverId: config.
|
3672
|
+
receiverId: config.btcToken,
|
3627
3673
|
signerId: csna,
|
3628
3674
|
actions: [
|
3629
3675
|
{
|
@@ -4167,20 +4213,16 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4167
4213
|
throw new Error("Wallet state is invalid, please reconnect your wallet.");
|
4168
4214
|
}
|
4169
4215
|
const btcContext = window.btcContext;
|
4170
|
-
const
|
4171
|
-
const accountInfo = yield getAccountInfo(
|
4216
|
+
const csna = state.getAccount();
|
4217
|
+
const accountInfo = yield getAccountInfo({ csna, env });
|
4172
4218
|
yield checkGasTokenDebt(accountInfo, env, true);
|
4173
4219
|
const trans = [...params.transactions];
|
4174
4220
|
console.log("signAndSendTransactions raw trans:", trans);
|
4175
|
-
const
|
4176
|
-
const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(
|
4177
|
-
gasTokenBalance,
|
4178
|
-
trans
|
4179
|
-
);
|
4221
|
+
const { transferGasTransaction, useNearPayGas, gasLimit } = yield calculateGasStrategy(trans);
|
4180
4222
|
console.log("transferGasTransaction:", transferGasTransaction);
|
4181
4223
|
console.log("useNearPayGas:", useNearPayGas);
|
4182
4224
|
console.log("gasLimit:", gasLimit);
|
4183
|
-
yield checkGasTokenBalance(
|
4225
|
+
yield checkGasTokenBalance(csna, gasLimit, env);
|
4184
4226
|
if (transferGasTransaction) {
|
4185
4227
|
trans.unshift(transferGasTransaction);
|
4186
4228
|
}
|
@@ -4188,14 +4230,14 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4188
4230
|
const newTrans = yield Promise.all(
|
4189
4231
|
trans.map((transaction, index) => convertTransactionToTxHex(transaction, index))
|
4190
4232
|
);
|
4191
|
-
const nonceFromApi = yield getNonce(currentConfig.base_url,
|
4233
|
+
const nonceFromApi = yield getNonce(currentConfig.base_url, csna);
|
4192
4234
|
const nonceFromContract = (accountInfo == null ? void 0 : accountInfo.nonce) || 0;
|
4193
4235
|
const nonce = Number(nonceFromApi) > Number(nonceFromContract) ? String(nonceFromApi) : String(nonceFromContract);
|
4194
4236
|
const intention = {
|
4195
4237
|
chain_id: "397",
|
4196
|
-
csna
|
4238
|
+
csna,
|
4197
4239
|
near_transactions: newTrans.map((t) => t.txHex),
|
4198
|
-
gas_token: currentConfig.
|
4240
|
+
gas_token: currentConfig.btcToken,
|
4199
4241
|
gas_limit: gasLimit,
|
4200
4242
|
use_near_pay_gas: useNearPayGas,
|
4201
4243
|
nonce
|
@@ -4208,7 +4250,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4208
4250
|
data: toHex(strIntention)
|
4209
4251
|
});
|
4210
4252
|
yield checkBtcTransactionStatus(currentConfig.base_url, signature);
|
4211
|
-
const hash = newTrans.map((t) => t.hash);
|
4253
|
+
const hash = newTrans.slice(1).map((t) => t.hash);
|
4212
4254
|
console.log("txHash:", hash);
|
4213
4255
|
const result = yield pollTransactionStatuses(options.network.networkId, hash);
|
4214
4256
|
return result;
|
@@ -4216,12 +4258,9 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4216
4258
|
}
|
4217
4259
|
function calculateGasLimit(params) {
|
4218
4260
|
return __async(this, null, function* () {
|
4219
|
-
const accountId = state.getAccount();
|
4220
|
-
const accountInfo = yield getAccountInfo(accountId, currentConfig.accountContractId);
|
4221
4261
|
const trans = [...params.transactions];
|
4222
4262
|
console.log("raw trans:", trans);
|
4223
|
-
const
|
4224
|
-
const { gasLimit } = yield calculateGasStrategy(gasTokenBalance, trans);
|
4263
|
+
const { gasLimit } = yield calculateGasStrategy(trans);
|
4225
4264
|
return gasLimit;
|
4226
4265
|
});
|
4227
4266
|
}
|
@@ -4229,7 +4268,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4229
4268
|
return __async(this, null, function* () {
|
4230
4269
|
return {
|
4231
4270
|
signerId: accountId,
|
4232
|
-
receiverId: currentConfig.
|
4271
|
+
receiverId: currentConfig.btcToken,
|
4233
4272
|
actions: [
|
4234
4273
|
{
|
4235
4274
|
type: "FunctionCall",
|
@@ -4257,7 +4296,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4257
4296
|
} else {
|
4258
4297
|
newGasLimit = yield getPredictedGasAmount(
|
4259
4298
|
currentConfig.accountContractId,
|
4260
|
-
currentConfig.
|
4299
|
+
currentConfig.btcToken,
|
4261
4300
|
[transferTxHex, ...transactions2.map((t) => t.txHex)]
|
4262
4301
|
);
|
4263
4302
|
}
|
@@ -4278,31 +4317,61 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4278
4317
|
return gasAmount.toString();
|
4279
4318
|
});
|
4280
4319
|
}
|
4281
|
-
function calculateGasStrategy(
|
4320
|
+
function calculateGasStrategy(transactions2) {
|
4282
4321
|
return __async(this, null, function* () {
|
4283
4322
|
var _a;
|
4284
4323
|
const accountId = state.getAccount();
|
4285
|
-
const
|
4286
|
-
|
4287
|
-
|
4288
|
-
|
4324
|
+
const accountInfo = yield getAccountInfo({ csna: accountId, env });
|
4325
|
+
const gasTokenBalance = (accountInfo == null ? void 0 : accountInfo.gas_token[currentConfig.btcToken]) || "0";
|
4326
|
+
const { balance: nearBalance } = yield getTokenBalance({
|
4327
|
+
csna: accountId,
|
4328
|
+
tokenId: currentConfig.nearToken,
|
4329
|
+
env
|
4330
|
+
});
|
4331
|
+
const { balance: btcBalance } = yield getTokenBalance({
|
4332
|
+
csna: accountId,
|
4333
|
+
tokenId: currentConfig.btcToken,
|
4334
|
+
env
|
4289
4335
|
});
|
4290
|
-
const
|
4291
|
-
|
4336
|
+
const transferAmount = transactions2.reduce(
|
4337
|
+
(acc, tx) => {
|
4338
|
+
tx.actions.forEach((action) => {
|
4339
|
+
if (action.params.deposit) {
|
4340
|
+
const amount = Number(action.params.deposit) / __pow(10, currentConfig.nearTokenDecimals);
|
4341
|
+
console.log("near deposit amount:", amount);
|
4342
|
+
acc.near = acc.near.plus(amount);
|
4343
|
+
}
|
4344
|
+
if (tx.receiverId === currentConfig.btcToken && ["ft_transfer_call", "ft_transfer"].includes(action.params.methodName)) {
|
4345
|
+
const amount = Number(action.params.args.amount) / __pow(10, currentConfig.btcTokenDecimals);
|
4346
|
+
console.log("btc transfer amount:", amount);
|
4347
|
+
acc.btc = acc.btc.plus(amount);
|
4348
|
+
}
|
4349
|
+
});
|
4350
|
+
return acc;
|
4351
|
+
},
|
4352
|
+
{ near: new Big2(0), btc: new Big2(0) }
|
4353
|
+
);
|
4354
|
+
const nearAvailableBalance = new Big2(nearBalance).minus(transferAmount.near).toNumber();
|
4355
|
+
const btcAvailableBalance = new Big2(btcBalance).minus(transferAmount.btc).toNumber();
|
4356
|
+
if (btcAvailableBalance < 8e-6) {
|
4357
|
+
throw new Error("BTC balance is not enough, please deposit more BTC.");
|
4358
|
+
}
|
4359
|
+
console.log("available near balance:", nearAvailableBalance);
|
4360
|
+
console.log("available btc balance:", btcAvailableBalance);
|
4292
4361
|
console.log("available gas token balance:", gasTokenBalance);
|
4293
4362
|
const convertTx = yield Promise.all(
|
4294
4363
|
transactions2.map((transaction, index) => convertTransactionToTxHex(transaction, index))
|
4295
4364
|
);
|
4296
|
-
if (
|
4365
|
+
if (nearAvailableBalance > 0.5) {
|
4297
4366
|
console.log("near balance is enough, get the protocol fee of each transaction");
|
4298
4367
|
const gasTokens = yield nearCall2(
|
4299
4368
|
currentConfig.accountContractId,
|
4300
4369
|
"list_gas_token",
|
4301
|
-
{ token_ids: [currentConfig.
|
4370
|
+
{ token_ids: [currentConfig.btcToken] }
|
4302
4371
|
);
|
4303
4372
|
console.log("list_gas_token gas tokens:", gasTokens);
|
4304
4373
|
const perTxFee = Math.max(
|
4305
|
-
Number(((_a = gasTokens[currentConfig.
|
4374
|
+
Number(((_a = gasTokens[currentConfig.btcToken]) == null ? void 0 : _a.per_tx_protocol_fee) || 0),
|
4306
4375
|
100
|
4307
4376
|
);
|
4308
4377
|
console.log("perTxFee:", perTxFee);
|
@@ -4320,7 +4389,7 @@ var BTCWallet = (_0) => __async(void 0, [_0], function* ({
|
|
4320
4389
|
console.log("near balance is not enough, predict the gas token amount required");
|
4321
4390
|
const adjustedGas = yield getPredictedGasAmount(
|
4322
4391
|
currentConfig.accountContractId,
|
4323
|
-
currentConfig.
|
4392
|
+
currentConfig.btcToken,
|
4324
4393
|
convertTx.map((t) => t.txHex)
|
4325
4394
|
);
|
4326
4395
|
if (new Big2(gasTokenBalance).gte(adjustedGas)) {
|
@@ -4436,7 +4505,7 @@ function setupBTCWallet({
|
|
4436
4505
|
|
4437
4506
|
// src/index.ts
|
4438
4507
|
var getVersion = () => {
|
4439
|
-
return "0.5.
|
4508
|
+
return "0.5.12-beta";
|
4440
4509
|
};
|
4441
4510
|
if (typeof window !== "undefined") {
|
4442
4511
|
window.__BTC_WALLET_VERSION = getVersion();
|
@@ -4466,7 +4535,7 @@ export {
|
|
4466
4535
|
getConfig,
|
4467
4536
|
getCsnaAccountId,
|
4468
4537
|
getDepositAmount,
|
4469
|
-
|
4538
|
+
getTokenBalance,
|
4470
4539
|
getVersion,
|
4471
4540
|
getWithdrawTransaction,
|
4472
4541
|
sendBitcoin,
|