Skip to content

Commit

Permalink
feat(stream): add Connection#pay() method which auto-manages stream
Browse files Browse the repository at this point in the history
  • Loading branch information
justmoon committed Oct 29, 2024
1 parent 071c8d9 commit d5dba31
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
9 changes: 9 additions & 0 deletions packages/lib-protocol-stream/src/connection/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Stream } from "../stream/stream"
import type { EventEmitter } from "../types/event-emitter"
import { closeConnection } from "./close"
import { createStream } from "./create-stream"
import { makePayment } from "./make-payment"
import { measureExchangeRate } from "./measure-exchange-rate"
import { sendUntilDone } from "./send-until-done"
import {
Expand All @@ -14,6 +15,10 @@ import {
} from "./set-exchange-rate"
import type { ConnectionEvents, ConnectionState } from "./state"

interface PayOptions {
sourceAmountLimit: bigint
}

export class Connection implements EventEmitter<ConnectionEvents> {
constructor(private readonly state: ConnectionState) {}

Expand All @@ -39,6 +44,10 @@ export class Connection implements EventEmitter<ConnectionEvents> {
return new Stream(this.state, streamState, streamId)
}

pay({ sourceAmountLimit }: PayOptions) {
return makePayment({ state: this.state, sourceAmountLimit })
}

async close() {
return closeConnection(this.state)
}
Expand Down
30 changes: 30 additions & 0 deletions packages/lib-protocol-stream/src/connection/make-payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { isFailure } from "@dassie/lib-type-utils"

import { closeStream } from "../stream/close"
import { sendAndAwait } from "../stream/send-and-await"
import { createStream } from "./create-stream"
import type { ConnectionState } from "./state"

interface MakePaymentOptions {
state: ConnectionState
sourceAmountLimit: bigint
}

export async function makePayment({
state,
sourceAmountLimit,
}: MakePaymentOptions) {
const { streamId, streamState } = createStream({ state })

const result = await sendAndAwait({
connectionState: state,
state: streamState,
amount: sourceAmountLimit,
})

if (isFailure(result)) return result

closeStream(streamId, state, streamState)

return
}
4 changes: 1 addition & 3 deletions packages/lib-protocol-stream/src/test/connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,7 @@ describe("Connection", () => {
})
})

const stream = client.createStream()

unwrapFailure(await stream.send({ amount: 1_000_000n }))
unwrapFailure(await client.pay({ sourceAmountLimit: 1_000_000n }))

expect(moneyReceived).toBe(1_000_000n)

Expand Down

0 comments on commit d5dba31

Please sign in to comment.