admin channels

This commit is contained in:
boufni95 2024-11-06 19:55:10 +00:00
parent 03d4bfc28f
commit 70dc928f1b
16 changed files with 590 additions and 109 deletions

View file

@ -18,6 +18,11 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AddAppRequest](#AddAppRequest) - input: [AddAppRequest](#AddAppRequest)
- output: [AuthApp](#AuthApp) - output: [AuthApp](#AuthApp)
- AddPeer
- auth type: __Admin__
- input: [AddPeerRequest](#AddPeerRequest)
- This methods has an __empty__ __response__ body
- AddProduct - AddProduct
- auth type: __User__ - auth type: __User__
- input: [AddProductRequest](#AddProductRequest) - input: [AddProductRequest](#AddProductRequest)
@ -48,6 +53,11 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body - This methods has an __empty__ __request__ body
- This methods has an __empty__ __response__ body - This methods has an __empty__ __response__ body
- CloseChannel
- auth type: __Admin__
- input: [CloseChannelRequest](#CloseChannelRequest)
- output: [CloseChannelResponse](#CloseChannelResponse)
- CreateOneTimeInviteLink - CreateOneTimeInviteLink
- auth type: __Admin__ - auth type: __Admin__
- input: [CreateOneTimeInviteLinkRequest](#CreateOneTimeInviteLinkRequest) - input: [CreateOneTimeInviteLinkRequest](#CreateOneTimeInviteLinkRequest)
@ -181,7 +191,7 @@ The nostr server will send back a message response, and inside the body there wi
- output: [NewInvoiceResponse](#NewInvoiceResponse) - output: [NewInvoiceResponse](#NewInvoiceResponse)
- OpenChannel - OpenChannel
- auth type: __User__ - auth type: __Admin__
- input: [OpenChannelRequest](#OpenChannelRequest) - input: [OpenChannelRequest](#OpenChannelRequest)
- output: [OpenChannelResponse](#OpenChannelResponse) - output: [OpenChannelResponse](#OpenChannelResponse)
@ -282,6 +292,13 @@ The nostr server will send back a message response, and inside the body there wi
- input: [AddAppUserInvoiceRequest](#AddAppUserInvoiceRequest) - input: [AddAppUserInvoiceRequest](#AddAppUserInvoiceRequest)
- output: [NewInvoiceResponse](#NewInvoiceResponse) - output: [NewInvoiceResponse](#NewInvoiceResponse)
- AddPeer
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/peer__
- input: [AddPeerRequest](#AddPeerRequest)
- This methods has an __empty__ __response__ body
- AddProduct - AddProduct
- auth type: __User__ - auth type: __User__
- http method: __post__ - http method: __post__
@ -324,6 +341,13 @@ The nostr server will send back a message response, and inside the body there wi
- This methods has an __empty__ __request__ body - This methods has an __empty__ __request__ body
- This methods has an __empty__ __response__ body - This methods has an __empty__ __response__ body
- CloseChannel
- auth type: __Admin__
- http method: __post__
- http route: __/api/admin/channel/close__
- input: [CloseChannelRequest](#CloseChannelRequest)
- output: [CloseChannelResponse](#CloseChannelResponse)
- CreateOneTimeInviteLink - CreateOneTimeInviteLink
- auth type: __Admin__ - auth type: __Admin__
- http method: __post__ - http method: __post__
@ -600,9 +624,9 @@ The nostr server will send back a message response, and inside the body there wi
- output: [NewInvoiceResponse](#NewInvoiceResponse) - output: [NewInvoiceResponse](#NewInvoiceResponse)
- OpenChannel - OpenChannel
- auth type: __User__ - auth type: __Admin__
- http method: __post__ - http method: __post__
- http route: __/api/user/open/channel__ - http route: __/api/admin/channel/open__
- input: [OpenChannelRequest](#OpenChannelRequest) - input: [OpenChannelRequest](#OpenChannelRequest)
- output: [OpenChannelResponse](#OpenChannelResponse) - output: [OpenChannelResponse](#OpenChannelResponse)
@ -736,6 +760,11 @@ The nostr server will send back a message response, and inside the body there wi
- __fail_if_exists__: _boolean_ - __fail_if_exists__: _boolean_
- __identifier__: _string_ - __identifier__: _string_
### AddPeerRequest
- __host__: _string_
- __port__: _number_
- __pubkey__: _string_
### AddProductRequest ### AddProductRequest
- __name__: _string_ - __name__: _string_
- __price_sats__: _number_ - __price_sats__: _number_
@ -794,6 +823,15 @@ The nostr server will send back a message response, and inside the body there wi
### CallbackUrl ### CallbackUrl
- __url__: _string_ - __url__: _string_
### CloseChannelRequest
- __force__: _boolean_
- __funding_txid__: _string_
- __output_index__: _number_
- __sat_per_v_byte__: _number_
### CloseChannelResponse
- __closing_txid__: _string_
### ClosedChannel ### ClosedChannel
- __capacity__: _number_ - __capacity__: _number_
- __channel_id__: _string_ - __channel_id__: _string_
@ -863,6 +901,9 @@ The nostr server will send back a message response, and inside the body there wi
### GetAppUserRequest ### GetAppUserRequest
- __user_identifier__: _string_ - __user_identifier__: _string_
### GetChannelPolicyRequest
- __channel_id__: _string_
### GetInviteTokenStateRequest ### GetInviteTokenStateRequest
- __invite_token__: _string_ - __invite_token__: _string_
@ -1004,13 +1045,14 @@ The nostr server will send back a message response, and inside the body there wi
- __remote_balance__: _number_ - __remote_balance__: _number_
### OpenChannelRequest ### OpenChannelRequest
- __closeAddress__: _string_ - __close_address__: _string_ *this field is optional
- __destination__: _string_ - __local_funding_amount__: _number_
- __fundingAmount__: _number_ - __node_pubkey__: _string_
- __pushAmount__: _number_ - __push_sat__: _number_ *this field is optional
- __sat_per_v_byte__: _number_
### OpenChannelResponse ### OpenChannelResponse
- __channelId__: _string_ - __channel_id__: _string_
### PayAddressRequest ### PayAddressRequest
- __address__: _string_ - __address__: _string_

View file

@ -58,12 +58,14 @@ type Client struct {
AddAppInvoice func(req AddAppInvoiceRequest) (*NewInvoiceResponse, error) AddAppInvoice func(req AddAppInvoiceRequest) (*NewInvoiceResponse, error)
AddAppUser func(req AddAppUserRequest) (*AppUser, error) AddAppUser func(req AddAppUserRequest) (*AppUser, error)
AddAppUserInvoice func(req AddAppUserInvoiceRequest) (*NewInvoiceResponse, error) AddAppUserInvoice func(req AddAppUserInvoiceRequest) (*NewInvoiceResponse, error)
AddPeer func(req AddPeerRequest) error
AddProduct func(req AddProductRequest) (*Product, error) AddProduct func(req AddProductRequest) (*Product, error)
AuthApp func(req AuthAppRequest) (*AuthApp, error) AuthApp func(req AuthAppRequest) (*AuthApp, error)
AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error) AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error)
BanDebit func(req DebitOperation) error BanDebit func(req DebitOperation) error
BanUser func(req BanUserRequest) (*BanUserResponse, error) BanUser func(req BanUserRequest) (*BanUserResponse, error)
// batching method: BatchUser not implemented // batching method: BatchUser not implemented
CloseChannel func(req CloseChannelRequest) (*CloseChannelResponse, error)
CreateOneTimeInviteLink func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error) CreateOneTimeInviteLink func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error)
DecodeInvoice func(req DecodeInvoiceRequest) (*DecodeInvoiceResponse, error) DecodeInvoice func(req DecodeInvoiceRequest) (*DecodeInvoiceResponse, error)
EditDebit func(req DebitAuthorizationRequest) error EditDebit func(req DebitAuthorizationRequest) error
@ -237,6 +239,30 @@ func NewClient(params ClientParams) *Client {
} }
return &res, nil return &res, nil
}, },
AddPeer: func(req AddPeerRequest) error {
auth, err := params.RetrieveAdminAuth()
if err != nil {
return err
}
finalRoute := "/api/admin/peer"
body, err := json.Marshal(req)
if err != nil {
return err
}
resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth)
if err != nil {
return err
}
result := ResultError{}
err = json.Unmarshal(resBody, &result)
if err != nil {
return err
}
if result.Status == "ERROR" {
return fmt.Errorf(result.Reason)
}
return nil
},
AddProduct: func(req AddProductRequest) (*Product, error) { AddProduct: func(req AddProductRequest) (*Product, error) {
auth, err := params.RetrieveUserAuth() auth, err := params.RetrieveUserAuth()
if err != nil { if err != nil {
@ -378,6 +404,35 @@ func NewClient(params ClientParams) *Client {
return &res, nil return &res, nil
}, },
// batching method: BatchUser not implemented // batching method: BatchUser not implemented
CloseChannel: func(req CloseChannelRequest) (*CloseChannelResponse, error) {
auth, err := params.RetrieveAdminAuth()
if err != nil {
return nil, err
}
finalRoute := "/api/admin/channel/close"
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
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 := CloseChannelResponse{}
err = json.Unmarshal(resBody, &res)
if err != nil {
return nil, err
}
return &res, nil
},
CreateOneTimeInviteLink: func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error) { CreateOneTimeInviteLink: func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error) {
auth, err := params.RetrieveAdminAuth() auth, err := params.RetrieveAdminAuth()
if err != nil { if err != nil {
@ -1267,11 +1322,11 @@ func NewClient(params ClientParams) *Client {
return &res, nil return &res, nil
}, },
OpenChannel: func(req OpenChannelRequest) (*OpenChannelResponse, error) { OpenChannel: func(req OpenChannelRequest) (*OpenChannelResponse, error) {
auth, err := params.RetrieveUserAuth() auth, err := params.RetrieveAdminAuth()
if err != nil { if err != nil {
return nil, err return nil, err
} }
finalRoute := "/api/user/open/channel" finalRoute := "/api/admin/channel/open"
body, err := json.Marshal(req) body, err := json.Marshal(req)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -95,6 +95,11 @@ type AddAppUserRequest struct {
Fail_if_exists bool `json:"fail_if_exists"` Fail_if_exists bool `json:"fail_if_exists"`
Identifier string `json:"identifier"` Identifier string `json:"identifier"`
} }
type AddPeerRequest struct {
Host string `json:"host"`
Port int64 `json:"port"`
Pubkey string `json:"pubkey"`
}
type AddProductRequest struct { type AddProductRequest struct {
Name string `json:"name"` Name string `json:"name"`
Price_sats int64 `json:"price_sats"` Price_sats int64 `json:"price_sats"`
@ -153,6 +158,15 @@ type BannedAppUser struct {
type CallbackUrl struct { type CallbackUrl struct {
Url string `json:"url"` Url string `json:"url"`
} }
type CloseChannelRequest struct {
Force bool `json:"force"`
Funding_txid string `json:"funding_txid"`
Output_index int64 `json:"output_index"`
Sat_per_v_byte int64 `json:"sat_per_v_byte"`
}
type CloseChannelResponse struct {
Closing_txid string `json:"closing_txid"`
}
type ClosedChannel struct { type ClosedChannel struct {
Capacity int64 `json:"capacity"` Capacity int64 `json:"capacity"`
Channel_id string `json:"channel_id"` Channel_id string `json:"channel_id"`
@ -222,6 +236,9 @@ type GetAppUserLNURLInfoRequest struct {
type GetAppUserRequest struct { type GetAppUserRequest struct {
User_identifier string `json:"user_identifier"` User_identifier string `json:"user_identifier"`
} }
type GetChannelPolicyRequest struct {
Channel_id string `json:"channel_id"`
}
type GetInviteTokenStateRequest struct { type GetInviteTokenStateRequest struct {
Invite_token string `json:"invite_token"` Invite_token string `json:"invite_token"`
} }
@ -363,13 +380,14 @@ type OpenChannel struct {
Remote_balance int64 `json:"remote_balance"` Remote_balance int64 `json:"remote_balance"`
} }
type OpenChannelRequest struct { type OpenChannelRequest struct {
Closeaddress string `json:"closeAddress"` Close_address string `json:"close_address"`
Destination string `json:"destination"` Local_funding_amount int64 `json:"local_funding_amount"`
Fundingamount int64 `json:"fundingAmount"` Node_pubkey string `json:"node_pubkey"`
Pushamount int64 `json:"pushAmount"` Push_sat int64 `json:"push_sat"`
Sat_per_v_byte int64 `json:"sat_per_v_byte"`
} }
type OpenChannelResponse struct { type OpenChannelResponse struct {
Channelid string `json:"channelId"` Channel_id string `json:"channel_id"`
} }
type PayAddressRequest struct { type PayAddressRequest struct {
Address string `json:"address"` Address string `json:"address"`

View file

@ -122,6 +122,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...authContext }]) 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 } } 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.AddPeer) throw new Error('method: AddPeer is not implemented')
app.post('/api/admin/peer', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'AddPeer', 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.AddPeer) throw new Error('method: AddPeer is not implemented')
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
authCtx = authContext
stats.guard = process.hrtime.bigint()
const request = req.body
const error = Types.AddPeerRequestValidate(request)
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
const query = req.query
const params = req.params
await methods.AddPeer({rpcName:'AddPeer', ctx:authContext , req: request})
stats.handle = process.hrtime.bigint()
res.json({status: 'OK'})
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.AddProduct) throw new Error('method: AddProduct is not implemented') if (!opts.allowNotImplementedMethods && !methods.AddProduct) throw new Error('method: AddProduct is not implemented')
app.post('/api/user/product/add', async (req, res) => { app.post('/api/user/product/add', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'AddProduct', batch: false, nostr: false, batchSize: 0} const info: Types.RequestInfo = { rpcName: 'AddProduct', batch: false, nostr: false, batchSize: 0}
@ -433,18 +455,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
} }
break break
case 'OpenChannel':
if (!methods.OpenChannel) {
throw new Error('method OpenChannel not found' )
} else {
const error = Types.OpenChannelRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'PayAddress': case 'PayAddress':
if (!methods.PayAddress) { if (!methods.PayAddress) {
throw new Error('method PayAddress not found' ) throw new Error('method PayAddress not found' )
@ -525,6 +535,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics]) opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics])
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } } 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.CloseChannel) throw new Error('method: CloseChannel is not implemented')
app.post('/api/admin/channel/close', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'CloseChannel', 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.CloseChannel) throw new Error('method: CloseChannel is not implemented')
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
authCtx = authContext
stats.guard = process.hrtime.bigint()
const request = req.body
const error = Types.CloseChannelRequestValidate(request)
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
const query = req.query
const params = req.params
const response = await methods.CloseChannel({rpcName:'CloseChannel', ctx:authContext , req: request})
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.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented') if (!opts.allowNotImplementedMethods && !methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented')
app.post('/api/admin/app/invite/create', async (req, res) => { app.post('/api/admin/app/invite/create', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'CreateOneTimeInviteLink', batch: false, nostr: false, batchSize: 0} const info: Types.RequestInfo = { rpcName: 'CreateOneTimeInviteLink', batch: false, nostr: false, batchSize: 0}
@ -1204,13 +1236,13 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } } 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.OpenChannel) throw new Error('method: OpenChannel is not implemented') if (!opts.allowNotImplementedMethods && !methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
app.post('/api/user/open/channel', async (req, res) => { app.post('/api/admin/channel/open', async (req, res) => {
const info: Types.RequestInfo = { rpcName: 'OpenChannel', batch: false, nostr: false, batchSize: 0} const info: Types.RequestInfo = { rpcName: 'OpenChannel', 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 } 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 = {} let authCtx: Types.AuthContext = {}
try { try {
if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented') if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
const authContext = await opts.UserAuthGuard(req.headers['authorization']) const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
authCtx = authContext authCtx = authContext
stats.guard = process.hrtime.bigint() stats.guard = process.hrtime.bigint()
const request = req.body const request = req.body

View file

@ -73,6 +73,17 @@ export default (params: ClientParams) => ({
} }
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
AddPeer: async (request: Types.AddPeerRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/admin/peer'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
AddProduct: async (request: Types.AddProductRequest): Promise<ResultError | ({ status: 'OK' }& Types.Product)> => { AddProduct: async (request: Types.AddProductRequest): Promise<ResultError | ({ status: 'OK' }& Types.Product)> => {
const auth = await params.retrieveUserAuth() const auth = await params.retrieveUserAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null') if (auth === null) throw new Error('retrieveUserAuth() returned null')
@ -151,6 +162,20 @@ export default (params: ClientParams) => ({
} }
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
CloseChannel: async (request: Types.CloseChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.CloseChannelResponse)> => {
const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/admin/channel/close'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { 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.CloseChannelResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => { CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => {
const auth = await params.retrieveAdminAuth() const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveAdminAuth() returned null') if (auth === null) throw new Error('retrieveAdminAuth() returned null')
@ -611,9 +636,9 @@ export default (params: ClientParams) => ({
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
OpenChannel: async (request: Types.OpenChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.OpenChannelResponse)> => { OpenChannel: async (request: Types.OpenChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.OpenChannelResponse)> => {
const auth = await params.retrieveUserAuth() const auth = await params.retrieveAdminAuth()
if (auth === null) throw new Error('retrieveUserAuth() returned null') if (auth === null) throw new Error('retrieveAdminAuth() returned null')
let finalRoute = '/api/user/open/channel' let finalRoute = '/api/admin/channel/open'
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') { if (data.status === 'OK') {

View file

@ -27,6 +27,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
} }
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
AddPeer: async (request: Types.AddPeerRequest): Promise<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
const nostrRequest: NostrRequest = {}
nostrRequest.body = request
const data = await send(params.pubDestination, {rpcName:'AddPeer',authIdentifier:auth, ...nostrRequest })
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
if (data.status === 'OK') {
return data
}
return { status: 'ERROR', reason: 'invalid response' }
},
AddProduct: async (request: Types.AddProductRequest): Promise<ResultError | ({ status: 'OK' }& Types.Product)> => { AddProduct: async (request: Types.AddProductRequest): Promise<ResultError | ({ status: 'OK' }& Types.Product)> => {
const auth = await params.retrieveNostrUserAuth() const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
@ -110,6 +122,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
} }
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
CloseChannel: async (request: Types.CloseChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.CloseChannelResponse)> => {
const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
const nostrRequest: NostrRequest = {}
nostrRequest.body = request
const data = await send(params.pubDestination, {rpcName:'CloseChannel',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.CloseChannelResponseValidate(result)
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
}
return { status: 'ERROR', reason: 'invalid response' }
},
CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => { CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise<ResultError | ({ status: 'OK' }& Types.CreateOneTimeInviteLinkResponse)> => {
const auth = await params.retrieveNostrAdminAuth() const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null') if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
@ -484,8 +511,8 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
return { status: 'ERROR', reason: 'invalid response' } return { status: 'ERROR', reason: 'invalid response' }
}, },
OpenChannel: async (request: Types.OpenChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.OpenChannelResponse)> => { OpenChannel: async (request: Types.OpenChannelRequest): Promise<ResultError | ({ status: 'OK' }& Types.OpenChannelResponse)> => {
const auth = await params.retrieveNostrUserAuth() const auth = await params.retrieveNostrAdminAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null')
const nostrRequest: NostrRequest = {} const nostrRequest: NostrRequest = {}
nostrRequest.body = request nostrRequest.body = request
const data = await send(params.pubDestination, {rpcName:'OpenChannel',authIdentifier:auth, ...nostrRequest }) const data = await send(params.pubDestination, {rpcName:'OpenChannel',authIdentifier:auth, ...nostrRequest })

View file

@ -48,6 +48,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...authContext }]) 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 } }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 break
case 'AddPeer':
try {
if (!methods.AddPeer) throw new Error('method: AddPeer is not implemented')
const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.AddPeerRequestValidate(request)
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
await methods.AddPeer({rpcName:'AddPeer', ctx:authContext , req: request})
stats.handle = process.hrtime.bigint()
res({status: 'OK'})
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 'AddProduct': case 'AddProduct':
try { try {
if (!methods.AddProduct) throw new Error('method: AddProduct is not implemented') if (!methods.AddProduct) throw new Error('method: AddProduct is not implemented')
@ -327,18 +343,6 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
} }
break break
case 'OpenChannel':
if (!methods.OpenChannel) {
throw new Error('method not defined: OpenChannel')
} else {
const error = Types.OpenChannelRequestValidate(operation.req)
opStats.validate = process.hrtime.bigint()
if (error !== null) throw error
const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res })
opStats.handle = process.hrtime.bigint()
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
}
break
case 'PayAddress': case 'PayAddress':
if (!methods.PayAddress) { if (!methods.PayAddress) {
throw new Error('method not defined: PayAddress') throw new Error('method not defined: PayAddress')
@ -419,6 +423,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics]) opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics])
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }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 break
case 'CloseChannel':
try {
if (!methods.CloseChannel) throw new Error('method: CloseChannel is not implemented')
const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint()
authCtx = authContext
const request = req.body
const error = Types.CloseChannelRequestValidate(request)
stats.validate = process.hrtime.bigint()
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
const response = await methods.CloseChannel({rpcName:'CloseChannel', ctx:authContext , req: request})
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 'CreateOneTimeInviteLink': case 'CreateOneTimeInviteLink':
try { try {
if (!methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented') if (!methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented')
@ -799,7 +819,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
case 'OpenChannel': case 'OpenChannel':
try { try {
if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented') if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier)
stats.guard = process.hrtime.bigint() stats.guard = process.hrtime.bigint()
authCtx = authContext authCtx = authContext
const request = req.body const request = req.body

View file

@ -7,8 +7,8 @@ export type RequestMetric = AuthContext & RequestInfo & RequestStats & { error?:
export type AdminContext = { export type AdminContext = {
admin_id: string admin_id: string
} }
export type AdminMethodInputs = AddApp_Input | AuthApp_Input | BanUser_Input | CreateOneTimeInviteLink_Input | GetInviteLinkState_Input | GetSeed_Input | ListChannels_Input | LndGetInfo_Input export type AdminMethodInputs = AddApp_Input | AddPeer_Input | AuthApp_Input | BanUser_Input | CloseChannel_Input | CreateOneTimeInviteLink_Input | GetInviteLinkState_Input | GetSeed_Input | ListChannels_Input | LndGetInfo_Input | OpenChannel_Input
export type AdminMethodOutputs = AddApp_Output | AuthApp_Output | BanUser_Output | CreateOneTimeInviteLink_Output | GetInviteLinkState_Output | GetSeed_Output | ListChannels_Output | LndGetInfo_Output export type AdminMethodOutputs = AddApp_Output | AddPeer_Output | AuthApp_Output | BanUser_Output | CloseChannel_Output | CreateOneTimeInviteLink_Output | GetInviteLinkState_Output | GetSeed_Output | ListChannels_Output | LndGetInfo_Output | OpenChannel_Output
export type AppContext = { export type AppContext = {
app_id: string app_id: string
} }
@ -34,8 +34,8 @@ export type UserContext = {
app_user_id: string app_user_id: string
user_id: string user_id: string
} }
export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input
export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest} export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
@ -50,6 +50,9 @@ export type AddAppUser_Output = ResultError | ({ status: 'OK' } & AppUser)
export type AddAppUserInvoice_Input = {rpcName:'AddAppUserInvoice', req: AddAppUserInvoiceRequest} export type AddAppUserInvoice_Input = {rpcName:'AddAppUserInvoice', req: AddAppUserInvoiceRequest}
export type AddAppUserInvoice_Output = ResultError | ({ status: 'OK' } & NewInvoiceResponse) export type AddAppUserInvoice_Output = ResultError | ({ status: 'OK' } & NewInvoiceResponse)
export type AddPeer_Input = {rpcName:'AddPeer', req: AddPeerRequest}
export type AddPeer_Output = ResultError | { status: 'OK' }
export type AddProduct_Input = {rpcName:'AddProduct', req: AddProductRequest} export type AddProduct_Input = {rpcName:'AddProduct', req: AddProductRequest}
export type AddProduct_Output = ResultError | ({ status: 'OK' } & Product) export type AddProduct_Output = ResultError | ({ status: 'OK' } & Product)
@ -68,6 +71,9 @@ export type BanUser_Output = ResultError | ({ status: 'OK' } & BanUserResponse)
export type BatchUser_Input = UserMethodInputs export type BatchUser_Input = UserMethodInputs
export type BatchUser_Output = UserMethodOutputs export type BatchUser_Output = UserMethodOutputs
export type CloseChannel_Input = {rpcName:'CloseChannel', req: CloseChannelRequest}
export type CloseChannel_Output = ResultError | ({ status: 'OK' } & CloseChannelResponse)
export type CreateOneTimeInviteLink_Input = {rpcName:'CreateOneTimeInviteLink', req: CreateOneTimeInviteLinkRequest} export type CreateOneTimeInviteLink_Input = {rpcName:'CreateOneTimeInviteLink', req: CreateOneTimeInviteLinkRequest}
export type CreateOneTimeInviteLink_Output = ResultError | ({ status: 'OK' } & CreateOneTimeInviteLinkResponse) export type CreateOneTimeInviteLink_Output = ResultError | ({ status: 'OK' } & CreateOneTimeInviteLinkResponse)
@ -254,11 +260,13 @@ export type ServerMethods = {
AddAppInvoice?: (req: AddAppInvoice_Input & {ctx: AppContext }) => Promise<NewInvoiceResponse> AddAppInvoice?: (req: AddAppInvoice_Input & {ctx: AppContext }) => Promise<NewInvoiceResponse>
AddAppUser?: (req: AddAppUser_Input & {ctx: AppContext }) => Promise<AppUser> AddAppUser?: (req: AddAppUser_Input & {ctx: AppContext }) => Promise<AppUser>
AddAppUserInvoice?: (req: AddAppUserInvoice_Input & {ctx: AppContext }) => Promise<NewInvoiceResponse> AddAppUserInvoice?: (req: AddAppUserInvoice_Input & {ctx: AppContext }) => Promise<NewInvoiceResponse>
AddPeer?: (req: AddPeer_Input & {ctx: AdminContext }) => Promise<void>
AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise<Product> AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise<Product>
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp> AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization> AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization>
BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void> BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void>
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse> BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise<CloseChannelResponse>
CreateOneTimeInviteLink?: (req: CreateOneTimeInviteLink_Input & {ctx: AdminContext }) => Promise<CreateOneTimeInviteLinkResponse> CreateOneTimeInviteLink?: (req: CreateOneTimeInviteLink_Input & {ctx: AdminContext }) => Promise<CreateOneTimeInviteLinkResponse>
DecodeInvoice?: (req: DecodeInvoice_Input & {ctx: UserContext }) => Promise<DecodeInvoiceResponse> DecodeInvoice?: (req: DecodeInvoice_Input & {ctx: UserContext }) => Promise<DecodeInvoiceResponse>
EditDebit?: (req: EditDebit_Input & {ctx: UserContext }) => Promise<void> EditDebit?: (req: EditDebit_Input & {ctx: UserContext }) => Promise<void>
@ -296,7 +304,7 @@ export type ServerMethods = {
NewAddress?: (req: NewAddress_Input & {ctx: UserContext }) => Promise<NewAddressResponse> NewAddress?: (req: NewAddress_Input & {ctx: UserContext }) => Promise<NewAddressResponse>
NewInvoice?: (req: NewInvoice_Input & {ctx: UserContext }) => Promise<NewInvoiceResponse> NewInvoice?: (req: NewInvoice_Input & {ctx: UserContext }) => Promise<NewInvoiceResponse>
NewProductInvoice?: (req: NewProductInvoice_Input & {ctx: UserContext }) => Promise<NewInvoiceResponse> NewProductInvoice?: (req: NewProductInvoice_Input & {ctx: UserContext }) => Promise<NewInvoiceResponse>
OpenChannel?: (req: OpenChannel_Input & {ctx: UserContext }) => Promise<OpenChannelResponse> OpenChannel?: (req: OpenChannel_Input & {ctx: AdminContext }) => Promise<OpenChannelResponse>
PayAddress?: (req: PayAddress_Input & {ctx: UserContext }) => Promise<PayAddressResponse> PayAddress?: (req: PayAddress_Input & {ctx: UserContext }) => Promise<PayAddressResponse>
PayAppUserInvoice?: (req: PayAppUserInvoice_Input & {ctx: AppContext }) => Promise<PayInvoiceResponse> PayAppUserInvoice?: (req: PayAppUserInvoice_Input & {ctx: AppContext }) => Promise<PayInvoiceResponse>
PayInvoice?: (req: PayInvoice_Input & {ctx: UserContext }) => Promise<PayInvoiceResponse> PayInvoice?: (req: PayInvoice_Input & {ctx: UserContext }) => Promise<PayInvoiceResponse>
@ -463,6 +471,34 @@ export const AddAppUserRequestValidate = (o?: AddAppUserRequest, opts: AddAppUse
return null return null
} }
export type AddPeerRequest = {
host: string
port: number
pubkey: string
}
export const AddPeerRequestOptionalFields: [] = []
export type AddPeerRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
host_CustomCheck?: (v: string) => boolean
port_CustomCheck?: (v: number) => boolean
pubkey_CustomCheck?: (v: string) => boolean
}
export const AddPeerRequestValidate = (o?: AddPeerRequest, opts: AddPeerRequestOptions = {}, path: string = 'AddPeerRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.host !== 'string') return new Error(`${path}.host: is not a string`)
if (opts.host_CustomCheck && !opts.host_CustomCheck(o.host)) return new Error(`${path}.host: custom check failed`)
if (typeof o.port !== 'number') return new Error(`${path}.port: is not a number`)
if (opts.port_CustomCheck && !opts.port_CustomCheck(o.port)) return new Error(`${path}.port: custom check failed`)
if (typeof o.pubkey !== 'string') return new Error(`${path}.pubkey: is not a string`)
if (opts.pubkey_CustomCheck && !opts.pubkey_CustomCheck(o.pubkey)) return new Error(`${path}.pubkey: custom check failed`)
return null
}
export type AddProductRequest = { export type AddProductRequest = {
name: string name: string
price_sats: number price_sats: number
@ -810,6 +846,57 @@ export const CallbackUrlValidate = (o?: CallbackUrl, opts: CallbackUrlOptions =
return null return null
} }
export type CloseChannelRequest = {
force: boolean
funding_txid: string
output_index: number
sat_per_v_byte: number
}
export const CloseChannelRequestOptionalFields: [] = []
export type CloseChannelRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
force_CustomCheck?: (v: boolean) => boolean
funding_txid_CustomCheck?: (v: string) => boolean
output_index_CustomCheck?: (v: number) => boolean
sat_per_v_byte_CustomCheck?: (v: number) => boolean
}
export const CloseChannelRequestValidate = (o?: CloseChannelRequest, opts: CloseChannelRequestOptions = {}, path: string = 'CloseChannelRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.force !== 'boolean') return new Error(`${path}.force: is not a boolean`)
if (opts.force_CustomCheck && !opts.force_CustomCheck(o.force)) return new Error(`${path}.force: custom check failed`)
if (typeof o.funding_txid !== 'string') return new Error(`${path}.funding_txid: is not a string`)
if (opts.funding_txid_CustomCheck && !opts.funding_txid_CustomCheck(o.funding_txid)) return new Error(`${path}.funding_txid: custom check failed`)
if (typeof o.output_index !== 'number') return new Error(`${path}.output_index: is not a number`)
if (opts.output_index_CustomCheck && !opts.output_index_CustomCheck(o.output_index)) return new Error(`${path}.output_index: custom check failed`)
if (typeof o.sat_per_v_byte !== 'number') return new Error(`${path}.sat_per_v_byte: is not a number`)
if (opts.sat_per_v_byte_CustomCheck && !opts.sat_per_v_byte_CustomCheck(o.sat_per_v_byte)) return new Error(`${path}.sat_per_v_byte: custom check failed`)
return null
}
export type CloseChannelResponse = {
closing_txid: string
}
export const CloseChannelResponseOptionalFields: [] = []
export type CloseChannelResponseOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
closing_txid_CustomCheck?: (v: string) => boolean
}
export const CloseChannelResponseValidate = (o?: CloseChannelResponse, opts: CloseChannelResponseOptions = {}, path: string = 'CloseChannelResponse::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.closing_txid !== 'string') return new Error(`${path}.closing_txid: is not a string`)
if (opts.closing_txid_CustomCheck && !opts.closing_txid_CustomCheck(o.closing_txid)) return new Error(`${path}.closing_txid: custom check failed`)
return null
}
export type ClosedChannel = { export type ClosedChannel = {
capacity: number capacity: number
channel_id: string channel_id: string
@ -1231,6 +1318,24 @@ export const GetAppUserRequestValidate = (o?: GetAppUserRequest, opts: GetAppUse
return null return null
} }
export type GetChannelPolicyRequest = {
channel_id: string
}
export const GetChannelPolicyRequestOptionalFields: [] = []
export type GetChannelPolicyRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: []
channel_id_CustomCheck?: (v: string) => boolean
}
export const GetChannelPolicyRequestValidate = (o?: GetChannelPolicyRequest, opts: GetChannelPolicyRequestOptions = {}, path: string = 'GetChannelPolicyRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.channel_id !== 'string') return new Error(`${path}.channel_id: is not a string`)
if (opts.channel_id_CustomCheck && !opts.channel_id_CustomCheck(o.channel_id)) return new Error(`${path}.channel_id: custom check failed`)
return null
}
export type GetInviteTokenStateRequest = { export type GetInviteTokenStateRequest = {
invite_token: string invite_token: string
} }
@ -2083,52 +2188,58 @@ export const OpenChannelValidate = (o?: OpenChannel, opts: OpenChannelOptions =
} }
export type OpenChannelRequest = { export type OpenChannelRequest = {
closeAddress: string close_address?: string
destination: string local_funding_amount: number
fundingAmount: number node_pubkey: string
pushAmount: number push_sat?: number
sat_per_v_byte: number
} }
export const OpenChannelRequestOptionalFields: [] = [] export type OpenChannelRequestOptionalField = 'close_address' | 'push_sat'
export const OpenChannelRequestOptionalFields: OpenChannelRequestOptionalField[] = ['close_address', 'push_sat']
export type OpenChannelRequestOptions = OptionsBaseMessage & { export type OpenChannelRequestOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: [] checkOptionalsAreSet?: OpenChannelRequestOptionalField[]
closeAddress_CustomCheck?: (v: string) => boolean close_address_CustomCheck?: (v?: string) => boolean
destination_CustomCheck?: (v: string) => boolean local_funding_amount_CustomCheck?: (v: number) => boolean
fundingAmount_CustomCheck?: (v: number) => boolean node_pubkey_CustomCheck?: (v: string) => boolean
pushAmount_CustomCheck?: (v: number) => boolean push_sat_CustomCheck?: (v?: number) => boolean
sat_per_v_byte_CustomCheck?: (v: number) => boolean
} }
export const OpenChannelRequestValidate = (o?: OpenChannelRequest, opts: OpenChannelRequestOptions = {}, path: string = 'OpenChannelRequest::root.'): Error | null => { export const OpenChannelRequestValidate = (o?: OpenChannelRequest, opts: OpenChannelRequestOptions = {}, path: string = 'OpenChannelRequest::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.closeAddress !== 'string') return new Error(`${path}.closeAddress: is not a string`) if ((o.close_address || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('close_address')) && typeof o.close_address !== 'string') return new Error(`${path}.close_address: is not a string`)
if (opts.closeAddress_CustomCheck && !opts.closeAddress_CustomCheck(o.closeAddress)) return new Error(`${path}.closeAddress: custom check failed`) if (opts.close_address_CustomCheck && !opts.close_address_CustomCheck(o.close_address)) return new Error(`${path}.close_address: custom check failed`)
if (typeof o.destination !== 'string') return new Error(`${path}.destination: is not a string`) if (typeof o.local_funding_amount !== 'number') return new Error(`${path}.local_funding_amount: is not a number`)
if (opts.destination_CustomCheck && !opts.destination_CustomCheck(o.destination)) return new Error(`${path}.destination: custom check failed`) if (opts.local_funding_amount_CustomCheck && !opts.local_funding_amount_CustomCheck(o.local_funding_amount)) return new Error(`${path}.local_funding_amount: custom check failed`)
if (typeof o.fundingAmount !== 'number') return new Error(`${path}.fundingAmount: is not a number`) if (typeof o.node_pubkey !== 'string') return new Error(`${path}.node_pubkey: is not a string`)
if (opts.fundingAmount_CustomCheck && !opts.fundingAmount_CustomCheck(o.fundingAmount)) return new Error(`${path}.fundingAmount: custom check failed`) if (opts.node_pubkey_CustomCheck && !opts.node_pubkey_CustomCheck(o.node_pubkey)) return new Error(`${path}.node_pubkey: custom check failed`)
if (typeof o.pushAmount !== 'number') return new Error(`${path}.pushAmount: is not a number`) if ((o.push_sat || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('push_sat')) && typeof o.push_sat !== 'number') return new Error(`${path}.push_sat: is not a number`)
if (opts.pushAmount_CustomCheck && !opts.pushAmount_CustomCheck(o.pushAmount)) return new Error(`${path}.pushAmount: custom check failed`) if (opts.push_sat_CustomCheck && !opts.push_sat_CustomCheck(o.push_sat)) return new Error(`${path}.push_sat: custom check failed`)
if (typeof o.sat_per_v_byte !== 'number') return new Error(`${path}.sat_per_v_byte: is not a number`)
if (opts.sat_per_v_byte_CustomCheck && !opts.sat_per_v_byte_CustomCheck(o.sat_per_v_byte)) return new Error(`${path}.sat_per_v_byte: custom check failed`)
return null return null
} }
export type OpenChannelResponse = { export type OpenChannelResponse = {
channelId: string channel_id: string
} }
export const OpenChannelResponseOptionalFields: [] = [] export const OpenChannelResponseOptionalFields: [] = []
export type OpenChannelResponseOptions = OptionsBaseMessage & { export type OpenChannelResponseOptions = OptionsBaseMessage & {
checkOptionalsAreSet?: [] checkOptionalsAreSet?: []
channelId_CustomCheck?: (v: string) => boolean channel_id_CustomCheck?: (v: string) => boolean
} }
export const OpenChannelResponseValidate = (o?: OpenChannelResponse, opts: OpenChannelResponseOptions = {}, path: string = 'OpenChannelResponse::root.'): Error | null => { export const OpenChannelResponseValidate = (o?: OpenChannelResponse, opts: OpenChannelResponseOptions = {}, path: string = 'OpenChannelResponse::root.'): Error | null => {
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
if (typeof o.channelId !== 'string') return new Error(`${path}.channelId: is not a string`) if (typeof o.channel_id !== 'string') return new Error(`${path}.channel_id: is not a string`)
if (opts.channelId_CustomCheck && !opts.channelId_CustomCheck(o.channelId)) return new Error(`${path}.channelId: custom check failed`) if (opts.channel_id_CustomCheck && !opts.channel_id_CustomCheck(o.channel_id)) return new Error(`${path}.channel_id: custom check failed`)
return null return null
} }

View file

@ -144,6 +144,27 @@ service LightningPub {
option (nostr) = true; option (nostr) = true;
} }
rpc AddPeer(structs.AddPeerRequest) returns (structs.Empty) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/peer";
option (nostr) = true;
}
rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/channel/open";
option (nostr) = true;
}
rpc CloseChannel(structs.CloseChannelRequest) returns (structs.CloseChannelResponse) {
option (auth_type) = "Admin";
option (http_method) = "post";
option (http_route) = "/api/admin/channel/close";
option (nostr) = true;
}
rpc GetUsageMetrics(structs.Empty) returns (structs.UsageMetrics) { rpc GetUsageMetrics(structs.Empty) returns (structs.UsageMetrics) {
option (auth_type) = "Metrics"; option (auth_type) = "Metrics";
option (http_method) = "post"; option (http_method) = "post";
@ -419,13 +440,6 @@ service LightningPub {
option (nostr) = true; option (nostr) = true;
} }
rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse){
option (auth_type) = "User";
option (http_method) = "post";
option (http_route) = "/api/user/open/channel";
option (nostr) = true;
}
rpc GetLnurlWithdrawLink(structs.Empty) returns (structs.LnurlLinkResponse){ rpc GetLnurlWithdrawLink(structs.Empty) returns (structs.LnurlLinkResponse){
option (auth_type) = "User"; option (auth_type) = "User";
option (http_method) = "get"; option (http_method) = "get";

View file

@ -131,6 +131,41 @@ message LndChannels {
repeated OpenChannel open_channels = 1; repeated OpenChannel open_channels = 1;
} }
message GetChannelPolicyRequest {
string channel_id = 1;
}
message OpenChannelRequest{
string node_pubkey = 1;
int64 local_funding_amount = 2;
int64 sat_per_v_byte = 3;
optional int64 push_sat = 5;
optional string close_address = 6;
}
message OpenChannelResponse{
string channel_id = 1;
}
message CloseChannelRequest{
bool force = 2;
int64 sat_per_v_byte = 3;
string funding_txid = 4;
int64 output_index = 5;
}
message CloseChannelResponse{
string closing_txid = 1;
}
message AddPeerRequest {
string pubkey = 1;
string host = 2;
int64 port = 3;
}
message LndGetInfoRequest { message LndGetInfoRequest {
int64 nodeId = 1; int64 nodeId = 1;
} }
@ -308,17 +343,6 @@ message PaymentState{
int64 network_fee = 4; int64 network_fee = 4;
} }
message OpenChannelRequest{
string destination = 1;
int64 fundingAmount = 2;
int64 pushAmount = 3;
string closeAddress = 4;
}
message OpenChannelResponse{
string channelId = 1;
}
message LnurlLinkResponse{ message LnurlLinkResponse{
string lnurl = 1; string lnurl = 1;
string k1 = 2; string k1 = 2;

View file

@ -8,7 +8,7 @@ import { LightningClient } from '../../../proto/lnd/lightning.client.js'
import { InvoicesClient } from '../../../proto/lnd/invoices.client.js' import { InvoicesClient } from '../../../proto/lnd/invoices.client.js'
import { RouterClient } from '../../../proto/lnd/router.client.js' import { RouterClient } from '../../../proto/lnd/router.client.js'
import { ChainNotifierClient } from '../../../proto/lnd/chainnotifier.client.js' import { ChainNotifierClient } from '../../../proto/lnd/chainnotifier.client.js'
import { GetInfoResponse, AddressType, NewAddressResponse, AddInvoiceResponse, Invoice_InvoiceState, PayReq, Payment_PaymentStatus, Payment, PaymentFailureReason, SendCoinsResponse, EstimateFeeResponse, ChannelBalanceResponse, TransactionDetails, ListChannelsResponse, ClosedChannelsResponse, PendingChannelsResponse, ForwardingHistoryResponse, CoinSelectionStrategy } from '../../../proto/lnd/lightning.js' import { GetInfoResponse, AddressType, NewAddressResponse, AddInvoiceResponse, Invoice_InvoiceState, PayReq, Payment_PaymentStatus, Payment, PaymentFailureReason, SendCoinsResponse, EstimateFeeResponse, ChannelBalanceResponse, TransactionDetails, ListChannelsResponse, ClosedChannelsResponse, PendingChannelsResponse, ForwardingHistoryResponse, CoinSelectionStrategy, OpenStatusUpdate, CloseStatusUpdate, PendingUpdate } from '../../../proto/lnd/lightning.js'
import { OpenChannelReq } from './openChannelReq.js'; import { OpenChannelReq } from './openChannelReq.js';
import { AddInvoiceReq } from './addInvoiceReq.js'; import { AddInvoiceReq } from './addInvoiceReq.js';
import { PayInvoiceReq } from './payInvoiceReq.js'; import { PayInvoiceReq } from './payInvoiceReq.js';
@ -380,6 +380,11 @@ export default class {
return res.response return res.response
} }
async GetChannelInfo(chanId: string) {
const res = await this.lightning.getChanInfo({ chanId, chanPoint: "" }, DeadLineMetadata())
return res.response
}
async GetChannelBalance() { async GetChannelBalance() {
const res = await this.lightning.channelBalance({}, DeadLineMetadata()) const res = await this.lightning.channelBalance({}, DeadLineMetadata())
return res.response return res.response
@ -485,21 +490,66 @@ export default class {
} }
async AddPeer(pub: string, host: string, port: number) {
const res = await this.lightning.connectPeer({
addr: {
pubkey: pub,
host: host + ":" + port,
},
perm: true,
timeout: 0n
})
return res.response
}
async ListPeers() { async ListPeers() {
const res = await this.lightning.listPeers({ latestError: true }, DeadLineMetadata()) const res = await this.lightning.listPeers({ latestError: true }, DeadLineMetadata())
return res.response return res.response
} }
async OpenChannel(destination: string, closeAddress: string, fundingAmount: number, pushSats: number) { async OpenChannel(destination: string, closeAddress: string, fundingAmount: number, pushSats: number, satsPerVByte: number): Promise<OpenStatusUpdate> {
const abortController = new AbortController() const abortController = new AbortController()
const req = OpenChannelReq(destination, closeAddress, fundingAmount, pushSats) const req = OpenChannelReq(destination, closeAddress, fundingAmount, pushSats, satsPerVByte)
const stream = this.lightning.openChannel(req, { abort: abortController.signal }) const stream = this.lightning.openChannel(req, { abort: abortController.signal })
return new Promise((res, rej) => { return new Promise((res, rej) => {
stream.responses.onMessage(message => { stream.responses.onMessage(message => {
console.log("message", message) console.log("message", message)
switch (message.update.oneofKind) { switch (message.update.oneofKind) {
case 'chanPending': case 'chanPending':
res(Buffer.from(message.pendingChanId).toString('base64')) res(message)
break
}
})
stream.responses.onError(error => {
console.log("error", error)
rej(error)
})
})
}
async CloseChannel(fundingTx: string, outputIndex: number, force: boolean, satPerVByte: number): Promise<PendingUpdate> {
const stream = this.lightning.closeChannel({
deliveryAddress: "",
force: force,
satPerByte: 0n,
satPerVbyte: BigInt(satPerVByte),
noWait: false,
maxFeePerVbyte: 0n,
targetConf: 0,
channelPoint: {
fundingTxid: {
fundingTxidStr: fundingTx,
oneofKind: "fundingTxidStr"
},
outputIndex: outputIndex
},
}, DeadLineMetadata())
return new Promise((res, rej) => {
stream.responses.onMessage(message => {
console.log("message", message)
switch (message.update.oneofKind) {
case 'closePending':
res(message.update.closePending)
break break
} }
}) })

View file

@ -1,12 +1,12 @@
import { CommitmentType, OpenChannelRequest } from "../../../proto/lnd/lightning.js"; import { CommitmentType, OpenChannelRequest } from "../../../proto/lnd/lightning.js";
export const OpenChannelReq = (destination: string, closeAddress: string, fundingAmount: number, pushSats: number): OpenChannelRequest => ({ export const OpenChannelReq = (destination: string, closeAddress: string, fundingAmount: number, pushSats: number, satsPerVByte: number): OpenChannelRequest => ({
nodePubkey: Buffer.from(destination, 'hex'), nodePubkey: Buffer.from(destination, 'hex'),
closeAddress: closeAddress, closeAddress: closeAddress,
localFundingAmount: BigInt(fundingAmount), localFundingAmount: BigInt(fundingAmount),
pushSat: BigInt(pushSats), pushSat: BigInt(pushSats),
satPerVbyte: 0n, // TBD satPerVbyte: BigInt(satsPerVByte), // TBD
private: false, private: false,
minConfs: 0, // TBD minConfs: 0, // TBD
baseFee: 1n, // TBD baseFee: 1n, // TBD

View file

@ -7,6 +7,9 @@ import * as Types from '../../../proto/autogenerated/ts/types.js'
import LND from "../lnd/lnd.js"; import LND from "../lnd/lnd.js";
export class AdminManager { export class AdminManager {
storage: Storage storage: Storage
log = getLogger({ component: "adminManager" }) log = getLogger({ component: "adminManager" })
adminNpub = "" adminNpub = ""
@ -144,6 +147,7 @@ export class AdminManager {
ListChannels = async (): Promise<Types.LndChannels> => { ListChannels = async (): Promise<Types.LndChannels> => {
const channels = await this.lnd.ListChannels(true) const channels = await this.lnd.ListChannels(true)
return { return {
open_channels: channels.channels.map(c => ({ open_channels: channels.channels.map(c => ({
active: c.active, active: c.active,
@ -156,4 +160,28 @@ export class AdminManager {
})) }))
} }
} }
async AddPeer(req: Types.AddPeerRequest) {
await this.lnd.AddPeer(req.pubkey, req.host, req.port)
}
async OpenChannel(req: Types.OpenChannelRequest): Promise<Types.OpenChannelResponse> {
let closeAddr = req.close_address
if (!closeAddr) {
const addr = await this.lnd.NewAddress(Types.AddressType.WITNESS_PUBKEY_HASH, { useProvider: false, from: 'system' })
closeAddr = addr.address
}
const res = await this.lnd.OpenChannel(req.node_pubkey, closeAddr, req.local_funding_amount, req.push_sat || 0, req.sat_per_v_byte)
return {
channel_id: Buffer.from(res.pendingChanId).toString('hex')
}
}
async CloseChannel(req: Types.CloseChannelRequest): Promise<Types.CloseChannelResponse> {
const res = await this.lnd.CloseChannel(req.funding_txid, req.output_index, req.force, req.sat_per_v_byte)
return {
closing_txid: Buffer.from(res.txid).toString('hex')
}
}
} }

View file

@ -626,8 +626,6 @@ export default class {
return this.GetLnurlPayInfoFromUser(linkedUser.user.user_id, linkedUser.application, { metadata: defaultLnAddressMetadata(this.settings.lnurlMetaText, addressName) }) return this.GetLnurlPayInfoFromUser(linkedUser.user.user_id, linkedUser.application, { metadata: defaultLnAddressMetadata(this.settings.lnurlMetaText, addressName) })
} }
async OpenChannel(userId: string, req: Types.OpenChannelRequest): Promise<Types.OpenChannelResponse> { throw new Error("WIP") }
mapOperations(operations: UserOperationInfo[], type: Types.UserOperationType, inbound: boolean): Types.UserOperations { mapOperations(operations: UserOperationInfo[], type: Types.UserOperationType, inbound: boolean): Types.UserOperations {
if (operations.length === 0) { if (operations.length === 0) {
return { return {

View file

@ -16,6 +16,32 @@ export default (mainHandler: Main): Types.ServerMethods => {
ListChannels: async ({ ctx }) => { ListChannels: async ({ ctx }) => {
return mainHandler.adminManager.ListChannels() return mainHandler.adminManager.ListChannels()
}, },
AddPeer: async ({ ctx, req }) => {
const err = Types.AddPeerRequestValidate(req, {
pubkey_CustomCheck: pubkey => pubkey !== '',
host_CustomCheck: host => host !== '',
port_CustomCheck: port => port > 0
})
if (err != null) throw new Error(err.message)
return mainHandler.adminManager.AddPeer(req)
},
OpenChannel: async ({ ctx, req }) => {
const err = Types.OpenChannelRequestValidate(req, {
node_pubkey_CustomCheck: pubkey => pubkey !== '',
local_funding_amount_CustomCheck: amt => amt > 0,
sat_per_v_byte_CustomCheck: spv => spv > 0,
})
if (err != null) throw new Error(err.message)
return mainHandler.adminManager.OpenChannel(req)
},
CloseChannel: async ({ ctx, req }) => {
const err = Types.CloseChannelRequestValidate(req, {
funding_txid_CustomCheck: chanId => chanId !== '',
sat_per_v_byte_CustomCheck: spv => spv > 0
})
if (err != null) throw new Error(err.message)
return mainHandler.adminManager.CloseChannel(req)
},
EncryptionExchange: async () => { }, EncryptionExchange: async () => { },
Health: async () => { await mainHandler.lnd.Health() }, Health: async () => { await mainHandler.lnd.Health() },
LndGetInfo: async ({ ctx }) => { LndGetInfo: async ({ ctx }) => {
@ -54,15 +80,6 @@ export default (mainHandler: Main): Types.ServerMethods => {
if (err != null) throw new Error(err.message) if (err != null) throw new Error(err.message)
return mainHandler.paymentManager.GetPaymentState(ctx.user_id, req) return mainHandler.paymentManager.GetPaymentState(ctx.user_id, req)
}, },
OpenChannel: async ({ ctx, req }) => {
const err = Types.OpenChannelRequestValidate(req, {
fundingAmount_CustomCheck: amt => amt > 0,
pushAmount_CustomCheck: amt => amt > 0,
destination_CustomCheck: dest => dest !== ""
})
if (err != null) throw new Error(err.message)
return mainHandler.paymentManager.OpenChannel(ctx.user_id, req)
},
NewAddress: ({ ctx, req }) => mainHandler.paymentManager.NewAddress(ctx, req), NewAddress: ({ ctx, req }) => mainHandler.paymentManager.NewAddress(ctx, req),
PayAddress: async ({ ctx, req }) => { PayAddress: async ({ ctx, req }) => {
const err = Types.PayAddressRequestValidate(req, { const err = Types.PayAddressRequestValidate(req, {

View file

@ -0,0 +1,20 @@
import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js'
import { runSanityCheck, safelySetUserBalance, TestBase } from './testBase.js'
export const ignore = false
export const dev = false
export default async (T: TestBase) => {
await safelySetUserBalance(T, T.user1, 2000)
await openAdminChannel(T)
await runSanityCheck(T)
}
const openAdminChannel = async (T: TestBase) => {
T.d("starting openAdminChannel")
const otherPub = (await T.externalAccessToOtherLnd.GetInfo()).identityPubkey
const openChannel = await T.main.adminManager.OpenChannel({
node_pubkey: otherPub, local_funding_amount: 100000, sat_per_v_byte: 1
})
console.log(openChannel)
T.d("opened admin channel")
}