@swapkit/toolboxes 1.0.0-beta.0 → 1.0.0-beta.10

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.
Files changed (103) hide show
  1. package/dist/chunk-0f0249b1.js +3 -0
  2. package/dist/chunk-0f0249b1.js.map +10 -0
  3. package/dist/chunk-0h4xdrwz.js +4 -0
  4. package/dist/chunk-0h4xdrwz.js.map +10 -0
  5. package/dist/chunk-4yap1fvd.js +3 -0
  6. package/dist/chunk-4yap1fvd.js.map +10 -0
  7. package/dist/chunk-fjfxga2v.js +3 -0
  8. package/dist/chunk-fjfxga2v.js.map +10 -0
  9. package/dist/{chunk-tvrdndbw.js → chunk-p1kdg37m.js} +2 -2
  10. package/dist/{chunk-tvrdndbw.js.map → chunk-p1kdg37m.js.map} +1 -1
  11. package/dist/cosmos/index.cjs +2 -2
  12. package/dist/cosmos/index.cjs.map +10 -13
  13. package/dist/cosmos/index.js +2 -2
  14. package/dist/cosmos/index.js.map +10 -13
  15. package/dist/evm/index.cjs +2 -2
  16. package/dist/evm/index.cjs.map +10 -16
  17. package/dist/evm/index.js +2 -2
  18. package/dist/evm/index.js.map +10 -16
  19. package/dist/index.cjs +2 -2
  20. package/dist/index.cjs.map +4 -3
  21. package/dist/index.js +2 -2
  22. package/dist/index.js.map +4 -3
  23. package/dist/radix/index.cjs +2 -2
  24. package/dist/radix/index.cjs.map +3 -3
  25. package/dist/radix/index.js +2 -2
  26. package/dist/radix/index.js.map +3 -3
  27. package/dist/ripple/index.cjs +3 -0
  28. package/dist/ripple/index.cjs.map +10 -0
  29. package/dist/ripple/index.js +3 -0
  30. package/dist/ripple/index.js.map +10 -0
  31. package/dist/solana/index.cjs +2 -2
  32. package/dist/solana/index.cjs.map +3 -3
  33. package/dist/solana/index.js +2 -2
  34. package/dist/solana/index.js.map +3 -3
  35. package/dist/substrate/index.cjs +2 -2
  36. package/dist/substrate/index.cjs.map +5 -6
  37. package/dist/substrate/index.js +2 -2
  38. package/dist/substrate/index.js.map +5 -6
  39. package/dist/utxo/index.cjs +2 -2
  40. package/dist/utxo/index.cjs.map +9 -11
  41. package/dist/utxo/index.js +2 -2
  42. package/dist/utxo/index.js.map +9 -11
  43. package/package.json +27 -23
  44. package/src/cosmos/index.ts +2 -9
  45. package/src/cosmos/thorchainUtils/addressFormat.ts +1 -2
  46. package/src/cosmos/thorchainUtils/index.ts +1 -1
  47. package/src/cosmos/thorchainUtils/messages.ts +74 -56
  48. package/src/cosmos/thorchainUtils/registry.ts +19 -26
  49. package/src/cosmos/thorchainUtils/types/{proto/MsgCompiled.ts → MsgCompiled.ts} +1 -3
  50. package/src/cosmos/thorchainUtils/types/client-types.ts +16 -23
  51. package/src/cosmos/toolbox/cosmos.ts +334 -0
  52. package/src/cosmos/toolbox/index.ts +33 -0
  53. package/src/cosmos/toolbox/thorchain.ts +125 -137
  54. package/src/cosmos/types.ts +37 -18
  55. package/src/cosmos/util.ts +24 -74
  56. package/src/evm/__tests__/ethereum.test.ts +110 -116
  57. package/src/evm/api.ts +11 -147
  58. package/src/evm/helpers.ts +111 -83
  59. package/src/evm/index.ts +1 -17
  60. package/src/evm/toolbox/baseEVMToolbox.ts +744 -0
  61. package/src/evm/toolbox/evm.ts +69 -0
  62. package/src/evm/toolbox/index.ts +36 -0
  63. package/src/evm/toolbox/op.ts +97 -143
  64. package/src/evm/types.ts +50 -28
  65. package/src/index.ts +235 -0
  66. package/src/radix/index.ts +18 -19
  67. package/src/ripple/index.ts +199 -0
  68. package/src/solana/index.ts +11 -5
  69. package/src/solana/toolbox.ts +227 -137
  70. package/src/substrate/index.ts +2 -3
  71. package/src/substrate/{toolbox/baseSubstrateToolbox.ts → substrate.ts} +104 -72
  72. package/src/substrate/types.ts +120 -0
  73. package/src/utils.ts +27 -0
  74. package/src/utxo/helpers/api.ts +27 -23
  75. package/src/utxo/helpers/bchaddrjs.ts +21 -21
  76. package/src/utxo/helpers/index.ts +0 -1
  77. package/src/utxo/helpers/txSize.ts +3 -4
  78. package/src/utxo/index.ts +3 -7
  79. package/src/utxo/toolbox/bitcoinCash.ts +165 -155
  80. package/src/utxo/toolbox/index.ts +63 -24
  81. package/src/utxo/toolbox/utxo.ts +376 -229
  82. package/src/utxo/types.ts +26 -39
  83. package/src/cosmos/thorchainUtils/types/proto/MsgCompiled.js +0 -2806
  84. package/src/cosmos/thorchainUtils/util.ts +0 -46
  85. package/src/cosmos/toolbox/BaseCosmosToolbox.ts +0 -254
  86. package/src/cosmos/toolbox/gaia.ts +0 -39
  87. package/src/cosmos/toolbox/getToolboxByChain.ts +0 -29
  88. package/src/cosmos/toolbox/kujira.ts +0 -61
  89. package/src/evm/provider.ts +0 -6
  90. package/src/evm/toolbox/EVMToolbox.ts +0 -662
  91. package/src/evm/toolbox/arb.ts +0 -61
  92. package/src/evm/toolbox/avax.ts +0 -36
  93. package/src/evm/toolbox/base.ts +0 -42
  94. package/src/evm/toolbox/bsc.ts +0 -34
  95. package/src/evm/toolbox/eth.ts +0 -44
  96. package/src/evm/toolbox/getToolboxByChain.ts +0 -42
  97. package/src/evm/toolbox/matic.ts +0 -42
  98. package/src/radix/toolbox.ts +0 -693
  99. package/src/substrate/toolbox/index.ts +0 -40
  100. package/src/substrate/types/index.ts +0 -2
  101. package/src/substrate/types/network.ts +0 -42
  102. package/src/substrate/types/wallet.ts +0 -78
  103. package/src/utxo/helpers/utils.ts +0 -45
