@swapkit/toolboxes 1.0.0-beta.16 → 1.0.0-beta.18
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-p1kdg37m.js → chunk-38ztynv0.js} +1 -1
- package/dist/{chunk-p1kdg37m.js.map → chunk-38ztynv0.js.map} +1 -1
- 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-cv69ewns.js} +1 -1
- package/dist/chunk-vhc011em.js +4 -0
- package/dist/{chunk-0h4xdrwz.js.map → chunk-vhc011em.js.map} +2 -2
- 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/{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.js +3 -0
- package/dist/{ripple → src/ripple}/index.js.map +1 -1
- package/dist/src/solana/index.js +3 -0
- package/dist/{solana → src/solana}/index.js.map +1 -1
- 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 +24 -18
- package/src/cosmos/thorchainUtils/addressFormat.ts +4 -1
- package/src/cosmos/thorchainUtils/messages.ts +2 -2
- package/src/cosmos/toolbox/cosmos.ts +2 -4
- package/src/cosmos/toolbox/index.ts +2 -2
- package/src/cosmos/toolbox/thorchain.ts +3 -2
- package/src/cosmos/util.ts +10 -3
- package/src/evm/helpers.ts +4 -3
- package/src/evm/toolbox/baseEVMToolbox.ts +15 -12
- package/src/evm/toolbox/index.ts +2 -2
- package/src/evm/toolbox/op.ts +10 -2
- package/src/index.ts +104 -104
- package/src/radix/index.ts +8 -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 +25 -11
- package/src/utxo/helpers/bchaddrjs.ts +8 -8
- package/src/utxo/helpers/coinselect.ts +2 -2
- package/src/utxo/helpers/txSize.ts +2 -1
- package/src/utxo/toolbox/bitcoinCash.ts +14 -6
- package/src/utxo/toolbox/index.ts +2 -1
- package/src/utxo/toolbox/utxo.ts +23 -9
- 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.js +0 -3
- package/dist/solana/index.js +0 -3
- 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-cv69ewns.js.map} +0 -0
- /package/dist/{ripple → src/ripple}/index.cjs +0 -0
- /package/dist/{ripple → src/ripple}/index.cjs.map +0 -0
- /package/dist/{solana → src/solana}/index.cjs +0 -0
- /package/dist/{solana → src/solana}/index.cjs.map +0 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/utxo/toolbox/index.ts", "../src/utxo/toolbox/bitcoinCash.ts", "../src/utxo/helpers/api.ts", "../src/utxo/helpers/bchaddrjs.ts", "../src/utxo/helpers/coinselect.ts", "../src/utxo/helpers/txSize.ts", "../src/utxo/toolbox/utxo.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n SwapKitError,\n type UTXOChain,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\n\nimport type { TransactionBuilderType, TransactionType, UTXOType } from \"../types\";\nimport { createBCHToolbox } from \"./bitcoinCash\";\nimport { createUTXOToolbox } from \"./utxo\";\n\ntype BCHToolbox = Awaited<ReturnType<typeof createBCHToolbox>>;\ntype CommonUTXOToolbox = Awaited<\n ReturnType<typeof createUTXOToolbox<Exclude<UTXOChain, Chain.BitcoinCash>>>\n>;\n\nexport type UTXOToolboxes = {\n [Chain.BitcoinCash]: BCHToolbox;\n [Chain.Bitcoin]: CommonUTXOToolbox;\n [Chain.Dogecoin]: CommonUTXOToolbox;\n [Chain.Litecoin]: CommonUTXOToolbox;\n [Chain.Dash]: CommonUTXOToolbox;\n};\n\nexport type UTXOWallets = {\n [key in keyof UTXOToolboxes]: UTXOToolboxes[key];\n};\n\nexport type UtxoToolboxParams = {\n [Chain.BitcoinCash]: {\n signer: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n };\n [Chain.Bitcoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dogecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Litecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dash]: { signer: ChainSigner<Psbt, Psbt> };\n};\n\nexport async function getUtxoToolbox<T extends keyof UTXOToolboxes>(\n chain: T,\n params?:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n): Promise<UTXOToolboxes[T]> {\n switch (chain) {\n case Chain.BitcoinCash: {\n const toolbox = await createBCHToolbox(params as UtxoToolboxParams[Chain.BitcoinCash]);\n return toolbox as UTXOToolboxes[T];\n }\n\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n const toolbox = await createUTXOToolbox({\n chain,\n ...(params as UtxoToolboxParams[Exclude<T, Chain.BitcoinCash>]),\n });\n return toolbox as UTXOToolboxes[Exclude<T, Chain.BitcoinCash>];\n }\n\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport {\n stripToCashAddress,\n stripPrefix,\n bchValidateAddress,\n} from \"./bitcoinCash\";\n",
|
|
6
|
+
"import {\n Transaction,\n TransactionBuilder,\n address as bchAddress,\n // @ts-ignore\n} from \"@psf/bitcoincashjs-lib\";\nimport {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt } from \"bitcoinjs-lib\";\nimport type { UtxoToolboxParams } from \".\";\nimport {\n accumulative,\n UtxoNetwork as bchNetwork,\n compileMemo,\n detectAddressNetwork,\n getUtxoApi,\n getUtxoNetwork,\n isValidAddress,\n toCashAddress,\n toLegacyAddress,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n TransactionBuilderType,\n TransactionType,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { createUTXOToolbox, getCreateKeysForPath } from \"./utxo\";\n\nconst chain = Chain.BitcoinCash;\n\nexport function stripPrefix(address: string) {\n return address.replace(/(bchtest:|bitcoincash:)/, \"\");\n}\n\nexport function bchValidateAddress(address: string) {\n const strippedAddress = stripPrefix(address);\n return (\n isValidAddress(strippedAddress) && detectAddressNetwork(strippedAddress) === bchNetwork.Mainnet\n );\n}\n\nexport function stripToCashAddress(address: string) {\n return stripPrefix(toCashAddress(address));\n}\n\nasync function createSignerWithKeys(keys: BchECPair) {\n async function signTransaction({\n builder,\n utxos,\n }: { builder: TransactionBuilderType; utxos: UTXOType[] }) {\n utxos.forEach((utxo, index) => {\n builder.sign(index, keys, undefined, 0x41, utxo.witnessUtxo?.value);\n });\n\n return builder.build();\n }\n\n const getAddress = () => {\n const address = keys.getAddress(0);\n return Promise.resolve(stripToCashAddress(address));\n };\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createBCHToolbox<T extends Chain.BitcoinCash>(\n toolboxParams:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const keys = (await getCreateKeysForPath(chain))({ phrase, derivationPath });\n\n const signer = keys\n ? await createSignerWithKeys(keys)\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n const { getBalance, getFeeRates, broadcastTx, ...toolbox } = await createUTXOToolbox({ chain });\n\n function handleGetBalance(address: string, _scamFilter = true) {\n return getBalance(stripPrefix(toCashAddress(address)));\n }\n\n return {\n ...toolbox,\n getAddress,\n broadcastTx,\n createTransaction,\n buildTx,\n getAddressFromKeys,\n getBalance: handleGetBalance,\n getFeeRates,\n stripPrefix,\n stripToCashAddress,\n validateAddress: bchValidateAddress,\n transfer: transfer({ getFeeRates, broadcastTx, signer }),\n };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n}: UTXOBuildTxParams) {\n if (!bchValidateAddress(recipient))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipient });\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs: TargetOutput[] = [];\n // output to recipient\n targetOutputs.push({\n address: recipient,\n value: assetValue.getBaseValue(\"number\"),\n });\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const builder = new TransactionBuilder(getNetwork(chain)) as TransactionBuilderType;\n\n await Promise.all(\n inputs.map(async (utxo: UTXOType) => {\n const txHex = await getUtxoApi(chain).getRawTx(utxo.hash);\n\n builder.addInput(Transaction.fromBuffer(Buffer.from(txHex, \"hex\")), utxo.index);\n }),\n );\n\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const getNetwork = await getUtxoNetwork();\n const outputScript = bchAddress.toOutputScript(toLegacyAddress(address), getNetwork(chain));\n\n builder.addOutput(outputScript, output.value);\n }\n\n // add output for memo\n if (compiledMemo) {\n builder.addOutput(compiledMemo, 0); // Add OP_RETURN {script, value}\n }\n\n return { builder, utxos: inputs };\n}\n\nfunction transfer({\n broadcastTx,\n getFeeRates,\n signer,\n}: {\n broadcastTx: (txHash: string) => Promise<string>;\n getFeeRates: () => Promise<Record<FeeOption, number>>;\n signer?: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n}) {\n return async function transfer({\n recipient,\n assetValue,\n feeOptionKey = FeeOption.Fast,\n ...rest\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n\n const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];\n\n // try out if psbt tx is faster/better/nicer\n const { builder, utxos } = await createTransaction({\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n });\n\n const tx = await signer.signTransaction({ builder, utxos });\n const txHex = tx.toHex();\n\n return broadcastTx(txHex);\n };\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\nasync function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBuildTxParams) {\n const recipientCashAddress = toCashAddress(recipient);\n if (!bchValidateAddress(recipientCashAddress))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipientCashAddress });\n\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const feeRateWhole = Number(feeRate.toFixed(0));\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs = [] as TargetOutput[];\n\n // output to recipient\n targetOutputs.push({\n address: toLegacyAddress(recipient),\n value: assetValue.getBaseValue(\"number\"),\n });\n\n //2. add output memo to targets (optional)\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 });\n }\n\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate: feeRateWhole,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) }); // Network-specific\n\n for (const { hash, index, witnessUtxo } of inputs) {\n psbt.addInput({ hash, index, witnessUtxo });\n }\n\n // Outputs\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const params = output.script\n ? compiledMemo\n ? { script: compiledMemo, value: 0 }\n : undefined\n : { address, value: output.value };\n\n if (params) {\n psbt.addOutput(params);\n }\n }\n\n return { psbt, utxos, inputs: inputs as UTXOType[] };\n}\n\nfunction getAddressFromKeys(keys: { getAddress: (index?: number) => string }) {\n const address = keys.getAddress(0);\n return stripToCashAddress(address);\n}\n",
|
|
7
|
+
"import {\n Chain,\n RequestClient,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n warnOnce,\n} from \"@swapkit/helpers\";\nimport { networks } from \"bitcoinjs-lib\";\nimport { uniqid } from \"../../utils\";\n\n// @ts-ignore\nimport coininfo from \"coininfo\";\n\ntype BlockchairParams<T> = T & { chain: Chain; apiKey?: string };\ntype BlockchairFetchUnspentUtxoParams = BlockchairParams<{\n offset?: number;\n limit?: number;\n address: string;\n}>;\n\nasync function broadcastUTXOTx({ chain, txHash }: { chain: Chain; txHash: string }) {\n const rpcUrl = SKConfig.get(\"rpcUrls\")[chain];\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"sendrawtransaction\",\n params: [txHash],\n id: uniqid(),\n });\n\n const response = await RequestClient.post<{\n id: string;\n result: string;\n error: { message: string; code?: number } | null;\n }>(rpcUrl, { headers: { \"Content-Type\": \"application/json\" }, body });\n\n if (response.error) {\n throw new SwapKitError(\"toolbox_utxo_broadcast_failed\", { error: response.error?.message });\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new SwapKitError(\"toolbox_utxo_invalid_transaction\", {\n error: \"Transaction amount was too low\",\n });\n }\n\n return response.result;\n}\n\nfunction baseUrl(chain: Chain) {\n return `https://api.blockchair.com/${mapChainToBlockchairChain(chain)}`;\n}\n\nfunction getDefaultTxFeeByChain(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return 5;\n case Chain.Dogecoin:\n return 10000;\n case Chain.Litecoin:\n return 1;\n default:\n return 2;\n }\n}\n\nfunction mapChainToBlockchairChain(chain: Chain) {\n switch (chain) {\n case Chain.BitcoinCash:\n return \"bitcoin-cash\";\n case Chain.Litecoin:\n return \"litecoin\";\n case Chain.Dash:\n return \"dash\";\n case Chain.Dogecoin:\n return \"dogecoin\";\n case Chain.Polkadot:\n return \"polkadot\";\n default:\n return \"bitcoin\";\n }\n}\n\nasync function getSuggestedTxFee(chain: Chain) {\n try {\n //Use Bitgo API for fee estimation\n //Refer: https://app.bitgo.com/docs/#operation/v2.tx.getfeeestimate\n const { feePerKb } = await RequestClient.get<{\n feePerKb: number;\n cpfpFeePerKb: number;\n numBlocks: number;\n feeByBlockTarget: { 1: number; 3: number };\n }>(`https://app.bitgo.com/api/v2/${chain.toLowerCase()}/tx/fee`);\n const suggestedFee = feePerKb / 1000;\n\n return Math.max(suggestedFee, getDefaultTxFeeByChain(chain));\n } catch (_error) {\n return getDefaultTxFeeByChain(chain);\n }\n}\n\nasync function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {\n try {\n const response = await RequestClient.get<BlockchairResponse<T>>(url);\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n } catch (error) {\n if (!apiKey) throw error;\n const response = await RequestClient.get<BlockchairResponse<T>>(\n `${url}${apiKey ? `&key=${apiKey}` : \"\"}`,\n );\n\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n }\n}\n\nasync function getAddressData({ address, chain, apiKey }: BlockchairParams<{ address?: string }>) {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const response = await blockchairRequest<BlockchairAddressResponse>(\n `${baseUrl(chain)}/dashboards/address/${address}?transaction_details=true`,\n apiKey,\n );\n\n return response[address];\n } catch (_error) {\n return { utxo: [], address: { balance: 0, transaction_count: 0 } };\n }\n}\n\nasync function getUnconfirmedBalance({\n address,\n chain,\n apiKey,\n}: BlockchairParams<{ address?: string }>) {\n const response = await getAddressData({ address, chain, apiKey });\n\n return response?.address.balance || 0;\n}\n\nasync function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {\n if (!txHash)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"TxHash is required\" });\n\n try {\n const rawTxResponse = await blockchairRequest<BlockchairRawTransactionResponse>(\n `${baseUrl(chain)}/raw/transaction/${txHash}`,\n apiKey,\n );\n return rawTxResponse?.[txHash]?.raw_transaction || \"\";\n } catch (error) {\n console.error(\"Failed to fetch raw transaction:\", error);\n return \"\";\n }\n}\n\nasync function fetchUnspentUtxoBatch({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams) {\n const response = await blockchairRequest<BlockchairOutputsResponse[]>(\n `${baseUrl(chain)}/outputs?q=is_spent(false),recipient(${address})&limit=${limit}&offset=${offset}`,\n apiKey,\n );\n\n const txs = response\n .filter(({ is_spent }) => !is_spent)\n .map(({ script_hex, block_id, transaction_hash, index, value, spending_signature_hex }) => ({\n hash: transaction_hash,\n index,\n value,\n txHex: spending_signature_hex,\n script_hex,\n is_confirmed: block_id !== -1,\n }));\n\n return txs;\n}\n\nasync function getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams): Promise<Awaited<ReturnType<typeof fetchUnspentUtxoBatch>>> {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const txs = await fetchUnspentUtxoBatch({ chain, address, apiKey, offset, limit });\n\n if (txs.length <= limit) return txs;\n\n const nextBatch = await getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset: offset + limit,\n limit,\n });\n\n return [...txs, ...nextBatch];\n } catch (error) {\n console.error(\"Failed to fetch unspent UTXOs:\", error);\n return [];\n }\n}\n\nasync function scanUTXOs({\n address,\n chain,\n apiKey,\n fetchTxHex = true,\n}: BlockchairParams<{ address: string; fetchTxHex?: boolean }>) {\n const utxos = await getUnspentUtxos({ chain, address, apiKey });\n const results = [];\n\n for (const { hash, index, script_hex, value } of utxos) {\n let txHex: string | undefined;\n if (fetchTxHex) {\n txHex = await getRawTx({ txHash: hash, chain, apiKey });\n }\n results.push({\n address,\n hash,\n index,\n txHex,\n value,\n witnessUtxo: { value, script: Buffer.from(script_hex, \"hex\") },\n });\n }\n return results;\n}\n\nfunction utxoApi(chain: UTXOChain) {\n const apiKey = SKConfig.get(\"apiKeys\").blockchair || \"\";\n\n warnOnce(!apiKey, \"No Blockchair API key found. Functionality will be limited.\");\n\n return {\n broadcastTx: (txHash: string) => broadcastUTXOTx({ txHash, chain }),\n getRawTx: (txHash: string) => getRawTx({ txHash, chain, apiKey }),\n getSuggestedTxFee: () => getSuggestedTxFee(chain),\n getBalance: (address: string) => getUnconfirmedBalance({ address, chain, apiKey }),\n getAddressData: (address: string) => getAddressData({ address, chain, apiKey }),\n scanUTXOs: (params: { address: string; fetchTxHex?: boolean }) =>\n scanUTXOs({ ...params, chain, apiKey }),\n };\n}\n\n/**\n * \"Factory\" to ensure typing for custom UTXO APIs\n */\nexport function createCustomUtxoApi(methods: ReturnType<typeof utxoApi>) {\n return methods;\n}\n\nexport function getUtxoApi(chain: UTXOChain) {\n const customUtxoApi = SKConfig.get(\"apis\")[chain];\n\n if (customUtxoApi) {\n warnOnce(true, \"Using custom UTXO API. Be sure to implement all methods to avoid issues.\");\n return customUtxoApi as ReturnType<typeof utxoApi>;\n }\n\n return utxoApi(chain);\n}\n\nexport function getUtxoNetwork() {\n return function getNetwork(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return networks.bitcoin;\n case Chain.BitcoinCash:\n return coininfo.bitcoincash.main.toBitcoinJS();\n case Chain.Dash:\n return coininfo.dash.main.toBitcoinJS();\n case Chain.Litecoin:\n return coininfo.litecoin.main.toBitcoinJS();\n\n case Chain.Dogecoin: {\n const bip32 = { private: 0x04358394, public: 0x043587cf };\n const test = coininfo.dogecoin.test;\n test.versions.bip32 = bip32;\n return coininfo.dogecoin.main.toBitcoinJS();\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n };\n}\n\ninterface BlockchairVin {\n txid: string;\n vout: number;\n scriptSig: {\n asm: string;\n hex: string;\n };\n sequence: number;\n}\n\ninterface BlockchairVout {\n value: number;\n n: number;\n scriptPubKey: {\n asm: string;\n hex: string;\n address: string;\n type: string;\n addresses: string[];\n reqSigs: number;\n };\n}\n\ninterface BlockchairTransaction {\n block_id: number;\n hash: string;\n time: string;\n balance_change: number;\n}\n\ninterface BlockchairUtxo {\n block_id: number;\n transaction_hash: string;\n index: number;\n value: number;\n}\n\ninterface BlockchairAddressCoreData {\n type: string;\n script_hex: string;\n balance: number;\n balance_usd: number;\n received: number;\n received_usd: number;\n spent: number;\n spent_usd: number;\n output_count: number;\n unspent_output_count: number;\n first_seen_receiving: string;\n last_seen_receiving: string;\n first_seen_spending: null | string;\n last_seen_spending: null | string;\n transaction_count: number;\n scripthash_type: null | string;\n}\n\ninterface BlockchairInputOutputCommonData {\n block_id: number;\n transaction_id: number;\n index: number;\n transaction_hash: string;\n date: string;\n time: string;\n value: number;\n value_usd: number;\n recipient: string;\n type: string;\n script_hex: string;\n is_from_coinbase: boolean;\n is_spendable: boolean | null;\n is_spent: boolean;\n lifespan: number | null;\n cdd: number | null;\n}\n\ninterface BlockchairSpendingBlockData {\n spending_block_id: number | null;\n spending_transaction_id: number | null;\n spending_index: number | null;\n spending_transaction_hash: string | null;\n spending_date: string | null;\n spending_time: string | null;\n spending_value_usd: number | null;\n spending_sequence: number | null;\n spending_signature_hex: string | null;\n spending_witness: string | null;\n}\n\ninterface BlockchairAddressResponse {\n [key: string]: {\n address: BlockchairAddressCoreData;\n transactions: BlockchairTransaction[];\n utxo: BlockchairUtxo[];\n };\n}\n\ninterface BlockchairOutputsResponse\n extends BlockchairSpendingBlockData,\n BlockchairInputOutputCommonData {}\n\ninterface BlockchairRawTransactionResponse {\n [key: string]: {\n raw_transaction: string;\n decoded_raw_transaction: {\n txid: string;\n hash: string;\n version: number;\n size: number;\n vsize: number;\n weight: number;\n locktime: number;\n vin: BlockchairVin[];\n vout: BlockchairVout[];\n };\n };\n}\n\ninterface BlockchairResponse<T> {\n data: T;\n context: {\n code: number;\n source: string;\n results: number;\n state: number;\n market_price_usd: number;\n cache: {\n live: boolean;\n duration: number;\n since: string;\n until: string;\n time: any;\n };\n api: {\n version: string;\n last_major_update: string;\n next_major_update: null | string;\n documentation: string;\n notice: string;\n };\n servers: string;\n time: number;\n render_time: number;\n full_time: number;\n request_cost: number;\n };\n}\n",
|
|
8
|
+
"import { SwapKitError } from \"@swapkit/helpers\";\nimport base58check from \"bs58check\";\n// @ts-ignore\nimport cashaddr from \"cashaddrjs\";\n\nenum Format {\n Legacy = \"legacy\",\n Bitpay = \"bitpay\",\n Cashaddr = \"cashaddr\",\n}\nenum UtxoNetwork {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n}\nenum Type {\n P2PKH = \"p2pkh\",\n P2SH = \"p2sh\",\n}\n\nconst VERSION_BYTE = {\n [Format.Legacy]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 0,\n [Type.P2SH]: 5,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n [Format.Bitpay]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 28,\n [Type.P2SH]: 40,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n};\n\ntype DecodedType = {\n format: Format;\n network: UtxoNetwork;\n type: Type;\n hash: any;\n};\n\nfunction isValidAddress(input: any) {\n try {\n decodeAddress(input);\n return true;\n } catch (_error) {\n return false;\n }\n}\n\nfunction detectAddressNetwork(address: string) {\n return decodeAddress(address)?.network;\n}\n\nfunction toLegacyAddress(address: string): string {\n const decoded = decodeAddress(address);\n if (decoded?.format === Format.Legacy) {\n return address;\n }\n return encodeAsLegacy(decoded);\n}\n\nfunction toCashAddress(address: string): string {\n const decoded = decodeAddress(address);\n return encodeAsCashaddr(decoded);\n}\n\nfunction decodeAddress(address: string) {\n try {\n return decodeBase58Address(address);\n } catch (_error) {\n // Try to decode as cashaddr if base58 decoding fails.\n }\n try {\n return decodeCashAddress(address);\n } catch (_error) {\n // Try to decode as bitpay if cashaddr decoding fails.\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeBase58Address(address: string) {\n try {\n const payload = base58check.decode(address);\n\n // BASE_58_CHECK_PAYLOAD_LENGTH\n if (payload.length !== 21) throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n const versionByte = payload[0];\n const hash = Array.prototype.slice.call(payload, 1);\n\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n default:\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction decodeCashAddress(address: string) {\n if (address.indexOf(\":\") !== -1) {\n try {\n return decodeCashAddressWithPrefix(address);\n } catch (_error) {\n // Try to decode as legacy if cashaddr decoding fails.\n }\n } else {\n const prefixes = [\"bitcoincash\", \"bchtest\", \"bchreg\"];\n for (const prefix of prefixes) {\n try {\n return decodeCashAddressWithPrefix(`${prefix}:${address}`);\n } catch (_error) {\n // Try next prefix if decoding fails.\n }\n }\n }\n\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeCashAddressWithPrefix(address: string): DecodedType {\n try {\n const { hash, prefix, type } = cashaddr.decode(address);\n\n return {\n format: Format.Cashaddr,\n hash: Array.prototype.slice.call(hash, 0),\n network: prefix === \"bitcoincash\" ? UtxoNetwork.Mainnet : UtxoNetwork.Testnet,\n type: type === \"P2PKH\" ? Type.P2PKH : Type.P2SH,\n };\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction encodeAsLegacy(decoded: DecodedType) {\n const versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type];\n const buffer = Buffer.alloc(1 + decoded.hash.length);\n buffer[0] = versionByte;\n buffer.set(decoded.hash, 1);\n return base58check.encode(buffer);\n}\n\nfunction encodeAsCashaddr(decoded: DecodedType) {\n const prefix = decoded.network === UtxoNetwork.Mainnet ? \"bitcoincash\" : \"bchtest\";\n const type = decoded.type === Type.P2PKH ? \"P2PKH\" : \"P2SH\";\n const hash = new Uint8Array(decoded.hash);\n return cashaddr.encode(prefix, type, hash);\n}\n\nexport { detectAddressNetwork, isValidAddress, UtxoNetwork, toCashAddress, toLegacyAddress };\n",
|
|
9
|
+
"import { Chain, SwapKitError, type UTXOChain } from \"@swapkit/helpers\";\n\nimport {\n TX_OVERHEAD,\n UTXOScriptType,\n calculateTxSize,\n getInputSize,\n getOutputSize,\n getScriptTypeForAddress,\n} from \"../helpers\";\nimport type { TargetOutput, UTXOCalculateTxSizeParams, UTXOType } from \"../types\";\n\nexport const getDustThreshold = (chain: UTXOChain) => {\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n return 550;\n case Chain.Dash:\n case Chain.Litecoin:\n return 5500;\n case Chain.Dogecoin:\n return 100000;\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n};\n\nexport const accumulative = ({\n inputs,\n outputs,\n feeRate: initialFeeRate = 1,\n chain = Chain.Bitcoin,\n}: UTXOCalculateTxSizeParams & { outputs: TargetOutput[]; chain: UTXOChain }) => {\n const feeRate = Math.ceil(initialFeeRate);\n\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n // skip input if adding it would cost more than input is worth\n const filteredInputs = inputs.filter((input) => getInputSize(input) * feeRate <= input.value);\n\n const txSizeWithoutInputs =\n TX_OVERHEAD + outputs.reduce((total, output) => total + getOutputSize(output, newTxType), 0);\n\n const amountToSend = outputs.reduce((total, output) => total + output.value, 0);\n\n let fees = txSizeWithoutInputs * feeRate;\n let inputsValue = 0;\n const inputsToUse: typeof inputs = [];\n\n for (const input of filteredInputs) {\n const inputSize = getInputSize(input);\n const inputFee = feeRate * inputSize;\n\n fees += inputFee;\n inputsValue += input.value;\n\n inputsToUse.push(input);\n\n const totalCost = fees + amountToSend;\n\n // we need more inputs\n if (inputsValue < totalCost) continue;\n\n const remainder = inputsValue - totalCost;\n\n const feeForExtraOutput = feeRate * getOutputSize({ address: \"\", value: 0 }, newTxType);\n\n // potential change address\n if (remainder > feeForExtraOutput) {\n const feeAfterExtraOutput = feeForExtraOutput + fees;\n const remainderAfterExtraOutput = inputsValue - (amountToSend + feeAfterExtraOutput);\n\n // is it worth a change output aka can we send it in the future?\n if (\n remainderAfterExtraOutput >\n Math.max(getInputSize({} as UTXOType) * feeRate, getDustThreshold(chain))\n ) {\n return {\n inputs: inputsToUse,\n outputs: outputs.concat({ value: remainderAfterExtraOutput, address: \"\" }),\n fee: feeAfterExtraOutput,\n };\n }\n }\n return {\n inputs: inputsToUse,\n outputs,\n fee: fees,\n };\n }\n\n // We don't have enough inputs, let's calculate transaction fee accrude to the last input\n return { fee: feeRate * calculateTxSize({ inputs, outputs, feeRate }) };\n};\n",
|
|
10
|
+
"import { SwapKitError } from \"@swapkit/helpers\";\nimport { opcodes, script } from \"bitcoinjs-lib\";\nimport type {\n TargetOutput,\n UTXOCalculateTxSizeParams,\n UTXOInputWithScriptType,\n UTXOType,\n} from \"../types\";\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000;\nexport const TX_OVERHEAD = 4 + 1 + 1 + 4; //10\nexport const OP_RETURN_OVERHEAD = 1 + 8 + 1; //10\nconst TX_INPUT_BASE = 32 + 4 + 1 + 4; // 41\nconst TX_INPUT_PUBKEYHASH = 107;\n\nexport function compileMemo(memo: string) {\n const data = Buffer.from(memo, \"utf8\"); // converts MEMO to buffer\n return script.compile([opcodes.OP_RETURN as number, data]); // Compile OP_RETURN script\n}\n\nexport enum UTXOScriptType {\n P2PKH = \"P2PKH\", // legacy\n // P2SH = 'P2SH', // multisig\n P2WPKH = \"P2WPKH\", // bech32 - native segwit\n // P2TR = \"P2TR\", // taproot\n}\n\nexport const InputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 148,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 68,\n};\n\nexport const OutputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 34,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 31,\n};\n\nexport const getScriptTypeForAddress = (address: string) => {\n if (address.startsWith(\"bc1\") || address.startsWith(\"ltc1\")) {\n return UTXOScriptType.P2WPKH;\n }\n // if (address.startsWith('3') || address.startsWith('M')) {\n // return UTXOScriptType.P2SH;\n // }\n if (\n address.startsWith(\"1\") ||\n address.startsWith(\"3\") ||\n address.startsWith(\"L\") ||\n address.startsWith(\"M\") ||\n address.startsWith(\"X\") ||\n address.startsWith(\"D\") ||\n address.startsWith(\"bitcoincash:q\") ||\n address.startsWith(\"q\")\n ) {\n return UTXOScriptType.P2PKH;\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n};\n\nexport const calculateTxSize = ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => {\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n const inputSize = inputs\n .filter(\n (utxo) =>\n utxo.value >=\n InputSizes[\"type\" in utxo ? utxo.type : UTXOScriptType.P2PKH] * Math.ceil(feeRate),\n )\n .reduce((total, utxo) => total + getInputSize(utxo), 0);\n\n const outputSize =\n outputs?.reduce((total, output) => total + getOutputSize(output), 0) || OutputSizes[newTxType];\n\n return TX_OVERHEAD + inputSize + outputSize;\n};\n\nexport const getInputSize = (input: UTXOInputWithScriptType | UTXOType) => {\n if (\"type\" in input) {\n return InputSizes[input.type];\n }\n if (\"address\" in input && input.address) {\n return InputSizes[getScriptTypeForAddress(input.address as string)];\n }\n return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH;\n};\n\nexport const getOutputSize = (output: TargetOutput, scriptType?: UTXOScriptType) => {\n if (output?.script) {\n return OP_RETURN_OVERHEAD + output.script.length + (output.script.length >= 74 ? 2 : 1);\n }\n if (scriptType) {\n return OutputSizes[scriptType];\n }\n return OutputSizes[UTXOScriptType.P2PKH];\n};\n",
|
|
11
|
+
"import {\n AssetValue,\n Chain,\n type ChainSigner,\n DerivationPath,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n SwapKitNumber,\n type UTXOChain,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt, address as btcLibAddress, initEccLib, payments } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } from \"ecpair\";\nimport ECPairFactory from \"ecpair\";\nimport type { UtxoToolboxParams } from \".\";\nimport { getBalance } from \"../../utils\";\nimport {\n UTXOScriptType,\n accumulative,\n calculateTxSize,\n compileMemo,\n getDustThreshold,\n getInputSize,\n getUtxoApi,\n getUtxoNetwork,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { bchValidateAddress } from \"./bitcoinCash\";\n\nimport secp256k1 from \"@bitcoinerlab/secp256k1\";\n// @ts-ignore\nimport { ECPair, HDNode } from \"@psf/bitcoincashjs-lib\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\n\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nfunction addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n}: {\n inputs: UTXOType[];\n outputs: TargetOutput[];\n chain: UTXOChain;\n psbt: Psbt;\n sender: string;\n compiledMemo: Buffer<ArrayBufferLike> | null;\n}) {\n for (const utxo of inputs) {\n const witnessInfo = !!utxo.witnessUtxo &&\n !nonSegwitChains.includes(chain) && { witnessUtxo: utxo.witnessUtxo };\n\n const nonWitnessInfo = nonSegwitChains.includes(chain) && {\n nonWitnessUtxo: utxo.txHex ? Buffer.from(utxo.txHex, \"hex\") : undefined,\n };\n\n psbt.addInput({ hash: utxo.hash, index: utxo.index, ...witnessInfo, ...nonWitnessInfo });\n }\n\n for (const output of outputs) {\n const address = \"address\" in output && output.address ? output.address : sender;\n const hasOutputScript = output.script;\n\n if (hasOutputScript && !compiledMemo) {\n continue;\n }\n\n const mappedOutput = hasOutputScript\n ? {\n script: compiledMemo as Buffer<ArrayBufferLike>,\n value: 0,\n }\n : {\n address,\n value: output.value,\n };\n\n initEccLib(secp256k1);\n psbt.addOutput(mappedOutput);\n }\n\n return { psbt, inputs };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n fetchTxHex = false,\n}: UTXOBuildTxParams): Promise<{\n psbt: Psbt;\n utxos: UTXOType[];\n inputs: UTXOType[];\n}> {\n const chain = assetValue.chain as UTXOChain;\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex,\n });\n\n const { inputs, outputs } = accumulative({ ...inputsAndOutputs, feeRate, chain });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) });\n\n if (chain === Chain.Dogecoin) psbt.setMaximumFeeRate(650000000);\n\n const { psbt: mappedPsbt, inputs: mappedInputs } = await addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n });\n\n return {\n psbt: mappedPsbt,\n utxos: inputsAndOutputs.inputs,\n inputs: mappedInputs,\n };\n}\n\nexport async function getUTXOAddressValidator() {\n const getNetwork = await getUtxoNetwork();\n\n return function validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {\n if (chain === Chain.BitcoinCash) {\n return bchValidateAddress(address);\n }\n\n try {\n initEccLib(secp256k1);\n btcLibAddress.toOutputScript(address, getNetwork(chain));\n return true;\n } catch (_error) {\n return false;\n }\n };\n}\n\nasync function createSignerWithKeys({\n chain,\n phrase,\n derivationPath,\n}: { chain: UTXOChain; phrase: string; derivationPath: string }) {\n const keyPair = (await getCreateKeysForPath(chain as Chain.Bitcoin))({ phrase, derivationPath });\n\n async function signTransaction(psbt: Psbt) {\n await psbt.signAllInputs(keyPair);\n return psbt;\n }\n\n async function getAddress() {\n const addressGetter = await addressFromKeysGetter(chain);\n return addressGetter(keyPair);\n }\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createUTXOToolbox<T extends UTXOChain>({\n chain,\n ...toolboxParams\n}: (\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n }\n) & { chain: T }) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const signer = phrase\n ? await createSignerWithKeys({ chain, phrase, derivationPath })\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n // const { signer } = params || {};\n const getAddressFromKeys = await addressFromKeysGetter(chain);\n const validateAddress = await getUTXOAddressValidator();\n const createKeysForPath = await getCreateKeysForPath(chain);\n\n return {\n accumulative,\n calculateTxSize,\n getAddressFromKeys,\n getAddress,\n validateAddress: (address: string) => validateAddress({ address, chain }),\n broadcastTx: (txHash: string) => getUtxoApi(chain).broadcastTx(txHash),\n createTransaction,\n createKeysForPath,\n getFeeRates: () => getFeeRates(chain),\n getInputsOutputsFee,\n transfer: transfer(signer as UtxoToolboxParams[\"BTC\"][\"signer\"]),\n getPrivateKeyFromMnemonic: (params: { phrase: string; derivationPath: string }) => {\n const keys = createKeysForPath(params);\n return keys.toWIF();\n },\n\n getBalance: getBalance(chain),\n estimateTransactionFee: estimateTransactionFee(chain),\n estimateMaxSendableAmount: estimateMaxSendableAmount(chain),\n };\n}\n\nasync function getInputsOutputsFee({\n assetValue,\n feeOptionKey = FeeOption.Fast,\n feeRate,\n memo,\n sender,\n recipient,\n}: Omit<UTXOBuildTxParams, \"feeRate\"> & {\n feeOptionKey?: FeeOption;\n feeRate?: number;\n}) {\n const chain = assetValue.chain as UTXOChain;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n sender,\n memo,\n recipient,\n });\n\n const feeRateWhole = feeRate ? Math.floor(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n return accumulative({ ...inputsAndOutputs, feeRate: feeRateWhole, chain });\n}\n\nfunction estimateMaxSendableAmount(chain: UTXOChain) {\n return async function estimateMaxSendableAmount({\n from,\n memo,\n feeRate,\n feeOptionKey = FeeOption.Fast,\n recipients = 1,\n }: {\n from: string;\n memo?: string;\n feeRate?: number;\n feeOptionKey?: FeeOption;\n recipients?: number | TargetOutput[];\n }) {\n const addressData = await getUtxoApi(chain).getAddressData(from);\n const feeRateWhole = feeRate ? Math.ceil(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n const inputs = addressData?.utxo\n .map((utxo) => ({\n ...utxo,\n // type: utxo.witnessUtxo ? UTXOScriptType.P2WPKH : UTXOScriptType.P2PKH,\n type: UTXOScriptType.P2PKH,\n hash: \"\",\n }))\n .filter(\n (utxo) => utxo.value > Math.max(getDustThreshold(chain), getInputSize(utxo) * feeRateWhole),\n );\n\n if (!inputs?.length) return AssetValue.from({ chain });\n\n const balance = AssetValue.from({\n chain,\n value: inputs.reduce((sum, utxo) => sum + utxo.value, 0),\n });\n\n const outputs =\n typeof recipients === \"number\"\n ? (Array.from({ length: recipients }, () => ({\n address: from,\n value: 0,\n })) as TargetOutput[])\n : recipients;\n\n if (memo) {\n const script = await compileMemo(memo);\n outputs.push({ address: from, script, value: 0 });\n }\n\n const txSize = calculateTxSize({ inputs, outputs, feeRate: feeRateWhole });\n\n const fee = txSize * feeRateWhole;\n\n return balance.sub(fee);\n };\n}\n\nfunction estimateTransactionFee(chain: UTXOChain) {\n return async (params: {\n assetValue: AssetValue;\n recipient: string;\n sender: string;\n memo?: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) => {\n const inputFees = await getInputsOutputsFee(params);\n\n return AssetValue.from({\n chain,\n value: SwapKitNumber.fromBigInt(BigInt(inputFees.fee), 8).getValue(\"string\"),\n });\n };\n}\n\ntype CreateKeysForPathReturnType = {\n [Chain.BitcoinCash]: BchECPair;\n [Chain.Bitcoin]: ECPairInterface;\n [Chain.Dash]: ECPairInterface;\n [Chain.Dogecoin]: ECPairInterface;\n [Chain.Litecoin]: ECPairInterface;\n};\n\nexport async function getCreateKeysForPath<T extends keyof CreateKeysForPathReturnType>(\n chain: T,\n): Promise<\n (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T]\n> {\n const getNetwork = await getUtxoNetwork();\n\n switch (chain) {\n case Chain.BitcoinCash: {\n return function createKeysForPath({\n phrase,\n derivationPath = `${DerivationPath.BCH}/0`,\n wif,\n }: { wif?: string; phrase?: string; derivationPath?: string }) {\n const network = getNetwork(chain);\n\n if (wif) {\n return ECPair.fromWIF(wif, network) as BchECPair;\n }\n if (!phrase)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"No phrase provided\" });\n\n const masterHDNode = HDNode.fromSeedBuffer(\n Buffer.from(mnemonicToSeedSync(phrase)),\n network,\n );\n const keyPair = masterHDNode.derivePath(derivationPath).keyPair;\n\n return keyPair as BchECPair;\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n return function createKeysForPath({\n phrase,\n wif,\n derivationPath,\n }: { phrase?: string; wif?: string; derivationPath: string }) {\n if (!(wif || phrase))\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Either phrase or wif must be provided\",\n });\n\n const factory = ECPairFactory(secp256k1);\n const network = getNetwork(chain);\n\n if (wif) return factory.fromWIF(wif, network);\n\n const seed = mnemonicToSeedSync(phrase as string);\n const master = HDKey.fromMasterSeed(seed, network).derive(derivationPath);\n if (!master.privateKey)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Could not get private key from phrase\",\n });\n\n return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport async function addressFromKeysGetter(chain: UTXOChain) {\n const getNetwork = await getUtxoNetwork();\n\n return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {\n if (!keys)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Keys must be provided\" });\n\n const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;\n const { address } = method({ pubkey: keys.publicKey as Buffer, network: getNetwork(chain) });\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { error: \"Address not defined\" });\n\n return address;\n };\n}\n\nfunction transfer(signer?: ChainSigner<Psbt, Psbt>) {\n return async function transfer({\n memo,\n recipient,\n feeOptionKey,\n feeRate,\n assetValue,\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n\n const chain = assetValue.chain as UTXOChain;\n\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await createTransaction({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n assetValue,\n memo,\n });\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return getUtxoApi(chain).broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return {\n [FeeOption.Average]: suggestedFeeRate,\n [FeeOption.Fast]: suggestedFeeRate * 1.5,\n [FeeOption.Fastest]: suggestedFeeRate * 2.0,\n };\n}\n\nasync function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex: fetchTxOverwrite = false,\n}: Omit<UTXOBuildTxParams, \"feeRate\">) {\n const chain = assetValue.chain as UTXOChain;\n\n const fetchTxHex = fetchTxOverwrite || nonSegwitChains.includes(chain);\n\n const inputs = await getUtxoApi(chain).scanUTXOs({ address: sender, fetchTxHex });\n\n //1. add output amount and recipient to targets\n //2. add output memo to targets (optional)\n\n return {\n inputs,\n outputs: [\n { address: recipient, value: Number(assetValue.bigIntValue) },\n ...(memo ? [{ address: \"\", script: await compileMemo(memo), value: 0 }] : []),\n ],\n };\n}\n"
|
|
12
|
+
],
|
|
13
|
+
"mappings": "6tBAMO,IANP,8BCKO,IALP,oCAMA,8BAUA,4BCTO,IAPP,8BAQA,4BAIqB,IAArB,yBASA,eAAe,EAAe,EAAG,QAAO,UAA4C,CAClF,IAAM,EAAS,WAAS,IAAI,SAAS,EAAE,GACjC,EAAO,KAAK,UAAU,CAC1B,QAAS,MACT,OAAQ,qBACR,OAAQ,CAAC,CAAM,EACf,GAAI,GAAO,CACb,CAAC,EAEK,EAAW,MAAM,gBAAc,KAIlC,EAAQ,CAAE,QAAS,CAAE,eAAgB,kBAAmB,EAAG,MAAK,CAAC,EAEpE,GAAI,EAAS,MACX,MAAM,IAA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
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as WX,b as _X}from"../../chunk-vhc011em.js";import"../../chunk-38ztynv0.js";import{Chain as x,SwapKitError as yG}from"@swapkit/helpers";import{Transaction as BG,TransactionBuilder as UG,address as vG}from"@psf/bitcoincashjs-lib";import{Chain as MG,FeeOption as zG,NetworkDerivationPath as TG,SwapKitError as R,derivationPathToString as CG,updateDerivationPath as HG}from"@swapkit/helpers";import{Psbt as YG}from"bitcoinjs-lib";import{Chain as T,RequestClient as m,SKConfig as i,SwapKitError as P,warnOnce as qX}from"@swapkit/helpers";import{networks as VX}from"bitcoinjs-lib";import f from"coininfo";async function AX({chain:X,txHash:G}){let J=i.get("rpcUrls")[X],Q=JSON.stringify({jsonrpc:"2.0",method:"sendrawtransaction",params:[G],id:WX()}),$=await m.post(J,{headers:{"Content-Type":"application/json"},body:Q});if($.error)throw new P("toolbox_utxo_broadcast_failed",{error:$.error?.message});if($.result.includes('"code":-26'))throw new P("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return $.result}function a(X){return`https://api.blockchair.com/${KX(X)}`}function LX(X){switch(X){case T.Bitcoin:return 5;case T.Dogecoin:return 1e4;case T.Litecoin:return 1;default:return 2}}function KX(X){switch(X){case T.BitcoinCash:return"bitcoin-cash";case T.Litecoin:return"litecoin";case T.Dash:return"dash";case T.Dogecoin:return"dogecoin";case T.Polkadot:return"polkadot";default:return"bitcoin"}}async function RX(X){try{let{feePerKb:G}=await m.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=G/1000;return Math.max(J,LX(X))}catch(G){return LX(X)}}async function s(X,G){try{let J=await m.get(X);if(!J||J.context.code!==200)throw new P("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}catch(J){if(!G)throw J;let Q=await m.get(`${X}${G?`&key=${G}`:""}`);if(!Q||Q.context.code!==200)throw new P("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return Q.data}}async function DX({address:X,chain:G,apiKey:J}){if(!X)throw new P("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await s(`${a(G)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch(Q){return{utxo:[],address:{balance:0,transaction_count:0}}}}async function wX({address:X,chain:G,apiKey:J}){return(await DX({address:X,chain:G,apiKey:J}))?.address.balance||0}async function BX({chain:X,apiKey:G,txHash:J}){if(!J)throw new P("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await s(`${a(X)}/raw/transaction/${J}`,G))?.[J]?.raw_transaction||""}catch(Q){return console.error("Failed to fetch raw transaction:",Q),""}}async function fX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){return(await s(`${a(X)}/outputs?q=is_spent(false),recipient(${G})&limit=${$}&offset=${Q}`,J)).filter(({is_spent:W})=>!W).map(({script_hex:W,block_id:L,transaction_hash:q,index:D,value:U,spending_signature_hex:B})=>({hash:q,index:D,value:U,txHex:B,script_hex:W,is_confirmed:L!==-1}))}async function UX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){if(!G)throw new P("toolbox_utxo_invalid_params",{error:"Address is required"});try{let j=await fX({chain:X,address:G,apiKey:J,offset:Q,limit:$});if(j.length<=$)return j;let Z=await UX({chain:X,address:G,apiKey:J,offset:Q+$,limit:$});return[...j,...Z]}catch(j){return console.error("Failed to fetch unspent UTXOs:",j),[]}}async function EX({address:X,chain:G,apiKey:J,fetchTxHex:Q=!0}){let $=await UX({chain:G,address:X,apiKey:J}),j=[];for(let{hash:Z,index:W,script_hex:L,value:q}of $){let D;if(Q)D=await BX({txHash:Z,chain:G,apiKey:J});j.push({address:X,hash:Z,index:W,txHex:D,value:q,witnessUtxo:{value:q,script:Buffer.from(L,"hex")}})}return j}function SX(X){let G=i.get("apiKeys").blockchair||"";return qX(!G,"No Blockchair API key found. Functionality will be limited."),{broadcastTx:(J)=>AX({txHash:J,chain:X}),getRawTx:(J)=>BX({txHash:J,chain:X,apiKey:G}),getSuggestedTxFee:()=>RX(X),getBalance:(J)=>wX({address:J,chain:X,apiKey:G}),getAddressData:(J)=>DX({address:J,chain:X,apiKey:G}),scanUTXOs:(J)=>EX({...J,chain:X,apiKey:G})}}function VG(X){return X}function Y(X){let G=i.get("apis")[X];if(G)return qX(!0,"Using custom UTXO API. Be sure to implement all methods to avoid issues."),G;return SX(X)}function I(){return function X(G){switch(G){case T.Bitcoin:return VX.bitcoin;case T.BitcoinCash:return f.bitcoincash.main.toBitcoinJS();case T.Dash:return f.dash.main.toBitcoinJS();case T.Litecoin:return f.litecoin.main.toBitcoinJS();case T.Dogecoin:{let J={private:70615956,public:70617039},Q=f.dogecoin.test;return Q.versions.bip32=J,f.dogecoin.main.toBitcoinJS()}default:throw new P("toolbox_utxo_not_supported",{chain:G})}}}import{SwapKitError as b}from"@swapkit/helpers";import MX from"bs58check";import zX from"cashaddrjs";var TX;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(TX||={});var v={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function CX(X){try{return h(X),!0}catch(G){return!1}}function HX(X){return h(X)?.network}function E(X){let G=h(X);if(G?.format==="legacy")return X;return mX(G)}function l(X){let G=h(X);return lX(G)}function h(X){try{return gX(X)}catch(G){}try{return xX(X)}catch(G){}throw new b("toolbox_utxo_invalid_address",{address:X})}function gX(X){try{let G=MX.decode(X);if(G.length!==21)throw new b("toolbox_utxo_invalid_address",{address:X});let J=G[0],Q=Array.prototype.slice.call(G,1);switch(J){case v.legacy.mainnet.p2pkh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2pkh"};case v.legacy.mainnet.p2sh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2sh"};case v.legacy.testnet.p2pkh:return{hash:Q,format:"legacy",network:"testnet",type:"p2pkh"};case v.legacy.testnet.p2sh:return{hash:Q,format:"legacy",network:"testnet",type:"p2sh"};case v.bitpay.mainnet.p2pkh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2pkh"};case v.bitpay.mainnet.p2sh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2sh"};default:throw new b("toolbox_utxo_invalid_address",{address:X})}}catch(G){throw new b("toolbox_utxo_invalid_address",{address:X})}}function xX(X){if(X.indexOf(":")!==-1)try{return vX(X)}catch(G){}else{let G=["bitcoincash","bchtest","bchreg"];for(let J of G)try{return vX(`${J}:${X}`)}catch(Q){}}throw new b("toolbox_utxo_invalid_address",{address:X})}function vX(X){try{let{hash:G,prefix:J,type:Q}=zX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call(G,0),network:J==="bitcoincash"?"mainnet":"testnet",type:Q==="P2PKH"?"p2pkh":"p2sh"}}catch(G){throw new b("toolbox_utxo_invalid_address",{address:X})}}function mX(X){let G=v.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=G,J.set(X.hash,1),MX.encode(J)}function lX(X){let G=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",Q=new Uint8Array(X.hash);return zX.encode(G,J,Q)}import{Chain as V,SwapKitError as hX}from"@swapkit/helpers";var t=(X)=>{switch(X){case V.Bitcoin:case V.BitcoinCash:return 550;case V.Dash:case V.Litecoin:return 5500;case V.Dogecoin:return 1e5;default:throw new hX("toolbox_utxo_not_supported",{chain:X})}},N=({inputs:X,outputs:G,feeRate:J=1,chain:Q=V.Bitcoin})=>{let $=Math.ceil(J),j=X[0]&&"address"in X[0]&&X[0].address?u(X[0].address):"P2PKH",Z=X.filter((B)=>y(B)*$<=B.value),W=e+G.reduce((B,z)=>B+c(z,j),0),L=G.reduce((B,z)=>B+z.value,0),q=W*$,D=0,U=[];for(let B of Z){let z=y(B),M=$*z;q+=M,D+=B.value,U.push(B);let H=q+L;if(D<H)continue;let k=D-H,ZX=$*c({address:"",value:0},j);if(k>ZX){let $X=ZX+q,jX=D-(L+$X);if(jX>Math.max(y({})*$,t(Q)))return{inputs:U,outputs:G.concat({value:jX,address:""}),fee:$X}}return{inputs:U,outputs:G,fee:q}}return{fee:$*S({inputs:X,outputs:G,feeRate:$})}};import{SwapKitError as cX}from"@swapkit/helpers";import{opcodes as uX,script as pX}from"bitcoinjs-lib";var lG=1000,e=10,oX=10,nX=41,rX=107;function O(X){let G=Buffer.from(X,"utf8");return pX.compile([uX.OP_RETURN,G])}var XX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(XX||={});var GX={["P2PKH"]:148,["P2WPKH"]:68},p={["P2PKH"]:34,["P2WPKH"]:31},u=(X)=>{if(X.startsWith("bc1")||X.startsWith("ltc1"))return"P2WPKH";if(X.startsWith("1")||X.startsWith("3")||X.startsWith("L")||X.startsWith("M")||X.startsWith("X")||X.startsWith("D")||X.startsWith("bitcoincash:q")||X.startsWith("q"))return"P2PKH";throw new cX("toolbox_utxo_invalid_address",{address:X})},S=({inputs:X,outputs:G,feeRate:J})=>{let Q=X[0]&&"address"in X[0]&&X[0].address?u(X[0].address):"P2PKH",$=X.filter((Z)=>Z.value>=GX["type"in Z?Z.type:"P2PKH"]*Math.ceil(J)).reduce((Z,W)=>Z+y(W),0),j=G?.reduce((Z,W)=>Z+c(W),0)||p[Q];return e+$+j},y=(X)=>{if("type"in X)return GX[X.type];if("address"in X&&X.address)return GX[u(X.address)];return nX+rX},c=(X,G)=>{if(X?.script)return oX+X.script.length+(X.script.length>=74?2:1);if(G)return p[G];return p.P2PKH};import{AssetValue as JX,Chain as _,DerivationPath as dX,FeeOption as A,NetworkDerivationPath as iX,SwapKitError as F,SwapKitNumber as aX,derivationPathToString as sX,updateDerivationPath as tX}from"@swapkit/helpers";import{Psbt as eX,address as XG,initEccLib as FX,payments as YX}from"bitcoinjs-lib";import GG from"ecpair";import QX from"@bitcoinerlab/secp256k1";import{ECPair as JG,HDNode as QG}from"@psf/bitcoincashjs-lib";import{HDKey as ZG}from"@scure/bip32";import{mnemonicToSeedSync as IX}from"@scure/bip39";var o=[_.Dash,_.Dogecoin];function $G({inputs:X,outputs:G,chain:J,psbt:Q,sender:$,compiledMemo:j}){for(let Z of X){let W=!!Z.witnessUtxo&&!o.includes(J)&&{witnessUtxo:Z.witnessUtxo},L=o.includes(J)&&{nonWitnessUtxo:Z.txHex?Buffer.from(Z.txHex,"hex"):void 0};Q.addInput({hash:Z.hash,index:Z.index,...W,...L})}for(let Z of G){let W="address"in Z&&Z.address?Z.address:$,L=Z.script;if(L&&!j)continue;let q=L?{script:j,value:0}:{address:W,value:Z.value};FX(QX),Q.addOutput(q)}return{psbt:Q,inputs:X}}async function PX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$,fetchTxHex:j=!1}){let Z=X.chain,W=J?await O(J):null,L=await OX({assetValue:X,recipient:G,memo:J,sender:$,fetchTxHex:j}),{inputs:q,outputs:D}=N({...L,feeRate:Q,chain:Z});if(!(q&&D))throw new F("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let U=await I(),B=new eX({network:U(Z)});if(Z===_.Dogecoin)B.setMaximumFeeRate(650000000);let{psbt:z,inputs:M}=await $G({inputs:q,outputs:D,chain:Z,psbt:B,sender:$,compiledMemo:W});return{psbt:z,utxos:L.inputs,inputs:M}}async function jG(){let X=await I();return function G({address:J,chain:Q}){if(Q===_.BitcoinCash)return K(J);try{return FX(QX),XG.toOutputScript(J,X(Q)),!0}catch($){return!1}}}async function LG({chain:X,phrase:G,derivationPath:J}){let Q=(await r(X))({phrase:G,derivationPath:J});async function $(Z){return await Z.signAllInputs(Q),Z}async function j(){return(await NX(X))(Q)}return{getAddress:j,signTransaction:$}}async function n({chain:X,...G}){let J="phrase"in G?G.phrase:void 0,Q="index"in G?G.index||0:0,$=sX("derivationPath"in G&&G.derivationPath?G.derivationPath:tX(iX[X],{index:Q})),j=J?await LG({chain:X,phrase:J,derivationPath:$}):("signer"in G)?G.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let W=await NX(X),L=await jG(),q=await r(X);return{accumulative:N,calculateTxSize:S,getAddressFromKeys:W,getAddress:Z,validateAddress:(D)=>L({address:D,chain:X}),broadcastTx:(D)=>Y(X).broadcastTx(D),createTransaction:PX,createKeysForPath:q,getFeeRates:()=>d(X),getInputsOutputsFee:yX,transfer:DG(j),getPrivateKeyFromMnemonic:(D)=>{return q(D).toWIF()},getBalance:_X(X),estimateTransactionFee:qG(X),estimateMaxSendableAmount:WG(X)}}async function yX({assetValue:X,feeOptionKey:G=A.Fast,feeRate:J,memo:Q,sender:$,recipient:j}){let Z=X.chain,W=await OX({assetValue:X,sender:$,memo:Q,recipient:j}),L=J?Math.floor(J):(await d(Z))[G];return N({...W,feeRate:L,chain:Z})}function WG(X){return async function G({from:J,memo:Q,feeRate:$,feeOptionKey:j=A.Fast,recipients:Z=1}){let W=await Y(X).getAddressData(J),L=$?Math.ceil($):(await d(X))[j],q=W?.utxo.map((M)=>({...M,type:"P2PKH",hash:""})).filter((M)=>M.value>Math.max(t(X),y(M)*L));if(!q?.length)return JX.from({chain:X});let D=JX.from({chain:X,value:q.reduce((M,H)=>M+H.value,0)}),U=typeof Z==="number"?Array.from({length:Z},()=>({address:J,value:0})):Z;if(Q){let M=await O(Q);U.push({address:J,script:M,value:0})}let z=S({inputs:q,outputs:U,feeRate:L})*L;return D.sub(z)}}function qG(X){return async(G)=>{let J=await yX(G);return JX.from({chain:X,value:aX.fromBigInt(BigInt(J.fee),8).getValue("string")})}}async function r(X){let G=await I();switch(X){case _.BitcoinCash:return function J({phrase:Q,derivationPath:$=`${dX.BCH}/0`,wif:j}){let Z=G(X);if(j)return JG.fromWIF(j,Z);if(!Q)throw new F("toolbox_utxo_invalid_params",{error:"No phrase provided"});return QG.fromSeedBuffer(Buffer.from(IX(Q)),Z).derivePath($).keyPair};case _.Bitcoin:case _.Dogecoin:case _.Litecoin:case _.Dash:return function J({phrase:Q,wif:$,derivationPath:j}){if(!($||Q))throw new F("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let Z=GG(QX),W=G(X);if($)return Z.fromWIF($,W);let L=IX(Q),q=ZG.fromMasterSeed(L,W).derive(j);if(!q.privateKey)throw new F("toolbox_utxo_invalid_params",{error:"Could not get private key from phrase"});return Z.fromPrivateKey(Buffer.from(q.privateKey),{network:W})};default:throw new F("toolbox_utxo_not_supported",{chain:X})}}async function NX(X){let G=await I();return function J(Q){if(!Q)throw new F("toolbox_utxo_invalid_params",{error:"Keys must be provided"});let $=o.includes(X)?YX.p2pkh:YX.p2wpkh,{address:j}=$({pubkey:Q.publicKey,network:G(X)});if(!j)throw new F("toolbox_utxo_invalid_address",{error:"Address not defined"});return j}}function DG(X){return async function G({memo:J,recipient:Q,feeOptionKey:$,feeRate:j,assetValue:Z}){let W=await X?.getAddress(),L=Z.chain;if(!(X&&W))throw new F("toolbox_utxo_no_signer");if(!Q)throw new F("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let q=j||(await d(L))[$||A.Fast],{psbt:D}=await PX({recipient:Q,feeRate:q,sender:W,assetValue:Z,memo:J}),U=await X.signTransaction(D);return U.finalizeAllInputs(),Y(L).broadcastTx(U.extractTransaction().toHex())}}async function d(X){let G=await Y(X).getSuggestedTxFee();return{[A.Average]:G,[A.Fast]:G*1.5,[A.Fastest]:G*2}}async function OX({assetValue:X,recipient:G,memo:J,sender:Q,fetchTxHex:$=!1}){let j=X.chain,Z=$||o.includes(j);return{inputs:await Y(j).scanUTXOs({address:Q,fetchTxHex:Z}),outputs:[{address:G,value:Number(X.bigIntValue)},...J?[{address:"",script:await O(J),value:0}]:[]]}}var C=MG.BitcoinCash;function g(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function K(X){let G=g(X);return CX(G)&&HX(G)==="mainnet"}function w(X){return g(l(X))}async function IG(X){async function G({builder:Q,utxos:$}){return $.forEach((j,Z)=>{Q.sign(Z,X,void 0,65,j.witnessUtxo?.value)}),Q.build()}return{getAddress:()=>{let Q=X.getAddress(0);return Promise.resolve(w(Q))},signTransaction:G}}async function kX(X){let G="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,Q=CG("derivationPath"in X&&X.derivationPath?X.derivationPath:HG(TG[C],{index:J})),$=(await r(C))({phrase:G,derivationPath:Q}),j=$?await IG($):("signer"in X)?X.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let{getBalance:W,getFeeRates:L,broadcastTx:q,...D}=await n({chain:C});function U(B,z=!0){return W(g(l(B)))}return{...D,getAddress:Z,broadcastTx:q,createTransaction:bX,buildTx:FG,getAddressFromKeys:PG,getBalance:U,getFeeRates:L,stripPrefix:g,stripToCashAddress:w,validateAddress:K,transfer:_G({getFeeRates:L,broadcastTx:q,signer:j})}}async function bX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){if(!K(G))throw new R("toolbox_utxo_invalid_address",{address:G});let j=await Y(C).scanUTXOs({address:w($),fetchTxHex:!0}),Z=J?await O(J):null,W=[];W.push({address:G,value:X.getBaseValue("number")});let{inputs:L,outputs:q}=N({inputs:j,outputs:W,feeRate:Q,chain:C});if(!(L&&q))throw new R("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let D=await I(),U=new UG(D(C));await Promise.all(L.map(async(B)=>{let z=await Y(C).getRawTx(B.hash);U.addInput(BG.fromBuffer(Buffer.from(z,"hex")),B.index)}));for(let B of q){let z="address"in B&&B.address?B.address:E($),M=await I(),H=vG.toOutputScript(E(z),M(C));U.addOutput(H,B.value)}if(Z)U.addOutput(Z,0);return{builder:U,utxos:L}}function _G({broadcastTx:X,getFeeRates:G,signer:J}){return async function Q({recipient:$,assetValue:j,feeOptionKey:Z=zG.Fast,...W}){let L=await J?.getAddress();if(!(J&&L))throw new R("toolbox_utxo_no_signer");if(!$)throw new R("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let q=W.feeRate||(await G())[Z],{builder:D,utxos:U}=await bX({...W,assetValue:j,feeRate:q,recipient:$,sender:L}),z=(await J.signTransaction({builder:D,utxos:U})).toHex();return X(z)}}async function FG({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){let j=l(G);if(!K(j))throw new R("toolbox_utxo_invalid_address",{address:j});let Z=await Y(C).scanUTXOs({address:w($),fetchTxHex:!0}),W=Number(Q.toFixed(0)),L=J?await O(J):null,q=[];if(q.push({address:E(G),value:X.getBaseValue("number")}),L)q.push({script:L,value:0});let{inputs:D,outputs:U}=N({inputs:Z,outputs:q,feeRate:W,chain:C});if(!(D&&U))throw new R("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let B=await I(),z=new YG({network:B(C)});for(let{hash:M,index:H,witnessUtxo:k}of D)z.addInput({hash:M,index:H,witnessUtxo:k});for(let M of U){let H="address"in M&&M.address?M.address:E($),k=M.script?L?{script:L,value:0}:void 0:{address:H,value:M.value};if(k)z.addOutput(k)}return{psbt:z,utxos:Z,inputs:D}}function PG(X){let G=X.getAddress(0);return w(G)}async function vJ(X,G){switch(X){case x.BitcoinCash:return await kX(G);case x.Bitcoin:case x.Dogecoin:case x.Litecoin:case x.Dash:return await n({chain:X,...G});default:throw new yG("toolbox_utxo_not_supported",{chain:X})}}export{E as toLegacyAddress,l as toCashAddress,w as stripToCashAddress,g as stripPrefix,o as nonSegwitChains,CX as isValidAddress,vJ as getUtxoToolbox,I as getUtxoNetwork,Y as getUtxoApi,jG as getUTXOAddressValidator,u as getScriptTypeForAddress,c as getOutputSize,y as getInputSize,t as getDustThreshold,r as getCreateKeysForPath,HX as detectAddressNetwork,n as createUTXOToolbox,VG as createCustomUtxoApi,kX as createBCHToolbox,O as compileMemo,S as calculateTxSize,K as bchValidateAddress,NX as addressFromKeysGetter,N as accumulative,TX as UtxoNetwork,XX as UTXOScriptType,e as TX_OVERHEAD,p as OutputSizes,oX as OP_RETURN_OVERHEAD,lG as MIN_TX_FEE,GX as InputSizes};
|
|
2
|
+
|
|
3
|
+
//# debugId=A3DD28B1B9CE223364756E2164756E21
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/utxo/toolbox/index.ts", "../src/utxo/toolbox/bitcoinCash.ts", "../src/utxo/helpers/api.ts", "../src/utxo/helpers/bchaddrjs.ts", "../src/utxo/helpers/coinselect.ts", "../src/utxo/helpers/txSize.ts", "../src/utxo/toolbox/utxo.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n SwapKitError,\n type UTXOChain,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\n\nimport type { TransactionBuilderType, TransactionType, UTXOType } from \"../types\";\nimport { createBCHToolbox } from \"./bitcoinCash\";\nimport { createUTXOToolbox } from \"./utxo\";\n\ntype BCHToolbox = Awaited<ReturnType<typeof createBCHToolbox>>;\ntype CommonUTXOToolbox = Awaited<\n ReturnType<typeof createUTXOToolbox<Exclude<UTXOChain, Chain.BitcoinCash>>>\n>;\n\nexport type UTXOToolboxes = {\n [Chain.BitcoinCash]: BCHToolbox;\n [Chain.Bitcoin]: CommonUTXOToolbox;\n [Chain.Dogecoin]: CommonUTXOToolbox;\n [Chain.Litecoin]: CommonUTXOToolbox;\n [Chain.Dash]: CommonUTXOToolbox;\n};\n\nexport type UTXOWallets = {\n [key in keyof UTXOToolboxes]: UTXOToolboxes[key];\n};\n\nexport type UtxoToolboxParams = {\n [Chain.BitcoinCash]: {\n signer: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n };\n [Chain.Bitcoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dogecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Litecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dash]: { signer: ChainSigner<Psbt, Psbt> };\n};\n\nexport async function getUtxoToolbox<T extends keyof UTXOToolboxes>(\n chain: T,\n params?:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n): Promise<UTXOToolboxes[T]> {\n switch (chain) {\n case Chain.BitcoinCash: {\n const toolbox = await createBCHToolbox(params as UtxoToolboxParams[Chain.BitcoinCash]);\n return toolbox as UTXOToolboxes[T];\n }\n\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n const toolbox = await createUTXOToolbox({\n chain,\n ...(params as UtxoToolboxParams[Exclude<T, Chain.BitcoinCash>]),\n });\n return toolbox as UTXOToolboxes[Exclude<T, Chain.BitcoinCash>];\n }\n\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport {\n stripToCashAddress,\n stripPrefix,\n bchValidateAddress,\n} from \"./bitcoinCash\";\n",
|
|
6
|
+
"import {\n Transaction,\n TransactionBuilder,\n address as bchAddress,\n // @ts-ignore\n} from \"@psf/bitcoincashjs-lib\";\nimport {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt } from \"bitcoinjs-lib\";\nimport type { UtxoToolboxParams } from \".\";\nimport {\n accumulative,\n UtxoNetwork as bchNetwork,\n compileMemo,\n detectAddressNetwork,\n getUtxoApi,\n getUtxoNetwork,\n isValidAddress,\n toCashAddress,\n toLegacyAddress,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n TransactionBuilderType,\n TransactionType,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { createUTXOToolbox, getCreateKeysForPath } from \"./utxo\";\n\nconst chain = Chain.BitcoinCash;\n\nexport function stripPrefix(address: string) {\n return address.replace(/(bchtest:|bitcoincash:)/, \"\");\n}\n\nexport function bchValidateAddress(address: string) {\n const strippedAddress = stripPrefix(address);\n return (\n isValidAddress(strippedAddress) && detectAddressNetwork(strippedAddress) === bchNetwork.Mainnet\n );\n}\n\nexport function stripToCashAddress(address: string) {\n return stripPrefix(toCashAddress(address));\n}\n\nasync function createSignerWithKeys(keys: BchECPair) {\n async function signTransaction({\n builder,\n utxos,\n }: { builder: TransactionBuilderType; utxos: UTXOType[] }) {\n utxos.forEach((utxo, index) => {\n builder.sign(index, keys, undefined, 0x41, utxo.witnessUtxo?.value);\n });\n\n return builder.build();\n }\n\n const getAddress = () => {\n const address = keys.getAddress(0);\n return Promise.resolve(stripToCashAddress(address));\n };\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createBCHToolbox<T extends Chain.BitcoinCash>(\n toolboxParams:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const keys = (await getCreateKeysForPath(chain))({ phrase, derivationPath });\n\n const signer = keys\n ? await createSignerWithKeys(keys)\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n const { getBalance, getFeeRates, broadcastTx, ...toolbox } = await createUTXOToolbox({ chain });\n\n function handleGetBalance(address: string, _scamFilter = true) {\n return getBalance(stripPrefix(toCashAddress(address)));\n }\n\n return {\n ...toolbox,\n getAddress,\n broadcastTx,\n createTransaction,\n buildTx,\n getAddressFromKeys,\n getBalance: handleGetBalance,\n getFeeRates,\n stripPrefix,\n stripToCashAddress,\n validateAddress: bchValidateAddress,\n transfer: transfer({ getFeeRates, broadcastTx, signer }),\n };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n}: UTXOBuildTxParams) {\n if (!bchValidateAddress(recipient))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipient });\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs: TargetOutput[] = [];\n // output to recipient\n targetOutputs.push({\n address: recipient,\n value: assetValue.getBaseValue(\"number\"),\n });\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const builder = new TransactionBuilder(getNetwork(chain)) as TransactionBuilderType;\n\n await Promise.all(\n inputs.map(async (utxo: UTXOType) => {\n const txHex = await getUtxoApi(chain).getRawTx(utxo.hash);\n\n builder.addInput(Transaction.fromBuffer(Buffer.from(txHex, \"hex\")), utxo.index);\n }),\n );\n\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const getNetwork = await getUtxoNetwork();\n const outputScript = bchAddress.toOutputScript(toLegacyAddress(address), getNetwork(chain));\n\n builder.addOutput(outputScript, output.value);\n }\n\n // add output for memo\n if (compiledMemo) {\n builder.addOutput(compiledMemo, 0); // Add OP_RETURN {script, value}\n }\n\n return { builder, utxos: inputs };\n}\n\nfunction transfer({\n broadcastTx,\n getFeeRates,\n signer,\n}: {\n broadcastTx: (txHash: string) => Promise<string>;\n getFeeRates: () => Promise<Record<FeeOption, number>>;\n signer?: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n}) {\n return async function transfer({\n recipient,\n assetValue,\n feeOptionKey = FeeOption.Fast,\n ...rest\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n\n const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];\n\n // try out if psbt tx is faster/better/nicer\n const { builder, utxos } = await createTransaction({\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n });\n\n const tx = await signer.signTransaction({ builder, utxos });\n const txHex = tx.toHex();\n\n return broadcastTx(txHex);\n };\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\nasync function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBuildTxParams) {\n const recipientCashAddress = toCashAddress(recipient);\n if (!bchValidateAddress(recipientCashAddress))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipientCashAddress });\n\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const feeRateWhole = Number(feeRate.toFixed(0));\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs = [] as TargetOutput[];\n\n // output to recipient\n targetOutputs.push({\n address: toLegacyAddress(recipient),\n value: assetValue.getBaseValue(\"number\"),\n });\n\n //2. add output memo to targets (optional)\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 });\n }\n\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate: feeRateWhole,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) }); // Network-specific\n\n for (const { hash, index, witnessUtxo } of inputs) {\n psbt.addInput({ hash, index, witnessUtxo });\n }\n\n // Outputs\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const params = output.script\n ? compiledMemo\n ? { script: compiledMemo, value: 0 }\n : undefined\n : { address, value: output.value };\n\n if (params) {\n psbt.addOutput(params);\n }\n }\n\n return { psbt, utxos, inputs: inputs as UTXOType[] };\n}\n\nfunction getAddressFromKeys(keys: { getAddress: (index?: number) => string }) {\n const address = keys.getAddress(0);\n return stripToCashAddress(address);\n}\n",
|
|
7
|
+
"import {\n Chain,\n RequestClient,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n warnOnce,\n} from \"@swapkit/helpers\";\nimport { networks } from \"bitcoinjs-lib\";\nimport { uniqid } from \"../../utils\";\n\n// @ts-ignore\nimport coininfo from \"coininfo\";\n\ntype BlockchairParams<T> = T & { chain: Chain; apiKey?: string };\ntype BlockchairFetchUnspentUtxoParams = BlockchairParams<{\n offset?: number;\n limit?: number;\n address: string;\n}>;\n\nasync function broadcastUTXOTx({ chain, txHash }: { chain: Chain; txHash: string }) {\n const rpcUrl = SKConfig.get(\"rpcUrls\")[chain];\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"sendrawtransaction\",\n params: [txHash],\n id: uniqid(),\n });\n\n const response = await RequestClient.post<{\n id: string;\n result: string;\n error: { message: string; code?: number } | null;\n }>(rpcUrl, { headers: { \"Content-Type\": \"application/json\" }, body });\n\n if (response.error) {\n throw new SwapKitError(\"toolbox_utxo_broadcast_failed\", { error: response.error?.message });\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new SwapKitError(\"toolbox_utxo_invalid_transaction\", {\n error: \"Transaction amount was too low\",\n });\n }\n\n return response.result;\n}\n\nfunction baseUrl(chain: Chain) {\n return `https://api.blockchair.com/${mapChainToBlockchairChain(chain)}`;\n}\n\nfunction getDefaultTxFeeByChain(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return 5;\n case Chain.Dogecoin:\n return 10000;\n case Chain.Litecoin:\n return 1;\n default:\n return 2;\n }\n}\n\nfunction mapChainToBlockchairChain(chain: Chain) {\n switch (chain) {\n case Chain.BitcoinCash:\n return \"bitcoin-cash\";\n case Chain.Litecoin:\n return \"litecoin\";\n case Chain.Dash:\n return \"dash\";\n case Chain.Dogecoin:\n return \"dogecoin\";\n case Chain.Polkadot:\n return \"polkadot\";\n default:\n return \"bitcoin\";\n }\n}\n\nasync function getSuggestedTxFee(chain: Chain) {\n try {\n //Use Bitgo API for fee estimation\n //Refer: https://app.bitgo.com/docs/#operation/v2.tx.getfeeestimate\n const { feePerKb } = await RequestClient.get<{\n feePerKb: number;\n cpfpFeePerKb: number;\n numBlocks: number;\n feeByBlockTarget: { 1: number; 3: number };\n }>(`https://app.bitgo.com/api/v2/${chain.toLowerCase()}/tx/fee`);\n const suggestedFee = feePerKb / 1000;\n\n return Math.max(suggestedFee, getDefaultTxFeeByChain(chain));\n } catch (_error) {\n return getDefaultTxFeeByChain(chain);\n }\n}\n\nasync function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {\n try {\n const response = await RequestClient.get<BlockchairResponse<T>>(url);\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n } catch (error) {\n if (!apiKey) throw error;\n const response = await RequestClient.get<BlockchairResponse<T>>(\n `${url}${apiKey ? `&key=${apiKey}` : \"\"}`,\n );\n\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n }\n}\n\nasync function getAddressData({ address, chain, apiKey }: BlockchairParams<{ address?: string }>) {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const response = await blockchairRequest<BlockchairAddressResponse>(\n `${baseUrl(chain)}/dashboards/address/${address}?transaction_details=true`,\n apiKey,\n );\n\n return response[address];\n } catch (_error) {\n return { utxo: [], address: { balance: 0, transaction_count: 0 } };\n }\n}\n\nasync function getUnconfirmedBalance({\n address,\n chain,\n apiKey,\n}: BlockchairParams<{ address?: string }>) {\n const response = await getAddressData({ address, chain, apiKey });\n\n return response?.address.balance || 0;\n}\n\nasync function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {\n if (!txHash)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"TxHash is required\" });\n\n try {\n const rawTxResponse = await blockchairRequest<BlockchairRawTransactionResponse>(\n `${baseUrl(chain)}/raw/transaction/${txHash}`,\n apiKey,\n );\n return rawTxResponse?.[txHash]?.raw_transaction || \"\";\n } catch (error) {\n console.error(\"Failed to fetch raw transaction:\", error);\n return \"\";\n }\n}\n\nasync function fetchUnspentUtxoBatch({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams) {\n const response = await blockchairRequest<BlockchairOutputsResponse[]>(\n `${baseUrl(chain)}/outputs?q=is_spent(false),recipient(${address})&limit=${limit}&offset=${offset}`,\n apiKey,\n );\n\n const txs = response\n .filter(({ is_spent }) => !is_spent)\n .map(({ script_hex, block_id, transaction_hash, index, value, spending_signature_hex }) => ({\n hash: transaction_hash,\n index,\n value,\n txHex: spending_signature_hex,\n script_hex,\n is_confirmed: block_id !== -1,\n }));\n\n return txs;\n}\n\nasync function getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams): Promise<Awaited<ReturnType<typeof fetchUnspentUtxoBatch>>> {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const txs = await fetchUnspentUtxoBatch({ chain, address, apiKey, offset, limit });\n\n if (txs.length <= limit) return txs;\n\n const nextBatch = await getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset: offset + limit,\n limit,\n });\n\n return [...txs, ...nextBatch];\n } catch (error) {\n console.error(\"Failed to fetch unspent UTXOs:\", error);\n return [];\n }\n}\n\nasync function scanUTXOs({\n address,\n chain,\n apiKey,\n fetchTxHex = true,\n}: BlockchairParams<{ address: string; fetchTxHex?: boolean }>) {\n const utxos = await getUnspentUtxos({ chain, address, apiKey });\n const results = [];\n\n for (const { hash, index, script_hex, value } of utxos) {\n let txHex: string | undefined;\n if (fetchTxHex) {\n txHex = await getRawTx({ txHash: hash, chain, apiKey });\n }\n results.push({\n address,\n hash,\n index,\n txHex,\n value,\n witnessUtxo: { value, script: Buffer.from(script_hex, \"hex\") },\n });\n }\n return results;\n}\n\nfunction utxoApi(chain: UTXOChain) {\n const apiKey = SKConfig.get(\"apiKeys\").blockchair || \"\";\n\n warnOnce(!apiKey, \"No Blockchair API key found. Functionality will be limited.\");\n\n return {\n broadcastTx: (txHash: string) => broadcastUTXOTx({ txHash, chain }),\n getRawTx: (txHash: string) => getRawTx({ txHash, chain, apiKey }),\n getSuggestedTxFee: () => getSuggestedTxFee(chain),\n getBalance: (address: string) => getUnconfirmedBalance({ address, chain, apiKey }),\n getAddressData: (address: string) => getAddressData({ address, chain, apiKey }),\n scanUTXOs: (params: { address: string; fetchTxHex?: boolean }) =>\n scanUTXOs({ ...params, chain, apiKey }),\n };\n}\n\n/**\n * \"Factory\" to ensure typing for custom UTXO APIs\n */\nexport function createCustomUtxoApi(methods: ReturnType<typeof utxoApi>) {\n return methods;\n}\n\nexport function getUtxoApi(chain: UTXOChain) {\n const customUtxoApi = SKConfig.get(\"apis\")[chain];\n\n if (customUtxoApi) {\n warnOnce(true, \"Using custom UTXO API. Be sure to implement all methods to avoid issues.\");\n return customUtxoApi as ReturnType<typeof utxoApi>;\n }\n\n return utxoApi(chain);\n}\n\nexport function getUtxoNetwork() {\n return function getNetwork(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return networks.bitcoin;\n case Chain.BitcoinCash:\n return coininfo.bitcoincash.main.toBitcoinJS();\n case Chain.Dash:\n return coininfo.dash.main.toBitcoinJS();\n case Chain.Litecoin:\n return coininfo.litecoin.main.toBitcoinJS();\n\n case Chain.Dogecoin: {\n const bip32 = { private: 0x04358394, public: 0x043587cf };\n const test = coininfo.dogecoin.test;\n test.versions.bip32 = bip32;\n return coininfo.dogecoin.main.toBitcoinJS();\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n };\n}\n\ninterface BlockchairVin {\n txid: string;\n vout: number;\n scriptSig: {\n asm: string;\n hex: string;\n };\n sequence: number;\n}\n\ninterface BlockchairVout {\n value: number;\n n: number;\n scriptPubKey: {\n asm: string;\n hex: string;\n address: string;\n type: string;\n addresses: string[];\n reqSigs: number;\n };\n}\n\ninterface BlockchairTransaction {\n block_id: number;\n hash: string;\n time: string;\n balance_change: number;\n}\n\ninterface BlockchairUtxo {\n block_id: number;\n transaction_hash: string;\n index: number;\n value: number;\n}\n\ninterface BlockchairAddressCoreData {\n type: string;\n script_hex: string;\n balance: number;\n balance_usd: number;\n received: number;\n received_usd: number;\n spent: number;\n spent_usd: number;\n output_count: number;\n unspent_output_count: number;\n first_seen_receiving: string;\n last_seen_receiving: string;\n first_seen_spending: null | string;\n last_seen_spending: null | string;\n transaction_count: number;\n scripthash_type: null | string;\n}\n\ninterface BlockchairInputOutputCommonData {\n block_id: number;\n transaction_id: number;\n index: number;\n transaction_hash: string;\n date: string;\n time: string;\n value: number;\n value_usd: number;\n recipient: string;\n type: string;\n script_hex: string;\n is_from_coinbase: boolean;\n is_spendable: boolean | null;\n is_spent: boolean;\n lifespan: number | null;\n cdd: number | null;\n}\n\ninterface BlockchairSpendingBlockData {\n spending_block_id: number | null;\n spending_transaction_id: number | null;\n spending_index: number | null;\n spending_transaction_hash: string | null;\n spending_date: string | null;\n spending_time: string | null;\n spending_value_usd: number | null;\n spending_sequence: number | null;\n spending_signature_hex: string | null;\n spending_witness: string | null;\n}\n\ninterface BlockchairAddressResponse {\n [key: string]: {\n address: BlockchairAddressCoreData;\n transactions: BlockchairTransaction[];\n utxo: BlockchairUtxo[];\n };\n}\n\ninterface BlockchairOutputsResponse\n extends BlockchairSpendingBlockData,\n BlockchairInputOutputCommonData {}\n\ninterface BlockchairRawTransactionResponse {\n [key: string]: {\n raw_transaction: string;\n decoded_raw_transaction: {\n txid: string;\n hash: string;\n version: number;\n size: number;\n vsize: number;\n weight: number;\n locktime: number;\n vin: BlockchairVin[];\n vout: BlockchairVout[];\n };\n };\n}\n\ninterface BlockchairResponse<T> {\n data: T;\n context: {\n code: number;\n source: string;\n results: number;\n state: number;\n market_price_usd: number;\n cache: {\n live: boolean;\n duration: number;\n since: string;\n until: string;\n time: any;\n };\n api: {\n version: string;\n last_major_update: string;\n next_major_update: null | string;\n documentation: string;\n notice: string;\n };\n servers: string;\n time: number;\n render_time: number;\n full_time: number;\n request_cost: number;\n };\n}\n",
|
|
8
|
+
"import { SwapKitError } from \"@swapkit/helpers\";\nimport base58check from \"bs58check\";\n// @ts-ignore\nimport cashaddr from \"cashaddrjs\";\n\nenum Format {\n Legacy = \"legacy\",\n Bitpay = \"bitpay\",\n Cashaddr = \"cashaddr\",\n}\nenum UtxoNetwork {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n}\nenum Type {\n P2PKH = \"p2pkh\",\n P2SH = \"p2sh\",\n}\n\nconst VERSION_BYTE = {\n [Format.Legacy]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 0,\n [Type.P2SH]: 5,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n [Format.Bitpay]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 28,\n [Type.P2SH]: 40,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n};\n\ntype DecodedType = {\n format: Format;\n network: UtxoNetwork;\n type: Type;\n hash: any;\n};\n\nfunction isValidAddress(input: any) {\n try {\n decodeAddress(input);\n return true;\n } catch (_error) {\n return false;\n }\n}\n\nfunction detectAddressNetwork(address: string) {\n return decodeAddress(address)?.network;\n}\n\nfunction toLegacyAddress(address: string): string {\n const decoded = decodeAddress(address);\n if (decoded?.format === Format.Legacy) {\n return address;\n }\n return encodeAsLegacy(decoded);\n}\n\nfunction toCashAddress(address: string): string {\n const decoded = decodeAddress(address);\n return encodeAsCashaddr(decoded);\n}\n\nfunction decodeAddress(address: string) {\n try {\n return decodeBase58Address(address);\n } catch (_error) {\n // Try to decode as cashaddr if base58 decoding fails.\n }\n try {\n return decodeCashAddress(address);\n } catch (_error) {\n // Try to decode as bitpay if cashaddr decoding fails.\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeBase58Address(address: string) {\n try {\n const payload = base58check.decode(address);\n\n // BASE_58_CHECK_PAYLOAD_LENGTH\n if (payload.length !== 21) throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n const versionByte = payload[0];\n const hash = Array.prototype.slice.call(payload, 1);\n\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n default:\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction decodeCashAddress(address: string) {\n if (address.indexOf(\":\") !== -1) {\n try {\n return decodeCashAddressWithPrefix(address);\n } catch (_error) {\n // Try to decode as legacy if cashaddr decoding fails.\n }\n } else {\n const prefixes = [\"bitcoincash\", \"bchtest\", \"bchreg\"];\n for (const prefix of prefixes) {\n try {\n return decodeCashAddressWithPrefix(`${prefix}:${address}`);\n } catch (_error) {\n // Try next prefix if decoding fails.\n }\n }\n }\n\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeCashAddressWithPrefix(address: string): DecodedType {\n try {\n const { hash, prefix, type } = cashaddr.decode(address);\n\n return {\n format: Format.Cashaddr,\n hash: Array.prototype.slice.call(hash, 0),\n network: prefix === \"bitcoincash\" ? UtxoNetwork.Mainnet : UtxoNetwork.Testnet,\n type: type === \"P2PKH\" ? Type.P2PKH : Type.P2SH,\n };\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction encodeAsLegacy(decoded: DecodedType) {\n const versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type];\n const buffer = Buffer.alloc(1 + decoded.hash.length);\n buffer[0] = versionByte;\n buffer.set(decoded.hash, 1);\n return base58check.encode(buffer);\n}\n\nfunction encodeAsCashaddr(decoded: DecodedType) {\n const prefix = decoded.network === UtxoNetwork.Mainnet ? \"bitcoincash\" : \"bchtest\";\n const type = decoded.type === Type.P2PKH ? \"P2PKH\" : \"P2SH\";\n const hash = new Uint8Array(decoded.hash);\n return cashaddr.encode(prefix, type, hash);\n}\n\nexport { detectAddressNetwork, isValidAddress, UtxoNetwork, toCashAddress, toLegacyAddress };\n",
|
|
9
|
+
"import { Chain, SwapKitError, type UTXOChain } from \"@swapkit/helpers\";\n\nimport {\n TX_OVERHEAD,\n UTXOScriptType,\n calculateTxSize,\n getInputSize,\n getOutputSize,\n getScriptTypeForAddress,\n} from \"../helpers\";\nimport type { TargetOutput, UTXOCalculateTxSizeParams, UTXOType } from \"../types\";\n\nexport const getDustThreshold = (chain: UTXOChain) => {\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n return 550;\n case Chain.Dash:\n case Chain.Litecoin:\n return 5500;\n case Chain.Dogecoin:\n return 100000;\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n};\n\nexport const accumulative = ({\n inputs,\n outputs,\n feeRate: initialFeeRate = 1,\n chain = Chain.Bitcoin,\n}: UTXOCalculateTxSizeParams & { outputs: TargetOutput[]; chain: UTXOChain }) => {\n const feeRate = Math.ceil(initialFeeRate);\n\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n // skip input if adding it would cost more than input is worth\n const filteredInputs = inputs.filter((input) => getInputSize(input) * feeRate <= input.value);\n\n const txSizeWithoutInputs =\n TX_OVERHEAD + outputs.reduce((total, output) => total + getOutputSize(output, newTxType), 0);\n\n const amountToSend = outputs.reduce((total, output) => total + output.value, 0);\n\n let fees = txSizeWithoutInputs * feeRate;\n let inputsValue = 0;\n const inputsToUse: typeof inputs = [];\n\n for (const input of filteredInputs) {\n const inputSize = getInputSize(input);\n const inputFee = feeRate * inputSize;\n\n fees += inputFee;\n inputsValue += input.value;\n\n inputsToUse.push(input);\n\n const totalCost = fees + amountToSend;\n\n // we need more inputs\n if (inputsValue < totalCost) continue;\n\n const remainder = inputsValue - totalCost;\n\n const feeForExtraOutput = feeRate * getOutputSize({ address: \"\", value: 0 }, newTxType);\n\n // potential change address\n if (remainder > feeForExtraOutput) {\n const feeAfterExtraOutput = feeForExtraOutput + fees;\n const remainderAfterExtraOutput = inputsValue - (amountToSend + feeAfterExtraOutput);\n\n // is it worth a change output aka can we send it in the future?\n if (\n remainderAfterExtraOutput >\n Math.max(getInputSize({} as UTXOType) * feeRate, getDustThreshold(chain))\n ) {\n return {\n inputs: inputsToUse,\n outputs: outputs.concat({ value: remainderAfterExtraOutput, address: \"\" }),\n fee: feeAfterExtraOutput,\n };\n }\n }\n return {\n inputs: inputsToUse,\n outputs,\n fee: fees,\n };\n }\n\n // We don't have enough inputs, let's calculate transaction fee accrude to the last input\n return { fee: feeRate * calculateTxSize({ inputs, outputs, feeRate }) };\n};\n",
|
|
10
|
+
"import { SwapKitError } from \"@swapkit/helpers\";\nimport { opcodes, script } from \"bitcoinjs-lib\";\nimport type {\n TargetOutput,\n UTXOCalculateTxSizeParams,\n UTXOInputWithScriptType,\n UTXOType,\n} from \"../types\";\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000;\nexport const TX_OVERHEAD = 4 + 1 + 1 + 4; //10\nexport const OP_RETURN_OVERHEAD = 1 + 8 + 1; //10\nconst TX_INPUT_BASE = 32 + 4 + 1 + 4; // 41\nconst TX_INPUT_PUBKEYHASH = 107;\n\nexport function compileMemo(memo: string) {\n const data = Buffer.from(memo, \"utf8\"); // converts MEMO to buffer\n return script.compile([opcodes.OP_RETURN as number, data]); // Compile OP_RETURN script\n}\n\nexport enum UTXOScriptType {\n P2PKH = \"P2PKH\", // legacy\n // P2SH = 'P2SH', // multisig\n P2WPKH = \"P2WPKH\", // bech32 - native segwit\n // P2TR = \"P2TR\", // taproot\n}\n\nexport const InputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 148,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 68,\n};\n\nexport const OutputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 34,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 31,\n};\n\nexport const getScriptTypeForAddress = (address: string) => {\n if (address.startsWith(\"bc1\") || address.startsWith(\"ltc1\")) {\n return UTXOScriptType.P2WPKH;\n }\n // if (address.startsWith('3') || address.startsWith('M')) {\n // return UTXOScriptType.P2SH;\n // }\n if (\n address.startsWith(\"1\") ||\n address.startsWith(\"3\") ||\n address.startsWith(\"L\") ||\n address.startsWith(\"M\") ||\n address.startsWith(\"X\") ||\n address.startsWith(\"D\") ||\n address.startsWith(\"bitcoincash:q\") ||\n address.startsWith(\"q\")\n ) {\n return UTXOScriptType.P2PKH;\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n};\n\nexport const calculateTxSize = ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => {\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n const inputSize = inputs\n .filter(\n (utxo) =>\n utxo.value >=\n InputSizes[\"type\" in utxo ? utxo.type : UTXOScriptType.P2PKH] * Math.ceil(feeRate),\n )\n .reduce((total, utxo) => total + getInputSize(utxo), 0);\n\n const outputSize =\n outputs?.reduce((total, output) => total + getOutputSize(output), 0) || OutputSizes[newTxType];\n\n return TX_OVERHEAD + inputSize + outputSize;\n};\n\nexport const getInputSize = (input: UTXOInputWithScriptType | UTXOType) => {\n if (\"type\" in input) {\n return InputSizes[input.type];\n }\n if (\"address\" in input && input.address) {\n return InputSizes[getScriptTypeForAddress(input.address as string)];\n }\n return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH;\n};\n\nexport const getOutputSize = (output: TargetOutput, scriptType?: UTXOScriptType) => {\n if (output?.script) {\n return OP_RETURN_OVERHEAD + output.script.length + (output.script.length >= 74 ? 2 : 1);\n }\n if (scriptType) {\n return OutputSizes[scriptType];\n }\n return OutputSizes[UTXOScriptType.P2PKH];\n};\n",
|
|
11
|
+
"import {\n AssetValue,\n Chain,\n type ChainSigner,\n DerivationPath,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n SwapKitNumber,\n type UTXOChain,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt, address as btcLibAddress, initEccLib, payments } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } from \"ecpair\";\nimport ECPairFactory from \"ecpair\";\nimport type { UtxoToolboxParams } from \".\";\nimport { getBalance } from \"../../utils\";\nimport {\n UTXOScriptType,\n accumulative,\n calculateTxSize,\n compileMemo,\n getDustThreshold,\n getInputSize,\n getUtxoApi,\n getUtxoNetwork,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { bchValidateAddress } from \"./bitcoinCash\";\n\nimport secp256k1 from \"@bitcoinerlab/secp256k1\";\n// @ts-ignore\nimport { ECPair, HDNode } from \"@psf/bitcoincashjs-lib\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\n\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nfunction addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n}: {\n inputs: UTXOType[];\n outputs: TargetOutput[];\n chain: UTXOChain;\n psbt: Psbt;\n sender: string;\n compiledMemo: Buffer<ArrayBufferLike> | null;\n}) {\n for (const utxo of inputs) {\n const witnessInfo = !!utxo.witnessUtxo &&\n !nonSegwitChains.includes(chain) && { witnessUtxo: utxo.witnessUtxo };\n\n const nonWitnessInfo = nonSegwitChains.includes(chain) && {\n nonWitnessUtxo: utxo.txHex ? Buffer.from(utxo.txHex, \"hex\") : undefined,\n };\n\n psbt.addInput({ hash: utxo.hash, index: utxo.index, ...witnessInfo, ...nonWitnessInfo });\n }\n\n for (const output of outputs) {\n const address = \"address\" in output && output.address ? output.address : sender;\n const hasOutputScript = output.script;\n\n if (hasOutputScript && !compiledMemo) {\n continue;\n }\n\n const mappedOutput = hasOutputScript\n ? {\n script: compiledMemo as Buffer<ArrayBufferLike>,\n value: 0,\n }\n : {\n address,\n value: output.value,\n };\n\n initEccLib(secp256k1);\n psbt.addOutput(mappedOutput);\n }\n\n return { psbt, inputs };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n fetchTxHex = false,\n}: UTXOBuildTxParams): Promise<{\n psbt: Psbt;\n utxos: UTXOType[];\n inputs: UTXOType[];\n}> {\n const chain = assetValue.chain as UTXOChain;\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex,\n });\n\n const { inputs, outputs } = accumulative({ ...inputsAndOutputs, feeRate, chain });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) });\n\n if (chain === Chain.Dogecoin) psbt.setMaximumFeeRate(650000000);\n\n const { psbt: mappedPsbt, inputs: mappedInputs } = await addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n });\n\n return {\n psbt: mappedPsbt,\n utxos: inputsAndOutputs.inputs,\n inputs: mappedInputs,\n };\n}\n\nexport async function getUTXOAddressValidator() {\n const getNetwork = await getUtxoNetwork();\n\n return function validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {\n if (chain === Chain.BitcoinCash) {\n return bchValidateAddress(address);\n }\n\n try {\n initEccLib(secp256k1);\n btcLibAddress.toOutputScript(address, getNetwork(chain));\n return true;\n } catch (_error) {\n return false;\n }\n };\n}\n\nasync function createSignerWithKeys({\n chain,\n phrase,\n derivationPath,\n}: { chain: UTXOChain; phrase: string; derivationPath: string }) {\n const keyPair = (await getCreateKeysForPath(chain as Chain.Bitcoin))({ phrase, derivationPath });\n\n async function signTransaction(psbt: Psbt) {\n await psbt.signAllInputs(keyPair);\n return psbt;\n }\n\n async function getAddress() {\n const addressGetter = await addressFromKeysGetter(chain);\n return addressGetter(keyPair);\n }\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createUTXOToolbox<T extends UTXOChain>({\n chain,\n ...toolboxParams\n}: (\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n }\n) & { chain: T }) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const signer = phrase\n ? await createSignerWithKeys({ chain, phrase, derivationPath })\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n // const { signer } = params || {};\n const getAddressFromKeys = await addressFromKeysGetter(chain);\n const validateAddress = await getUTXOAddressValidator();\n const createKeysForPath = await getCreateKeysForPath(chain);\n\n return {\n accumulative,\n calculateTxSize,\n getAddressFromKeys,\n getAddress,\n validateAddress: (address: string) => validateAddress({ address, chain }),\n broadcastTx: (txHash: string) => getUtxoApi(chain).broadcastTx(txHash),\n createTransaction,\n createKeysForPath,\n getFeeRates: () => getFeeRates(chain),\n getInputsOutputsFee,\n transfer: transfer(signer as UtxoToolboxParams[\"BTC\"][\"signer\"]),\n getPrivateKeyFromMnemonic: (params: { phrase: string; derivationPath: string }) => {\n const keys = createKeysForPath(params);\n return keys.toWIF();\n },\n\n getBalance: getBalance(chain),\n estimateTransactionFee: estimateTransactionFee(chain),\n estimateMaxSendableAmount: estimateMaxSendableAmount(chain),\n };\n}\n\nasync function getInputsOutputsFee({\n assetValue,\n feeOptionKey = FeeOption.Fast,\n feeRate,\n memo,\n sender,\n recipient,\n}: Omit<UTXOBuildTxParams, \"feeRate\"> & {\n feeOptionKey?: FeeOption;\n feeRate?: number;\n}) {\n const chain = assetValue.chain as UTXOChain;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n sender,\n memo,\n recipient,\n });\n\n const feeRateWhole = feeRate ? Math.floor(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n return accumulative({ ...inputsAndOutputs, feeRate: feeRateWhole, chain });\n}\n\nfunction estimateMaxSendableAmount(chain: UTXOChain) {\n return async function estimateMaxSendableAmount({\n from,\n memo,\n feeRate,\n feeOptionKey = FeeOption.Fast,\n recipients = 1,\n }: {\n from: string;\n memo?: string;\n feeRate?: number;\n feeOptionKey?: FeeOption;\n recipients?: number | TargetOutput[];\n }) {\n const addressData = await getUtxoApi(chain).getAddressData(from);\n const feeRateWhole = feeRate ? Math.ceil(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n const inputs = addressData?.utxo\n .map((utxo) => ({\n ...utxo,\n // type: utxo.witnessUtxo ? UTXOScriptType.P2WPKH : UTXOScriptType.P2PKH,\n type: UTXOScriptType.P2PKH,\n hash: \"\",\n }))\n .filter(\n (utxo) => utxo.value > Math.max(getDustThreshold(chain), getInputSize(utxo) * feeRateWhole),\n );\n\n if (!inputs?.length) return AssetValue.from({ chain });\n\n const balance = AssetValue.from({\n chain,\n value: inputs.reduce((sum, utxo) => sum + utxo.value, 0),\n });\n\n const outputs =\n typeof recipients === \"number\"\n ? (Array.from({ length: recipients }, () => ({\n address: from,\n value: 0,\n })) as TargetOutput[])\n : recipients;\n\n if (memo) {\n const script = await compileMemo(memo);\n outputs.push({ address: from, script, value: 0 });\n }\n\n const txSize = calculateTxSize({ inputs, outputs, feeRate: feeRateWhole });\n\n const fee = txSize * feeRateWhole;\n\n return balance.sub(fee);\n };\n}\n\nfunction estimateTransactionFee(chain: UTXOChain) {\n return async (params: {\n assetValue: AssetValue;\n recipient: string;\n sender: string;\n memo?: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) => {\n const inputFees = await getInputsOutputsFee(params);\n\n return AssetValue.from({\n chain,\n value: SwapKitNumber.fromBigInt(BigInt(inputFees.fee), 8).getValue(\"string\"),\n });\n };\n}\n\ntype CreateKeysForPathReturnType = {\n [Chain.BitcoinCash]: BchECPair;\n [Chain.Bitcoin]: ECPairInterface;\n [Chain.Dash]: ECPairInterface;\n [Chain.Dogecoin]: ECPairInterface;\n [Chain.Litecoin]: ECPairInterface;\n};\n\nexport async function getCreateKeysForPath<T extends keyof CreateKeysForPathReturnType>(\n chain: T,\n): Promise<\n (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T]\n> {\n const getNetwork = await getUtxoNetwork();\n\n switch (chain) {\n case Chain.BitcoinCash: {\n return function createKeysForPath({\n phrase,\n derivationPath = `${DerivationPath.BCH}/0`,\n wif,\n }: { wif?: string; phrase?: string; derivationPath?: string }) {\n const network = getNetwork(chain);\n\n if (wif) {\n return ECPair.fromWIF(wif, network) as BchECPair;\n }\n if (!phrase)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"No phrase provided\" });\n\n const masterHDNode = HDNode.fromSeedBuffer(\n Buffer.from(mnemonicToSeedSync(phrase)),\n network,\n );\n const keyPair = masterHDNode.derivePath(derivationPath).keyPair;\n\n return keyPair as BchECPair;\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n return function createKeysForPath({\n phrase,\n wif,\n derivationPath,\n }: { phrase?: string; wif?: string; derivationPath: string }) {\n if (!(wif || phrase))\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Either phrase or wif must be provided\",\n });\n\n const factory = ECPairFactory(secp256k1);\n const network = getNetwork(chain);\n\n if (wif) return factory.fromWIF(wif, network);\n\n const seed = mnemonicToSeedSync(phrase as string);\n const master = HDKey.fromMasterSeed(seed, network).derive(derivationPath);\n if (!master.privateKey)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Could not get private key from phrase\",\n });\n\n return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport async function addressFromKeysGetter(chain: UTXOChain) {\n const getNetwork = await getUtxoNetwork();\n\n return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {\n if (!keys)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Keys must be provided\" });\n\n const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;\n const { address } = method({ pubkey: keys.publicKey as Buffer, network: getNetwork(chain) });\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { error: \"Address not defined\" });\n\n return address;\n };\n}\n\nfunction transfer(signer?: ChainSigner<Psbt, Psbt>) {\n return async function transfer({\n memo,\n recipient,\n feeOptionKey,\n feeRate,\n assetValue,\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n\n const chain = assetValue.chain as UTXOChain;\n\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await createTransaction({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n assetValue,\n memo,\n });\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return getUtxoApi(chain).broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return {\n [FeeOption.Average]: suggestedFeeRate,\n [FeeOption.Fast]: suggestedFeeRate * 1.5,\n [FeeOption.Fastest]: suggestedFeeRate * 2.0,\n };\n}\n\nasync function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex: fetchTxOverwrite = false,\n}: Omit<UTXOBuildTxParams, \"feeRate\">) {\n const chain = assetValue.chain as UTXOChain;\n\n const fetchTxHex = fetchTxOverwrite || nonSegwitChains.includes(chain);\n\n const inputs = await getUtxoApi(chain).scanUTXOs({ address: sender, fetchTxHex });\n\n //1. add output amount and recipient to targets\n //2. add output memo to targets (optional)\n\n return {\n inputs,\n outputs: [\n { address: recipient, value: Number(assetValue.bigIntValue) },\n ...(memo ? [{ address: \"\", script: await compileMemo(memo), value: 0 }] : []),\n ],\n };\n}\n"
|
|
12
|
+
],
|
|
13
|
+
"mappings": "uFAAA,cACE,kBAGA,0BCJF,sBACE,yBACA,cACA,gCAGF,gBACE,gBAGA,4BACA,mBACA,4BACA,2BACA,0BAEF,eAAS,uBChBT,gBACE,mBACA,cACA,kBACA,cAEA,0BAEF,mBAAS,uBAIT,wBASA,eAAe,EAAe,EAAG,QAAO,UAA4C,CAClF,IAAM,EAAS,EAAS,IAAI,SAAS,EAAE,GACjC,EAAO,KAAK,UAAU,CAC1B,QAAS,MACT,OAAQ,qBACR,OAAQ,CAAC,CAAM,EACf,GAAI,GAAO,CACb,CAAC,EAEK,EAAW,MAAM,EAAc,KAIlC,EAAQ,CAAE,QAAS,CAAE,eAAgB,kBAAmB,EAAG,MAAK,CAAC,EAEpE,GAAI,EAAS,MACX,MAAM,IAAI,EAAa,gCAAiC,CAAE,MAAO,EAAS,OAAO,OAAQ,CAAC,EAG5F,GAAI,EAAS,OAAO,SAAS,YAAY,EACvC,MAAM,IAAI,EAAa,mCAAoC,CACzD,MAAO,gCACT,CAAC,EAGH,OAAO,EAAS,OAGlB,SAAS,CAAO,CAAC,EAAc,CAC7B,MAAO,8BAA8B,GAA0B,CAAK,IAGtE,SAAS,EAAsB,CAAC,EAAc,CAC5C,OAAQ,QACD,EAAM,QACT,MAAO,QACJ,EAAM,SACT,MAAO,UACJ,EAAM,SACT,MAAO,WAEP,MAAO,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EAAa,CACvC,OAAQ,EACR,QAAS,EACT,QAAS,EACT,OACF,CAAC,EAGD,KAAM,GAAU,GACd,MAAM,IAAI,EAAa,oCAAqC,CAAE,SAAQ,YAAW,CAAC,EACpF,IAAM,EAAa,MAAM,EAAe,EAClC,EAAO,IAAI,GAAK,CAAE,QAAS,EAAW,CAAK,CAAE,CAAC,EAEpD,QAAa,OAAM,QAAO,iBAAiB,EACzC,EAAK,SAAS,CAAE,OAAM,QAAO,aAAY,CAAC,EAI5C,QAAW,KAAU,EAAS,CAC5B,IAAM,EACJ,YAAa,GAAU,EAAO,QAAU,EAAO,QAAU,EAAgB,CAAM,EAC3E,EAAS,EAAO,OAClB,EACE,CAAE,OAAQ,EAAc,MAAO,CAAE,EACjC,OACF,CAAE,UAAS,MAAO,EAAO,KAAM,EAEnC,GAAI,EACF,EAAK,UAAU,CAAM,EAIzB,MAAO,CAAE,OAAM,QAAO,OAAQ,CAAqB,EAGrD,SAAS,EAAkB,CAAC,EAAkD,CAC5E,IAAM,EAAU,EAAK,WAAW,CAAC,EACjC,OAAO,EAAmB,CAAO,EDjQnC,eAAsB,EAA6C,CACjE,EACA,EAO2B,CAC3B,OAAQ,QACD,EAAM,YAET,OADgB,MAAM,GAAiB,CAA8C,OAIlF,EAAM,aACN,EAAM,cACN,EAAM,cACN,EAAM,KAKT,OAJgB,MAAM,EAAkB,CACtC,WACI,CACN,CAAC,UAKD,MAAM,IAAI,GAAa,6BAA8B,CAAE,OAAM,CAAC",
|
|
14
|
+
"debugId": "A3DD28B1B9CE223364756E2164756E21",
|
|
15
|
+
"names": []
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"@solana/spl-memo": "0.2.5",
|
|
24
24
|
"@solana/spl-token": "0.4.13",
|
|
25
25
|
"@solana/web3.js": "1.98.2",
|
|
26
|
-
"@swapkit/helpers": "3.0.0-beta.
|
|
26
|
+
"@swapkit/helpers": "3.0.0-beta.13",
|
|
27
27
|
"base64-js": "1.5.1",
|
|
28
28
|
"bitcoinjs-lib": "6.1.7",
|
|
29
29
|
"bs58check": "4.0.0",
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
"ethers": "6.14.3",
|
|
35
35
|
"micro-key-producer": "0.7.6",
|
|
36
36
|
"protobufjs": "7.5.3",
|
|
37
|
+
"tronweb": "6.0.3",
|
|
37
38
|
"ts-pattern": "5.7.1",
|
|
38
39
|
"xrpl": "4.3.0"
|
|
39
40
|
},
|
|
@@ -48,43 +49,48 @@
|
|
|
48
49
|
},
|
|
49
50
|
"exports": {
|
|
50
51
|
".": {
|
|
51
|
-
"default": "./dist/index.js",
|
|
52
|
-
"require": "./dist/index.cjs",
|
|
52
|
+
"default": "./dist/src/index.js",
|
|
53
|
+
"require": "./dist/src/index.cjs",
|
|
53
54
|
"types": "./src/index.ts"
|
|
54
55
|
},
|
|
55
56
|
"./cosmos": {
|
|
56
|
-
"default": "./dist/cosmos/index.js",
|
|
57
|
-
"require": "./dist/cosmos/index.cjs",
|
|
57
|
+
"default": "./dist/src/cosmos/index.js",
|
|
58
|
+
"require": "./dist/src/cosmos/index.cjs",
|
|
58
59
|
"types": "./src/cosmos/index.ts"
|
|
59
60
|
},
|
|
60
61
|
"./evm": {
|
|
61
|
-
"default": "./dist/evm/index.js",
|
|
62
|
-
"require": "./dist/evm/index.cjs",
|
|
62
|
+
"default": "./dist/src/evm/index.js",
|
|
63
|
+
"require": "./dist/src/evm/index.cjs",
|
|
63
64
|
"types": "./src/evm/index.ts"
|
|
64
65
|
},
|
|
65
66
|
"./radix": {
|
|
66
|
-
"default": "./dist/radix/index.js",
|
|
67
|
-
"require": "./dist/radix/index.cjs",
|
|
67
|
+
"default": "./dist/src/radix/index.js",
|
|
68
|
+
"require": "./dist/src/radix/index.cjs",
|
|
68
69
|
"types": "./src/radix/index.ts"
|
|
69
70
|
},
|
|
70
71
|
"./ripple": {
|
|
71
|
-
"default": "./dist/ripple/index.js",
|
|
72
|
-
"require": "./dist/ripple/index.cjs",
|
|
72
|
+
"default": "./dist/src/ripple/index.js",
|
|
73
|
+
"require": "./dist/src/ripple/index.cjs",
|
|
73
74
|
"types": "./src/ripple/index.ts"
|
|
74
75
|
},
|
|
75
76
|
"./solana": {
|
|
76
|
-
"default": "./dist/solana/index.js",
|
|
77
|
-
"require": "./dist/solana/index.cjs",
|
|
77
|
+
"default": "./dist/src/solana/index.js",
|
|
78
|
+
"require": "./dist/src/solana/index.cjs",
|
|
78
79
|
"types": "./src/solana/index.ts"
|
|
79
80
|
},
|
|
80
81
|
"./substrate": {
|
|
81
|
-
"default": "./dist/substrate/index.js",
|
|
82
|
-
"require": "./dist/substrate/index.cjs",
|
|
82
|
+
"default": "./dist/src/substrate/index.js",
|
|
83
|
+
"require": "./dist/src/substrate/index.cjs",
|
|
83
84
|
"types": "./src/substrate/index.ts"
|
|
84
85
|
},
|
|
86
|
+
"./tron": {
|
|
87
|
+
"default": "./dist/src/tron/index.js",
|
|
88
|
+
"require": "./dist/src/tron/index.cjs",
|
|
89
|
+
"types": "./src/tron/index.ts"
|
|
90
|
+
},
|
|
85
91
|
"./utxo": {
|
|
86
|
-
"default": "./dist/utxo/index.js",
|
|
87
|
-
"require": "./dist/utxo/index.cjs",
|
|
92
|
+
"default": "./dist/src/utxo/index.js",
|
|
93
|
+
"require": "./dist/src/utxo/index.cjs",
|
|
88
94
|
"types": "./src/utxo/index.ts"
|
|
89
95
|
}
|
|
90
96
|
},
|
|
@@ -105,5 +111,5 @@
|
|
|
105
111
|
"type-check:go": "tsgo"
|
|
106
112
|
},
|
|
107
113
|
"type": "module",
|
|
108
|
-
"version": "1.0.0-beta.
|
|
114
|
+
"version": "1.0.0-beta.18"
|
|
109
115
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { base64, bech32 } from "@scure/base";
|
|
2
|
+
import { SwapKitError } from "@swapkit/helpers";
|
|
2
3
|
import { fromByteArray, toByteArray } from "base64-js";
|
|
3
4
|
|
|
4
5
|
export function bech32ToBase64(address: string) {
|
|
@@ -17,7 +18,9 @@ export function toBase64(data: Uint8Array) {
|
|
|
17
18
|
|
|
18
19
|
export function fromBase64(base64String: string) {
|
|
19
20
|
if (!base64String.match(/^[a-zA-Z0-9+/]*={0,2}$/)) {
|
|
20
|
-
throw new
|
|
21
|
+
throw new SwapKitError("toolbox_cosmos_invalid_params", {
|
|
22
|
+
error: "Invalid base64 string format",
|
|
23
|
+
});
|
|
21
24
|
}
|
|
22
25
|
return toByteArray(base64String);
|
|
23
26
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TxBodyEncodeObject } from "@cosmjs/proto-signing";
|
|
2
|
-
import { AssetValue, Chain, ChainToChainId } from "@swapkit/helpers";
|
|
2
|
+
import { AssetValue, Chain, ChainToChainId, SwapKitError } from "@swapkit/helpers";
|
|
3
3
|
|
|
4
4
|
import {
|
|
5
5
|
createStargateClient,
|
|
@@ -104,7 +104,7 @@ const getAccount = async ({ rpcUrl, sender }: { sender: string; rpcUrl: string }
|
|
|
104
104
|
const account = await client.getAccount(sender);
|
|
105
105
|
|
|
106
106
|
if (!account) {
|
|
107
|
-
throw new
|
|
107
|
+
throw new SwapKitError("toolbox_cosmos_account_not_found", { sender });
|
|
108
108
|
}
|
|
109
109
|
|
|
110
110
|
return account;
|
|
@@ -38,8 +38,7 @@ export async function fetchFeeRateFromSwapKit(chainId: ChainId, safeDefault: num
|
|
|
38
38
|
const responseGasRate = response.find((gas) => gas.chainId === chainId)?.value;
|
|
39
39
|
|
|
40
40
|
return responseGasRate ? Number.parseFloat(responseGasRate) : safeDefault;
|
|
41
|
-
} catch (
|
|
42
|
-
console.error(e);
|
|
41
|
+
} catch (_e) {
|
|
43
42
|
return safeDefault;
|
|
44
43
|
}
|
|
45
44
|
}
|
|
@@ -217,8 +216,7 @@ export async function getFeeRateFromThorswap(chainId: ChainId, safeDefault: numb
|
|
|
217
216
|
const responseGasRate = response.find((gas) => gas.chainId === chainId)?.value;
|
|
218
217
|
|
|
219
218
|
return responseGasRate ? Number.parseFloat(responseGasRate) : safeDefault;
|
|
220
|
-
} catch (
|
|
221
|
-
console.error(e);
|
|
219
|
+
} catch (_e) {
|
|
222
220
|
return safeDefault;
|
|
223
221
|
}
|
|
224
222
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Chain, type CosmosChain } from "@swapkit/helpers";
|
|
1
|
+
import { Chain, type CosmosChain, SwapKitError } from "@swapkit/helpers";
|
|
2
2
|
|
|
3
3
|
import type { CosmosToolboxParams } from "../types";
|
|
4
4
|
import { createCosmosToolbox } from "./cosmos";
|
|
@@ -25,7 +25,7 @@ export const getCosmosToolbox = <T extends CosmosChain>(
|
|
|
25
25
|
return createThorchainToolbox({ chain, ...params }) as CosmosToolboxes[T];
|
|
26
26
|
|
|
27
27
|
default:
|
|
28
|
-
throw new
|
|
28
|
+
throw new SwapKitError("toolbox_cosmos_not_supported", { chain });
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
31
|
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
NetworkDerivationPath,
|
|
10
10
|
RequestClient,
|
|
11
11
|
SKConfig,
|
|
12
|
+
SwapKitError,
|
|
12
13
|
SwapKitNumber,
|
|
13
14
|
derivationPathToString,
|
|
14
15
|
updateDerivationPath,
|
|
@@ -210,7 +211,7 @@ export async function createThorchainToolbox({
|
|
|
210
211
|
} = await RequestClient.get<ThorchainConstantsResponse>(constantsUrl);
|
|
211
212
|
|
|
212
213
|
if (!nativeFee || Number.isNaN(nativeFee) || nativeFee < 0) {
|
|
213
|
-
throw new
|
|
214
|
+
throw new SwapKitError("toolbox_cosmos_invalid_fee", { nativeFee: nativeFee.toString() });
|
|
214
215
|
}
|
|
215
216
|
|
|
216
217
|
fee = new SwapKitNumber(nativeFee);
|
|
@@ -231,7 +232,7 @@ export async function createThorchainToolbox({
|
|
|
231
232
|
}: Omit<GenericTransferParams, "recipient"> & { recipient?: string }) {
|
|
232
233
|
const { TxRaw } = await import("cosmjs-types/cosmos/tx/v1beta1/tx");
|
|
233
234
|
const sender = (await signer?.getAccounts())?.[0]?.address;
|
|
234
|
-
if (!(sender && signer)) throw new
|
|
235
|
+
if (!(sender && signer)) throw new SwapKitError("toolbox_cosmos_no_signer");
|
|
235
236
|
|
|
236
237
|
const isAminoSigner = "signAmino" in signer;
|
|
237
238
|
const registry = await createDefaultRegistry();
|