Skip to content
Open
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
62 changes: 62 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
backend: ${{ steps.filter.outputs.backend }}
frontend: ${{ steps.filter.outputs.frontend }}
packages: ${{ steps.filter.outputs.packages }}
migrations: ${{ steps.filter.outputs.migrations }}
steps:
- name: Checkout code
uses: actions/checkout@v4
Expand All @@ -45,6 +46,11 @@
- 'package.json'
- 'package-lock.json'
- '.github/workflows/**'
migrations:
- 'backend/prisma/**'
- 'package.json'
- 'package-lock.json'
- '.github/workflows/**'

docs-encoding:
name: Docs encoding check
Expand Down Expand Up @@ -173,6 +179,62 @@
run: bash ./scripts/check-bundle-size.sh
working-directory: frontend

migrations:
name: Fresh-database migration replay
runs-on: ubuntu-latest
needs: changes
if: >-
github.event_name == 'push' ||
needs.changes.outputs.migrations == 'true'
permissions:
contents: read
services:
postgres:
image: postgres:16-alpine@sha256:e013e867e712fec275706a6c51c966f0bb0c93cfa8f51000f85a15f9865a28cb
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: flowfi_migrate
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: "npm"
cache-dependency-path: package-lock.json

- name: Install dependencies
run: npm ci --include=optional

# The service database starts empty, so this replays the entire migration
# history from scratch. A migration that only works against an already
# drifted database (or that was papered over with `db push`) fails here.
- name: Replay every migration on an empty database
working-directory: backend
env:
DATABASE_URL: postgresql://postgres:password@127.0.0.1:5432/flowfi_migrate
run: |
set -euo pipefail
npx prisma generate --schema=prisma/schema.prisma
npx prisma migrate deploy --schema=prisma/schema.prisma

- name: Fail if the migrated database drifts from schema.prisma
working-directory: backend
env:
DATABASE_URL: postgresql://postgres:password@127.0.0.1:5432/flowfi_migrate
run: npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --exit-code

backend:
name: Backend CI
runs-on: ubuntu-latest
Expand Down
15 changes: 14 additions & 1 deletion .github/workflows/deploy-contracts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,24 @@ jobs:
echo '```'
} >> "$GITHUB_STEP_SUMMARY"

