Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/transaction-manager/lib/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ export class Transaction {

readonly attempts: Attempt[]

createdAt: Date

updatedAt: Date

/**
* Stores additional information for the transaction.
* Enables originators to provide extra details, such as gas limits, which can be leveraged by customizable services.
Expand All @@ -66,6 +70,8 @@ export class Transaction {
deadline,
status,
attempts,
createdAt,
updatedAt,
metadata,
}: {
intentId?: UUID
Expand All @@ -77,6 +83,8 @@ export class Transaction {
deadline?: number
status?: TransactionStatus
attempts?: Attempt[]
createdAt?: Date
updatedAt?: Date
metadata?: Record<string, unknown>
}) {
this.intentId = intentId ?? createUUID()
Expand All @@ -88,18 +96,22 @@ export class Transaction {
this.deadline = deadline
this.status = status ?? TransactionStatus.Pending
this.attempts = attempts ?? []
this.createdAt = createdAt ?? new Date()
this.updatedAt = updatedAt ?? new Date()
this.metadata = metadata
}

addAttempt(attempt: Attempt): void {
this.attempts.push(attempt)
this.updatedAt = new Date()
}

removeAttempt(hash: Hash): void {
const index = this.attempts.findIndex((attempt) => attempt.hash === hash)
if (index > -1) {
this.attempts.splice(index, 1)
}
this.updatedAt = new Date()
}

getInAirAttempts(): Attempt[] {
Expand All @@ -114,7 +126,7 @@ export class Transaction {

changeStatus(status: TransactionStatus): void {
this.status = status

this.updatedAt = new Date()
eventBus.emit(Topics.TransactionStatusChanged, {
transaction: this,
})
Expand All @@ -140,6 +152,8 @@ export class Transaction {
status: this.status,
attempts: JSON.stringify(this.attempts, bigIntReplacer),
metadata: this.metadata ? JSON.stringify(this.metadata, bigIntReplacer) : undefined,
createdAt: this.createdAt.getTime(),
updatedAt: this.updatedAt.getTime(),
}
}

Expand All @@ -149,6 +163,8 @@ export class Transaction {
args: JSON.parse(row.args, bigIntReviver),
attempts: JSON.parse(row.attempts, bigIntReviver),
metadata: row.metadata ? JSON.parse(row.metadata, bigIntReviver) : undefined,
createdAt: new Date(row.createdAt),
updatedAt: new Date(row.updatedAt),
})
}
}
9 changes: 9 additions & 0 deletions packages/transaction-manager/lib/TransactionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ export type TransactionManagerConfig = {
*/
blockTime?: bigint

/**
* The time (in milliseconds) after which finalized transactions are purged from the database.
* If finalizedTransactionPurgeTime is 0, finalized transactions are not purged from the database.
* Defaults to 2 minutes.
*/
finalizedTransactionPurgeTime?: number

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we enable setting this to 0 to disable purging?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a good idea. I just implemented it


/**
* The gas estimator to use for estimating the gas limit of a transaction.
* You can provide your own implementation to override the default one.
Expand Down Expand Up @@ -99,6 +106,7 @@ export class TransactionManager {
public readonly maxPriorityFeePerGas: bigint
public readonly rpcAllowDebug: boolean
public readonly blockTime: bigint
public readonly finalizedTransactionPurgeTime: number

constructor(_config: TransactionManagerConfig) {
this.collectors = []
Expand Down Expand Up @@ -136,6 +144,7 @@ export class TransactionManager {

this.rpcAllowDebug = _config.rpcAllowDebug || false
this.blockTime = _config.blockTime || 2n
this.finalizedTransactionPurgeTime = _config.finalizedTransactionPurgeTime || 2 * 60 * 1000
}

/**
Expand Down
23 changes: 23 additions & 0 deletions packages/transaction-manager/lib/TransactionRepository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { unknownToError } from "@happychain/common"
import type { UUID } from "@happychain/common"
import { type Result, ResultAsync } from "neverthrow"
import { Topics, eventBus } from "./EventBus.js"
import { NotFinalizedStatuses, Transaction } from "./Transaction.js"
import type { TransactionManager } from "./TransactionManager.js"
import { db } from "./db/driver.js"
Expand All @@ -22,6 +23,10 @@ export class TransactionRepository {
.execute()

this.notFinalizedTransactions = transactionRows.map((row) => Transaction.fromDbRow(row))

if (this.transactionManager.finalizedTransactionPurgeTime > 0) {
eventBus.on(Topics.NewBlock, this.purgeFinalizedTransactions.bind(this))
}
}

getNotFinalizedTransactions(): Transaction[] {
Expand Down Expand Up @@ -72,6 +77,11 @@ export class TransactionRepository {
.execute(),
unknownToError,
)

this.notFinalizedTransactions = this.notFinalizedTransactions.filter((transaction) =>
NotFinalizedStatuses.includes(transaction.status),
)

return result.map(() => undefined)
}

Expand All @@ -89,6 +99,11 @@ export class TransactionRepository {
}),
unknownToError,
)

this.notFinalizedTransactions = this.notFinalizedTransactions.filter((transaction) =>
NotFinalizedStatuses.includes(transaction.status),
)

return result
}

Expand All @@ -103,4 +118,12 @@ export class TransactionRepository {
(n) => !this.notFinalizedTransactions.some((t) => t.attempts.some((a) => a.nonce === n)),
)
}

async purgeFinalizedTransactions() {
await db
.deleteFrom("transaction")
.where("status", "not in", NotFinalizedStatuses)
.where("updatedAt", "<", Date.now() - this.transactionManager.finalizedTransactionPurgeTime)
.execute()
}
}
2 changes: 2 additions & 0 deletions packages/transaction-manager/lib/db/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export interface TransactionTable {
status: TransactionStatus
attempts: string
metadata: string | undefined
createdAt: number
updatedAt: number
}

export interface Database {
Expand Down
10 changes: 10 additions & 0 deletions packages/transaction-manager/migrations/Migration20241111223000.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
SQLite does not have native time types. The SQL interface allows arbitrary type names including "DATE" and "DATETIME",
but this is invalid in this API, and results in "NUMERIC" affinity instead of "INTEGER" affinity,
which is the one we want here
*/
export async function up(db) {
await db.schema.alterTable("transaction").addColumn("createdAt", "integer").execute()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this not be some timestamp column?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SQLite doesn't have a timestamp type, so what I'm doing is saving the timestamp in a numeric format. https://www.sqlite.org/datatype3.html

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the more i use sqlite the more my lovehate relationship with it grows 😄

I guess i would still be inclined to use a date or datetime https://www.sqlite.org/datatype3.html#affinity_name_examples here in the migration, then if we use something other than sqlite it'll still make sense 🤔 maybe this will strictly always be sqlite though 🤷

just sharing thoughts, don't have to change

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I use the datetime type, I get this error: invalid column data type "DATETIME"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably the explanation: https://stackoverflow.com/questions/17227110/how-do-datetime-values-work-in-sqlite

SQLite allows anything (including DATETIME) as declared type of a column. Based on that, it gives that column an affinity with a storage class (it even has the example of how this works for DATETIME in the documentation). That affinity is more like a hint, as each entry the column can actually have a different storage class. A storage class is still a step weaker than a type and can be backed by multiple types. So yes, you can use DATETIME. No, it does not actually support it as a type or storage class. Yes, the documentation actually contains the word "DATETIME".

So there's probably something here that validates that the type is one of the "standard" types.

In any case, DATETYPE gives NUMERIC affinity which is probably not what we want to store timestamps.

Let's add a comment here though to explain this. Somethiing like "SQLite does not have native time types. The SQL interface allows arbitrary type names including "DATE" and "DATETIME", but this is invalid in this API, and results in "NUMERIC" affinity instead of "INTEGER" affinity, which is the one we want here."


await db.schema.alterTable("transaction").addColumn("updatedAt", "integer").execute()
}