@@ -1,18 +1,16 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/utxo/index.ts", "../src/utxo/toolbox/index.ts", "../src/utxo/toolbox/bitcoinCash.ts", "../src/utxo/helpers/api.ts", "../src/utxo/helpers/utils.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"],
4
4
  "sourcesContent": [
5
- "export { type Network, networks, Psbt, Transaction } from \"bitcoinjs-lib\";\n\n/**\n * Package\n */\nexport * from \"./toolbox/index\";\nexport * from \"./toolbox/utxo\";\nexport * from \"./helpers/index\";\nexport * from \"./types\";\n",
6
- "import { Chain } from \"@swapkit/helpers\";\n\nimport { createBCHToolbox } from \"./bitcoinCash\";\nimport { BaseUTXOToolbox } from \"./utxo\";\n\ntype ToolboxType = {\n BCH: typeof BCHToolbox;\n BTC: typeof BTCToolbox;\n DOGE: typeof DOGEToolbox;\n LTC: typeof LTCToolbox;\n DASH: typeof DASHToolbox;\n};\n\nexport const BCHToolbox = createBCHToolbox;\nexport const BTCToolbox = () => BaseUTXOToolbox(Chain.Bitcoin);\nexport const DASHToolbox = () => BaseUTXOToolbox(Chain.Dash);\nexport const DOGEToolbox = () => BaseUTXOToolbox(Chain.Dogecoin);\nexport const LTCToolbox = () => BaseUTXOToolbox(Chain.Litecoin);\n\nexport const getToolboxByChain = <T extends keyof ToolboxType>(chain: T): ToolboxType[T] => {\n switch (chain) {\n case Chain.BitcoinCash:\n return BCHToolbox as ToolboxType[T];\n case Chain.Bitcoin:\n return BTCToolbox as ToolboxType[T];\n case Chain.Dogecoin:\n return DOGEToolbox as ToolboxType[T];\n case Chain.Litecoin:\n return LTCToolbox as ToolboxType[T];\n case Chain.Dash:\n return DASHToolbox as ToolboxType[T];\n default:\n throw new Error(`Chain ${chain} is not supported`);\n }\n};\n\nexport { stripToCashAddress, stripPrefix, validateAddress } from \"./bitcoinCash\";\n",
7
- "import * as secp256k1 from \"@bitcoinerlab/secp256k1\";\nimport {\n HDNode,\n Transaction,\n TransactionBuilder,\n address as bchAddress,\n // @ts-ignore TODO: check why wallets doesn't see modules included in toolbox\n} from \"@psf/bitcoincashjs-lib\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\nimport { Chain, DerivationPath, FeeOption, type UTXOChain } from \"@swapkit/helpers\";\nimport { Psbt } from \"bitcoinjs-lib\";\n\nimport {\n accumulative,\n Network as bchNetwork,\n compileMemo,\n detectAddressNetwork,\n getNetwork,\n getUtxoApi,\n isValidAddress,\n toCashAddress,\n toLegacyAddress,\n} from \"../helpers\";\nimport type {\n TargetOutput,\n TransactionBuilderType,\n TransactionType,\n UTXOBuildTxParams,\n UTXOType,\n UTXOWalletTransferParams,\n} from \"../types\";\n\nimport { BaseUTXOToolbox } from \"./utxo\";\n\n// needed because TS can not infer types\ntype BCHMethods = {\n stripPrefix: (address: string) => string;\n stripToCashAddress: (address: string) => string;\n validateAddress: (address: string, chain?: UTXOChain) => boolean;\n createKeysForPath: (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => Promise<{ getAddress: (index?: number) => string }>;\n getAddressFromKeys: (keys: { getAddress: (index?: number) => string }) => string;\n buildBCHTx: (\n params: UTXOBuildTxParams,\n ) => Promise<{ builder: TransactionBuilderType; utxos: UTXOType[] }>;\n buildTx: (params: UTXOBuildTxParams) => Promise<{ psbt: Psbt }>;\n transfer: (\n params: UTXOWalletTransferParams<\n { builder: TransactionBuilderType; utxos: UTXOType[] },\n TransactionType\n >,\n ) => Promise<string>;\n};\n\nconst chain = Chain.BitcoinCash as UTXOChain;\n\nexport const stripToCashAddress = (address: string) => stripPrefix(toCashAddress(address));\n\nconst buildBCHTx: BCHMethods[\"buildBCHTx\"] = async ({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n}) => {\n if (!validateAddress(recipient)) throw new Error(\"Invalid address\");\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const compiledMemo = memo ? compileMemo(memo) : null;\n\n const targetOutputs: TargetOutput[] = [];\n // output to recipient\n targetOutputs.push({ address: recipient, value: assetValue.getBaseValue(\"number\") });\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)) throw new Error(\"Balance insufficient for transaction\");\n\n const builder = new TransactionBuilder(getNetwork(chain));\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 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\nconst transfer = async ({\n signTransaction,\n from,\n recipient,\n assetValue,\n broadcastTx,\n getFeeRates,\n ...rest\n}: UTXOWalletTransferParams<\n { builder: TransactionBuilderType; utxos: UTXOType[] },\n TransactionType\n> & {\n broadcastTx: (txHash: string) => Promise<string>;\n getFeeRates: () => Promise<Record<FeeOption, number>>;\n}) => {\n if (!from) throw new Error(\"From address must be provided\");\n if (!recipient) throw new Error(\"Recipient address must be provided\");\n if (!signTransaction) throw new Error(\"signTransaction must be provided\");\n\n const feeRate = rest.feeRate || (await getFeeRates())[FeeOption.Fast];\n\n // try out if psbt tx is faster/better/nicer\n const { builder, utxos } = await buildBCHTx({\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n });\n\n const tx = await signTransaction({ builder, utxos });\n const txHex = tx.toHex();\n\n return broadcastTx(txHex);\n};\n\nconst buildTx = async ({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\n}: UTXOBuildTxParams) => {\n const recipientCashAddress = toCashAddress(recipient);\n if (!validateAddress(recipientCashAddress)) throw new Error(\"Invalid address\");\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 ? 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)) throw new Error(\"Balance insufficient for transaction\");\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\nexport const stripPrefix = (address: string) => address.replace(/(bchtest:|bitcoincash:)/, \"\");\n\nexport const validateAddress = (address: string) => {\n const strippedAddress = stripPrefix(address);\n return (\n isValidAddress(strippedAddress) && detectAddressNetwork(strippedAddress) === bchNetwork.Mainnet\n );\n};\n\nconst createKeysForPath: BCHMethods[\"createKeysForPath\"] = async ({\n phrase,\n derivationPath = `${DerivationPath.BCH}/0`,\n wif,\n}) => {\n const { ECPairFactory } = await import(\"ecpair\");\n\n const network = getNetwork(chain);\n\n if (wif) {\n return ECPairFactory(secp256k1).fromWIF(wif, network);\n }\n if (!phrase) throw new Error(\"No phrase provided\");\n\n const masterHDNode = HDNode.fromSeedBuffer(Buffer.from(mnemonicToSeedSync(phrase)), network);\n const keyPair = masterHDNode.derivePath(derivationPath).keyPair;\n // TODO: Figure out same pattern as in BTC\n // const testWif = keyPair.toWIF();\n // const k = ECPairFactory(secp256k1).fromWIF(testWif, network);\n // const a = payments.p2pkh({ pubkey: k.publicKey, network });\n\n return keyPair;\n};\n\nconst getAddressFromKeys = (keys: { getAddress: (index?: number) => string }) => {\n const address = keys.getAddress(0);\n return stripToCashAddress(address);\n};\n\nexport const createBCHToolbox = (): Omit<\n ReturnType<typeof BaseUTXOToolbox>,\n \"getAddressFromKeys\" | \"transfer\" | \"createKeysForPath\"\n> &\n BCHMethods => {\n const { getBalance, ...toolbox } = BaseUTXOToolbox(Chain.BitcoinCash);\n\n return {\n ...toolbox,\n stripPrefix,\n stripToCashAddress,\n validateAddress,\n createKeysForPath,\n getAddressFromKeys,\n buildBCHTx,\n buildTx,\n getBalance: (address: string, _potentialScamFilter?: boolean) =>\n getBalance(stripPrefix(toCashAddress(address))),\n transfer: (\n params: UTXOWalletTransferParams<\n { builder: TransactionBuilderType; utxos: UTXOType[] },\n TransactionType\n >,\n ) =>\n transfer({ ...params, getFeeRates: toolbox.getFeeRates, broadcastTx: toolbox.broadcastTx }),\n };\n};\n",
8
- "import { Chain, RequestClient, SKConfig, type UTXOChain, warnOnce } from \"@swapkit/helpers\";\nimport { uniqid } from \"./utils\";\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 Error(`failed to broadcast a transaction: ${response.error?.message}`);\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new Error(\"Invalid transaction: the transaction amount was too low\");\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) throw new 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) throw new 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) throw new 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 getConfirmedBalance({\n chain,\n address,\n apiKey,\n}: BlockchairParams<{ address?: string }>) {\n if (!address) throw new Error(\"address is required\");\n\n try {\n const response = await blockchairRequest<BlockchairMultipleBalancesResponse>(\n `${baseUrl(chain)}/addresses/balances?addresses=${address}`,\n apiKey,\n );\n\n return response[address] || 0;\n } catch (_error) {\n return 0;\n }\n}\n\nasync function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {\n if (!txHash) throw new 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(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) throw new 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(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 getConfirmedBalance: (address: string) => getConfirmedBalance({ chain, address, apiKey }),\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\ninterface BlockchairMultipleBalancesResponse {\n [key: string]: number;\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",
9
- "import { Chain, FeeOption } from \"@swapkit/helpers\";\nimport { networks } from \"bitcoinjs-lib\";\n// @ts-ignore TODO: check why wallets doesn't see modules included in toolbox\nimport coininfo from \"coininfo\";\n\nconst pid = typeof process !== \"undefined\" && process.pid ? process.pid.toString(36) : \"\";\n\nexport const 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 Error(\"Invalid chain\");\n }\n};\n\nexport const standardFeeRates = (rate: number) => ({\n [FeeOption.Average]: rate,\n [FeeOption.Fast]: rate * 1.5,\n [FeeOption.Fastest]: rate * 2.0,\n});\n\nlet last = 0;\nconst now = () => {\n const time = Date.now();\n const lastTime = last || time;\n last = lastTime;\n\n return time > last ? time : lastTime + 1;\n};\n\nexport const uniqid = () => pid + now().toString(36);\n",
10
- "import base58check from \"bs58check\";\n// @ts-expect-error\nimport cashaddr from \"cashaddrjs\";\n\nenum Format {\n Legacy = \"legacy\",\n Bitpay = \"bitpay\",\n Cashaddr = \"cashaddr\",\n}\nenum Network {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n}\nenum Type {\n P2PKH = \"p2pkh\",\n P2SH = \"p2sh\",\n}\n\nconst VERSION_BYTE = {\n [Format.Legacy]: {\n [Network.Mainnet]: {\n [Type.P2PKH]: 0,\n [Type.P2SH]: 5,\n },\n [Network.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n [Format.Bitpay]: {\n [Network.Mainnet]: {\n [Type.P2PKH]: 28,\n [Type.P2SH]: 40,\n },\n [Network.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n};\n\ntype DecodedType = {\n format: Format;\n network: Network;\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\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)\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\n const versionByte = payload[0];\n const hash = Array.prototype.slice.call(payload, 1);\n\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: Network.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: Network.Mainnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: Network.Testnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: Network.Testnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Bitpay, network: Network.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2SH]:\n return { hash, format: Format.Bitpay, network: Network.Mainnet, type: Type.P2SH };\n\n default:\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\n }\n } catch (_error) {\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\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\" ? Network.Mainnet : Network.Testnet,\n type: type === \"P2PKH\" ? Type.P2PKH : Type.P2SH,\n };\n } catch (_error) {\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\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 === Network.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, Network, toCashAddress, toLegacyAddress };\n",
5
+ "import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\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 Error(`Chain ${chain} is not supported`);\n }\n}\n\nexport {\n stripToCashAddress,\n stripPrefix,\n bchValidateAddress,\n} from \"./bitcoinCash\";\n",
6
+ "import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\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 const {\n Transaction,\n TransactionBuilder,\n address: bchAddress,\n // @ts-ignore\n } = await import(\"@psf/bitcoincashjs-lib\");\n if (!bchValidateAddress(recipient)) throw new Error(\"Invalid address\");\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)) throw new Error(\"Balance insufficient for transaction\");\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 Error(\"Signer must provider address\");\n if (!recipient) throw new Error(\"Recipient address must be provided\");\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 { Psbt } = (await import(\"bitcoinjs-lib\")).default;\n const recipientCashAddress = toCashAddress(recipient);\n if (!bchValidateAddress(recipientCashAddress)) throw new Error(\"Invalid address\");\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)) throw new Error(\"Balance insufficient for transaction\");\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 { Chain, RequestClient, SKConfig, type UTXOChain, warnOnce } from \"@swapkit/helpers\";\nimport { uniqid } from \"../../utils\";\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 Error(`failed to broadcast a transaction: ${response.error?.message}`);\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new Error(\"Invalid transaction: the transaction amount was too low\");\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) throw new 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) throw new 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) throw new 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) throw new 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(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) throw new 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(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 async function getUtxoNetwork() {\n // @ts-ignore\n const coininfo = await import(\"coininfo\");\n const { networks } = (await import(\"bitcoinjs-lib\")).default;\n\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 Error(\"Invalid chain\");\n }\n };\n}\n\ninterface BlockchairVin {\n txid: string;\n vout: number;\n scriptSig: {\n asm: string;\n hex: string;\n };\n sequence: number;\n}\n\ninterface BlockchairVout {\n value: number;\n n: number;\n scriptPubKey: {\n asm: string;\n hex: string;\n address: string;\n type: string;\n addresses: string[];\n reqSigs: number;\n };\n}\n\ninterface BlockchairTransaction {\n block_id: number;\n hash: string;\n time: string;\n balance_change: number;\n}\n\ninterface BlockchairUtxo {\n block_id: number;\n transaction_hash: string;\n index: number;\n value: number;\n}\n\ninterface BlockchairAddressCoreData {\n type: string;\n script_hex: string;\n balance: number;\n balance_usd: number;\n received: number;\n received_usd: number;\n spent: number;\n spent_usd: number;\n output_count: number;\n unspent_output_count: number;\n first_seen_receiving: string;\n last_seen_receiving: string;\n first_seen_spending: null | string;\n last_seen_spending: null | string;\n transaction_count: number;\n scripthash_type: null | string;\n}\n\ninterface BlockchairInputOutputCommonData {\n block_id: number;\n transaction_id: number;\n index: number;\n transaction_hash: string;\n date: string;\n time: string;\n value: number;\n value_usd: number;\n recipient: string;\n type: string;\n script_hex: string;\n is_from_coinbase: boolean;\n is_spendable: boolean | null;\n is_spent: boolean;\n lifespan: number | null;\n cdd: number | null;\n}\n\ninterface BlockchairSpendingBlockData {\n spending_block_id: number | null;\n spending_transaction_id: number | null;\n spending_index: number | null;\n spending_transaction_hash: string | null;\n spending_date: string | null;\n spending_time: string | null;\n spending_value_usd: number | null;\n spending_sequence: number | null;\n spending_signature_hex: string | null;\n spending_witness: string | null;\n}\n\ninterface BlockchairAddressResponse {\n [key: string]: {\n address: BlockchairAddressCoreData;\n transactions: BlockchairTransaction[];\n utxo: BlockchairUtxo[];\n };\n}\n\ninterface BlockchairOutputsResponse\n extends BlockchairSpendingBlockData,\n BlockchairInputOutputCommonData {}\n\ninterface BlockchairRawTransactionResponse {\n [key: string]: {\n raw_transaction: string;\n decoded_raw_transaction: {\n txid: string;\n hash: string;\n version: number;\n size: number;\n vsize: number;\n weight: number;\n locktime: number;\n vin: BlockchairVin[];\n vout: BlockchairVout[];\n };\n };\n}\n\ninterface BlockchairResponse<T> {\n data: T;\n context: {\n code: number;\n source: string;\n results: number;\n state: number;\n market_price_usd: number;\n cache: {\n live: boolean;\n duration: number;\n since: string;\n until: string;\n time: any;\n };\n api: {\n version: string;\n last_major_update: string;\n next_major_update: null | string;\n documentation: string;\n notice: string;\n };\n servers: string;\n time: number;\n render_time: number;\n full_time: number;\n request_cost: number;\n };\n}\n",
8
+ "import base58check from \"bs58check\";\n// @ts-expect-error\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\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)\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\n }\n } catch (_error) {\n throw new Error(\"Received an invalid Bitcoin Cash address as input.\");\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\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 Error(\"Received an invalid Bitcoin Cash address as input.\");\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",
11
9
  "import { Chain, 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 Error(\"Invalid 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",
12
- "import { opcodes, script } from \"bitcoinjs-lib\";\n\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 const 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 Error(\"Invalid 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",
13
- "import * as secp256k1 from \"@bitcoinerlab/secp256k1\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\nimport {\n AssetValue,\n BaseDecimal,\n Chain,\n FeeOption,\n SwapKitNumber,\n type UTXOChain,\n} from \"@swapkit/helpers\";\nimport { Psbt, address as btcLibAddress, initEccLib, payments } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } from \"ecpair\";\n\nimport {\n UTXOScriptType,\n accumulative,\n calculateTxSize,\n compileMemo,\n getDustThreshold,\n getInputSize,\n getNetwork,\n getUtxoApi,\n standardFeeRates,\n} from \"../helpers\";\nimport type { TargetOutput, UTXOBuildTxParams, UTXOType, UTXOWalletTransferParams } from \"../types\";\nimport { validateAddress as validateBCHAddress } from \"./bitcoinCash\";\nimport type { BCHToolbox, BTCToolbox, DASHToolbox, DOGEToolbox, LTCToolbox } from \"./index\";\n\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nasync function createKeysForPath({\n phrase,\n wif,\n derivationPath,\n chain,\n}: { phrase?: string; wif?: string; derivationPath: string; chain: Chain }) {\n const { ECPairFactory } = await import(\"ecpair\");\n if (!(wif || phrase)) throw new Error(\"Either phrase or wif must be provided\");\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) throw new Error(\"Could not get private key from phrase\");\n\n return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });\n}\n\nfunction validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {\n try {\n initEccLib(secp256k1);\n btcLibAddress.toOutputScript(address, getNetwork(chain));\n return true;\n } catch (_error) {\n return false;\n }\n}\n\nfunction getAddressFromKeys({ keys, chain }: { chain: UTXOChain; keys: ECPairInterface }) {\n if (!keys) throw new Error(\"Keys must be provided\");\n\n const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;\n const { address } = method({ pubkey: keys.publicKey, network: getNetwork(chain) });\n if (!address) throw new Error(\"Address not defined\");\n\n return address;\n}\n\nfunction transfer(chain: UTXOChain) {\n return async function transfer({\n signTransaction,\n from,\n memo,\n recipient,\n feeOptionKey,\n broadcastTx,\n feeRate,\n assetValue,\n }: UTXOWalletTransferParams<Psbt, Psbt>) {\n if (!from) throw new Error(\"From address must be provided\");\n if (!recipient) throw new Error(\"Recipient address must be provided\");\n if (!signTransaction) throw new Error(\"Sign transaction must be provided\");\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await buildTx(chain)({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n fetchTxHex: nonSegwitChains.includes(chain),\n assetValue,\n memo,\n });\n const signedPsbt = await signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nconst getBalance = async ({ address, chain }: { address: string; chain: UTXOChain }) => {\n const baseBalance = await getUtxoApi(chain).getBalance(address);\n const balance = SwapKitNumber.fromBigInt(BigInt(baseBalance), BaseDecimal[chain]).getValue(\n \"string\",\n );\n const asset = AssetValue.from({ asset: `${chain}.${chain}`, value: balance });\n\n return [asset];\n};\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return standardFeeRates(suggestedFeeRate);\n}\n\nfunction getInputsAndTargetOutputs(chain: UTXOChain) {\n return async function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex = false,\n }: {\n assetValue: AssetValue;\n recipient: string;\n memo?: string;\n sender: string;\n fetchTxHex?: boolean;\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: compileMemo(memo), value: 0 }] : []),\n ],\n };\n };\n}\n\nexport function buildTx(chain: UTXOChain) {\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\n return async function buildTx({\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 compiledMemo = memo ? compileMemo(memo) : null;\n const getInputsAndOutputs = getInputsAndTargetOutputs(chain);\n\n const inputsAndOutputs = await getInputsAndOutputs({\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)) throw new Error(\"Insufficient Balance for transaction\");\n const psbt = new Psbt({ network: getNetwork(chain) });\n\n if (chain === Chain.Dogecoin) psbt.setMaximumFeeRate(650000000);\n\n for (const utxo of inputs) {\n psbt.addInput({\n hash: utxo.hash,\n index: utxo.index,\n ...(!!utxo.witnessUtxo &&\n !nonSegwitChains.includes(chain) && { witnessUtxo: utxo.witnessUtxo }),\n ...(nonSegwitChains.includes(chain) && {\n nonWitnessUtxo: utxo.txHex ? Buffer.from(utxo.txHex, \"hex\") : undefined,\n }),\n });\n }\n\n for (const output of outputs) {\n const address = \"address\" in output && output.address ? output.address : 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 initEccLib(secp256k1);\n psbt.addOutput(params);\n }\n }\n\n return { psbt, utxos: inputsAndOutputs.inputs, inputs };\n };\n}\n\nfunction getInputsOutputsFee(chain: UTXOChain) {\n return async function getInputsOutputsFee({\n assetValue,\n feeOptionKey = FeeOption.Fast,\n feeRate,\n fetchTxHex = false,\n memo,\n recipient,\n from,\n }: {\n assetValue: AssetValue;\n recipient: string;\n memo?: string;\n from: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) {\n const getInputsAndOutputs = getInputsAndTargetOutputs(chain);\n const inputsAndOutputs = await getInputsAndOutputs({\n assetValue,\n recipient,\n memo,\n sender: from,\n fetchTxHex,\n });\n\n const feeRateWhole = feeRate ? Math.floor(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n return accumulative({ ...inputsAndOutputs, feeRate: feeRateWhole, chain });\n };\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 compiledMemo = compileMemo(memo);\n outputs.push({ address: from, script: compiledMemo, 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\nexport const BaseUTXOToolbox = (chain: UTXOChain) => ({\n accumulative,\n calculateTxSize,\n getFeeRates: () => getFeeRates(chain),\n buildTx: buildTx(chain),\n transfer: transfer(chain),\n getInputsOutputsFee: getInputsOutputsFee(chain),\n\n broadcastTx: (txHash: string) => getUtxoApi(chain).broadcastTx(txHash),\n getAddressFromKeys: (keys: ECPairInterface) => getAddressFromKeys({ keys, chain }),\n validateAddress: (address: string) => validateAddress({ address, chain }),\n createKeysForPath: (params: any) => createKeysForPath({ ...params, chain }),\n\n getPrivateKeyFromMnemonic: async (params: {\n phrase: string;\n derivationPath: string;\n }) => {\n const keys = await createKeysForPath({ ...params, chain });\n return keys.toWIF();\n },\n\n getBalance: async (address: string, _potentialScamFilter?: boolean) =>\n getBalance({ address, chain }),\n\n estimateTransactionFee: async (params: {\n assetValue: AssetValue;\n recipient: string;\n from: string;\n memo?: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) => {\n const getInputsFee = getInputsOutputsFee(chain);\n const inputFees = await getInputsFee(params);\n\n return AssetValue.from({\n chain,\n value: SwapKitNumber.fromBigInt(BigInt(inputFees.fee), 8).getValue(\"string\"),\n });\n },\n\n estimateMaxSendableAmount: async (params: any) => estimateMaxSendableAmount({ ...params, chain }),\n});\n\nexport function utxoValidateAddress({ chain, address }: { chain: UTXOChain; address: string }) {\n return chain === Chain.BitcoinCash\n ? validateBCHAddress(address)\n : validateAddress({ address, chain });\n}\n\nexport type BaseUTXOWallet = ReturnType<typeof BaseUTXOToolbox>;\ntype UTXOWalletType = {\n [Chain.Bitcoin]: ReturnType<typeof BTCToolbox>;\n [Chain.BitcoinCash]: ReturnType<typeof BCHToolbox>;\n [Chain.Dogecoin]: ReturnType<typeof DOGEToolbox>;\n [Chain.Litecoin]: ReturnType<typeof LTCToolbox>;\n [Chain.Dash]: ReturnType<typeof DASHToolbox>;\n};\nexport type UTXOWallets = { [chain in UTXOChain]: BaseUTXOWallet & UTXOWalletType[chain] };\n"
10
+ "import 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 async function compileMemo(memo: string) {\n const { script, opcodes } = (await import(\"bitcoinjs-lib\")).default;\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 Error(\"Invalid 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 SwapKitNumber,\n type UTXOChain,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } 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\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nasync function 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 const { initEccLib } = (await import(\"bitcoinjs-lib\")).default;\n const secp256k1 = (await import(\"@bitcoinerlab/secp256k1\")).default;\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\n const { Psbt } = (await import(\"bitcoinjs-lib\")).default;\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)) throw new Error(\"Insufficient Balance for transaction\");\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 secp256k1 = (await import(\"@bitcoinerlab/secp256k1\")).default;\n const { initEccLib, address: btcLibAddress } = (await import(\"bitcoinjs-lib\")).default;\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 { ECPairFactory } = await import(\"ecpair\");\n const secp256k1 = (await import(\"@bitcoinerlab/secp256k1\")).default;\n const { HDKey } = await import(\"@scure/bip32\");\n const { mnemonicToSeedSync } = await import(\"@scure/bip39\");\n const getNetwork = await getUtxoNetwork();\n // @ts-ignore\n const { HDNode, ECPair } = await import(\"@psf/bitcoincashjs-lib\");\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) throw new 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)) throw new Error(\"Either phrase or wif must be provided\");\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) throw new Error(\"Could not get private key from phrase\");\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 Error(`Chain ${chain} is not supported`);\n }\n}\n\nexport async function addressFromKeysGetter(chain: UTXOChain) {\n const { payments } = (await import(\"bitcoinjs-lib\")).default;\n const getNetwork = await getUtxoNetwork();\n\n return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {\n if (!keys) throw new 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) throw new 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 Error(\"From address must be provided\");\n if (!recipient) throw new Error(\"Recipient address must be provided\");\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await createTransaction({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n assetValue,\n memo,\n });\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return getUtxoApi(chain).broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return {\n [FeeOption.Average]: suggestedFeeRate,\n [FeeOption.Fast]: suggestedFeeRate * 1.5,\n [FeeOption.Fastest]: suggestedFeeRate * 2.0,\n };\n}\n\nasync function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex: fetchTxOverwrite = false,\n}: Omit<UTXOBuildTxParams, \"feeRate\">) {\n const chain = assetValue.chain as UTXOChain;\n\n const fetchTxHex = fetchTxOverwrite || nonSegwitChains.includes(chain);\n\n const inputs = await getUtxoApi(chain).scanUTXOs({ address: sender, fetchTxHex });\n\n //1. add output amount and recipient to targets\n //2. add output memo to targets (optional)\n\n return {\n inputs,\n outputs: [\n { address: recipient, value: Number(assetValue.bigIntValue) },\n ...(memo ? [{ address: \"\", script: await compileMemo(memo), value: 0 }] : []),\n ],\n };\n}\n"
14
12
  ],