- name: Verify Optimized WASM Exists
run: |
set -euo pipefail
WASM=contracts/target/wasm32-unknown-unknown/release/stream_contract.optimized.wasm
if [ ! -f "$WASM" ]; then
echo "ERROR: expected optimized WASM at $WASM"
ls -la contracts/target/wasm32-unknown-unknown/release/*.wasm || true
exit 1
fi
echo "Found optimized WASM at $WASM"

- name: Upload Optimized WASM Artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: stream-contract-${{ env.NETWORK }}
path: contracts/target/wasm32-unknown-unknown/optimized/*.wasm
# Same directory the Build & Optimize step writes to, and the same one
# ci.yml uploads from.
path: contracts/target/wasm32-unknown-unknown/release/*.optimized.wasm
if-no-files-found: error

- name: Upload Deployment Info
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/testnet-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ jobs:
working-directory: backend
run: |
npx prisma generate --schema=prisma/schema.prisma
npx prisma db push --accept-data-loss --schema=prisma/schema.prisma
npx prisma migrate deploy --schema=prisma/schema.prisma

- name: Run Testnet E2E suite
working-directory: backend
Expand Down
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"test": "vitest run",
"test:unit": "vitest run --exclude='tests/integration/**'",
"test:integration": "vitest run tests/integration",
"test:integration:docker": "docker compose up -d postgres && vitest run tests/integration/stream-lifecycle.test.ts; docker compose stop postgres",
"test:integration:docker": "docker compose up -d --wait postgres && vitest run tests/integration; rc=$?; docker compose stop postgres; exit $rc",
"test:e2e:testnet": "vitest run --config e2e/testnet/vitest.config.ts",
"dev": "nodemon",
"build": "tsc",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
DROP TABLE IF EXISTS "IndexerDeadLetterEvent" CASCADE;

-- CreateTable
CREATE TABLE "IndexerDeadLetterEvent" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"eventType" TEXT NOT NULL,
"txHash" TEXT NOT NULL,
"ledgerSequence" INTEGER NOT NULL,
"cursor" TEXT,
"payload" TEXT NOT NULL,
"errorMessage" TEXT NOT NULL,
"attempts" INTEGER NOT NULL DEFAULT 1,
"lastAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "IndexerDeadLetterEvent_pkey" PRIMARY KEY ("id")
);
-- The dead-letter table was first created by
-- 20260830000000_add_indexer_dead_letter_event with a narrower shape
-- (transactionHash/ledger/rawPayload). This migration used to DROP it with
-- CASCADE and recreate it, which destroyed every quarantined event on any
-- replay. Evolve the existing table in place instead: rename the columns that
-- moved, add the ones that are new, and swap the indexes for the ones the model
-- declares.

-- RenameColumn
ALTER TABLE "IndexerDeadLetterEvent" RENAME COLUMN "transactionHash" TO "txHash";
ALTER TABLE "IndexerDeadLetterEvent" RENAME COLUMN "ledger" TO "ledgerSequence";
ALTER TABLE "IndexerDeadLetterEvent" RENAME COLUMN "rawPayload" TO "payload";

-- AddColumn (existing rows predate event types, so they get an empty one)
ALTER TABLE "IndexerDeadLetterEvent" ADD COLUMN "eventType" TEXT NOT NULL DEFAULT '';
ALTER TABLE "IndexerDeadLetterEvent" ALTER COLUMN "eventType" DROP DEFAULT;
ALTER TABLE "IndexerDeadLetterEvent" ADD COLUMN "cursor" TEXT;

-- DropIndex (superseded by the eventId+eventType uniqueness below)
DROP INDEX "IndexerDeadLetterEvent_eventId_key";
DROP INDEX "IndexerDeadLetterEvent_ledger_idx";
DROP INDEX "IndexerDeadLetterEvent_transactionHash_idx";
DROP INDEX "IndexerDeadLetterEvent_createdAt_idx";

-- CreateIndex
CREATE UNIQUE INDEX "IndexerDeadLetterEvent_eventId_eventType_key" ON "IndexerDeadLetterEvent"("eventId", "eventType");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
-- The notification, webhook and alert models below existed in schema.prisma but no
-- migration ever created their tables: preview environments pushed them with
-- `prisma db push`, which is exactly the drift that hid a broken migration
-- history. This migration brings a fresh `prisma migrate deploy` database up to
-- the schema the application expects.

-- CreateTable
CREATE TABLE "WebhookSubscription" (
"id" TEXT NOT NULL,
"userAddress" TEXT NOT NULL,
"targetUrl" TEXT NOT NULL,
"secretKey" TEXT NOT NULL,
"eventTypes" TEXT[],
"isActive" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "WebhookSubscription_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WebhookDelivery" (
"id" TEXT NOT NULL,
"subscriptionId" TEXT NOT NULL,
"eventType" TEXT NOT NULL,
"payload" TEXT NOT NULL,
"responseStatus" INTEGER,
"attempts" INTEGER NOT NULL DEFAULT 0,
"deliveredAt" TIMESTAMP(3),
"error" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AlertHistory" (
"id" TEXT NOT NULL,
"streamId" BIGINT NOT NULL,
"alertType" TEXT NOT NULL,
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AlertHistory_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PushSubscription" (
"id" TEXT NOT NULL,
"address" TEXT NOT NULL,
"endpoint" TEXT NOT NULL,
"p256dh" TEXT NOT NULL,
"auth" TEXT NOT NULL,
"userAgent" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PushSubscription_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "NotificationChannel" (
"id" TEXT NOT NULL,
"address" TEXT NOT NULL,
"telegramChatId" TEXT,
"discordWebhook" TEXT,
"events" TEXT[] DEFAULT ARRAY['STREAM_CREATED', 'CLIFF_REACHED', 'RUNWAY_WARNING', 'TOKENS_CLAIMED']::TEXT[],
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "NotificationChannel_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "LinkCode" (
"code" TEXT NOT NULL,
"address" TEXT NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,
"usedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LinkCode_pkey" PRIMARY KEY ("code")
);
-- CreateTable
CREATE TABLE "NotificationLog" (
"id" TEXT NOT NULL,
"address" TEXT NOT NULL,
"event" TEXT NOT NULL,
"channel" TEXT NOT NULL,
"status" TEXT NOT NULL,
"error" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "NotificationLog_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "WebhookSubscription_userAddress_idx" ON "WebhookSubscription"("userAddress");
-- CreateIndex
CREATE INDEX "WebhookSubscription_isActive_idx" ON "WebhookSubscription"("isActive");
-- CreateIndex
CREATE INDEX "WebhookDelivery_subscriptionId_idx" ON "WebhookDelivery"("subscriptionId");
-- CreateIndex
CREATE INDEX "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt");
-- CreateIndex
CREATE INDEX "AlertHistory_streamId_idx" ON "AlertHistory"("streamId");
-- CreateIndex
CREATE INDEX "AlertHistory_sentAt_idx" ON "AlertHistory"("sentAt");
-- CreateIndex
CREATE UNIQUE INDEX "AlertHistory_streamId_alertType_sentAt_key" ON "AlertHistory"("streamId", "alertType", "sentAt");
-- CreateIndex
CREATE UNIQUE INDEX "PushSubscription_endpoint_key" ON "PushSubscription"("endpoint");
-- CreateIndex
CREATE INDEX "PushSubscription_address_idx" ON "PushSubscription"("address");
-- CreateIndex
CREATE UNIQUE INDEX "NotificationChannel_address_key" ON "NotificationChannel"("address");
-- CreateIndex
CREATE INDEX "LinkCode_address_idx" ON "LinkCode"("address");
-- CreateIndex
CREATE INDEX "NotificationLog_address_createdAt_idx" ON "NotificationLog"("address", "createdAt");
-- CreateIndex
CREATE INDEX "StreamEvent_createdAt_idx" ON "StreamEvent"("createdAt");
-- AddForeignKey
ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_subscriptionId_fkey" FOREIGN KEY ("subscriptionId") REFERENCES "WebhookSubscription"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17 changes: 12 additions & 5 deletions contracts/stream_contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ use events::{
};
use storage::{
bump_position_ttl, config_exists, get_contract_version, get_recorded_wasm_hash, load_config,
load_stream, load_stream_counter, next_stream_id, remove_stream, save_config,
save_contract_version, save_fee_config, save_position_metadata, save_recorded_wasm_hash,
save_stream, try_load_config, try_load_fee_config, try_load_position_metadata,
try_load_positions_by_owner, try_load_stream,
load_stream, load_stream_counter, next_stream_id, remove_conditional_metadata,
remove_position_metadata, remove_stream, save_config, save_contract_version, save_fee_config,
save_position_metadata, save_recorded_wasm_hash, save_stream, try_load_config,
try_load_fee_config, try_load_position_metadata, try_load_positions_by_owner, try_load_stream,
};
use types::{
BatchStreamInput, ConditionalMilestone, DataKey, DexRouter, DisputeStatus, FeeRecipient,
Expand Down Expand Up @@ -2376,7 +2376,9 @@ impl StreamContract {
/// close a stream. The stream must already be terminal (`Completed` or
/// `Cancelled`), inactive, and hold zero remaining balance.
///
/// On success the `DataKey::Stream(stream_id)` entry is removed and a
/// On success the `DataKey::Stream(stream_id)` entry is removed together
/// with the stream's conditional bookkeeping (`ConditionalMilestones`,
/// `AttestedIds`) and the position metadata of both roles, and a
/// `stream_closed` event is emitted for the backend indexer to mark the
/// stream as archived.
///
Expand Down Expand Up @@ -2421,7 +2423,12 @@ impl StreamContract {
}
}

// Prune every record keyed by this stream, not just the stream itself:
// conditional bookkeeping lives in instance storage and position
// metadata in persistent storage, and neither expires on its own.
remove_stream(&env, stream_id);
remove_conditional_metadata(&env, stream_id);
remove_position_metadata(&env, stream_id);

let timestamp = env.ledger().timestamp();
emit_stream_closed(
Expand Down
27 changes: 27 additions & 0 deletions contracts/stream_contract/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,33 @@ pub fn remove_stream(env: &Env, stream_id: u64) {
.remove(&DataKey::Stream(stream_id));
}

/// Removes the position metadata for a pruned stream.
///
/// **Keys:** [`DataKey::StreamPosition(stream_id, role)`] in persistent storage,
/// one per [`PositionRole`]. Positions are keyed by role, so both entries have
/// to go: leaving one behind keeps paying rent for a stream that no longer
/// exists.
pub fn remove_position_metadata(env: &Env, stream_id: u64) {
let storage = env.storage().persistent();
storage.remove(&DataKey::StreamPosition(stream_id, PositionRole::Sender));
storage.remove(&DataKey::StreamPosition(stream_id, PositionRole::Recipient));
}

/// Removes the conditional-stream bookkeeping for a pruned stream.
///
/// **Keys:** [`DataKey::ConditionalMilestones(stream_id)`] and
/// [`DataKey::AttestedIds(stream_id)`] in instance storage. Both are written
/// for every conditional stream and never expire on their own, so a closed
/// stream would otherwise leave them in the shared instance entry forever.
pub fn remove_conditional_metadata(env: &Env, stream_id: u64) {
env.storage()
.instance()
.remove(&DataKey::ConditionalMilestones(stream_id));
env.storage()
.instance()
.remove(&DataKey::AttestedIds(stream_id));
}

/// Returns the stream if it exists, `None` otherwise (used by read-only queries).
///
/// **Key:** `DataKey::Stream(stream_id)` in persistent storage.
Expand Down
Loading
Loading