@swapkit/toolboxes 1.0.0-beta.23 → 1.0.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-12xtvbsp.js → chunk-6f98phv2.js} +2 -2
- package/dist/{chunk-12xtvbsp.js.map → chunk-6f98phv2.js.map} +1 -1
- package/dist/{chunk-kbnwrc5b.js → chunk-zcdeg6h9.js} +2 -2
- package/dist/{chunk-kbnwrc5b.js.map → chunk-zcdeg6h9.js.map} +1 -1
- package/dist/src/cosmos/index.cjs +2 -2
- package/dist/src/cosmos/index.cjs.map +6 -6
- package/dist/src/cosmos/index.js +2 -2
- package/dist/src/cosmos/index.js.map +6 -6
- package/dist/src/evm/index.js +2 -2
- package/dist/src/evm/index.js.map +1 -1
- package/dist/src/index.cjs +2 -2
- package/dist/src/index.cjs.map +3 -3
- package/dist/src/index.js +2 -2
- package/dist/src/index.js.map +3 -3
- package/dist/src/near/index.cjs +2 -2
- package/dist/src/near/index.cjs.map +3 -3
- package/dist/src/near/index.js +2 -2
- package/dist/src/near/index.js.map +3 -3
- package/dist/src/substrate/index.cjs +2 -2
- package/dist/src/substrate/index.cjs.map +5 -4
- package/dist/src/substrate/index.js +2 -2
- package/dist/src/substrate/index.js.map +5 -4
- package/dist/src/tron/index.cjs +2 -2
- package/dist/src/tron/index.cjs.map +3 -3
- package/dist/src/tron/index.js +2 -2
- package/dist/src/tron/index.js.map +3 -3
- package/dist/src/utxo/index.cjs +4 -2
- package/dist/src/utxo/index.cjs.map +8 -7
- package/dist/src/utxo/index.js +4 -2
- package/dist/src/utxo/index.js.map +8 -7
- package/package.json +2 -2
- package/src/cosmos/thorchainUtils/registry.ts +3 -3
- package/src/cosmos/toolbox/cosmos.ts +21 -7
- package/src/cosmos/toolbox/thorchain.ts +6 -6
- package/src/cosmos/util.ts +66 -3
- package/src/evm/__tests__/address-validation.test.ts +86 -0
- package/src/index.ts +1 -0
- package/src/near/toolbox.ts +22 -1
- package/src/substrate/balance.ts +92 -0
- package/src/substrate/substrate.ts +6 -4
- package/src/tron/toolbox.ts +1 -1
- package/src/utxo/__tests__/zcash-integration.test.ts +114 -0
- package/src/utxo/helpers/api.ts +36 -0
- package/src/utxo/helpers/coinselect.ts +2 -0
- package/src/utxo/index.ts +1 -0
- package/src/utxo/toolbox/index.ts +14 -3
- package/src/utxo/toolbox/utxo.ts +7 -0
- package/src/utxo/toolbox/zcash.ts +208 -0
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
{
|
|
2
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"],
|
|
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", "../src/utxo/toolbox/zcash.ts"],
|
|
4
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",
|
|
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\";\nimport { createZcashToolbox } from \"./zcash\";\n\ntype BCHToolbox = Awaited<ReturnType<typeof createBCHToolbox>>;\ntype CommonUTXOToolbox = Awaited<\n ReturnType<typeof createUTXOToolbox<Exclude<UTXOChain, Chain.BitcoinCash | Chain.Zcash>>>\n>;\ntype ZcashToolbox = Awaited<ReturnType<typeof createZcashToolbox>>;\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 [Chain.Zcash]: ZcashToolbox;\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 [Chain.Zcash]: {\n signer?: ChainSigner<Psbt, Psbt>;\n };\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.Zcash: {\n const toolbox = await createZcashToolbox(params as UtxoToolboxParams[Chain.Zcash]);\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 | Chain.Zcash>]),\n });\n return toolbox as UTXOToolboxes[Exclude<T, Chain.BitcoinCash | Chain.Zcash>];\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
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",
|
|
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 case Chain.Zcash:\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.Zcash:\n return \"zcash\";\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\n// Define Zcash network objects that match ECPair's expected interface\nconst ZCASH_MAINNET = {\n messagePrefix: \"\\x19Zcash Signed Message:\\n\",\n bech32: \"zc\",\n bip32: {\n public: 0x0488b21e,\n private: 0x0488ade4,\n },\n pubKeyHash: 0x1c, // 28 in decimal - correct for Zcash mainnet\n scriptHash: 0x1c, // 28 in decimal\n wif: 0x80, // 128 in decimal\n};\n\nconst ZCASH_TESTNET = {\n messagePrefix: \"\\x19Zcash Signed Message:\\n\",\n bech32: \"ztestsapling\",\n bip32: {\n public: 0x043587cf,\n private: 0x04358394,\n },\n pubKeyHash: 0x1d, // 29 in decimal - correct for Zcash testnet\n scriptHash: 0x1c, // 28 in decimal\n wif: 0xef, // 239 in decimal\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\n case Chain.Zcash: {\n // Get Zcash network configuration using our custom objects\n const { isStagenet } = SKConfig.get(\"envs\");\n return isStagenet ? ZCASH_TESTNET : ZCASH_MAINNET;\n }\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
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",
|
|
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 case Chain.Zcash:\n return 546;\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
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 applyFeeMultiplier,\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]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fast),\n [FeeOption.Fastest]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fastest),\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"
|
|
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 applyFeeMultiplier,\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\";\nimport { validateZcashAddress } from \"./zcash\";\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 if (chain === Chain.Zcash) {\n return validateZcashAddress(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 [Chain.Zcash]: 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.Zcash:\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]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fast),\n [FeeOption.Fastest]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fastest),\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
|
+
"import secp256k1 from \"@bitcoinerlab/secp256k1\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\nimport {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SKConfig,\n SwapKitError,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\nimport { hash160 } from \"bitcoinjs-lib/src/crypto\";\nimport bs58check from \"bs58check\";\nimport ECPairFactory from \"ecpair\";\nimport { P, match } from \"ts-pattern\";\nimport { getUtxoNetwork } from \"../helpers\";\nimport type { UTXOBuildTxParams, UTXOTransferParams } from \"../types\";\nimport { createUTXOToolbox } from \"./utxo\";\n\nconst chain = Chain.Zcash;\nconst network = getUtxoNetwork()(chain);\n\n/**\n * Custom Zcash address generation that handles 2-byte prefixes\n *\n * Zcash transparent addresses use 2-byte version prefixes, unlike Bitcoin's single byte.\n * This is incompatible with bitcoinjs-lib's payment methods which expect UInt8 values.\n *\n * @param publicKey - The public key buffer to generate address from\n * @param isTestnet - Whether to generate testnet or mainnet address\n * @returns A valid Zcash transparent address (t1... for mainnet, tm... for testnet)\n */\nfunction generateZcashAddress(publicKey: Buffer, isTestnet = false): string {\n // Hash the public key using RIPEMD160(SHA256(pubkey))\n const publicKeyHash = hash160(publicKey);\n\n // Zcash uses 2-byte prefixes for transparent addresses\n // These prefixes ensure addresses start with expected characters when base58 encoded\n const prefix = isTestnet\n ? Buffer.from([0x1c, 0xba]) // testnet prefix (results in tm... addresses)\n : Buffer.from([0x1c, 0xb8]); // mainnet prefix (results in t1... addresses)\n\n // Combine prefix + hash (22 bytes total: 2 byte prefix + 20 byte hash)\n const payload = Buffer.concat([prefix, publicKeyHash]);\n\n // Encode with base58check for final address\n return bs58check.encode(payload);\n}\n\nexport function validateZcashAddress(address: string) {\n try {\n // Shielded addresses are not supported\n if (address.startsWith(\"z\")) {\n console.warn(\n \"Shielded Zcash addresses (z-addresses) are not supported. Use transparent addresses (t1/t3) only.\",\n );\n return false;\n }\n\n const isMainnet = address.startsWith(\"t1\");\n const isTestnet = address.startsWith(\"t3\");\n\n if (!(isMainnet || isTestnet)) {\n return false;\n }\n\n // Verify network matches address type\n const { isStagenet } = SKConfig.get(\"envs\");\n if ((isMainnet && isStagenet) || (isTestnet && !isStagenet)) {\n return false;\n }\n\n return validateBase58Check(address, network);\n } catch {\n return false;\n }\n}\n\nfunction validateBase58Check(\n address: string,\n network: ReturnType<ReturnType<typeof getUtxoNetwork>>,\n) {\n try {\n const decoded = bs58check.decode(address);\n\n if (decoded.length < 21) {\n return false;\n }\n\n const version = decoded[0];\n return version === network.pubKeyHash || version === network.scriptHash;\n } catch {\n return false;\n }\n}\n\nconst ECPair = ECPairFactory(secp256k1);\n\ntype ZcashSigner = ChainSigner<Psbt, Psbt>;\n\nasync function createZcashSignerFromPhrase({\n phrase,\n derivationPathString,\n}: {\n phrase: string;\n derivationPathString: string;\n}) {\n const seed = mnemonicToSeedSync(phrase);\n const root = HDKey.fromMasterSeed(seed);\n\n const node = root.derive(derivationPathString);\n\n if (!node.privateKey) {\n throw new Error(\"Unable to derive private key\");\n }\n\n const keyPair = ECPair.fromPrivateKey(Buffer.from(node.privateKey), { network });\n\n const { isStagenet } = SKConfig.get(\"envs\");\n const address = generateZcashAddress(keyPair.publicKey, isStagenet);\n\n return {\n getAddress() {\n return Promise.resolve(address);\n },\n\n signTransaction(psbt: Psbt) {\n for (let i = 0; i < psbt.inputCount; i++) {\n psbt.signInput(i, keyPair);\n }\n return Promise.resolve(psbt);\n },\n };\n}\n\nexport async function createZcashToolbox(\n toolboxParams:\n | {\n signer?: ZcashSigner;\n }\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n) {\n const signer = await match(toolboxParams)\n .with({ signer: P.not(P.nullish) }, ({ signer }) => Promise.resolve(signer))\n .with({ phrase: P.string }, ({ phrase, derivationPath, index = 0 }) => {\n // Handle derivation path processing at toolbox level\n const baseDerivationPath = derivationPath ||\n NetworkDerivationPath[Chain.Zcash] || [44, 133, 0, 0, 0];\n const updatedDerivationPath = updateDerivationPath(baseDerivationPath, { index });\n const derivationPathString = derivationPathToString(updatedDerivationPath);\n\n return createZcashSignerFromPhrase({ phrase, derivationPathString });\n })\n .otherwise(() => Promise.resolve(undefined));\n\n const { getFeeRates, broadcastTx, ...toolbox } = await createUTXOToolbox({\n chain: Chain.Zcash,\n signer,\n });\n\n function getAddressFromKeys(keys: { getAddress: () => string }) {\n return keys.getAddress();\n }\n\n 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\n const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];\n\n const buildTxParams: UTXOBuildTxParams = {\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n };\n\n const { psbt } = await toolbox.createTransaction(buildTxParams);\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs();\n const txHex = signedPsbt.extractTransaction().toHex();\n\n return broadcastTx(txHex);\n }\n\n return {\n ...toolbox,\n broadcastTx,\n getFeeRates,\n transfer,\n getAddressFromKeys,\n validateAddress: validateZcashAddress,\n };\n}\n"
|
|
12
13
|
],
|
|
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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CAAE,OAAM,CAAC",
|
|
15
|
+
"debugId": "700A28C14D0CB40E64756E2164756E21",
|
|
15
16
|
"names": []
|
|
16
17
|
}
|
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.17",
|
|
27
27
|
"base64-js": "1.5.1",
|
|
28
28
|
"bitcoinjs-lib": "6.1.7",
|
|
29
29
|
"bs58check": "4.0.0",
|
|
@@ -119,5 +119,5 @@
|
|
|
119
119
|
"type-check:go": "tsgo"
|
|
120
120
|
},
|
|
121
121
|
"type": "module",
|
|
122
|
-
"version": "1.0.0-beta.
|
|
122
|
+
"version": "1.0.0-beta.24"
|
|
123
123
|
}
|
|
@@ -3,8 +3,8 @@ import { base64ToBech32, bech32ToBase64 } from "./addressFormat";
|
|
|
3
3
|
|
|
4
4
|
export async function createDefaultRegistry() {
|
|
5
5
|
const { $root } = await import("./types/MsgCompiled");
|
|
6
|
-
const { Registry } =
|
|
7
|
-
const { defaultRegistryTypes } =
|
|
6
|
+
const { Registry } = await import("@cosmjs/proto-signing");
|
|
7
|
+
const { defaultRegistryTypes } = await import("@cosmjs/stargate");
|
|
8
8
|
|
|
9
9
|
return new Registry([
|
|
10
10
|
...defaultRegistryTypes,
|
|
@@ -14,7 +14,7 @@ export async function createDefaultRegistry() {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export async function createDefaultAminoTypes(chain: Chain.THORChain | Chain.Maya) {
|
|
17
|
-
const { AminoTypes } =
|
|
17
|
+
const { AminoTypes } = await import("@cosmjs/stargate");
|
|
18
18
|
const aminoTypePrefix = chain === Chain.THORChain ? "thorchain" : "mayachain";
|
|
19
19
|
|
|
20
20
|
return new AminoTypes({
|
|
@@ -23,12 +23,12 @@ import {
|
|
|
23
23
|
} from "@swapkit/helpers";
|
|
24
24
|
import { SwapKitApi } from "@swapkit/helpers/api";
|
|
25
25
|
import { P, match } from "ts-pattern";
|
|
26
|
-
import { getBalance } from "../../utils";
|
|
27
26
|
import type { CosmosToolboxParams } from "../types";
|
|
28
27
|
import {
|
|
29
28
|
cosmosCreateTransaction,
|
|
30
29
|
createSigningStargateClient,
|
|
31
30
|
createStargateClient,
|
|
31
|
+
getAssetFromDenom,
|
|
32
32
|
getDenomWithChain,
|
|
33
33
|
getMsgSendDenom,
|
|
34
34
|
} from "../util";
|
|
@@ -52,8 +52,8 @@ export async function getSignerFromPhrase({
|
|
|
52
52
|
| { chain: Chain; index?: number }
|
|
53
53
|
| { derivationPath: string }
|
|
54
54
|
)) {
|
|
55
|
-
const { DirectSecp256k1HdWallet } =
|
|
56
|
-
const { stringToPath } =
|
|
55
|
+
const { DirectSecp256k1HdWallet } = await import("@cosmjs/proto-signing");
|
|
56
|
+
const { stringToPath } = await import("@cosmjs/crypto");
|
|
57
57
|
|
|
58
58
|
const derivationPath =
|
|
59
59
|
"derivationPath" in derivationParams
|
|
@@ -73,7 +73,7 @@ export async function getSignerFromPrivateKey({
|
|
|
73
73
|
privateKey: Uint8Array;
|
|
74
74
|
prefix: string;
|
|
75
75
|
}) {
|
|
76
|
-
const { DirectSecp256k1Wallet } =
|
|
76
|
+
const { DirectSecp256k1Wallet } = await import("@cosmjs/proto-signing");
|
|
77
77
|
|
|
78
78
|
return DirectSecp256k1Wallet.fromKey(privateKey, prefix);
|
|
79
79
|
}
|
|
@@ -97,7 +97,7 @@ export function verifySignature(getAccount: (address: string) => Promise<Account
|
|
|
97
97
|
}) {
|
|
98
98
|
const account = await getAccount(address);
|
|
99
99
|
if (!account?.pubkey) throw new SwapKitError("toolbox_cosmos_verify_signature_no_pubkey");
|
|
100
|
-
const { Secp256k1Signature, Secp256k1 } =
|
|
100
|
+
const { Secp256k1Signature, Secp256k1 } = await import("@cosmjs/crypto");
|
|
101
101
|
|
|
102
102
|
const secpSignature = Secp256k1Signature.fromFixedLength(base64.decode(signature));
|
|
103
103
|
return Secp256k1.verifySignature(secpSignature, base64.decode(message), account.pubkey.value);
|
|
@@ -185,7 +185,21 @@ export async function createCosmosToolbox({ chain, ...toolboxParams }: CosmosToo
|
|
|
185
185
|
transfer,
|
|
186
186
|
getAddress,
|
|
187
187
|
getAccount,
|
|
188
|
-
getBalance:
|
|
188
|
+
getBalance: async (address: string, _potentialScamFilter?: boolean) => {
|
|
189
|
+
const denomBalances = await cosmosBalanceDenomsGetter(rpcUrl)(address);
|
|
190
|
+
return await Promise.all(
|
|
191
|
+
denomBalances
|
|
192
|
+
.filter(({ denom }) => denom && !denom.includes("IBC/"))
|
|
193
|
+
.map(({ denom, amount }) => {
|
|
194
|
+
const fullDenom =
|
|
195
|
+
[Chain.THORChain, Chain.Maya].includes(chain) &&
|
|
196
|
+
(denom.includes("/") || denom.includes("˜"))
|
|
197
|
+
? `${chain}.${denom}`
|
|
198
|
+
: denom;
|
|
199
|
+
return getAssetFromDenom(fullDenom, amount);
|
|
200
|
+
}),
|
|
201
|
+
);
|
|
202
|
+
},
|
|
189
203
|
getSignerFromPhrase: async ({
|
|
190
204
|
phrase,
|
|
191
205
|
derivationPath,
|
|
@@ -197,7 +211,7 @@ export async function createCosmosToolbox({ chain, ...toolboxParams }: CosmosToo
|
|
|
197
211
|
index,
|
|
198
212
|
}),
|
|
199
213
|
getSignerFromPrivateKey: async (privateKey: Uint8Array) => {
|
|
200
|
-
const { DirectSecp256k1Wallet } =
|
|
214
|
+
const { DirectSecp256k1Wallet } = await import("@cosmjs/proto-signing");
|
|
201
215
|
return DirectSecp256k1Wallet.fromKey(privateKey, chainPrefix);
|
|
202
216
|
},
|
|
203
217
|
createPrivateKeyFromPhrase: createPrivateKeyFromPhrase(derivationPath),
|
|
@@ -44,8 +44,8 @@ function secp256k1HdWalletFromMnemonic({
|
|
|
44
44
|
derivationPath?: string;
|
|
45
45
|
}) {
|
|
46
46
|
return async function secp256k1HdWalletFromMnemonic(mnemonic: string, index = 0) {
|
|
47
|
-
const { Secp256k1HdWallet } =
|
|
48
|
-
const { stringToPath } =
|
|
47
|
+
const { Secp256k1HdWallet } = await import("@cosmjs/amino");
|
|
48
|
+
const { stringToPath } = await import("@cosmjs/crypto");
|
|
49
49
|
|
|
50
50
|
return Secp256k1HdWallet.fromMnemonic(mnemonic, {
|
|
51
51
|
hdPaths: [stringToPath(`${derivationPath}/${index}`)],
|
|
@@ -115,8 +115,8 @@ function broadcastMultisigTx({
|
|
|
115
115
|
threshold: number,
|
|
116
116
|
bodyBytes: Uint8Array,
|
|
117
117
|
) {
|
|
118
|
-
const { encodeSecp256k1Pubkey, pubkeyToAddress } =
|
|
119
|
-
const { makeMultisignedTxBytes } =
|
|
118
|
+
const { encodeSecp256k1Pubkey, pubkeyToAddress } = await import("@cosmjs/amino");
|
|
119
|
+
const { makeMultisignedTxBytes } = await import("@cosmjs/stargate");
|
|
120
120
|
|
|
121
121
|
const { sequence, fee } = JSON.parse(tx);
|
|
122
122
|
const multisigPubkey = await createMultisig(membersPubKeys, threshold);
|
|
@@ -163,7 +163,7 @@ async function signWithPrivateKey({
|
|
|
163
163
|
privateKey: Uint8Array;
|
|
164
164
|
message: string;
|
|
165
165
|
}) {
|
|
166
|
-
const { Secp256k1 } =
|
|
166
|
+
const { Secp256k1 } = await import("@cosmjs/crypto");
|
|
167
167
|
|
|
168
168
|
const signature = await Secp256k1.createSignature(base64.decode(message), privateKey);
|
|
169
169
|
return base64.encode(Buffer.concat([signature.r(32), signature.s(32)]));
|
|
@@ -303,7 +303,7 @@ export async function createThorchainToolbox({
|
|
|
303
303
|
signWithPrivateKey,
|
|
304
304
|
transfer,
|
|
305
305
|
pubkeyToAddress: async (pubkey: Pubkey) => {
|
|
306
|
-
const { pubkeyToAddress } =
|
|
306
|
+
const { pubkeyToAddress } = await import("@cosmjs/amino");
|
|
307
307
|
return pubkeyToAddress(pubkey, chainPrefix);
|
|
308
308
|
},
|
|
309
309
|
};
|
package/src/cosmos/util.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { OfflineSigner } from "@cosmjs/proto-signing";
|
|
|
2
2
|
import type { SigningStargateClientOptions } from "@cosmjs/stargate";
|
|
3
3
|
import {
|
|
4
4
|
AssetValue,
|
|
5
|
+
BaseDecimal,
|
|
5
6
|
Chain,
|
|
6
7
|
ChainId,
|
|
7
8
|
type CosmosChain,
|
|
@@ -76,7 +77,7 @@ export const getDenomWithChain = ({ symbol, chain }: AssetValue) => {
|
|
|
76
77
|
};
|
|
77
78
|
|
|
78
79
|
export async function createStargateClient(url: string) {
|
|
79
|
-
const { StargateClient } =
|
|
80
|
+
const { StargateClient } = await import("@cosmjs/stargate");
|
|
80
81
|
|
|
81
82
|
return StargateClient.connect(url);
|
|
82
83
|
}
|
|
@@ -86,7 +87,7 @@ export async function createSigningStargateClient(
|
|
|
86
87
|
signer: any,
|
|
87
88
|
optionsOrBaseGas: string | SigningStargateClientOptions = {},
|
|
88
89
|
) {
|
|
89
|
-
const { SigningStargateClient, GasPrice } =
|
|
90
|
+
const { SigningStargateClient, GasPrice } = await import("@cosmjs/stargate");
|
|
90
91
|
const gasPrice = typeof optionsOrBaseGas === "string" ? optionsOrBaseGas : "0.0003uatom";
|
|
91
92
|
const options = typeof optionsOrBaseGas === "string" ? {} : optionsOrBaseGas;
|
|
92
93
|
|
|
@@ -100,7 +101,7 @@ export async function createOfflineStargateClient(
|
|
|
100
101
|
wallet: OfflineSigner,
|
|
101
102
|
registry?: SigningStargateClientOptions,
|
|
102
103
|
) {
|
|
103
|
-
const { SigningStargateClient } =
|
|
104
|
+
const { SigningStargateClient } = await import("@cosmjs/stargate");
|
|
104
105
|
|
|
105
106
|
return SigningStargateClient.offline(wallet, registry);
|
|
106
107
|
}
|
|
@@ -185,3 +186,65 @@ export const cosmosCreateTransaction = async ({
|
|
|
185
186
|
msgs: [{ typeUrl: getTransferMsgTypeByChain(chain as CosmosChain), value: msgSend }],
|
|
186
187
|
};
|
|
187
188
|
};
|
|
189
|
+
|
|
190
|
+
// Map of known denoms to their asset configurations
|
|
191
|
+
const DENOM_MAP = {
|
|
192
|
+
// THORChain denoms
|
|
193
|
+
rune: { chain: Chain.THORChain, decimals: BaseDecimal[Chain.THORChain] },
|
|
194
|
+
tcy: { asset: "THOR.TCY", decimals: BaseDecimal[Chain.THORChain] },
|
|
195
|
+
"x/kuji": { asset: "THOR.KUJI", decimals: BaseDecimal[Chain.THORChain] },
|
|
196
|
+
|
|
197
|
+
// Cosmos denoms
|
|
198
|
+
uatom: { chain: Chain.Cosmos, decimals: BaseDecimal[Chain.Cosmos] },
|
|
199
|
+
atom: { chain: Chain.Cosmos, decimals: BaseDecimal[Chain.Cosmos] },
|
|
200
|
+
|
|
201
|
+
// Maya denoms
|
|
202
|
+
cacao: { chain: Chain.Maya, decimals: 10 }, // Maya uses 10 decimals for CACAO
|
|
203
|
+
maya: { asset: `${Chain.Maya}.${Chain.Maya}`, decimals: 4 }, // MAYA token uses 4 decimals
|
|
204
|
+
|
|
205
|
+
// Kujira denoms
|
|
206
|
+
ukuji: { chain: Chain.Kujira, decimals: BaseDecimal[Chain.Kujira] },
|
|
207
|
+
kuji: { chain: Chain.Kujira, decimals: BaseDecimal[Chain.Kujira] },
|
|
208
|
+
|
|
209
|
+
// USK on Kujira (lowercase version of the factory denom)
|
|
210
|
+
[USK_KUJIRA_FACTORY_DENOM.toLowerCase()]: {
|
|
211
|
+
asset: `${Chain.Kujira}.USK`,
|
|
212
|
+
decimals: BaseDecimal[Chain.Kujira],
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Converts a Cosmos denom and amount to an AssetValue with proper decimal handling
|
|
218
|
+
* @param denom - The denomination string
|
|
219
|
+
* @param amount - The amount in base units as a string
|
|
220
|
+
* @returns AssetValue with the correct decimal conversion
|
|
221
|
+
*/
|
|
222
|
+
export const getAssetFromDenom = (denom: string, amount: string) => {
|
|
223
|
+
const config = DENOM_MAP[denom.toLowerCase()];
|
|
224
|
+
|
|
225
|
+
if (!config) {
|
|
226
|
+
// For unknown denoms, default to 8 decimals (common for many Cosmos chains)
|
|
227
|
+
// This preserves the original behavior while using fromBaseDecimal
|
|
228
|
+
return AssetValue.from({
|
|
229
|
+
asset: denom,
|
|
230
|
+
value: amount,
|
|
231
|
+
fromBaseDecimal: 8,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const { chain, asset, decimals } = config;
|
|
236
|
+
|
|
237
|
+
const assetOrChain = (
|
|
238
|
+
chain
|
|
239
|
+
? {
|
|
240
|
+
chain,
|
|
241
|
+
}
|
|
242
|
+
: { asset }
|
|
243
|
+
) as { asset: string } | { chain: CosmosChain };
|
|
244
|
+
|
|
245
|
+
return AssetValue.from({
|
|
246
|
+
...assetOrChain,
|
|
247
|
+
value: amount,
|
|
248
|
+
fromBaseDecimal: decimals,
|
|
249
|
+
});
|
|
250
|
+
};
|