15
- "mappings": "kDAAA,mBAAuB,WAAU,kBAAM,uBCAvC,gBAAS,yBCAT,2CACA,iBACE,kBACA,yBACA,cACA,gCAGF,6BAAS,sBACT,gBAAS,qBAAO,gBAAgB,0BAChC,eAAS,uBCVT,gBAAS,mBAAO,cAAe,cAA0B,0BCAzD,gBAAS,eAAO,yBAChB,mBAAS,uBAET,wBAEA,IAAM,UAAa,UAAY,aAAe,QAAQ,IAAM,QAAQ,IAAI,SAAS,EAAE,EAAI,GAE1E,EAAa,CAAC,IAAiB,CAC1C,OAAQ,QACD,EAAM,QACT,OAAO,GAAS,aACb,EAAM,YACT,OAAO,EAAS,YAAY,KAAK,YAAY,OAC1C,EAAM,KACT,OAAO,EAAS,KAAK,KAAK,YAAY,OACnC,EAAM,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AAI,EAAK,CAAE,QAAS,EAAW,CAAK,CAAE,CAAC,EAEpD,QAAa,OAAM,QAAO,iBAAiB,EACzC,EAAK,SAAS,CAAE,OAAM,QAAO,aAAY,CAAC,EAI5C,QAAW,KAAU,EAAS,CAC5B,IAAM,EACJ,YAAa,GAAU,EAAO,QAAU,EAAO,QAAU,EAAgB,CAAM,EAC3E,EAAS,EAAO,OAClB,EACE,CAAE,OAAQ,EAAc,MAAO,CAAE,EACjC,OACF,CAAE,UAAS,MAAO,EAAO,KAAM,EAEnC,GAAI,EACF,EAAK,UAAU,CAAM,EAIzB,MAAO,CAAE,OAAM,QAAO,OAAQ,CAAqB,EAGrD,SAAS,EAAkB,CAAC,EAAkD,CAC5E,IAAM,EAAU,EAAK,WAAW,CAAC,EACjC,OAAO,EAAmB,CAAO,ED1PnC,eAAsB,EAA6C,CACjE,EACA,EAO2B,CAC3B,OAAQ,QACD,EAAM,YAET,OADgB,MAAM,GAAiB,CAA8C,OAIlF,EAAM,aACN,EAAM,cACN,EAAM,cACN,EAAM,KAKT,OAJgB,MAAM,EAAkB,CACtC,WACI,CACN,CAAC,UAKD,MAAM,IAAI,MAAM,SAAS,oBAAwB",
14
+ "debugId": "1A09C092016276FC64756E2164756E21",
17
15
  "names": []
