Skip to content

Commit

Permalink
feat(stream): fluctuating exchange rate support in test environment
Browse files Browse the repository at this point in the history
  • Loading branch information
justmoon committed Oct 26, 2024
1 parent 7a78eb9 commit b5e2bf7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/fast-ducks-return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@dassie/lib-protocol-stream": patch
---

Support fluctuating exchange rates in the test environment
28 changes: 18 additions & 10 deletions packages/lib-protocol-stream/src/test/mocks/test-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ interface ContextOptions {
*
* Defaults to 1_000_000n
*/
unitsPerToken?: bigint
unitsPerToken?: bigint | (() => bigint)

startingBalance?: bigint
}

interface TestRoute {
handler: IlpEndpoint["sendPacket"]
unitsPerToken: bigint
unitsPerToken: bigint | (() => bigint)
}

interface PreparePacketEvent {
Expand Down Expand Up @@ -104,7 +104,7 @@ export function createTestEnvironment({
return {
createContext: ({
name,
unitsPerToken = 1_000_000n,
unitsPerToken = 1n,
startingBalance = 0n,
}: ContextOptions): StreamProtocolContext & {
_test: { balance: Signal<bigint> }
Expand Down Expand Up @@ -153,36 +153,44 @@ export function createTestEnvironment({
}
}

if (packet.amount > maxPacketAmount) {
const internalAmount =
packet.amount *
(typeof unitsPerToken === "function" ? unitsPerToken() : (
unitsPerToken
))

if (internalAmount > maxPacketAmount) {
return {
type: IlpType.Reject,
data: {
code: IlpErrorCode.F08_AMOUNT_TOO_LARGE,
message: "Amount exceeds maximum packet amount",
triggeredBy: "test.router",
data: serializeAmountTooLargeData({
receivedAmount: packet.amount,
receivedAmount: internalAmount,
maximumAmount: maxPacketAmount,
}),
},
}
}

const internalAmount = packet.amount * unitsPerToken

for (const [address, route] of routes.entries()) {
for (const [address, { handler, unitsPerToken }] of routes.entries()) {
if (packet.destination.startsWith(address)) {
logger.debug?.("routing packet to destination", {
destination: packet.destination,
})

const outputPacket = {
...packet,
amount: internalAmount / route.unitsPerToken,
amount:
internalAmount /
(typeof unitsPerToken === "function" ? unitsPerToken() : (
unitsPerToken
)),
}

packetsInFlight++
return route.handler(outputPacket).finally(() => {
return handler(outputPacket).finally(() => {
packetsInFlight--
})
}
Expand Down

0 comments on commit b5e2bf7

Please sign in to comment.