Compare commits

...
Author SHA1 Message Date
Michilis 217c718bc1 error fix 2025-05-19 17:47:24 +02:00
Michilis 5c0f0a38de Cashu fee calculation update 2025-05-19 17:23:00 +02:00
Michilis 24b623e5e4 Cashu fee fix 2025-05-19 15:50:24 +02:00
MichilisandGitHub 97aa1d28fe Update faucet.go 2025-05-16 18:48:13 +02:00
6 changed files with 85 additions and 37 deletions
BIN
View File
Binary file not shown.
+19 -29
View File
@@ -10,29 +10,16 @@ const app = express();
const port = process.env.PORT || 3333;
const debug = process.env.DEBUG === 'true';
const maxRedeemedTokens = parseInt(process.env.MAX_REDEEMED_TOKENS || '10000');
const tokenExpirationHours = parseInt(process.env.TOKEN_EXPIRATION_HOURS || '24');
app.use(bodyParser.json());
// Store for tracking redeemed tokens with timestamps
const redeemedTokens = new Map();
// Store for tracking redeemed tokens
const redeemedTokens = new Set();
// Initialize Cashu wallet
const mintUrl = process.env.MINT_URL || 'https://kashu.me';
const wallet = new CashuWallet(new CashuMint(mintUrl));
// Cleanup expired tokens periodically
setInterval(() => {
if (tokenExpirationHours > 0) {
const now = Date.now();
for (const [token, timestamp] of redeemedTokens.entries()) {
if (now - timestamp > tokenExpirationHours * 60 * 60 * 1000) {
redeemedTokens.delete(token);
}
}
}
}, 60 * 60 * 1000); // Check every hour
// Helper function to validate token format
function isValidTokenFormat(token) {
// Match both v1 and v3 token formats
@@ -103,6 +90,14 @@ async function decodeToken(token) {
}
}
// Helper function to calculate fee according to NUT-05 specification
function calculateFee(amount) {
// Calculate 2% of the amount, rounded up
const fee = Math.ceil(amount * 0.02);
// Return the greater of 1 sat or the calculated fee
return Math.max(1, fee);
}
// Redeem endpoint
app.post('/redeem', async (req, res) => {
try {
@@ -193,26 +188,23 @@ app.post('/redeem', async (req, res) => {
});
}
// Mark token as redeemed with timestamp
redeemedTokens.set(token, Date.now());
// Calculate fee according to NUT-05 specification
const fee = calculateFee(amount);
// Cleanup if we have too many tokens
if (redeemedTokens.size > maxRedeemedTokens) {
const oldestToken = redeemedTokens.entries().next().value[0];
redeemedTokens.delete(oldestToken);
}
// Mark token as redeemed
redeemedTokens.add(token);
if (debug) {
console.log(`Redeemed token: ${token}, amount: ${amount}`);
console.log(`Redeemed token: ${token}, amount: ${amount}, fee: ${fee}`);
}
res.json({
success: true,
amount: amount,
mint_url: tokenMintUrl,
fee: 1, // 1 sat fee
total_amount: amount,
net_amount: amount - 1 // amount after fee
fee: fee,
net_amount: amount - fee // Net amount after fee deduction
});
} catch (error) {
console.error('Error redeeming token:', error);
@@ -294,7 +286,7 @@ app.post('/pay', async (req, res) => {
try {
// Get the mint URL from the last redeemed token
const lastToken = Array.from(redeemedTokens.keys()).pop();
const lastToken = Array.from(redeemedTokens)[redeemedTokens.size - 1];
if (!lastToken) {
return res.status(400).json({
success: false,
@@ -409,8 +401,7 @@ app.get('/health', (req, res) => {
mint_url: mintUrl,
redeemed_tokens: redeemedTokens.size,
debug_mode: debug,
max_tokens: maxRedeemedTokens,
token_expiration_hours: tokenExpirationHours
max_tokens: maxRedeemedTokens
});
});
@@ -419,5 +410,4 @@ app.listen(port, () => {
console.log(`Cashu redeem service listening on port ${port}`);
console.log(`Using mint URL: ${mintUrl}`);
console.log(`Debug mode: ${debug}`);
console.log(`Token expiration: ${tokenExpirationHours} hours`);
});
+15 -1
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"regexp"
"strings"
@@ -22,6 +23,18 @@ type RedeemResponse struct {
NetAmount int64 `json:"net_amount"`
}
// calculateFee calculates the fee according to NUT-05 specification
// Returns at least 1 sat, or 2% of the amount, whichever is greater
func calculateFee(amount int64) int64 {
// Calculate 2% of the amount
fee := int64(math.Ceil(float64(amount) * 0.02))
// Return the greater of 1 sat or the calculated fee
if fee < 1 {
return 1
}
return fee
}
// ContainsCashuToken checks if a message contains a Cashu token
func ContainsCashuToken(msg string) bool {
// Match both v1 and v3 token formats
@@ -144,6 +157,7 @@ func GetRedeemResponse(token string, serviceURL string) (*RedeemResponse, error)
return nil, fmt.Errorf("token redemption failed")
}
log.Printf("[Cashu] Successfully got redemption response for %d sats", result.Amount)
log.Printf("[Cashu] Successfully got redemption response for %d sats (fee: %d sats, net: %d sats)",
result.Amount, result.Fee, result.NetAmount)
return &result, nil
}
+1 -1
View File
@@ -66,7 +66,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 5 || amount%perUserAmount != 0 {
if perUserAmount < 1 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := int(amount / perUserAmount)
+29
View File
@@ -1,6 +1,7 @@
package telegram
import (
"context"
"fmt"
"strconv"
"time"
@@ -9,6 +10,7 @@ import (
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
)
// getChatIdFromRecipient will parse the recipient to int64
@@ -182,3 +184,30 @@ func (bot *TipBot) isAdminAndCanInviteUsers(chat *tb.Chat, me *tb.User) bool {
}
return false
}
// wrapHandler converts our intercept.Context handler to telebot.HandlerFunc
func (bot *TipBot) wrapHandler(handler func(ctx intercept.Context) (intercept.Context, error)) tb.HandlerFunc {
return func(c tb.Context) error {
ctx := intercept.Context{
Context: context.Background(),
TeleContext: intercept.TeleContext{Context: c},
}
_, err := handler(ctx)
return err
}
}
// Register command handlers
func (bot *TipBot) RegisterCommandHandlers() {
bot.handle("/start", bot.wrapHandler(bot.startHandler))
bot.handle("/help", bot.wrapHandler(bot.helpHandler))
bot.handle("/basics", bot.wrapHandler(bot.basicsHandler))
bot.handle("/balance", bot.wrapHandler(bot.balanceHandler))
bot.handle("/tip", bot.wrapHandler(bot.tipHandler))
bot.handle("/send", bot.wrapHandler(bot.sendHandler))
bot.handle("/invoice", bot.wrapHandler(bot.invoiceHandler))
bot.handle("/pay", bot.wrapHandler(bot.payHandler))
bot.handle("/transactions", bot.wrapHandler(bot.transactionsHandler))
bot.handle("/lnurl", bot.wrapHandler(bot.lnurlHandler))
bot.handle("/faucet", bot.wrapHandler(bot.faucetHandler))
}
+21 -6
View File
@@ -58,16 +58,22 @@ func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, err
return ctx, err
}
// Add a small fee buffer to account for routing fees
feeBuffer := response.Fee // Use the fee from the response
invoiceAmount := response.NetAmount // Use the net amount after fees
if invoiceAmount <= 0 {
// Check if amount is sufficient after getting the mint's response
if response.Amount <= 0 {
bot.tryDeleteMessage(processingMsg)
bot.trySendMessage(m.Sender, Translate(ctx, "cashuAmountTooSmallMessage"))
return ctx, fmt.Errorf("token amount too small")
}
// Create an invoice for the user to receive the payment
// Deduct the fee from the invoice amount to ensure the mint has enough to cover fees
invoiceAmount := response.Amount - response.Fee
if invoiceAmount <= 0 {
bot.tryDeleteMessage(processingMsg)
bot.trySendMessage(m.Sender, Translate(ctx, "cashuAmountTooSmallMessage"))
return ctx, fmt.Errorf("token amount too small after fee deduction")
}
invoiceParams := lnbits.InvoiceParams{
Out: false, // false means receiving payment
Amount: invoiceAmount,
@@ -113,14 +119,23 @@ func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, err
// Delete processing message and send success message
bot.tryDeleteMessage(processingMsg)
feeText := "sat"
if feeBuffer > 1 {
if response.Fee > 1 {
feeText = "sats"
}
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "cashuSuccessMessage"),
invoiceAmount,
response.MintURL,
feeBuffer,
response.Fee,
feeText))
// Refresh user's balance
balance, err := bot.GetUserBalance(user)
if err != nil {
log.Errorf("[Cashu] Error getting user balance: %v", err)
} else {
bot.trySendMessage(m.Sender, fmt.Sprintf("💰 Your new balance: %d sat", balance))
}
return ctx, nil
}