18
16
  }
package/package.json CHANGED
@@ -6,28 +6,24 @@
6
6
  ],
7
7
  "dependencies": {
8
8
  "@bitcoinerlab/secp256k1": "1.2.0",
9
- "@cosmjs/amino": "0.33.0",
10
- "@cosmjs/crypto": "0.33.0",
11
- "@cosmjs/encoding": "0.33.0",
12
- "@cosmjs/proto-signing": "0.33.0",
13
- "@cosmjs/stargate": "0.33.0",
14
- "@polkadot/api": "15.6.1",
15
- "@polkadot/api-base": "15.6.1",
16
- "@polkadot/keyring": "13.4.3",
17
- "@polkadot/util": "13.4.3",
18
- "@polkadot/util-crypto": "13.4.3",
9
+ "@cosmjs/amino": "0.33.1",
10
+ "@cosmjs/crypto": "0.33.1",
11
+ "@cosmjs/proto-signing": "0.33.1",
12
+ "@cosmjs/stargate": "0.33.1",
13
+ "@polkadot/api": "15.9.2",
14
+ "@polkadot/keyring": "13.4.4",
15
+ "@polkadot/util": "13.4.4",
16
+ "@polkadot/util-crypto": "13.4.4",
19
17
  "@psf/bitcoincashjs-lib": "4.0.3",
20
- "@radixdlt/babylon-gateway-api-sdk": "1.9.2",
18
+ "@radixdlt/babylon-gateway-api-sdk": "1.10.1",
21
19
  "@radixdlt/radix-dapp-toolkit": "2.2.1",
22
- "@radixdlt/wallet-sdk": "1.0.1",
23
20
  "@scure/base": "1.2.4",
24
21
  "@scure/bip32": "1.6.2",
25
22
  "@scure/bip39": "1.5.4",
26
23
  "@solana/spl-memo": "0.2.5",
27
- "@solana/spl-token": "0.4.12",
28
- "@solana/spl-token-registry": "0.2.4574",
29
- "@solana/web3.js": "1.98.0",
30
- "@swapkit/helpers": "3.0.0-beta.0",
24
+ "@solana/spl-token": "0.4.13",
25
+ "@solana/web3.js": "1.98.2",
26
+ "@swapkit/helpers": "3.0.0-beta.9",
31
27
  "base64-js": "1.5.1",
32
28
  "bitcoinjs-lib": "6.1.7",
33
29
  "bs58check": "4.0.0",
@@ -37,16 +33,18 @@
37
33
  "ecpair": "2.1.0",
38
34
  "ethers": "6.13.5",
39
35
  "micro-key-producer": "0.7.5",
40
- "protobufjs": "7.4.0"
36
+ "protobufjs": "7.4.0",
37
+ "ts-pattern": "5.7.0",
38
+ "xrpl": "4.2.0"
41
39
  },
