@flashnet/sdk 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/src/client/FlashnetClient.d.ts +150 -0
- package/dist/cjs/src/client/FlashnetClient.d.ts.map +1 -1
- package/dist/cjs/src/client/FlashnetClient.js +582 -0
- package/dist/cjs/src/client/FlashnetClient.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/src/client/FlashnetClient.d.ts +150 -0
- package/dist/esm/src/client/FlashnetClient.d.ts.map +1 -1
- package/dist/esm/src/client/FlashnetClient.js +582 -0
- package/dist/esm/src/client/FlashnetClient.js.map +1 -1
- package/package.json +1 -1
|
@@ -1786,6 +1786,588 @@ class FlashnetClient {
|
|
|
1786
1786
|
throw new Error(errorMessage);
|
|
1787
1787
|
}
|
|
1788
1788
|
}
|
|
1789
|
+
// ===== Lightning Payment with Token =====
|
|
1790
|
+
/**
|
|
1791
|
+
* Get a quote for paying a Lightning invoice with a token.
|
|
1792
|
+
* This calculates the optimal pool and token amount needed.
|
|
1793
|
+
*
|
|
1794
|
+
* @param invoice - BOLT11-encoded Lightning invoice
|
|
1795
|
+
* @param tokenAddress - Token identifier to use for payment
|
|
1796
|
+
* @param options - Optional configuration (slippage, integrator fees, etc.)
|
|
1797
|
+
* @returns Quote with pricing details
|
|
1798
|
+
* @throws Error if invoice amount or token amount is below Flashnet minimums
|
|
1799
|
+
*/
|
|
1800
|
+
async getPayLightningWithTokenQuote(invoice, tokenAddress, options) {
|
|
1801
|
+
await this.ensureInitialized();
|
|
1802
|
+
// Decode the invoice to get the amount
|
|
1803
|
+
const invoiceAmountSats = await this.decodeInvoiceAmount(invoice);
|
|
1804
|
+
if (!invoiceAmountSats || invoiceAmountSats <= 0) {
|
|
1805
|
+
throw new Error("Unable to decode invoice amount. Zero-amount invoices are not supported for token payments.");
|
|
1806
|
+
}
|
|
1807
|
+
// Get Lightning fee estimate
|
|
1808
|
+
const lightningFeeEstimate = await this.getLightningFeeEstimate(invoice);
|
|
1809
|
+
// Total BTC needed = invoice amount + lightning fee
|
|
1810
|
+
const baseBtcNeeded = BigInt(invoiceAmountSats) + BigInt(lightningFeeEstimate);
|
|
1811
|
+
// Round up to next multiple of 64 (2^6) to account for BTC variable fee bit masking.
|
|
1812
|
+
// The AMM zeroes the lowest 6 bits of BTC output, so we need to request enough
|
|
1813
|
+
// that after masking we still have the required amount.
|
|
1814
|
+
// Example: 5014 -> masked to 4992, but if we request 5056, masked stays 5056
|
|
1815
|
+
const BTC_VARIABLE_FEE_BITS = 6n;
|
|
1816
|
+
const BTC_VARIABLE_FEE_MASK = 1n << BTC_VARIABLE_FEE_BITS; // 64
|
|
1817
|
+
const totalBtcNeeded = ((baseBtcNeeded + BTC_VARIABLE_FEE_MASK - 1n) / BTC_VARIABLE_FEE_MASK) *
|
|
1818
|
+
BTC_VARIABLE_FEE_MASK;
|
|
1819
|
+
// Check Flashnet minimum amounts early to provide clear error messages
|
|
1820
|
+
const minAmounts = await this.getEnabledMinAmountsMap();
|
|
1821
|
+
// Check BTC minimum (output from swap)
|
|
1822
|
+
const btcMinAmount = minAmounts.get(BTC_ASSET_PUBKEY.toLowerCase());
|
|
1823
|
+
if (btcMinAmount && totalBtcNeeded < btcMinAmount) {
|
|
1824
|
+
throw new Error(`Invoice amount too small. Flashnet minimum BTC output is ${btcMinAmount} sats, ` +
|
|
1825
|
+
`but invoice + lightning fee totals only ${totalBtcNeeded} sats. ` +
|
|
1826
|
+
`Please use an invoice of at least ${btcMinAmount} sats.`);
|
|
1827
|
+
}
|
|
1828
|
+
// Find the best pool to swap token -> BTC
|
|
1829
|
+
const poolQuote = await this.findBestPoolForTokenToBtc(tokenAddress, totalBtcNeeded.toString(), options?.integratorFeeRateBps);
|
|
1830
|
+
// Check token minimum (input to swap)
|
|
1831
|
+
const tokenHex = this.toHexTokenIdentifier(tokenAddress).toLowerCase();
|
|
1832
|
+
const tokenMinAmount = minAmounts.get(tokenHex);
|
|
1833
|
+
if (tokenMinAmount &&
|
|
1834
|
+
BigInt(poolQuote.tokenAmountRequired) < tokenMinAmount) {
|
|
1835
|
+
throw new Error(`Token amount too small. Flashnet minimum input is ${tokenMinAmount} units, ` +
|
|
1836
|
+
`but calculated amount is only ${poolQuote.tokenAmountRequired} units. ` +
|
|
1837
|
+
`Please use a larger invoice amount.`);
|
|
1838
|
+
}
|
|
1839
|
+
// Calculate the BTC variable fee adjustment (how much extra we're requesting)
|
|
1840
|
+
const btcVariableFeeAdjustment = Number(totalBtcNeeded - baseBtcNeeded);
|
|
1841
|
+
return {
|
|
1842
|
+
poolId: poolQuote.poolId,
|
|
1843
|
+
tokenAddress: this.toHexTokenIdentifier(tokenAddress),
|
|
1844
|
+
tokenAmountRequired: poolQuote.tokenAmountRequired,
|
|
1845
|
+
btcAmountRequired: totalBtcNeeded.toString(),
|
|
1846
|
+
invoiceAmountSats: invoiceAmountSats,
|
|
1847
|
+
estimatedAmmFee: poolQuote.estimatedAmmFee,
|
|
1848
|
+
estimatedLightningFee: lightningFeeEstimate,
|
|
1849
|
+
btcVariableFeeAdjustment,
|
|
1850
|
+
executionPrice: poolQuote.executionPrice,
|
|
1851
|
+
priceImpactPct: poolQuote.priceImpactPct,
|
|
1852
|
+
tokenIsAssetA: poolQuote.tokenIsAssetA,
|
|
1853
|
+
poolReserves: poolQuote.poolReserves,
|
|
1854
|
+
warningMessage: poolQuote.warningMessage,
|
|
1855
|
+
};
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* Pay a Lightning invoice using a token.
|
|
1859
|
+
* This swaps the token to BTC on Flashnet and uses the BTC to pay the invoice.
|
|
1860
|
+
*
|
|
1861
|
+
* @param options - Payment options including invoice and token address
|
|
1862
|
+
* @returns Payment result with transaction details
|
|
1863
|
+
*/
|
|
1864
|
+
async payLightningWithToken(options) {
|
|
1865
|
+
await this.ensureInitialized();
|
|
1866
|
+
const { invoice, tokenAddress, maxSlippageBps = 500, // 5% default
|
|
1867
|
+
maxLightningFeeSats, preferSpark = true, integratorFeeRateBps, integratorPublicKey, transferTimeoutMs = 30000, // 30s default
|
|
1868
|
+
rollbackOnFailure = false, useExistingBtcBalance = false, } = options;
|
|
1869
|
+
try {
|
|
1870
|
+
// Step 1: Get a quote for the payment
|
|
1871
|
+
const quote = await this.getPayLightningWithTokenQuote(invoice, tokenAddress, {
|
|
1872
|
+
maxSlippageBps,
|
|
1873
|
+
integratorFeeRateBps,
|
|
1874
|
+
});
|
|
1875
|
+
// Step 2: Check token balance (always required)
|
|
1876
|
+
await this.checkBalance({
|
|
1877
|
+
balancesToCheck: [
|
|
1878
|
+
{
|
|
1879
|
+
assetAddress: tokenAddress,
|
|
1880
|
+
amount: quote.tokenAmountRequired,
|
|
1881
|
+
},
|
|
1882
|
+
],
|
|
1883
|
+
errorPrefix: "Insufficient token balance for Lightning payment: ",
|
|
1884
|
+
});
|
|
1885
|
+
// Determine if we can pay immediately using existing BTC balance
|
|
1886
|
+
let canPayImmediately = false;
|
|
1887
|
+
if (useExistingBtcBalance) {
|
|
1888
|
+
const invoiceAmountSats = await this.decodeInvoiceAmount(invoice);
|
|
1889
|
+
const effectiveMaxLightningFee = maxLightningFeeSats ?? quote.estimatedLightningFee;
|
|
1890
|
+
const btcNeededForPayment = invoiceAmountSats + effectiveMaxLightningFee;
|
|
1891
|
+
// Check if we have enough BTC (don't throw if not, just fall back to waiting)
|
|
1892
|
+
const balance = await this.getBalance();
|
|
1893
|
+
canPayImmediately = balance.balance >= BigInt(btcNeededForPayment);
|
|
1894
|
+
}
|
|
1895
|
+
// Step 3: Get pool details
|
|
1896
|
+
const pool = await this.getPool(quote.poolId);
|
|
1897
|
+
// Step 4: Determine swap direction and execute
|
|
1898
|
+
const assetInAddress = quote.tokenIsAssetA
|
|
1899
|
+
? pool.assetAAddress
|
|
1900
|
+
: pool.assetBAddress;
|
|
1901
|
+
const assetOutAddress = quote.tokenIsAssetA
|
|
1902
|
+
? pool.assetBAddress
|
|
1903
|
+
: pool.assetAAddress;
|
|
1904
|
+
// Calculate min amount out with slippage protection
|
|
1905
|
+
const minBtcOut = this.calculateMinAmountOut(quote.btcAmountRequired, maxSlippageBps);
|
|
1906
|
+
// Execute the swap
|
|
1907
|
+
const swapResponse = await this.executeSwap({
|
|
1908
|
+
poolId: quote.poolId,
|
|
1909
|
+
assetInAddress,
|
|
1910
|
+
assetOutAddress,
|
|
1911
|
+
amountIn: quote.tokenAmountRequired,
|
|
1912
|
+
maxSlippageBps,
|
|
1913
|
+
minAmountOut: minBtcOut,
|
|
1914
|
+
integratorFeeRateBps,
|
|
1915
|
+
integratorPublicKey,
|
|
1916
|
+
});
|
|
1917
|
+
if (!swapResponse.accepted || !swapResponse.outboundTransferId) {
|
|
1918
|
+
return {
|
|
1919
|
+
success: false,
|
|
1920
|
+
poolId: quote.poolId,
|
|
1921
|
+
tokenAmountSpent: quote.tokenAmountRequired,
|
|
1922
|
+
btcAmountReceived: "0",
|
|
1923
|
+
swapTransferId: swapResponse.outboundTransferId || "",
|
|
1924
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
1925
|
+
error: swapResponse.error || "Swap was not accepted",
|
|
1926
|
+
};
|
|
1927
|
+
}
|
|
1928
|
+
// Step 5: Wait for the transfer to complete (unless paying immediately with existing BTC)
|
|
1929
|
+
if (!canPayImmediately) {
|
|
1930
|
+
const transferComplete = await this.waitForTransferCompletion(swapResponse.outboundTransferId, transferTimeoutMs);
|
|
1931
|
+
if (!transferComplete) {
|
|
1932
|
+
return {
|
|
1933
|
+
success: false,
|
|
1934
|
+
poolId: quote.poolId,
|
|
1935
|
+
tokenAmountSpent: quote.tokenAmountRequired,
|
|
1936
|
+
btcAmountReceived: swapResponse.amountOut || "0",
|
|
1937
|
+
swapTransferId: swapResponse.outboundTransferId,
|
|
1938
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
1939
|
+
error: "Transfer did not complete within timeout",
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
// Step 6: Calculate Lightning fee limit - use the quoted estimate, not a recalculation
|
|
1944
|
+
const effectiveMaxLightningFee = maxLightningFeeSats ?? quote.estimatedLightningFee;
|
|
1945
|
+
// Step 7: Pay the Lightning invoice
|
|
1946
|
+
const btcReceived = swapResponse.amountOut || quote.btcAmountRequired;
|
|
1947
|
+
try {
|
|
1948
|
+
const lightningPayment = await this._wallet.payLightningInvoice({
|
|
1949
|
+
invoice,
|
|
1950
|
+
maxFeeSats: effectiveMaxLightningFee,
|
|
1951
|
+
preferSpark,
|
|
1952
|
+
});
|
|
1953
|
+
return {
|
|
1954
|
+
success: true,
|
|
1955
|
+
poolId: quote.poolId,
|
|
1956
|
+
tokenAmountSpent: quote.tokenAmountRequired,
|
|
1957
|
+
btcAmountReceived: btcReceived,
|
|
1958
|
+
swapTransferId: swapResponse.outboundTransferId,
|
|
1959
|
+
lightningPaymentId: lightningPayment.id,
|
|
1960
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
1961
|
+
lightningFeePaid: effectiveMaxLightningFee,
|
|
1962
|
+
};
|
|
1963
|
+
}
|
|
1964
|
+
catch (lightningError) {
|
|
1965
|
+
// Lightning payment failed after swap succeeded
|
|
1966
|
+
const lightningErrorMessage = lightningError instanceof Error
|
|
1967
|
+
? lightningError.message
|
|
1968
|
+
: String(lightningError);
|
|
1969
|
+
// Attempt rollback if requested
|
|
1970
|
+
if (rollbackOnFailure) {
|
|
1971
|
+
try {
|
|
1972
|
+
const rollbackResult = await this.rollbackSwap(quote.poolId, btcReceived, tokenAddress, maxSlippageBps);
|
|
1973
|
+
if (rollbackResult.success) {
|
|
1974
|
+
return {
|
|
1975
|
+
success: false,
|
|
1976
|
+
poolId: quote.poolId,
|
|
1977
|
+
tokenAmountSpent: "0", // Rolled back
|
|
1978
|
+
btcAmountReceived: "0",
|
|
1979
|
+
swapTransferId: swapResponse.outboundTransferId,
|
|
1980
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
1981
|
+
error: `Lightning payment failed: ${lightningErrorMessage}. Funds rolled back to ${rollbackResult.tokenAmount} tokens.`,
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
catch (rollbackError) {
|
|
1986
|
+
const rollbackErrorMessage = rollbackError instanceof Error
|
|
1987
|
+
? rollbackError.message
|
|
1988
|
+
: String(rollbackError);
|
|
1989
|
+
return {
|
|
1990
|
+
success: false,
|
|
1991
|
+
poolId: quote.poolId,
|
|
1992
|
+
tokenAmountSpent: quote.tokenAmountRequired,
|
|
1993
|
+
btcAmountReceived: btcReceived,
|
|
1994
|
+
swapTransferId: swapResponse.outboundTransferId,
|
|
1995
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
1996
|
+
error: `Lightning payment failed: ${lightningErrorMessage}. Rollback also failed: ${rollbackErrorMessage}. BTC remains in wallet.`,
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
return {
|
|
2001
|
+
success: false,
|
|
2002
|
+
poolId: quote.poolId,
|
|
2003
|
+
tokenAmountSpent: quote.tokenAmountRequired,
|
|
2004
|
+
btcAmountReceived: btcReceived,
|
|
2005
|
+
swapTransferId: swapResponse.outboundTransferId,
|
|
2006
|
+
ammFeePaid: quote.estimatedAmmFee,
|
|
2007
|
+
error: `Lightning payment failed: ${lightningErrorMessage}. BTC (${btcReceived} sats) remains in wallet.`,
|
|
2008
|
+
};
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
catch (error) {
|
|
2012
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2013
|
+
return {
|
|
2014
|
+
success: false,
|
|
2015
|
+
poolId: "",
|
|
2016
|
+
tokenAmountSpent: "0",
|
|
2017
|
+
btcAmountReceived: "0",
|
|
2018
|
+
swapTransferId: "",
|
|
2019
|
+
ammFeePaid: "0",
|
|
2020
|
+
error: errorMessage,
|
|
2021
|
+
};
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Attempt to rollback a swap by swapping BTC back to the original token
|
|
2026
|
+
* @private
|
|
2027
|
+
*/
|
|
2028
|
+
async rollbackSwap(poolId, btcAmount, tokenAddress, maxSlippageBps) {
|
|
2029
|
+
const pool = await this.getPool(poolId);
|
|
2030
|
+
const tokenHex = this.toHexTokenIdentifier(tokenAddress);
|
|
2031
|
+
// Determine swap direction (BTC -> Token)
|
|
2032
|
+
const tokenIsAssetA = pool.assetAAddress === tokenHex;
|
|
2033
|
+
const assetInAddress = tokenIsAssetA
|
|
2034
|
+
? pool.assetBAddress
|
|
2035
|
+
: pool.assetAAddress; // BTC
|
|
2036
|
+
const assetOutAddress = tokenIsAssetA
|
|
2037
|
+
? pool.assetAAddress
|
|
2038
|
+
: pool.assetBAddress; // Token
|
|
2039
|
+
// Calculate expected token output and min amount with slippage
|
|
2040
|
+
// For rollback, we accept more slippage since we're recovering from failure
|
|
2041
|
+
const minAmountOut = "0"; // Accept any amount to ensure rollback succeeds
|
|
2042
|
+
// Execute reverse swap
|
|
2043
|
+
const swapResponse = await this.executeSwap({
|
|
2044
|
+
poolId,
|
|
2045
|
+
assetInAddress,
|
|
2046
|
+
assetOutAddress,
|
|
2047
|
+
amountIn: btcAmount,
|
|
2048
|
+
maxSlippageBps: maxSlippageBps * 2, // Double slippage for rollback
|
|
2049
|
+
minAmountOut,
|
|
2050
|
+
});
|
|
2051
|
+
if (!swapResponse.accepted) {
|
|
2052
|
+
throw new Error(swapResponse.error || "Rollback swap not accepted");
|
|
2053
|
+
}
|
|
2054
|
+
// Wait for the rollback transfer
|
|
2055
|
+
if (swapResponse.outboundTransferId) {
|
|
2056
|
+
await this.waitForTransferCompletion(swapResponse.outboundTransferId, 30000);
|
|
2057
|
+
}
|
|
2058
|
+
return {
|
|
2059
|
+
success: true,
|
|
2060
|
+
tokenAmount: swapResponse.amountOut,
|
|
2061
|
+
};
|
|
2062
|
+
}
|
|
2063
|
+
/**
|
|
2064
|
+
* Find the best pool for swapping a token to BTC
|
|
2065
|
+
* @private
|
|
2066
|
+
*/
|
|
2067
|
+
async findBestPoolForTokenToBtc(tokenAddress, btcAmountNeeded, integratorFeeRateBps) {
|
|
2068
|
+
const tokenHex = this.toHexTokenIdentifier(tokenAddress);
|
|
2069
|
+
const btcHex = BTC_ASSET_PUBKEY;
|
|
2070
|
+
// Find all pools that have this token paired with BTC
|
|
2071
|
+
const poolsWithTokenAsA = await this.listPools({
|
|
2072
|
+
assetAAddress: tokenHex,
|
|
2073
|
+
assetBAddress: btcHex,
|
|
2074
|
+
});
|
|
2075
|
+
const poolsWithTokenAsB = await this.listPools({
|
|
2076
|
+
assetAAddress: btcHex,
|
|
2077
|
+
assetBAddress: tokenHex,
|
|
2078
|
+
});
|
|
2079
|
+
const allPools = [
|
|
2080
|
+
...poolsWithTokenAsA.pools.map((p) => ({ ...p, tokenIsAssetA: true })),
|
|
2081
|
+
...poolsWithTokenAsB.pools.map((p) => ({ ...p, tokenIsAssetA: false })),
|
|
2082
|
+
];
|
|
2083
|
+
if (allPools.length === 0) {
|
|
2084
|
+
throw new Error(`No liquidity pool found for token ${tokenAddress} paired with BTC`);
|
|
2085
|
+
}
|
|
2086
|
+
// Find the best pool (lowest token cost for the required BTC)
|
|
2087
|
+
let bestPool = null;
|
|
2088
|
+
let bestTokenAmount = BigInt(Number.MAX_SAFE_INTEGER);
|
|
2089
|
+
let bestSimulation = null;
|
|
2090
|
+
for (const pool of allPools) {
|
|
2091
|
+
try {
|
|
2092
|
+
// Get pool details for reserves
|
|
2093
|
+
const poolDetails = await this.getPool(pool.lpPublicKey);
|
|
2094
|
+
// Calculate the token amount needed using AMM math
|
|
2095
|
+
const calculation = this.calculateTokenAmountForBtcOutput(btcAmountNeeded, poolDetails.assetAReserve, poolDetails.assetBReserve, poolDetails.lpFeeBps, poolDetails.hostFeeBps, pool.tokenIsAssetA, integratorFeeRateBps);
|
|
2096
|
+
const tokenAmount = BigInt(calculation.amountIn);
|
|
2097
|
+
// Check if this is better than our current best
|
|
2098
|
+
if (tokenAmount < bestTokenAmount) {
|
|
2099
|
+
// Verify with simulation
|
|
2100
|
+
const simulation = await this.simulateSwap({
|
|
2101
|
+
poolId: pool.lpPublicKey,
|
|
2102
|
+
assetInAddress: pool.tokenIsAssetA
|
|
2103
|
+
? poolDetails.assetAAddress
|
|
2104
|
+
: poolDetails.assetBAddress,
|
|
2105
|
+
assetOutAddress: pool.tokenIsAssetA
|
|
2106
|
+
? poolDetails.assetBAddress
|
|
2107
|
+
: poolDetails.assetAAddress,
|
|
2108
|
+
amountIn: calculation.amountIn,
|
|
2109
|
+
integratorBps: integratorFeeRateBps,
|
|
2110
|
+
});
|
|
2111
|
+
// Verify the output is sufficient
|
|
2112
|
+
if (BigInt(simulation.amountOut) >= BigInt(btcAmountNeeded)) {
|
|
2113
|
+
bestPool = pool;
|
|
2114
|
+
bestTokenAmount = tokenAmount;
|
|
2115
|
+
bestSimulation = {
|
|
2116
|
+
amountIn: calculation.amountIn,
|
|
2117
|
+
fee: calculation.totalFee,
|
|
2118
|
+
executionPrice: simulation.executionPrice || "0",
|
|
2119
|
+
priceImpactPct: simulation.priceImpactPct || "0",
|
|
2120
|
+
warningMessage: simulation.warningMessage,
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
catch { }
|
|
2126
|
+
}
|
|
2127
|
+
if (!bestPool || !bestSimulation) {
|
|
2128
|
+
throw new Error(`No pool has sufficient liquidity for ${btcAmountNeeded} sats`);
|
|
2129
|
+
}
|
|
2130
|
+
const poolDetails = await this.getPool(bestPool.lpPublicKey);
|
|
2131
|
+
return {
|
|
2132
|
+
poolId: bestPool.lpPublicKey,
|
|
2133
|
+
tokenAmountRequired: bestSimulation.amountIn,
|
|
2134
|
+
estimatedAmmFee: bestSimulation.fee,
|
|
2135
|
+
executionPrice: bestSimulation.executionPrice,
|
|
2136
|
+
priceImpactPct: bestSimulation.priceImpactPct,
|
|
2137
|
+
tokenIsAssetA: bestPool.tokenIsAssetA,
|
|
2138
|
+
poolReserves: {
|
|
2139
|
+
assetAReserve: poolDetails.assetAReserve,
|
|
2140
|
+
assetBReserve: poolDetails.assetBReserve,
|
|
2141
|
+
},
|
|
2142
|
+
warningMessage: bestSimulation.warningMessage,
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
/**
|
|
2146
|
+
* Calculate the token amount needed to get a specific BTC output.
|
|
2147
|
+
* Implements the AMM fee-inclusive model.
|
|
2148
|
+
* @private
|
|
2149
|
+
*/
|
|
2150
|
+
calculateTokenAmountForBtcOutput(btcAmountOut, reserveA, reserveB, lpFeeBps, hostFeeBps, tokenIsAssetA, integratorFeeBps) {
|
|
2151
|
+
const amountOut = BigInt(btcAmountOut);
|
|
2152
|
+
const resA = BigInt(reserveA);
|
|
2153
|
+
const resB = BigInt(reserveB);
|
|
2154
|
+
const totalFeeBps = lpFeeBps + hostFeeBps + (integratorFeeBps || 0);
|
|
2155
|
+
const feeRate = Number(totalFeeBps) / 10000; // Convert bps to decimal
|
|
2156
|
+
// Token is the input asset
|
|
2157
|
+
// BTC is the output asset
|
|
2158
|
+
if (tokenIsAssetA) {
|
|
2159
|
+
// Token is asset A, BTC is asset B
|
|
2160
|
+
// A → B swap: we want BTC out (asset B)
|
|
2161
|
+
// reserve_in = reserveA (token), reserve_out = reserveB (BTC)
|
|
2162
|
+
// Constant product formula for amount_in given amount_out:
|
|
2163
|
+
// amount_in_effective = (reserve_in * amount_out) / (reserve_out - amount_out)
|
|
2164
|
+
const reserveIn = resA;
|
|
2165
|
+
const reserveOut = resB;
|
|
2166
|
+
if (amountOut >= reserveOut) {
|
|
2167
|
+
throw new Error("Insufficient liquidity: requested BTC amount exceeds reserve");
|
|
2168
|
+
}
|
|
2169
|
+
// Calculate effective amount in (before fees)
|
|
2170
|
+
const amountInEffective = (reserveIn * amountOut) / (reserveOut - amountOut) + 1n; // +1 for rounding up
|
|
2171
|
+
// A→B swap: LP fee deducted from input A, integrator fee from output B
|
|
2172
|
+
// amount_in = amount_in_effective * (1 + lp_fee_rate)
|
|
2173
|
+
// Then integrator fee is deducted from output, so we need slightly more input
|
|
2174
|
+
const lpFeeRate = Number(lpFeeBps) / 10000;
|
|
2175
|
+
const integratorFeeRate = Number(integratorFeeBps || 0) / 10000;
|
|
2176
|
+
// Account for LP fee on input
|
|
2177
|
+
const amountInWithLpFee = BigInt(Math.ceil(Number(amountInEffective) * (1 + lpFeeRate)));
|
|
2178
|
+
// Account for integrator fee on output (need more input to get same output after fee)
|
|
2179
|
+
const amountIn = integratorFeeRate > 0
|
|
2180
|
+
? BigInt(Math.ceil(Number(amountInWithLpFee) * (1 + integratorFeeRate)))
|
|
2181
|
+
: amountInWithLpFee;
|
|
2182
|
+
const totalFee = amountIn - amountInEffective;
|
|
2183
|
+
return {
|
|
2184
|
+
amountIn: amountIn.toString(),
|
|
2185
|
+
totalFee: totalFee.toString(),
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
else {
|
|
2189
|
+
// Token is asset B, BTC is asset A
|
|
2190
|
+
// B → A swap: we want BTC out (asset A)
|
|
2191
|
+
// reserve_in = reserveB (token), reserve_out = reserveA (BTC)
|
|
2192
|
+
const reserveIn = resB;
|
|
2193
|
+
const reserveOut = resA;
|
|
2194
|
+
if (amountOut >= reserveOut) {
|
|
2195
|
+
throw new Error("Insufficient liquidity: requested BTC amount exceeds reserve");
|
|
2196
|
+
}
|
|
2197
|
+
// Calculate effective amount in (before fees)
|
|
2198
|
+
const amountInEffective = (reserveIn * amountOut) / (reserveOut - amountOut) + 1n; // +1 for rounding up
|
|
2199
|
+
// B→A swap: ALL fees (LP + integrator) deducted from input B
|
|
2200
|
+
// amount_in = amount_in_effective * (1 + total_fee_rate)
|
|
2201
|
+
const amountIn = BigInt(Math.ceil(Number(amountInEffective) * (1 + feeRate)));
|
|
2202
|
+
// Fee calculation: fee = amount_in * fee_rate / (1 + fee_rate)
|
|
2203
|
+
const totalFee = BigInt(Math.ceil((Number(amountIn) * feeRate) / (1 + feeRate)));
|
|
2204
|
+
return {
|
|
2205
|
+
amountIn: amountIn.toString(),
|
|
2206
|
+
totalFee: totalFee.toString(),
|
|
2207
|
+
};
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* Calculate minimum amount out with slippage protection
|
|
2212
|
+
* @private
|
|
2213
|
+
*/
|
|
2214
|
+
calculateMinAmountOut(expectedAmount, slippageBps) {
|
|
2215
|
+
const amount = BigInt(expectedAmount);
|
|
2216
|
+
const slippageFactor = BigInt(10000 - slippageBps);
|
|
2217
|
+
const minAmount = (amount * slippageFactor) / 10000n;
|
|
2218
|
+
return minAmount.toString();
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* Wait for a transfer to be claimed using wallet events.
|
|
2222
|
+
* This is more efficient than polling as it uses the wallet's event stream.
|
|
2223
|
+
* @private
|
|
2224
|
+
*/
|
|
2225
|
+
async waitForTransferCompletion(transferId, timeoutMs) {
|
|
2226
|
+
return new Promise((resolve) => {
|
|
2227
|
+
const timeout = setTimeout(() => {
|
|
2228
|
+
// Remove listener on timeout
|
|
2229
|
+
try {
|
|
2230
|
+
this._wallet.removeListener?.("transfer:claimed", handler);
|
|
2231
|
+
}
|
|
2232
|
+
catch {
|
|
2233
|
+
// Ignore if removeListener doesn't exist
|
|
2234
|
+
}
|
|
2235
|
+
resolve(false);
|
|
2236
|
+
}, timeoutMs);
|
|
2237
|
+
const handler = (claimedTransferId, _balance) => {
|
|
2238
|
+
if (claimedTransferId === transferId) {
|
|
2239
|
+
clearTimeout(timeout);
|
|
2240
|
+
try {
|
|
2241
|
+
this._wallet.removeListener?.("transfer:claimed", handler);
|
|
2242
|
+
}
|
|
2243
|
+
catch {
|
|
2244
|
+
// Ignore if removeListener doesn't exist
|
|
2245
|
+
}
|
|
2246
|
+
resolve(true);
|
|
2247
|
+
}
|
|
2248
|
+
};
|
|
2249
|
+
// Subscribe to transfer claimed events
|
|
2250
|
+
// The wallet's RPC stream will automatically claim incoming transfers
|
|
2251
|
+
try {
|
|
2252
|
+
this._wallet.on?.("transfer:claimed", handler);
|
|
2253
|
+
}
|
|
2254
|
+
catch {
|
|
2255
|
+
// If event subscription fails, fall back to polling
|
|
2256
|
+
clearTimeout(timeout);
|
|
2257
|
+
this.pollForTransferCompletion(transferId, timeoutMs).then(resolve);
|
|
2258
|
+
}
|
|
2259
|
+
});
|
|
2260
|
+
}
|
|
2261
|
+
/**
|
|
2262
|
+
* Fallback polling method for transfer completion
|
|
2263
|
+
* @private
|
|
2264
|
+
*/
|
|
2265
|
+
async pollForTransferCompletion(transferId, timeoutMs) {
|
|
2266
|
+
const startTime = Date.now();
|
|
2267
|
+
const pollIntervalMs = 500;
|
|
2268
|
+
while (Date.now() - startTime < timeoutMs) {
|
|
2269
|
+
try {
|
|
2270
|
+
const transfer = await this._wallet.getTransfer(transferId);
|
|
2271
|
+
if (transfer) {
|
|
2272
|
+
if (transfer.status === "TRANSFER_STATUS_COMPLETED") {
|
|
2273
|
+
return true;
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
catch {
|
|
2278
|
+
// Ignore errors and continue polling
|
|
2279
|
+
}
|
|
2280
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
2281
|
+
}
|
|
2282
|
+
return false;
|
|
2283
|
+
}
|
|
2284
|
+
/**
|
|
2285
|
+
* Get Lightning fee estimate for an invoice
|
|
2286
|
+
* @private
|
|
2287
|
+
*/
|
|
2288
|
+
async getLightningFeeEstimate(invoice) {
|
|
2289
|
+
try {
|
|
2290
|
+
const feeEstimate = await this._wallet.getLightningSendFeeEstimate({
|
|
2291
|
+
encodedInvoice: invoice,
|
|
2292
|
+
});
|
|
2293
|
+
// The fee estimate might be returned as a number or an object
|
|
2294
|
+
if (typeof feeEstimate === "number") {
|
|
2295
|
+
return feeEstimate;
|
|
2296
|
+
}
|
|
2297
|
+
if (feeEstimate?.fee || feeEstimate?.feeEstimate) {
|
|
2298
|
+
return Number(feeEstimate.fee || feeEstimate.feeEstimate);
|
|
2299
|
+
}
|
|
2300
|
+
// Fallback to invoice amount-based estimate
|
|
2301
|
+
const invoiceAmount = await this.decodeInvoiceAmount(invoice);
|
|
2302
|
+
return Math.max(5, Math.ceil(invoiceAmount * 0.0017)); // 17 bps or 5 sats minimum
|
|
2303
|
+
}
|
|
2304
|
+
catch {
|
|
2305
|
+
// Fallback to invoice amount-based estimate
|
|
2306
|
+
const invoiceAmount = await this.decodeInvoiceAmount(invoice);
|
|
2307
|
+
return Math.max(5, Math.ceil(invoiceAmount * 0.0017));
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
/**
|
|
2311
|
+
* Decode the amount from a Lightning invoice (in sats)
|
|
2312
|
+
* @private
|
|
2313
|
+
*/
|
|
2314
|
+
async decodeInvoiceAmount(invoice) {
|
|
2315
|
+
// Extract amount from BOLT11 invoice
|
|
2316
|
+
// Format: ln[network][amount][multiplier]...
|
|
2317
|
+
// Amount multipliers: m = milli (0.001), u = micro (0.000001), n = nano, p = pico
|
|
2318
|
+
const lowerInvoice = invoice.toLowerCase();
|
|
2319
|
+
// Find where the amount starts (after network prefix)
|
|
2320
|
+
let amountStart = 0;
|
|
2321
|
+
if (lowerInvoice.startsWith("lnbc")) {
|
|
2322
|
+
amountStart = 4;
|
|
2323
|
+
}
|
|
2324
|
+
else if (lowerInvoice.startsWith("lntb")) {
|
|
2325
|
+
amountStart = 4;
|
|
2326
|
+
}
|
|
2327
|
+
else if (lowerInvoice.startsWith("lnbcrt")) {
|
|
2328
|
+
amountStart = 6;
|
|
2329
|
+
}
|
|
2330
|
+
else if (lowerInvoice.startsWith("lntbs")) {
|
|
2331
|
+
amountStart = 5;
|
|
2332
|
+
}
|
|
2333
|
+
else {
|
|
2334
|
+
// Unknown format, try to find amount
|
|
2335
|
+
const match = lowerInvoice.match(/^ln[a-z]+/);
|
|
2336
|
+
if (match) {
|
|
2337
|
+
amountStart = match[0].length;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
// Extract amount and multiplier
|
|
2341
|
+
const afterPrefix = lowerInvoice.substring(amountStart);
|
|
2342
|
+
const amountMatch = afterPrefix.match(/^(\d+)([munp]?)/);
|
|
2343
|
+
if (!amountMatch || !amountMatch[1]) {
|
|
2344
|
+
return 0; // Zero-amount invoice
|
|
2345
|
+
}
|
|
2346
|
+
const amount = parseInt(amountMatch[1], 10);
|
|
2347
|
+
const multiplier = amountMatch[2] ?? "";
|
|
2348
|
+
// Convert to satoshis (1 BTC = 100,000,000 sats)
|
|
2349
|
+
// Invoice amounts are in BTC by default
|
|
2350
|
+
let btcAmount;
|
|
2351
|
+
switch (multiplier) {
|
|
2352
|
+
case "m": // milli-BTC (0.001 BTC)
|
|
2353
|
+
btcAmount = amount * 0.001;
|
|
2354
|
+
break;
|
|
2355
|
+
case "u": // micro-BTC (0.000001 BTC)
|
|
2356
|
+
btcAmount = amount * 0.000001;
|
|
2357
|
+
break;
|
|
2358
|
+
case "n": // nano-BTC (0.000000001 BTC)
|
|
2359
|
+
btcAmount = amount * 0.000000001;
|
|
2360
|
+
break;
|
|
2361
|
+
case "p": // pico-BTC (0.000000000001 BTC)
|
|
2362
|
+
btcAmount = amount * 0.000000000001;
|
|
2363
|
+
break;
|
|
2364
|
+
default: // BTC
|
|
2365
|
+
btcAmount = amount;
|
|
2366
|
+
break;
|
|
2367
|
+
}
|
|
2368
|
+
// Convert BTC to sats
|
|
2369
|
+
return Math.round(btcAmount * 100000000);
|
|
2370
|
+
}
|
|
1789
2371
|
/**
|
|
1790
2372
|
* Clean up wallet connections
|
|
1791
2373
|
*/
|