@swapkit/toolboxes 1.0.0-beta.2 → 1.0.0-beta.21
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/chunk-12xtvbsp.js +4 -0
- package/dist/{chunk-0h4xdrwz.js.map → chunk-12xtvbsp.js.map} +2 -2
- package/dist/{chunk-fjfxga2v.js → chunk-5yxc1e69.js} +1 -1
- package/dist/{chunk-fjfxga2v.js.map → chunk-5yxc1e69.js.map} +1 -1
- package/dist/{chunk-0f0249b1.js → chunk-9bqegm61.js} +1 -1
- package/dist/chunk-kbnwrc5b.js +4 -0
- package/dist/chunk-kbnwrc5b.js.map +10 -0
- package/dist/{chunk-p1kdg37m.js → chunk-s47y8512.js} +2 -2
- package/dist/{chunk-p1kdg37m.js.map → chunk-s47y8512.js.map} +1 -1
- package/dist/chunk-vtd17cje.js +3 -0
- package/dist/chunk-vtd17cje.js.map +10 -0
- package/dist/src/cosmos/index.cjs +3 -0
- package/dist/src/cosmos/index.cjs.map +16 -0
- package/dist/src/cosmos/index.js +3 -0
- package/dist/src/cosmos/index.js.map +16 -0
- package/dist/src/evm/index.cjs +3 -0
- package/dist/src/evm/index.cjs.map +18 -0
- package/dist/src/evm/index.js +3 -0
- package/dist/src/evm/index.js.map +18 -0
- package/dist/src/index.cjs +3 -0
- package/dist/src/index.cjs.map +10 -0
- package/dist/src/index.js +3 -0
- package/dist/src/index.js.map +10 -0
- package/dist/src/near/index.cjs +3 -0
- package/dist/src/near/index.cjs.map +13 -0
- package/dist/src/near/index.js +3 -0
- package/dist/src/near/index.js.map +13 -0
- package/dist/{radix → src/radix}/index.cjs +2 -2
- package/dist/src/radix/index.cjs.map +10 -0
- package/dist/src/radix/index.js +3 -0
- package/dist/src/radix/index.js.map +10 -0
- package/dist/src/ripple/index.cjs +3 -0
- package/dist/src/ripple/index.cjs.map +10 -0
- package/dist/src/ripple/index.js +3 -0
- package/dist/src/ripple/index.js.map +10 -0
- package/dist/src/solana/index.cjs +3 -0
- package/dist/src/solana/index.cjs.map +10 -0
- package/dist/src/solana/index.js +3 -0
- package/dist/src/solana/index.js.map +10 -0
- package/dist/src/substrate/index.cjs +3 -0
- package/dist/src/substrate/index.cjs.map +11 -0
- package/dist/src/substrate/index.js +3 -0
- package/dist/src/substrate/index.js.map +11 -0
- package/dist/src/tron/index.cjs +3 -0
- package/dist/src/tron/index.cjs.map +11 -0
- package/dist/src/tron/index.js +3 -0
- package/dist/src/tron/index.js.map +11 -0
- package/dist/src/utxo/index.cjs +3 -0
- package/dist/src/utxo/index.cjs.map +16 -0
- package/dist/src/utxo/index.js +3 -0
- package/dist/src/utxo/index.js.map +16 -0
- package/package.json +49 -37
- package/src/cosmos/thorchainUtils/addressFormat.ts +4 -1
- package/src/cosmos/thorchainUtils/messages.ts +2 -2
- package/src/cosmos/thorchainUtils/registry.ts +3 -3
- package/src/cosmos/toolbox/cosmos.ts +16 -11
- package/src/cosmos/toolbox/index.ts +2 -2
- package/src/cosmos/toolbox/thorchain.ts +11 -9
- package/src/cosmos/util.ts +13 -6
- package/src/evm/__tests__/ethereum.test.ts +1 -1
- package/src/evm/helpers.ts +4 -3
- package/src/evm/toolbox/baseEVMToolbox.ts +37 -25
- package/src/evm/toolbox/index.ts +2 -2
- package/src/evm/toolbox/op.ts +21 -7
- package/src/index.ts +117 -100
- package/src/near/helpers/contractFactory.ts +22 -0
- package/src/near/helpers/core.ts +86 -0
- package/src/near/helpers/gasEstimation.ts +110 -0
- package/src/near/helpers/index.ts +5 -0
- package/src/near/helpers/nep141.ts +110 -0
- package/src/near/index.ts +24 -0
- package/src/near/toolbox.ts +497 -0
- package/src/near/types/contract.ts +48 -0
- package/src/near/types/nep141.ts +66 -0
- package/src/near/types.ts +57 -0
- package/src/radix/index.ts +8 -2
- package/src/ripple/index.ts +15 -26
- package/src/solana/toolbox.ts +75 -2
- package/src/substrate/substrate.ts +1 -1
- package/src/tron/helpers/trc20.abi.ts +40 -0
- package/src/tron/index.ts +16 -0
- package/src/tron/toolbox.ts +328 -0
- package/src/tron/types.ts +22 -0
- package/src/utxo/helpers/api.ts +30 -16
- package/src/utxo/helpers/bchaddrjs.ts +8 -8
- package/src/utxo/helpers/coinselect.ts +2 -2
- package/src/utxo/helpers/txSize.ts +4 -3
- package/src/utxo/toolbox/bitcoinCash.ts +22 -14
- package/src/utxo/toolbox/index.ts +2 -1
- package/src/utxo/toolbox/utxo.ts +35 -27
- package/src/utxo/types.ts +2 -0
- package/dist/chunk-0h4xdrwz.js +0 -4
- package/dist/cosmos/index.cjs +0 -3
- package/dist/cosmos/index.cjs.map +0 -16
- package/dist/cosmos/index.js +0 -3
- package/dist/cosmos/index.js.map +0 -16
- package/dist/evm/index.cjs +0 -3
- package/dist/evm/index.cjs.map +0 -18
- package/dist/evm/index.js +0 -3
- package/dist/evm/index.js.map +0 -18
- package/dist/index.cjs +0 -3
- package/dist/index.cjs.map +0 -10
- package/dist/index.js +0 -3
- package/dist/index.js.map +0 -10
- package/dist/radix/index.cjs.map +0 -10
- package/dist/radix/index.js +0 -3
- package/dist/radix/index.js.map +0 -10
- package/dist/ripple/index.cjs +0 -3
- package/dist/ripple/index.cjs.map +0 -10
- package/dist/ripple/index.js +0 -3
- package/dist/ripple/index.js.map +0 -10
- package/dist/solana/index.cjs +0 -3
- package/dist/solana/index.cjs.map +0 -10
- package/dist/solana/index.js +0 -3
- package/dist/solana/index.js.map +0 -10
- package/dist/substrate/index.cjs +0 -3
- package/dist/substrate/index.cjs.map +0 -11
- package/dist/substrate/index.js +0 -3
- package/dist/substrate/index.js.map +0 -11
- package/dist/utxo/index.cjs +0 -3
- package/dist/utxo/index.cjs.map +0 -16
- package/dist/utxo/index.js +0 -3
- package/dist/utxo/index.js.map +0 -16
- /package/dist/{chunk-0f0249b1.js.map → chunk-9bqegm61.js.map} +0 -0
package/src/utxo/helpers/api.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
Chain,
|
|
3
|
+
RequestClient,
|
|
4
|
+
SKConfig,
|
|
5
|
+
SwapKitError,
|
|
6
|
+
type UTXOChain,
|
|
7
|
+
warnOnce,
|
|
8
|
+
} from "@swapkit/helpers";
|
|
9
|
+
import { networks } from "bitcoinjs-lib";
|
|
2
10
|
import { uniqid } from "../../utils";
|
|
3
11
|
|
|
12
|
+
// @ts-ignore
|
|
13
|
+
import coininfo from "coininfo";
|
|
14
|
+
|
|
4
15
|
type BlockchairParams<T> = T & { chain: Chain; apiKey?: string };
|
|
5
16
|
type BlockchairFetchUnspentUtxoParams = BlockchairParams<{
|
|
6
17
|
offset?: number;
|
|
@@ -24,11 +35,13 @@ async function broadcastUTXOTx({ chain, txHash }: { chain: Chain; txHash: string
|
|
|
24
35
|
}>(rpcUrl, { headers: { "Content-Type": "application/json" }, body });
|
|
25
36
|
|
|
26
37
|
if (response.error) {
|
|
27
|
-
throw new
|
|
38
|
+
throw new SwapKitError("toolbox_utxo_broadcast_failed", { error: response.error?.message });
|
|
28
39
|
}
|
|
29
40
|
|
|
30
41
|
if (response.result.includes('"code":-26')) {
|
|
31
|
-
throw new
|
|
42
|
+
throw new SwapKitError("toolbox_utxo_invalid_transaction", {
|
|
43
|
+
error: "Transaction amount was too low",
|
|
44
|
+
});
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
return response.result;
|
|
@@ -89,7 +102,8 @@ async function getSuggestedTxFee(chain: Chain) {
|
|
|
89
102
|
async function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {
|
|
90
103
|
try {
|
|
91
104
|
const response = await RequestClient.get<BlockchairResponse<T>>(url);
|
|
92
|
-
if (!response || response.context.code !== 200)
|
|
105
|
+
if (!response || response.context.code !== 200)
|
|
106
|
+
throw new SwapKitError("toolbox_utxo_api_error", { error: `Failed to query ${url}` });
|
|
93
107
|
|
|
94
108
|
return response.data as T;
|
|
95
109
|
} catch (error) {
|
|
@@ -98,14 +112,16 @@ async function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {
|
|
|
98
112
|
`${url}${apiKey ? `&key=${apiKey}` : ""}`,
|
|
99
113
|
);
|
|
100
114
|
|
|
101
|
-
if (!response || response.context.code !== 200)
|
|
115
|
+
if (!response || response.context.code !== 200)
|
|
116
|
+
throw new SwapKitError("toolbox_utxo_api_error", { error: `Failed to query ${url}` });
|
|
102
117
|
|
|
103
118
|
return response.data as T;
|
|
104
119
|
}
|
|
105
120
|
}
|
|
106
121
|
|
|
107
122
|
async function getAddressData({ address, chain, apiKey }: BlockchairParams<{ address?: string }>) {
|
|
108
|
-
if (!address)
|
|
123
|
+
if (!address)
|
|
124
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", { error: "Address is required" });
|
|
109
125
|
|
|
110
126
|
try {
|
|
111
127
|
const response = await blockchairRequest<BlockchairAddressResponse>(
|
|
@@ -130,7 +146,8 @@ async function getUnconfirmedBalance({
|
|
|
130
146
|
}
|
|
131
147
|
|
|
132
148
|
async function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {
|
|
133
|
-
if (!txHash)
|
|
149
|
+
if (!txHash)
|
|
150
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", { error: "TxHash is required" });
|
|
134
151
|
|
|
135
152
|
try {
|
|
136
153
|
const rawTxResponse = await blockchairRequest<BlockchairRawTransactionResponse>(
|
|
@@ -139,7 +156,7 @@ async function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: s
|
|
|
139
156
|
);
|
|
140
157
|
return rawTxResponse?.[txHash]?.raw_transaction || "";
|
|
141
158
|
} catch (error) {
|
|
142
|
-
console.error(error);
|
|
159
|
+
console.error("Failed to fetch raw transaction:", error);
|
|
143
160
|
return "";
|
|
144
161
|
}
|
|
145
162
|
}
|
|
@@ -177,7 +194,8 @@ async function getUnspentUtxos({
|
|
|
177
194
|
offset = 0,
|
|
178
195
|
limit = 100,
|
|
179
196
|
}: BlockchairFetchUnspentUtxoParams): Promise<Awaited<ReturnType<typeof fetchUnspentUtxoBatch>>> {
|
|
180
|
-
if (!address)
|
|
197
|
+
if (!address)
|
|
198
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", { error: "Address is required" });
|
|
181
199
|
|
|
182
200
|
try {
|
|
183
201
|
const txs = await fetchUnspentUtxoBatch({ chain, address, apiKey, offset, limit });
|
|
@@ -194,7 +212,7 @@ async function getUnspentUtxos({
|
|
|
194
212
|
|
|
195
213
|
return [...txs, ...nextBatch];
|
|
196
214
|
} catch (error) {
|
|
197
|
-
console.error(error);
|
|
215
|
+
console.error("Failed to fetch unspent UTXOs:", error);
|
|
198
216
|
return [];
|
|
199
217
|
}
|
|
200
218
|
}
|
|
@@ -259,11 +277,7 @@ export function getUtxoApi(chain: UTXOChain) {
|
|
|
259
277
|
return utxoApi(chain);
|
|
260
278
|
}
|
|
261
279
|
|
|
262
|
-
export
|
|
263
|
-
// @ts-ignore
|
|
264
|
-
const coininfo = await import("coininfo");
|
|
265
|
-
const { networks } = await import("bitcoinjs-lib");
|
|
266
|
-
|
|
280
|
+
export function getUtxoNetwork() {
|
|
267
281
|
return function getNetwork(chain: Chain) {
|
|
268
282
|
switch (chain) {
|
|
269
283
|
case Chain.Bitcoin:
|
|
@@ -282,7 +296,7 @@ export async function getUtxoNetwork() {
|
|
|
282
296
|
return coininfo.dogecoin.main.toBitcoinJS();
|
|
283
297
|
}
|
|
284
298
|
default:
|
|
285
|
-
throw new
|
|
299
|
+
throw new SwapKitError("toolbox_utxo_not_supported", { chain });
|
|
286
300
|
}
|
|
287
301
|
};
|
|
288
302
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { SwapKitError } from "@swapkit/helpers";
|
|
1
2
|
import base58check from "bs58check";
|
|
2
|
-
// @ts-
|
|
3
|
+
// @ts-ignore
|
|
3
4
|
import cashaddr from "cashaddrjs";
|
|
4
5
|
|
|
5
6
|
enum Format {
|
|
@@ -83,7 +84,7 @@ function decodeAddress(address: string) {
|
|
|
83
84
|
} catch (_error) {
|
|
84
85
|
// Try to decode as bitpay if cashaddr decoding fails.
|
|
85
86
|
}
|
|
86
|
-
throw new
|
|
87
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
function decodeBase58Address(address: string) {
|
|
@@ -91,8 +92,7 @@ function decodeBase58Address(address: string) {
|
|
|
91
92
|
const payload = base58check.decode(address);
|
|
92
93
|
|
|
93
94
|
// BASE_58_CHECK_PAYLOAD_LENGTH
|
|
94
|
-
if (payload.length !== 21)
|
|
95
|
-
throw new Error("Received an invalid Bitcoin Cash address as input.");
|
|
95
|
+
if (payload.length !== 21) throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
96
96
|
const versionByte = payload[0];
|
|
97
97
|
const hash = Array.prototype.slice.call(payload, 1);
|
|
98
98
|
|
|
@@ -116,10 +116,10 @@ function decodeBase58Address(address: string) {
|
|
|
116
116
|
return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2SH };
|
|
117
117
|
|
|
118
118
|
default:
|
|
119
|
-
throw new
|
|
119
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
120
120
|
}
|
|
121
121
|
} catch (_error) {
|
|
122
|
-
throw new
|
|
122
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
|
|
@@ -141,7 +141,7 @@ function decodeCashAddress(address: string) {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
throw new
|
|
144
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
function decodeCashAddressWithPrefix(address: string): DecodedType {
|
|
@@ -155,7 +155,7 @@ function decodeCashAddressWithPrefix(address: string): DecodedType {
|
|
|
155
155
|
type: type === "P2PKH" ? Type.P2PKH : Type.P2SH,
|
|
156
156
|
};
|
|
157
157
|
} catch (_error) {
|
|
158
|
-
throw new
|
|
158
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
159
159
|
}
|
|
160
160
|
}
|
|
161
161
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Chain, type UTXOChain } from "@swapkit/helpers";
|
|
1
|
+
import { Chain, SwapKitError, type UTXOChain } from "@swapkit/helpers";
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
TX_OVERHEAD,
|
|
@@ -21,7 +21,7 @@ export const getDustThreshold = (chain: UTXOChain) => {
|
|
|
21
21
|
case Chain.Dogecoin:
|
|
22
22
|
return 100000;
|
|
23
23
|
default:
|
|
24
|
-
throw new
|
|
24
|
+
throw new SwapKitError("toolbox_utxo_not_supported", { chain });
|
|
25
25
|
}
|
|
26
26
|
};
|
|
27
27
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { SwapKitError } from "@swapkit/helpers";
|
|
2
|
+
import { opcodes, script } from "bitcoinjs-lib";
|
|
1
3
|
import type {
|
|
2
4
|
TargetOutput,
|
|
3
5
|
UTXOCalculateTxSizeParams,
|
|
@@ -16,8 +18,7 @@ export const OP_RETURN_OVERHEAD = 1 + 8 + 1; //10
|
|
|
16
18
|
const TX_INPUT_BASE = 32 + 4 + 1 + 4; // 41
|
|
17
19
|
const TX_INPUT_PUBKEYHASH = 107;
|
|
18
20
|
|
|
19
|
-
export
|
|
20
|
-
const { script, opcodes } = await import("bitcoinjs-lib");
|
|
21
|
+
export function compileMemo(memo: string) {
|
|
21
22
|
const data = Buffer.from(memo, "utf8"); // converts MEMO to buffer
|
|
22
23
|
return script.compile([opcodes.OP_RETURN as number, data]); // Compile OP_RETURN script
|
|
23
24
|
}
|
|
@@ -60,7 +61,7 @@ export const getScriptTypeForAddress = (address: string) => {
|
|
|
60
61
|
) {
|
|
61
62
|
return UTXOScriptType.P2PKH;
|
|
62
63
|
}
|
|
63
|
-
throw new
|
|
64
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address });
|
|
64
65
|
};
|
|
65
66
|
|
|
66
67
|
export const calculateTxSize = ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => {
|
|
@@ -1,12 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Transaction,
|
|
3
|
+
TransactionBuilder,
|
|
4
|
+
address as bchAddress,
|
|
5
|
+
// @ts-ignore
|
|
6
|
+
} from "@psf/bitcoincashjs-lib";
|
|
1
7
|
import {
|
|
2
8
|
Chain,
|
|
3
9
|
type ChainSigner,
|
|
4
10
|
type DerivationPathArray,
|
|
5
11
|
FeeOption,
|
|
6
12
|
NetworkDerivationPath,
|
|
13
|
+
SwapKitError,
|
|
7
14
|
derivationPathToString,
|
|
8
15
|
updateDerivationPath,
|
|
9
16
|
} from "@swapkit/helpers";
|
|
17
|
+
import { Psbt } from "bitcoinjs-lib";
|
|
10
18
|
import type { UtxoToolboxParams } from ".";
|
|
11
19
|
import {
|
|
12
20
|
accumulative,
|
|
@@ -130,13 +138,8 @@ async function createTransaction({
|
|
|
130
138
|
feeRate,
|
|
131
139
|
sender,
|
|
132
140
|
}: UTXOBuildTxParams) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
TransactionBuilder,
|
|
136
|
-
address: bchAddress,
|
|
137
|
-
// @ts-ignore
|
|
138
|
-
} = await import("@psf/bitcoincashjs-lib");
|
|
139
|
-
if (!bchValidateAddress(recipient)) throw new Error("Invalid address");
|
|
141
|
+
if (!bchValidateAddress(recipient))
|
|
142
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address: recipient });
|
|
140
143
|
const utxos = await getUtxoApi(chain).scanUTXOs({
|
|
141
144
|
address: stripToCashAddress(sender),
|
|
142
145
|
fetchTxHex: true,
|
|
@@ -158,9 +161,10 @@ async function createTransaction({
|
|
|
158
161
|
});
|
|
159
162
|
|
|
160
163
|
// .inputs and .outputs will be undefined if no solution was found
|
|
161
|
-
if (!(inputs && outputs))
|
|
164
|
+
if (!(inputs && outputs))
|
|
165
|
+
throw new SwapKitError("toolbox_utxo_insufficient_balance", { sender, assetValue });
|
|
162
166
|
const getNetwork = await getUtxoNetwork();
|
|
163
|
-
const builder = new TransactionBuilder(getNetwork(chain));
|
|
167
|
+
const builder = new TransactionBuilder(getNetwork(chain)) as TransactionBuilderType;
|
|
164
168
|
|
|
165
169
|
await Promise.all(
|
|
166
170
|
inputs.map(async (utxo: UTXOType) => {
|
|
@@ -203,8 +207,11 @@ function transfer({
|
|
|
203
207
|
...rest
|
|
204
208
|
}: UTXOTransferParams) {
|
|
205
209
|
const from = await signer?.getAddress();
|
|
206
|
-
if (!(signer && from)) throw new
|
|
207
|
-
if (!recipient)
|
|
210
|
+
if (!(signer && from)) throw new SwapKitError("toolbox_utxo_no_signer");
|
|
211
|
+
if (!recipient)
|
|
212
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", {
|
|
213
|
+
error: "Recipient address must be provided",
|
|
214
|
+
});
|
|
208
215
|
|
|
209
216
|
const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];
|
|
210
217
|
|
|
@@ -226,9 +233,9 @@ function transfer({
|
|
|
226
233
|
|
|
227
234
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor
|
|
228
235
|
async function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBuildTxParams) {
|
|
229
|
-
const { Psbt } = await import("bitcoinjs-lib");
|
|
230
236
|
const recipientCashAddress = toCashAddress(recipient);
|
|
231
|
-
if (!bchValidateAddress(recipientCashAddress))
|
|
237
|
+
if (!bchValidateAddress(recipientCashAddress))
|
|
238
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { address: recipientCashAddress });
|
|
232
239
|
|
|
233
240
|
const utxos = await getUtxoApi(chain).scanUTXOs({
|
|
234
241
|
address: stripToCashAddress(sender),
|
|
@@ -259,7 +266,8 @@ async function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBui
|
|
|
259
266
|
});
|
|
260
267
|
|
|
261
268
|
// .inputs and .outputs will be undefined if no solution was found
|
|
262
|
-
if (!(inputs && outputs))
|
|
269
|
+
if (!(inputs && outputs))
|
|
270
|
+
throw new SwapKitError("toolbox_utxo_insufficient_balance", { sender, assetValue });
|
|
263
271
|
const getNetwork = await getUtxoNetwork();
|
|
264
272
|
const psbt = new Psbt({ network: getNetwork(chain) }); // Network-specific
|
|
265
273
|
|
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
Chain,
|
|
3
3
|
type ChainSigner,
|
|
4
4
|
type DerivationPathArray,
|
|
5
|
+
SwapKitError,
|
|
5
6
|
type UTXOChain,
|
|
6
7
|
} from "@swapkit/helpers";
|
|
7
8
|
import type { Psbt } from "bitcoinjs-lib";
|
|
@@ -65,7 +66,7 @@ export async function getUtxoToolbox<T extends keyof UTXOToolboxes>(
|
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
default:
|
|
68
|
-
throw new
|
|
69
|
+
throw new SwapKitError("toolbox_utxo_not_supported", { chain });
|
|
69
70
|
}
|
|
70
71
|
}
|
|
71
72
|
|
package/src/utxo/toolbox/utxo.ts
CHANGED
|
@@ -6,13 +6,16 @@ import {
|
|
|
6
6
|
type DerivationPathArray,
|
|
7
7
|
FeeOption,
|
|
8
8
|
NetworkDerivationPath,
|
|
9
|
+
SwapKitError,
|
|
9
10
|
SwapKitNumber,
|
|
10
11
|
type UTXOChain,
|
|
12
|
+
applyFeeMultiplier,
|
|
11
13
|
derivationPathToString,
|
|
12
14
|
updateDerivationPath,
|
|
13
15
|
} from "@swapkit/helpers";
|
|
14
|
-
import
|
|
16
|
+
import { Psbt, address as btcLibAddress, initEccLib, payments } from "bitcoinjs-lib";
|
|
15
17
|
import type { ECPairInterface } from "ecpair";
|
|
18
|
+
import ECPairFactory from "ecpair";
|
|
16
19
|
import type { UtxoToolboxParams } from ".";
|
|
17
20
|
import { getBalance } from "../../utils";
|
|
18
21
|
import {
|
|
@@ -34,9 +37,15 @@ import type {
|
|
|
34
37
|
} from "../types";
|
|
35
38
|
import { bchValidateAddress } from "./bitcoinCash";
|
|
36
39
|
|
|
40
|
+
import secp256k1 from "@bitcoinerlab/secp256k1";
|
|
41
|
+
// @ts-ignore
|
|
42
|
+
import { ECPair, HDNode } from "@psf/bitcoincashjs-lib";
|
|
43
|
+
import { HDKey } from "@scure/bip32";
|
|
44
|
+
import { mnemonicToSeedSync } from "@scure/bip39";
|
|
45
|
+
|
|
37
46
|
export const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];
|
|
38
47
|
|
|
39
|
-
|
|
48
|
+
function addInputsAndOutputs({
|
|
40
49
|
inputs,
|
|
41
50
|
outputs,
|
|
42
51
|
chain,
|
|
@@ -62,9 +71,6 @@ async function addInputsAndOutputs({
|
|
|
62
71
|
psbt.addInput({ hash: utxo.hash, index: utxo.index, ...witnessInfo, ...nonWitnessInfo });
|
|
63
72
|
}
|
|
64
73
|
|
|
65
|
-
const { initEccLib } = await import("bitcoinjs-lib");
|
|
66
|
-
const secp256k1 = await import("@bitcoinerlab/secp256k1");
|
|
67
|
-
|
|
68
74
|
for (const output of outputs) {
|
|
69
75
|
const address = "address" in output && output.address ? output.address : sender;
|
|
70
76
|
const hasOutputScript = output.script;
|
|
@@ -103,8 +109,6 @@ async function createTransaction({
|
|
|
103
109
|
inputs: UTXOType[];
|
|
104
110
|
}> {
|
|
105
111
|
const chain = assetValue.chain as UTXOChain;
|
|
106
|
-
|
|
107
|
-
const { Psbt } = await import("bitcoinjs-lib");
|
|
108
112
|
const compiledMemo = memo ? await compileMemo(memo) : null;
|
|
109
113
|
|
|
110
114
|
const inputsAndOutputs = await getInputsAndTargetOutputs({
|
|
@@ -118,7 +122,8 @@ async function createTransaction({
|
|
|
118
122
|
const { inputs, outputs } = accumulative({ ...inputsAndOutputs, feeRate, chain });
|
|
119
123
|
|
|
120
124
|
// .inputs and .outputs will be undefined if no solution was found
|
|
121
|
-
if (!(inputs && outputs))
|
|
125
|
+
if (!(inputs && outputs))
|
|
126
|
+
throw new SwapKitError("toolbox_utxo_insufficient_balance", { sender, assetValue });
|
|
122
127
|
const getNetwork = await getUtxoNetwork();
|
|
123
128
|
const psbt = new Psbt({ network: getNetwork(chain) });
|
|
124
129
|
|
|
@@ -141,8 +146,6 @@ async function createTransaction({
|
|
|
141
146
|
}
|
|
142
147
|
|
|
143
148
|
export async function getUTXOAddressValidator() {
|
|
144
|
-
const secp256k1 = await import("@bitcoinerlab/secp256k1");
|
|
145
|
-
const { initEccLib, address: btcLibAddress } = await import("bitcoinjs-lib");
|
|
146
149
|
const getNetwork = await getUtxoNetwork();
|
|
147
150
|
|
|
148
151
|
return function validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {
|
|
@@ -359,13 +362,7 @@ export async function getCreateKeysForPath<T extends keyof CreateKeysForPathRetu
|
|
|
359
362
|
derivationPath?: string;
|
|
360
363
|
}) => CreateKeysForPathReturnType[T]
|
|
361
364
|
> {
|
|
362
|
-
const { ECPairFactory } = await import("ecpair");
|
|
363
|
-
const secp256k1 = await import("@bitcoinerlab/secp256k1");
|
|
364
|
-
const { HDKey } = await import("@scure/bip32");
|
|
365
|
-
const { mnemonicToSeedSync } = await import("@scure/bip39");
|
|
366
365
|
const getNetwork = await getUtxoNetwork();
|
|
367
|
-
// @ts-ignore
|
|
368
|
-
const { HDNode, ECPair } = await import("@psf/bitcoincashjs-lib");
|
|
369
366
|
|
|
370
367
|
switch (chain) {
|
|
371
368
|
case Chain.BitcoinCash: {
|
|
@@ -379,7 +376,8 @@ export async function getCreateKeysForPath<T extends keyof CreateKeysForPathRetu
|
|
|
379
376
|
if (wif) {
|
|
380
377
|
return ECPair.fromWIF(wif, network) as BchECPair;
|
|
381
378
|
}
|
|
382
|
-
if (!phrase)
|
|
379
|
+
if (!phrase)
|
|
380
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", { error: "No phrase provided" });
|
|
383
381
|
|
|
384
382
|
const masterHDNode = HDNode.fromSeedBuffer(
|
|
385
383
|
Buffer.from(mnemonicToSeedSync(phrase)),
|
|
@@ -403,7 +401,10 @@ export async function getCreateKeysForPath<T extends keyof CreateKeysForPathRetu
|
|
|
403
401
|
wif,
|
|
404
402
|
derivationPath,
|
|
405
403
|
}: { phrase?: string; wif?: string; derivationPath: string }) {
|
|
406
|
-
if (!(wif || phrase))
|
|
404
|
+
if (!(wif || phrase))
|
|
405
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", {
|
|
406
|
+
error: "Either phrase or wif must be provided",
|
|
407
|
+
});
|
|
407
408
|
|
|
408
409
|
const factory = ECPairFactory(secp256k1);
|
|
409
410
|
const network = getNetwork(chain);
|
|
@@ -412,7 +413,10 @@ export async function getCreateKeysForPath<T extends keyof CreateKeysForPathRetu
|
|
|
412
413
|
|
|
413
414
|
const seed = mnemonicToSeedSync(phrase as string);
|
|
414
415
|
const master = HDKey.fromMasterSeed(seed, network).derive(derivationPath);
|
|
415
|
-
if (!master.privateKey)
|
|
416
|
+
if (!master.privateKey)
|
|
417
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", {
|
|
418
|
+
error: "Could not get private key from phrase",
|
|
419
|
+
});
|
|
416
420
|
|
|
417
421
|
return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });
|
|
418
422
|
} as (params: {
|
|
@@ -422,20 +426,21 @@ export async function getCreateKeysForPath<T extends keyof CreateKeysForPathRetu
|
|
|
422
426
|
}) => CreateKeysForPathReturnType[T];
|
|
423
427
|
}
|
|
424
428
|
default:
|
|
425
|
-
throw new
|
|
429
|
+
throw new SwapKitError("toolbox_utxo_not_supported", { chain });
|
|
426
430
|
}
|
|
427
431
|
}
|
|
428
432
|
|
|
429
433
|
export async function addressFromKeysGetter(chain: UTXOChain) {
|
|
430
|
-
const { payments } = await import("bitcoinjs-lib");
|
|
431
434
|
const getNetwork = await getUtxoNetwork();
|
|
432
435
|
|
|
433
436
|
return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {
|
|
434
|
-
if (!keys)
|
|
437
|
+
if (!keys)
|
|
438
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", { error: "Keys must be provided" });
|
|
435
439
|
|
|
436
440
|
const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;
|
|
437
441
|
const { address } = method({ pubkey: keys.publicKey as Buffer, network: getNetwork(chain) });
|
|
438
|
-
if (!address)
|
|
442
|
+
if (!address)
|
|
443
|
+
throw new SwapKitError("toolbox_utxo_invalid_address", { error: "Address not defined" });
|
|
439
444
|
|
|
440
445
|
return address;
|
|
441
446
|
};
|
|
@@ -453,8 +458,11 @@ function transfer(signer?: ChainSigner<Psbt, Psbt>) {
|
|
|
453
458
|
|
|
454
459
|
const chain = assetValue.chain as UTXOChain;
|
|
455
460
|
|
|
456
|
-
if (!(signer && from)) throw new
|
|
457
|
-
if (!recipient)
|
|
461
|
+
if (!(signer && from)) throw new SwapKitError("toolbox_utxo_no_signer");
|
|
462
|
+
if (!recipient)
|
|
463
|
+
throw new SwapKitError("toolbox_utxo_invalid_params", {
|
|
464
|
+
error: "Recipient address must be provided",
|
|
465
|
+
});
|
|
458
466
|
const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];
|
|
459
467
|
|
|
460
468
|
const { psbt } = await createTransaction({
|
|
@@ -476,8 +484,8 @@ async function getFeeRates(chain: UTXOChain) {
|
|
|
476
484
|
|
|
477
485
|
return {
|
|
478
486
|
[FeeOption.Average]: suggestedFeeRate,
|
|
479
|
-
[FeeOption.Fast]: suggestedFeeRate
|
|
480
|
-
[FeeOption.Fastest]: suggestedFeeRate
|
|
487
|
+
[FeeOption.Fast]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fast),
|
|
488
|
+
[FeeOption.Fastest]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fastest),
|
|
481
489
|
};
|
|
482
490
|
}
|
|
483
491
|
|
package/src/utxo/types.ts
CHANGED
|
@@ -52,4 +52,6 @@ export type TransactionBuilderType = {
|
|
|
52
52
|
signatureAlgorithm?: string,
|
|
53
53
|
): void;
|
|
54
54
|
build(): TransactionType;
|
|
55
|
+
addOutput(addressOrScriptBuffer: string | Buffer, value: number): void;
|
|
56
|
+
addInput(txHash: string | Buffer, vout: number, sequence?: number, prevOutScript?: Buffer): void;
|
|
55
57
|
};
|
package/dist/chunk-0h4xdrwz.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{AssetValue as c,BaseDecimal as p}from"@swapkit/helpers";import{SwapKitApi as u}from"@swapkit/helpers/api";var l=typeof process!=="undefined"&&process.pid?process.pid.toString(36):"",a=0;function g(){function t(){let e=Date.now(),n=a||e;return a=n,e>a?e:n+1}return l+t().toString(36)}function w(t){return async function e(n,i=!0){return(await u.getChainBalance({chain:t,address:n,scamFilter:i})).map(({identifier:r,value:o,decimal:s})=>{return new c({decimal:s||p[t],value:o,identifier:r})})}}
|
|
2
|
-
export{g as a,w as b};
|
|
3
|
-
|
|
4
|
-
//# debugId=7D1F4061F0771C8264756E2164756E21
|
package/dist/cosmos/index.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var go={};bo(go,{verifySignature:()=>Bo,transferMsgAmino:()=>a,toBase64:()=>Lo,parseAminoMessageForDirectSigning:()=>Z,getSignerFromPrivateKey:()=>Qo,getSignerFromPhrase:()=>to,getRPC:()=>xo,getMsgSendDenom:()=>L,getFeeRateFromThorswap:()=>Xo,getDenomWithChain:()=>Y,getDefaultChainFee:()=>A,getCreateTransaction:()=>oo,getCosmosToolbox:()=>eo,fromBase64:()=>Po,fetchFeeRateFromSwapKit:()=>no,estimateTransactionFee:()=>Do,depositMsgAmino:()=>l,createThorchainToolbox:()=>fo,createStargateClient:()=>u,createSigningStargateClient:()=>h,createOfflineStargateClient:()=>g,createDefaultRegistry:()=>X,createDefaultAminoTypes:()=>P,createCosmosToolbox:()=>q,cosmosValidateAddress:()=>Go,cosmosCreateTransaction:()=>s,convertToSignable:()=>k,buildTransferTx:()=>mo,buildEncodedTxBody:()=>O,buildDepositTx:()=>co,buildAminoMsg:()=>M,bech32ToBase64:()=>D,base64ToBech32:()=>J,YUM_KUJIRA_FACTORY_DENOM:()=>yo,USK_KUJIRA_FACTORY_DENOM:()=>po,THORCHAIN_GAS_VALUE:()=>Zo,MAYA_GAS_VALUE:()=>Ko,DEFAULT_KUJI_FEE_MAINNET:()=>io,DEFAULT_COSMOS_FEE_MAINNET:()=>wo});module.exports=Vo(go);var z=require("@scure/base"),S=require("base64-js");function D(o){return z.base64.encode(Uint8Array.from(z.bech32.fromWords(z.bech32.decode(o).words)))}function J(o,r="thor"){return z.bech32.encode(r,z.bech32.toWords(z.base64.decode(o)))}function Lo(o){return S.fromByteArray(o)}function Po(o){if(!o.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new Error("Invalid base64 string format");return S.toByteArray(o)}var _=require("@swapkit/helpers");var c=require("@swapkit/helpers"),po="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",yo="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",wo={amount:[{denom:"uatom",amount:"500"}],gas:"200000"},io={amount:[{denom:"ukuji",amount:"1000"}],gas:"200000"};function A(o){switch(o){case c.Chain.Maya:return{amount:[],gas:"10000000000"};case c.Chain.THORChain:return{amount:[],gas:"500000000"};case c.Chain.Kujira:return io;default:return wo}}var L=(o,r=!1)=>{if(r)return o.toLowerCase();switch(o){case"uUSK":case"USK":return po;case"uYUM":case"YUM":return yo;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";default:return o}},Y=({symbol:o,chain:r})=>{if(r===c.Chain.Maya)return(o.toUpperCase()!=="CACAO"?o:`${c.Chain.Maya}.${o}`).toUpperCase();if(r===c.Chain.THORChain)return(o.toUpperCase()!=="RUNE"?o:`${c.Chain.THORChain}.${o}`).toUpperCase();return L(o,!1)};async function u(o){let{StargateClient:r}=await import("@cosmjs/stargate");return r.connect(o)}async function h(o,r,t={}){let{SigningStargateClient:n,GasPrice:f}=await import("@cosmjs/stargate"),y=typeof t==="string"?t:"0.0003uatom",w=typeof t==="string"?{}:t;return n.connectWithSigner(o,r,{gasPrice:f.fromString(y),...w})}async function g(o,r){let{SigningStargateClient:t}=await import("@cosmjs/stargate");return t.offline(o,r)}var xo=(o)=>{let{isStagenet:r}=c.SKConfig.get("envs"),t=c.SKConfig.get("rpcUrls");switch(o){case c.ChainId.Kujira:return t.KUJI;case c.ChainId.THORChain:case"thorchain-mainnet-v1":return r?t.THOR_STAGENET:t.THOR;case c.ChainId.Maya:return r?t.MAYA_STAGENET:t.MAYA;default:return t.GAIA}},ko=(o)=>{switch(o){case c.Chain.Maya:case c.Chain.THORChain:return"/types.MsgSend";case c.Chain.Cosmos:case c.Chain.Kujira:return"/cosmos.bank.v1beta1.MsgSend";default:throw new Error("Unsupported chain")}},s=async({sender:o,recipient:r,assetValue:t,memo:n="",feeRate:f,sequence:y,accountNumber:w})=>{let{chain:T,chainId:C}=t,d=xo(C),i=await(await u(d)).getAccount(o);if(!i)throw new Error("Account does not exist");let W=c.AssetValue.from({chain:T}),H=L(W.symbol),m=A(T),B=H&&f?{amount:[{denom:H,amount:f.toString()}],gas:m.gas}:m,R={fromAddress:o,toAddress:r,amount:[{amount:t.getBaseValue("string"),denom:L(t.symbol)}]};return{accountNumber:w??i.accountNumber,chainId:C,fee:B,memo:n,sequence:y??i.sequence,msgs:[{typeUrl:ko(T),value:R}]}};var Co=require("@swapkit/helpers");async function X(){let{$root:o}=await import("../chunk-4yap1fvd.js"),{Registry:r}=await import("@cosmjs/proto-signing"),{defaultRegistryTypes:t}=await import("@cosmjs/stargate");return new r([...t,["/types.MsgSend",o.types.MsgSend],["/types.MsgDeposit",o.types.MsgDeposit]])}async function P(o){let{AminoTypes:r}=await import("@cosmjs/stargate"),t=o===Co.Chain.THORChain?"thorchain":"mayachain";return new r({"/types.MsgSend":{aminoType:`${t}/MsgSend`,toAmino:({fromAddress:n,toAddress:f,...y})=>({...y,from_address:J(n),to_address:J(f)}),fromAmino:({from_address:n,to_address:f,...y})=>({...y,fromAddress:D(n),toAddress:D(f)})},"/types.MsgDeposit":{aminoType:`${t}/MsgDeposit`,toAmino:({signer:n,...f})=>({...f,signer:J(n)}),fromAmino:({signer:n,...f})=>({...f,signer:D(n)})}})}var Zo=A(_.Chain.THORChain).gas,Ko=A(_.Chain.Maya).gas,a=({sender:o,recipient:r,assetValue:t})=>{return{type:`${t.chain===_.Chain.Maya?"mayachain":"thorchain"}/MsgSend`,value:{from_address:o,to_address:r,amount:[{amount:t.getBaseValue("string"),denom:L(t.symbol,!0)}]}}},l=({sender:o,assetValue:r,memo:t=""})=>{return{type:`${r.chain===_.Chain.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:r.getBaseValue("string"),asset:Y(r)}],signer:o,memo:t}}},M=({sender:o,recipient:r,assetValue:t,memo:n})=>{return!r?l({sender:o,assetValue:t,memo:n}):a({sender:o,recipient:r,assetValue:t})},k=async(o,r)=>{return(await P(r)).fromAmino(o)},To=async({rpcUrl:o,sender:r})=>{let n=await(await u(o)).getAccount(r);if(!n)throw new Error("Account does not exist");return n};function oo(o){return function r(t){let{assetValue:n,recipient:f,memo:y,sender:w,asSignable:T,asAminoMessage:C}=t;if(f)return mo(o)({sender:w,recipient:f,assetValue:n,memo:y,asSignable:T,asAminoMessage:C});return co(o)({sender:w,assetValue:n,memo:y,asSignable:T,asAminoMessage:C})}}var mo=(o)=>async({sender:r,recipient:t,assetValue:n,memo:f="",asSignable:y=!0,asAminoMessage:w=!1,sequence:T,accountNumber:C})=>{let d=await To({rpcUrl:o,sender:r}),$=n.chain,i=a({sender:r,recipient:t,assetValue:n}),W=y?await k(w?i:Z(i),$):i;return{chainId:_.ChainToChainId[$],accountNumber:C||d.accountNumber,sequence:T||d.sequence,msgs:[W],fee:A(n.chain),memo:f}},co=(o)=>async({sender:r,assetValue:t,memo:n="",asSignable:f=!0,asAminoMessage:y=!1,sequence:w,accountNumber:T})=>{let C=await To({rpcUrl:o,sender:r}),d=t.chain,$=l({sender:r,assetValue:t,memo:n}),i=f?await k(y?$:Z($),d):$;return{chainId:_.ChainToChainId[d],accountNumber:T||C.accountNumber,sequence:w||C.sequence,msgs:[i],fee:A(t.chain),memo:n}};function Z(o){if(o.type==="thorchain/MsgSend"||o.type==="mayachain/MsgSend")return o;return{...o,value:{...o.value,coins:o.value.coins.map((r)=>{let t=_.AssetValue.from({asset:r.asset}),n=(t.isSynthetic?t.symbol.split("/")?.[1]:t.symbol)?.toUpperCase(),f=(t.isSynthetic?t.symbol.split("/")?.[0]:t.chain)?.toUpperCase();return{...r,asset:{chain:f,symbol:n,ticker:t.ticker,synth:t.isSynthetic}}})}}}async function O({chain:o,memo:r,msgs:t}){let n=await X(),f=await P(o),y={typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:r,messages:t.map((w)=>f.fromAmino(w))}};return n.encode(y)}var N=require("@swapkit/helpers");var K=require("@scure/base"),p=require("@swapkit/helpers"),ro=require("@swapkit/helpers/api"),F=require("ts-pattern");async function no(o,r){try{let n=(await ro.SwapKitApi.getGasRate()).find((f)=>f.chainId===o)?.value;return n?Number.parseFloat(n):r}catch(t){return console.error(t),r}}async function to({phrase:o,prefix:r,...t}){let{DirectSecp256k1HdWallet:n}=await import("@cosmjs/proto-signing"),{stringToPath:f}=await import("@cosmjs/crypto"),y="derivationPath"in t?t.derivationPath:`${p.DerivationPath[t.chain]}/${t.index}`;return n.fromMnemonic(o,{prefix:r,hdPaths:[f(y)]})}async function Qo({privateKey:o,prefix:r}){let{DirectSecp256k1Wallet:t}=await import("@cosmjs/proto-signing");return t.fromKey(o,r)}var vo={[p.Chain.Cosmos]:500,[p.Chain.Kujira]:1000,[p.Chain.THORChain]:5000000,[p.Chain.Maya]:5000000};function Bo(o){return async function r({signature:t,message:n,address:f}){let y=await o(f);if(!y?.pubkey)throw new p.SwapKitError("toolbox_cosmos_verify_signature_no_pubkey");let{Secp256k1Signature:w,Secp256k1:T}=await import("@cosmjs/crypto"),C=w.fromFixedLength(K.base64.decode(t));return T.verifySignature(C,K.base64.decode(n),y.pubkey.value)}}async function q({chain:o,...r}){let t=p.SKConfig.get("rpcUrls")[o],n=p.CosmosChainPrefixes[o],f="index"in r?r.index||0:0,y=p.derivationPathToString("derivationPath"in r&&r.derivationPath?r.derivationPath:p.updateDerivationPath(p.NetworkDerivationPath[o],{index:f})),w=await F.match(r).with({phrase:F.P.string},({phrase:i})=>to({phrase:i,prefix:n,derivationPath:y})).with({signer:F.P.any},({signer:i})=>i).otherwise(()=>{return});async function T(i){return(await u(t)).getAccount(i)}async function C(){let[i]=await w?.getAccounts()||[];return i?.address}async function d(){let[i]=await w?.getAccounts()||[];if(!i?.pubkey)throw new p.SwapKitError("toolbox_cosmos_signer_not_defined");return K.base64.encode(i?.pubkey)}async function $({recipient:i,assetValue:W,memo:H="",feeRate:m,feeOptionKey:B=p.FeeOption.Fast}){let R=await C();if(!(w&&R))throw new p.SwapKitError("toolbox_cosmos_signer_not_defined");let j=p.AssetValue.from({chain:o}),I=Y(j),U=m||Yo((await $o(o,vo[o]))[B],I),e=await h(t,w),V=[{denom:L(`u${W.symbol}`).toLowerCase(),amount:W.getBaseValue("string")}],{transactionHash:G}=await e.sendTokens(R,i,V,U,H);return G}return{transfer:$,getAddress:C,getAccount:T,getBalance:Wo(o),getSignerFromPhrase:async({phrase:i,derivationPath:W})=>to({phrase:i,prefix:n,derivationPath:p.derivationPathToString(W),index:f}),getSignerFromPrivateKey:async(i)=>{let{DirectSecp256k1Wallet:W}=await import("@cosmjs/proto-signing");return W.fromKey(i,n)},createPrivateKeyFromPhrase:Fo(y),validateAddress:Ro(n),getPubKey:d,getFees:()=>$o(o,vo[o]),fetchFeeRateFromSwapKit:no,getBalanceAsDenoms:Oo(t),createTransaction:s,verifySignature:Bo(T)}}async function Xo(o,r){try{let n=(await ro.SwapKitApi.getGasRate()).find((f)=>f.chainId===o)?.value;return n?Number.parseFloat(n):r}catch(t){return console.error(t),r}}function Go({address:o,chain:r,prefix:t}){let n=t||Jo(r);if(!(n&&o))throw new p.SwapKitError("toolbox_cosmos_validate_address_prefix_not_found");return Ro(n)(o)}function Do({assetValue:{chain:o}}){return p.AssetValue.from({chain:o,value:ho(o)})}function Jo(o){let{isStagenet:r}=p.SKConfig.get("envs"),t=o?[p.Chain.THORChain,p.Chain.Maya].includes(o)&&r:!1,n=o?p.CosmosChainPrefixes[o]:void 0;return t?`s${n}`:n}async function $o(o,r){let t=await no(p.ChainToChainId[o],r);return{average:p.SwapKitNumber.fromBigInt(BigInt(t),p.BaseDecimal[o]),fast:p.SwapKitNumber.fromBigInt(BigInt(Math.floor(t*1.5)),p.BaseDecimal[o]),fastest:p.SwapKitNumber.fromBigInt(BigInt(Math.floor(t*2)),p.BaseDecimal[o])}}function Yo(o,r){return{amount:[{denom:r,amount:o.getBaseValue("string")}],gas:"200000"}}function ho(o){return{[p.Chain.Cosmos]:0.007,[p.Chain.Kujira]:0.02,[p.Chain.THORChain]:0.02,[p.Chain.Maya]:0.02}[o]||0}function Ro(o){return function r(t){if(!t.startsWith(o))return!1;try{let{prefix:n,words:f}=K.bech32.decode(t);return K.bech32.encode(n,f)===t.toLocaleLowerCase()}catch(n){return!1}}}function Oo(o){return async function r(t){return(await(await u(o)).getAllBalances(t)).map((w)=>({...w,denom:w.denom.includes("/")?w.denom.toUpperCase():w.denom}))}}function Fo(o){return async function r(t){let{Bip39:n,EnglishMnemonic:f,Slip10:y,Slip10Curve:w,stringToPath:T}=await import("@cosmjs/crypto"),C=new f(t),d=await n.mnemonicToSeed(C),{privkey:$}=y.derivePath(w.Secp256k1,d,T(o));return $}}var Q=require("@scure/base"),x=require("@swapkit/helpers"),E=require("ts-pattern");function qo({prefix:o,derivationPath:r}){return async function t(n,f=0){let{Secp256k1HdWallet:y}=await import("@cosmjs/amino"),{stringToPath:w}=await import("@cosmjs/crypto");return y.fromMnemonic(n,{hdPaths:[w(`${r}/${f}`)],prefix:o})}}function Eo(o){return Q.base64.encode(o)}function No(o){return async function r({wallet:t,tx:n}){let{msgs:f,accountNumber:y,sequence:w,chainId:T,fee:C,memo:d}=typeof n==="string"?JSON.parse(n):n,$=(await t.getAccounts())?.[0]?.address||"",i=await P(o),W=await X(),H=await g(t,{registry:W,aminoTypes:i}),m=[];for(let j of f){let I=await k(j,o);m.push(I)}let{signatures:[B]}=await H.sign($,m,C,d,{accountNumber:y,sequence:w,chainId:T}),R=await O({chain:o,memo:d,msgs:f.map(Z)});return{signature:Eo(B),bodyBytes:R}}}function So({prefix:o,rpcUrl:r}){return async function t(n,f,y,w,T){let{encodeSecp256k1Pubkey:C,pubkeyToAddress:d}=await import("@cosmjs/amino"),{makeMultisignedTxBytes:$}=await import("@cosmjs/stargate"),{sequence:i,fee:W}=JSON.parse(n),H=await Ho(y,w),m=f.map((j)=>[d(C(Q.base64.decode(j.pubKey)),o),Q.base64.decode(j.signature)]),B=await u(r),{transactionHash:R}=await B.broadcastTx($(H,i,W,T,new Map(m)));return R}}async function Ho(o,r,t=!0){let{createMultisigThresholdPubkey:n,encodeSecp256k1Pubkey:f}=await import("@cosmjs/amino");return n(o.map((y)=>f(Q.base64.decode(y))),r,t)}function Mo(o){return Q.base64.decode(o)}async function Uo({privateKey:o,message:r}){let{Secp256k1:t}=await import("@cosmjs/crypto"),n=await t.createSignature(Q.base64.decode(r),o);return Q.base64.encode(Buffer.concat([n.r(32),n.s(32)]))}async function fo({chain:o,...r}){let t=x.SKConfig.get("nodeUrls")[o],n=x.SKConfig.get("rpcUrls")[o],{isStagenet:f}=x.SKConfig.get("envs"),y=o===x.Chain.THORChain,w=`${f?"s":""}${x.CosmosChainPrefixes[o]}`,T="index"in r?r.index||0:0,C="derivationPath"in r&&r.derivationPath?r.derivationPath:x.updateDerivationPath(x.NetworkDerivationPath[o],{index:T}),d=await q({chain:o,...r}),$=await E.match(r).with({phrase:E.P.string},({phrase:m})=>d.getSignerFromPhrase({phrase:m,derivationPath:C})).with({signer:E.P.any},({signer:m})=>m).otherwise(()=>{return}),i=A(o);async function W(){let m,B=`${t}/${y?"thorchain":"mayachain"}/constants`;try{let{int_64_values:{NativeTransactionFee:R}}=await x.RequestClient.get(B);if(!R||Number.isNaN(R)||R<0)throw new Error(`Invalid nativeFee: ${R.toString()}`);m=new x.SwapKitNumber(R)}catch{m=new x.SwapKitNumber({value:y?0.02:1,decimal:x.BaseDecimal[o]})}return{[x.FeeOption.Average]:m,[x.FeeOption.Fast]:m,[x.FeeOption.Fastest]:m}}async function H({assetValue:m,memo:B="",recipient:R}){let{TxRaw:j}=await import("cosmjs-types/cosmos/tx/v1beta1/tx"),I=(await $?.getAccounts())?.[0]?.address;if(!(I&&$))throw new Error("Signer not defined");let U="signAmino"in $,e=await X(),V=await P(o),G=await h(n,$,{registry:e,aminoTypes:V}),b=M({assetValue:m,sender:I,recipient:R,memo:B});if(U){let uo=await k(b,o),{signatures:jo,authInfoBytes:Io}=await G.sign(I,[uo],i,B),zo=j.encode({signatures:jo,authInfoBytes:Io,bodyBytes:await O({chain:o,msgs:[b].map(Z),memo:B})}).finish();return(await G.broadcastTx(zo)).transactionHash}let _o=Z(b),Ao=await k(_o,o);return(await G.signAndBroadcast(I,[Ao],i,B)).transactionHash}return{...d,broadcastMultisigTx:So({prefix:w,rpcUrl:n}),buildAminoMsg:M,buildEncodedTxBody:O,convertToSignable:k,createDefaultAminoTypes:()=>P(o),createDefaultRegistry:X,createMultisig:Ho,createTransaction:oo(n),deposit:H,getFees:W,importSignature:Mo,parseAminoMessageForDirectSigning:Z,secp256k1HdWalletFromMnemonic:qo({derivationPath:x.derivationPathToString(C),prefix:w}),signMultisigTx:No(o),signWithPrivateKey:Uo,transfer:H,pubkeyToAddress:async(m)=>{let{pubkeyToAddress:B}=await import("@cosmjs/amino");return B(m,w)}}}var eo=(o,r)=>{switch(o){case N.Chain.Cosmos:case N.Chain.Kujira:return q({chain:o,...r});case N.Chain.Maya:case N.Chain.THORChain:return fo({chain:o,...r});default:throw new Error(`Chain ${o} is not supported`)}};
|
|
2
|
-
|
|
3
|
-
//# debugId=8D24779E21FD884964756E2164756E21
|