42
40
  "devDependencies": {
43
41
  "@nomicfoundation/hardhat-ethers": "3.0.8",
44
42
  "@nomicfoundation/hardhat-toolbox": "5.0.0",
45
- "@polkadot/types": "15.6.1",
43
+ "@polkadot/types": "15.9.2",
46
44
  "@types/bn.js": "5.1.6",
47
45
  "@types/crypto-js": "4.2.2",
48
46
  "@types/elliptic": "6.4.18",
49
- "hardhat": "2.22.18"
47
+ "hardhat": "2.23.0"
50
48
  },
51
49
  "exports": {
52
50
  ".": {
@@ -69,6 +67,11 @@
69
67
  "require": "./dist/radix/index.cjs",
70
68
  "types": "./src/radix/index.ts"
71
69
  },
70
+ "./ripple": {
71
+ "default": "./dist/ripple/index.js",
72
+ "require": "./dist/ripple/index.cjs",
73
+ "types": "./src/ripple/index.ts"
74
+ },
72
75
  "./solana": {
73
76
  "default": "./dist/solana/index.js",
74
77
  "require": "./dist/solana/index.cjs",
@@ -94,12 +97,13 @@
94
97
  },
95
98
  "scripts": {
96
99
  "build": "bun run ./build.ts",
100
+ "build:clean": "rm -rf dist && bun run ./build.ts",
97
101
  "clean": "rm -rf dist node_modules *.tsbuildinfo",
98
- "lint": "biome check --write ./src",
99
- "test": "echo 'bun test'",
102
+ "test": "bun test",
100
103
  "test:ci": "bun test --coverage",
101
- "type-check": "tsc --noEmit"
104
+ "type-check": "bun tsc --noEmit",
105
+ "type-check:go": "tsgo"
102
106
  },
103
107
  "type": "module",
104
- "version": "1.0.0-beta.0"
108
+ "version": "1.0.0-beta.10"
105
109
  }
