list admin swaps + payment state fixes

This commit is contained in:
boufni95 2026-01-10 14:21:54 +00:00
parent 0a385188ae
commit 008d11d047
15 changed files with 192 additions and 36 deletions

View file

@ -243,6 +243,11 @@ The nostr server will send back a message response, and inside the body there wi
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
- This methods has an __empty__ __response__ body
- ListAdminSwaps
- auth type: __Admin__
- This methods has an __empty__ __request__ body
- output: [SwapsList](#SwapsList)
- ListChannels
- auth type: __Admin__
- This methods has an __empty__ __request__ body
@ -829,6 +834,13 @@ The nostr server will send back a message response, and inside the body there wi
- input: [LinkNPubThroughTokenRequest](#LinkNPubThroughTokenRequest)
- This methods has an __empty__ __response__ body
- ListAdminSwaps
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/swap/list__
- This methods has an __empty__ __request__ body
- output: [SwapsList](#SwapsList)
- ListChannels
- auth type: __Admin__
- http method: __get__
@ -1548,8 +1560,11 @@ The nostr server will send back a message response, and inside the body there wi
### PaymentState
- __amount__: _number_
- __internal__: _boolean_
- __network_fee__: _number_
- __operation_id__: _string_
- __paid_at_unix__: _number_
- __preimage__: _string_ *this field is optional
- __service_fee__: _number_
### Product

View file

@ -114,6 +114,7 @@ type Client struct {
HandleLnurlWithdraw func(query HandleLnurlWithdraw_Query) error
Health func() error
LinkNPubThroughToken func(req LinkNPubThroughTokenRequest) error
ListAdminSwaps func() (*SwapsList, error)
ListChannels func() (*LndChannels, error)
ListSwaps func() (*SwapsList, error)
LndGetInfo func(req LndGetInfoRequest) (*LndGetInfoResponse, error)
@ -1642,6 +1643,32 @@ func NewClient(params ClientParams) *Client {
}
return nil
},
ListAdminSwaps: func() (*SwapsList, error) {
auth, err := params.RetrieveAdminAuth()
if err != nil {
return nil, err
}
finalRoute := "/api/admin/swap/list"
body := []byte{}
resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth)
if err != nil {
return nil, err
}
result := ResultError{}
err = json.Unmarshal(resBody, &result)
if err != nil {
return nil, err
}
if result.Status == "ERROR" {
return nil, fmt.Errorf(result.Reason)
}
res := SwapsList{}
err = json.Unmarshal(resBody, &res)
if err != nil {
return nil, err
}
return &res, nil
},
ListChannels: func() (*LndChannels, error) {
auth, err := params.RetrieveAdminAuth()
if err != nil {

View file

@ -584,10 +584,13 @@ type PayerData struct {
Data map[string]string `json:"data"`
}
type PaymentState struct {
Amount int64 `json:"amount"`
Network_fee int64 `json:"network_fee"`
Paid_at_unix int64 `json:"paid_at_unix"`
Service_fee int64 `json:"service_fee"`
Amount int64 `json:"amount"`
Internal bool `json:"internal"`
Network_fee int64 `json:"network_fee"`
Operation_id string `json:"operation_id"`
Paid_at_unix int64 `json:"paid_at_unix"`
Preimage string `json:"preimage"`
Service_fee int64 `json:"service_fee"`
}
type Product struct {
Id string `json:"id"`

View file

@ -1607,6 +1607,25 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.ListAdminSwaps) throw new Error('method: ListAdminSwaps is not implemented')
app.post('/api/admin/swap/list', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'ListAdminSwaps', batch: false, nostr: false, batchSize: 0}
const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n }
let authCtx: Types.AuthContext = {}
try {
if (!methods.ListAdminSwaps) throw new Error('method: ListAdminSwaps is not implemented')
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
authCtx = authContext
stats.guard = process.hrtime.bigint()
stats.validate = stats.guard
const query = req.query
const params = req.params
const response = await methods.ListAdminSwaps({rpcName:'ListAdminSwaps', ctx:authContext })
stats.handle = process.hrtime.bigint()
res.json({status: 'OK', ...response})
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
})
if (!opts.allowNotImplementedMethods && !methods.ListChannels) throw new Error('method: ListChannels is not implemented')
app.get('/api/admin/channels', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'ListChannels', batch: false, nostr: false, batchSize: 0}

View file

@ -781,6 +781,20 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
ListAdminSwaps: async (): Promise<ResultError | ({ status: 'OK' }& Types.SwapsList)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/admin/swap/list'
const { data } = await axios.post(params.baseUrl + finalRoute, {}, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.SwapsListValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
ListChannels: async (): Promise<ResultError | ({ status: 'OK' }& Types.LndChannels)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')

View file

@ -666,6 +666,20 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
}
return { status: 'ERROR', reason: 'invalid response' }
},
ListAdminSwaps: async (): Promise<ResultError | ({ status: 'OK' }& Types.SwapsList)> => {
const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
const nostrRequest: NostrRequest = {}
const data = await send(params.pubDestination, {rpcName:'ListAdminSwaps',authIdentifier:auth, ...nostrRequest })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
const result = data
if(!params.checkResult) return { status: 'OK', ...result }
const error = Types.SwapsListValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
ListChannels: async (): Promise<ResultError | ({ status: 'OK' }& Types.LndChannels)> => {
const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')

View file

@ -1122,6 +1122,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'ListAdminSwaps':
try {
if (!methods.ListAdminSwaps) throw new Error('method: ListAdminSwaps is not implemented')
const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
stats.validate = stats.guard
const response = await methods.ListAdminSwaps({rpcName:'ListAdminSwaps', ctx:authContext })
stats.handle = process.hrtime.bigint()
res({status: 'OK', ...response})
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
break
case 'ListChannels':
try {
if (!methods.ListChannels) throw new Error('method: ListChannels is not implemented')

View file

@ -7,8 +7,8 @@ export type RequestMetric = AuthContext & RequestInfo & RequestStats & { error?:
export type AdminContext = {
admin_id: string
}
export type AdminMethodInputs = AddApp_Input | AddPeer_Input | AuthApp_Input | BanUser_Input | CloseChannel_Input | CreateOneTimeInviteLink_Input | GetAdminTransactionSwapQuote_Input | GetInviteLinkState_Input | GetSeed_Input | ListChannels_Input | LndGetInfo_Input | OpenChannel_Input | PayAdminTransactionSwap_Input | UpdateChannelPolicy_Input
export type AdminMethodOutputs = AddApp_Output | AddPeer_Output | AuthApp_Output | BanUser_Output | CloseChannel_Output | CreateOneTimeInviteLink_Output | GetAdminTransactionSwapQuote_Output | GetInviteLinkState_Output | GetSeed_Output | ListChannels_Output | LndGetInfo_Output | OpenChannel_Output | PayAdminTransactionSwap_Output | UpdateChannelPolicy_Output
export type AdminMethodInputs = AddApp_Input | AddPeer_Input | AuthApp_Input | BanUser_Input | CloseChannel_Input | CreateOneTimeInviteLink_Input | GetAdminTransactionSwapQuote_Input | GetInviteLinkState_Input | GetSeed_Input | ListAdminSwaps_Input | ListChannels_Input | LndGetInfo_Input | OpenChannel_Input | PayAdminTransactionSwap_Input | UpdateChannelPolicy_Input
export type AdminMethodOutputs = AddApp_Output | AddPeer_Output | AuthApp_Output | BanUser_Output | CloseChannel_Output | CreateOneTimeInviteLink_Output | GetAdminTransactionSwapQuote_Output | GetInviteLinkState_Output | GetSeed_Output | ListAdminSwaps_Output | ListChannels_Output | LndGetInfo_Output | OpenChannel_Output | PayAdminTransactionSwap_Output | UpdateChannelPolicy_Output
export type AppContext = {
app_id: string
}
@ -238,6 +238,9 @@ export type Health_Output = ResultError | { status: 'OK' }
export type LinkNPubThroughToken_Input = {rpcName:'LinkNPubThroughToken', req: LinkNPubThroughTokenRequest}
export type LinkNPubThroughToken_Output = ResultError | { status: 'OK' }
export type ListAdminSwaps_Input = {rpcName:'ListAdminSwaps'}
export type ListAdminSwaps_Output = ResultError | ({ status: 'OK' } & SwapsList)
export type ListChannels_Input = {rpcName:'ListChannels'}
export type ListChannels_Output = ResultError | ({ status: 'OK' } & LndChannels)
@ -394,6 +397,7 @@ export type ServerMethods = {
HandleLnurlWithdraw?: (req: HandleLnurlWithdraw_Input & {ctx: GuestContext }) => Promise<void>
Health?: (req: Health_Input & {ctx: GuestContext }) => Promise<void>
LinkNPubThroughToken?: (req: LinkNPubThroughToken_Input & {ctx: GuestWithPubContext }) => Promise<void>
ListAdminSwaps?: (req: ListAdminSwaps_Input & {ctx: AdminContext }) => Promise<SwapsList>
ListChannels?: (req: ListChannels_Input & {ctx: AdminContext }) => Promise<LndChannels>
ListSwaps?: (req: ListSwaps_Input & {ctx: UserContext }) => Promise<SwapsList>
LndGetInfo?: (req: LndGetInfo_Input & {ctx: AdminContext }) => Promise<LndGetInfoResponse>
@ -3448,16 +3452,23 @@ export const PayerDataValidate = (o?: PayerData, opts: PayerDataOptions = {}, pa
export type PaymentState = {
amount: number
internal: boolean
network_fee: number
operation_id: string
paid_at_unix: number
preimage?: string
service_fee: number
}
export const PaymentStateOptionalFields: [] = []
export type PaymentStateOptionalField = 'preimage'
export const PaymentStateOptionalFields: PaymentStateOptionalField[] = ['preimage']
export type PaymentStateOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
checkOptionalsAreSet?: PaymentStateOptionalField[]
amount_CustomCheck?: (v: number) => boolean
internal_CustomCheck?: (v: boolean) => boolean
network_fee_CustomCheck?: (v: number) => boolean
operation_id_CustomCheck?: (v: string) => boolean
paid_at_unix_CustomCheck?: (v: number) => boolean
preimage_CustomCheck?: (v?: string) => boolean
service_fee_CustomCheck?: (v: number) => boolean
}
export const PaymentStateValidate = (o?: PaymentState, opts: PaymentStateOptions = {}, path: string = 'PaymentState::root.'): Error | null => {
@ -3467,12 +3478,21 @@ export const PaymentStateValidate = (o?: PaymentState, opts: PaymentStateOptions
if (typeof o.amount !== 'number') return new Error(`${path}.amount: is not a number`)
if (opts.amount_CustomCheck && !opts.amount_CustomCheck(o.amount)) return new Error(`${path}.amount: custom check failed`)
if (typeof o.internal !== 'boolean') return new Error(`${path}.internal: is not a boolean`)
if (opts.internal_CustomCheck && !opts.internal_CustomCheck(o.internal)) return new Error(`${path}.internal: custom check failed`)
if (typeof o.network_fee !== 'number') return new Error(`${path}.network_fee: is not a number`)
if (opts.network_fee_CustomCheck && !opts.network_fee_CustomCheck(o.network_fee)) return new Error(`${path}.network_fee: custom check failed`)
if (typeof o.operation_id !== 'string') return new Error(`${path}.operation_id: is not a string`)
if (opts.operation_id_CustomCheck && !opts.operation_id_CustomCheck(o.operation_id)) return new Error(`${path}.operation_id: custom check failed`)
if (typeof o.paid_at_unix !== 'number') return new Error(`${path}.paid_at_unix: is not a number`)
if (opts.paid_at_unix_CustomCheck && !opts.paid_at_unix_CustomCheck(o.paid_at_unix)) return new Error(`${path}.paid_at_unix: custom check failed`)
if ((o.preimage || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('preimage')) && typeof o.preimage !== 'string') return new Error(`${path}.preimage: is not a string`)
if (opts.preimage_CustomCheck && !opts.preimage_CustomCheck(o.preimage)) return new Error(`${path}.preimage: custom check failed`)
if (typeof o.service_fee !== 'number') return new Error(`${path}.service_fee: is not a number`)
if (opts.service_fee_CustomCheck && !opts.service_fee_CustomCheck(o.service_fee)) return new Error(`${path}.service_fee: custom check failed`)

View file

@ -189,6 +189,13 @@ service LightningPub {
option (nostr) = true;
}
rpc ListAdminSwaps(structs.Empty) returns (structs.SwapsList) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/swap/list";
option (nostr) = true;
}
rpc GetUsageMetrics(structs.LatestUsageMetricReq) returns (structs.UsageMetrics) {
option (auth_type) = "Metrics";
option (http_method) = "post";

View file

@ -490,6 +490,9 @@ message PaymentState{
int64 amount = 2;
int64 service_fee = 3;
int64 network_fee = 4;
bool internal = 5;
string operation_id = 6;
}
message LnurlLinkResponse{

View file

@ -17,6 +17,7 @@ import * as Types from '../../../proto/autogenerated/ts/types.js';
import { BTCNetwork } from '../main/settings.js';
import Storage from '../storage/index.js';
import LND from './lnd.js';
import { UserInvoicePayment } from '../storage/entity/UserInvoicePayment.js';
type InvoiceSwapResponse = { id: string, claimPublicKey: string, swapTree: string }
type InvoiceSwapInfo = { paymentHash: string, keys: ECPairInterface }
type InvoiceSwapData = { createdResponse: InvoiceSwapResponse, info: InvoiceSwapInfo }
@ -68,6 +69,34 @@ export class Swaps {
return keys
}
ListSwaps = async (appUserId: string, payments: UserInvoicePayment[], newOp: (p: UserInvoicePayment) => Types.UserOperation | undefined, getServiceFee: (amt: number) => number): Promise<Types.SwapsList> => {
const completedSwaps = await this.storage.paymentStorage.ListCompletedSwaps(appUserId, payments)
const pendingSwaps = await this.storage.paymentStorage.ListPendingTransactionSwaps(appUserId)
return {
swaps: completedSwaps.map(s => {
const p = s.payment
const op = p ? newOp(p) : undefined
return {
operation_payment: op,
swap_operation_id: s.swap.swap_operation_id,
address_paid: s.swap.address_paid,
failure_reason: s.swap.failure_reason,
}
}),
quotes: pendingSwaps.map(s => {
const serviceFee = getServiceFee(s.invoice_amount)
return {
swap_operation_id: s.swap_operation_id,
invoice_amount_sats: s.invoice_amount,
transaction_amount_sats: s.transaction_amount,
chain_fee_sats: s.chain_fee_sats,
service_fee_sats: serviceFee,
swap_fee_sats: s.swap_fee_sats,
}
})
}
}
async GetTxSwapQuote(appUserId: string, amt: number, getServiceFee: (decodedAmt: number) => number): Promise<Types.TransactionSwapQuote> {
this.log("getting transaction swap quote")
const feesRes = await this.reverseSwaps.GetFees()

View file

@ -260,6 +260,10 @@ export class AdminManager {
}
}
async ListAdminSwaps(): Promise<Types.SwapsList> {
return this.swaps.ListSwaps("admin", [], p => undefined, amt => 0)
}
async GetAdminTransactionSwapQuote(req: Types.TransactionSwapRequest): Promise<Types.TransactionSwapQuote> {
return this.swaps.GetTxSwapQuote("admin", req.transaction_amount_sats, () => 0)
}

View file

@ -616,34 +616,13 @@ export default class {
}
async ListSwaps(ctx: Types.UserContext): Promise<Types.SwapsList> {
const swaps = await this.storage.paymentStorage.ListCompletedSwaps(ctx.app_user_id)
const pendingSwaps = await this.storage.paymentStorage.ListPendingTransactionSwaps(ctx.app_user_id)
const payments = await this.storage.paymentStorage.ListSwapPayments(ctx.app_user_id)
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
const isManagedUser = ctx.user_id !== app.owner.user_id
return {
swaps: swaps.map(s => {
const p = s.payment
const opId = `${Types.UserOperationType.OUTGOING_TX}-${p?.serial_id}`
const op = p ? this.newInvoicePaymentOperation({ amount: p.paid_amount, confirmed: p.paid_at_unix !== 0, invoice: p.invoice, opId, networkFee: p.routing_fees, serviceFee: p.service_fees, paidAtUnix: p.paid_at_unix }) : undefined
return {
operation_payment: op,
swap_operation_id: s.swap.swap_operation_id,
address_paid: s.swap.address_paid,
failure_reason: s.swap.failure_reason,
}
}),
quotes: pendingSwaps.map(s => {
const serviceFee = this.getSendServiceFee(Types.UserOperationType.OUTGOING_INVOICE, s.invoice_amount, isManagedUser)
return {
swap_operation_id: s.swap_operation_id,
invoice_amount_sats: s.invoice_amount,
transaction_amount_sats: s.transaction_amount,
chain_fee_sats: s.chain_fee_sats,
service_fee_sats: serviceFee,
swap_fee_sats: s.swap_fee_sats,
}
})
}
return this.swaps.ListSwaps(ctx.app_user_id, payments, p => {
const opId = `${Types.UserOperationType.OUTGOING_TX}-${p.serial_id}`
return this.newInvoicePaymentOperation({ amount: p.paid_amount, confirmed: p.paid_at_unix !== 0, invoice: p.invoice, opId, networkFee: p.routing_fees, serviceFee: p.service_fees, paidAtUnix: p.paid_at_unix })
}, amt => this.getSendServiceFee(Types.UserOperationType.OUTGOING_INVOICE, amt, isManagedUser))
}
balanceCheckUrl(k1: string): string {
@ -918,6 +897,8 @@ export default class {
amount: invoice.paid_amount,
network_fee: 0,
service_fee: invoice.service_fees,
internal: invoice.internal,
operation_id: `${Types.UserOperationType.OUTGOING_INVOICE}-${invoice.serial_id}`,
}
}

View file

@ -137,6 +137,9 @@ export default (mainHandler: Main): Types.ServerMethods => {
GetUserOperations: async ({ ctx, req }) => {
return mainHandler.paymentManager.GetUserOperations(ctx.user_id, req)
},
ListAdminSwaps: async ({ ctx }) => {
return mainHandler.adminManager.ListAdminSwaps()
},
GetPaymentState: async ({ ctx, req }) => {
const err = Types.GetPaymentStateRequestValidate(req, {
invoice_CustomCheck: invoice => invoice !== ""

View file

@ -500,9 +500,13 @@ export default class {
return this.dbs.Find<TransactionSwap>('TransactionSwap', { where: { used: false, app_user_id: appUserId } }, txId)
}
async ListCompletedSwaps(appUserId: string, txId?: string) {
async ListSwapPayments(userId: string, txId?: string) {
return this.dbs.Find<UserInvoicePayment>('UserInvoicePayment', { where: { swap_operation_id: Not(IsNull()), user: { user_id: userId } } }, txId)
}
async ListCompletedSwaps(appUserId: string, payments: UserInvoicePayment[], txId?: string) {
const completed = await this.dbs.Find<TransactionSwap>('TransactionSwap', { where: { used: true, app_user_id: appUserId } }, txId)
const payments = await this.dbs.Find<UserInvoicePayment>('UserInvoicePayment', { where: { swap_operation_id: Not(IsNull()) } }, txId)
// const payments = await this.dbs.Find<UserInvoicePayment>('UserInvoicePayment', { where: { swap_operation_id: Not(IsNull()), } }, txId)
const paymentsMap = new Map<string, UserInvoicePayment>()
payments.forEach(p => {
paymentsMap.set(p.swap_operation_id, p)