@@ -1,11 +1,4 @@
1
- /**
2
- * Package
3
- */
4
- export * from "./thorchainUtils/index";
5
- export * from "./toolbox/BaseCosmosToolbox";
6
- export * from "./toolbox/gaia";
7
- export * from "./toolbox/getToolboxByChain";
8
- export * from "./toolbox/kujira";
9
- export * from "./toolbox/thorchain";
1
+ export * from "./thorchainUtils";
2
+ export * from "./toolbox";
10
3
  export * from "./types";
11
4
  export * from "./util";
@@ -1,4 +1,3 @@
1
- import { toBech32 } from "@cosmjs/encoding";
2
1
  import { base64, bech32 } from "@scure/base";
3
2
  import { fromByteArray, toByteArray } from "base64-js";
4
3
 
@@ -9,7 +8,7 @@ export function bech32ToBase64(address: string) {
9
8
  }
10
9
 
11
10
  export function base64ToBech32(address: string, prefix = "thor") {
12
- return toBech32(prefix, base64.decode(address));
11
+ return bech32.encode(prefix, bech32.toWords(base64.decode(address)));
13
12
  }
14
13
 
15
14
  export function toBase64(data: Uint8Array) {
@@ -1,4 +1,4 @@
1
1
  export * from "./addressFormat";
2
2
  export * from "./messages";
3
3
  export * from "./registry";
4
- export * from "./types/index";
4
+ export * from "./types";