diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ec88cea..69718ff6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ jobs: 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 @@ -45,6 +46,11 @@ jobs: - 'package.json' - 'package-lock.json' - '.github/workflows/**' + migrations: + - 'backend/prisma/**' + - 'package.json' + - 'package-lock.json' + - '.github/workflows/**' docs-encoding: name: Docs encoding check @@ -173,6 +179,62 @@ jobs: 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 diff --git a/.github/workflows/deploy-contracts.yml b/.github/workflows/deploy-contracts.yml index efbde9ac..6a3cb720 100644 --- a/.github/workflows/deploy-contracts.yml +++ b/.github/workflows/deploy-contracts.yml @@ -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 diff --git a/.github/workflows/testnet-e2e.yml b/.github/workflows/testnet-e2e.yml index 3ba2e81a..86b3dd42 100644 --- a/.github/workflows/testnet-e2e.yml +++ b/.github/workflows/testnet-e2e.yml @@ -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 diff --git a/backend/package.json b/backend/package.json index 1bc9cc19..94991e04 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/prisma/migrations/20260926000000_add_indexer_dead_letter_event/migration.sql b/backend/prisma/migrations/20260926000000_add_indexer_dead_letter_event/migration.sql index b7311529..1e2296b6 100644 --- a/backend/prisma/migrations/20260926000000_add_indexer_dead_letter_event/migration.sql +++ b/backend/prisma/migrations/20260926000000_add_indexer_dead_letter_event/migration.sql @@ -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"); diff --git a/backend/prisma/migrations/20261121000000_add_notification_webhook_tables/migration.sql b/backend/prisma/migrations/20261121000000_add_notification_webhook_tables/migration.sql new file mode 100644 index 00000000..7f7df51d --- /dev/null +++ b/backend/prisma/migrations/20261121000000_add_notification_webhook_tables/migration.sql @@ -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; diff --git a/contracts/stream_contract/src/lib.rs b/contracts/stream_contract/src/lib.rs index eee7a309..c30761f0 100644 --- a/contracts/stream_contract/src/lib.rs +++ b/contracts/stream_contract/src/lib.rs @@ -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, @@ -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. /// @@ -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( diff --git a/contracts/stream_contract/src/storage.rs b/contracts/stream_contract/src/storage.rs index 860fe97f..56137021 100644 --- a/contracts/stream_contract/src/storage.rs +++ b/contracts/stream_contract/src/storage.rs @@ -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. diff --git a/contracts/stream_contract/src/test.rs b/contracts/stream_contract/src/test.rs index a5ef6d3e..677f86af 100644 --- a/contracts/stream_contract/src/test.rs +++ b/contracts/stream_contract/src/test.rs @@ -8319,3 +8319,69 @@ fn test_coverage_set_stream_arbiter_is_locked_once_a_dispute_is_open() { Err(Ok(StreamError::ArbiterLocked)) ); } + +// ─── close_stream prunes per-stream side tables (#1863) ──────────────────── + +#[test] +fn test_close_stream_prunes_conditional_entry_and_positions() { + let env = Env::default(); + env.mock_all_auths(); + let (token, _) = create_token(&env); + let client = create_contract(&env); + let sender = Address::generate(&env); + let recipient = Address::generate(&env); + mint(&env, &token, &sender, 1_000); + + let milestones = vec![ + &env, + ConditionalMilestone { + milestone_id: 1, + amount: 600, + condition: UnlockCondition::TimeOnly(200), + is_unlocked: false, + }, + ConditionalMilestone { + milestone_id: 2, + amount: 400, + condition: UnlockCondition::TimeOnly(500), + is_unlocked: false, + }, + ]; + let id = client.create_conditional_stream(&sender, &recipient, &token, &1_000, &milestones); + client.mint_stream_position(&id, &sender, &recipient, &token, &10, &0, &500, &true); + + // Drive the stream to a terminal, fully withdrawn state. + advance(&env, 500); + client.verify_and_unlock_milestone(&recipient, &id, &1); + client.verify_and_unlock_milestone(&recipient, &id, &2); + assert_eq!(client.withdraw(&recipient, &id), 1_000); + assert!(client.is_stream_completed(&id)); + + // Everything keyed by the stream is present before the close. + env.as_contract(&client.address, || { + assert!(env + .storage() + .instance() + .has(&DataKey::ConditionalMilestones(id))); + assert!(env.storage().instance().has(&DataKey::AttestedIds(id))); + assert!( + crate::storage::try_load_position_metadata(&env, id, PositionRole::Sender).is_some() + ); + }); + + client.close_stream(&sender, &id); + assert!(client.get_stream(&id).is_none()); + + // ...and all of it is gone afterwards. + env.as_contract(&client.address, || { + assert!(!env + .storage() + .instance() + .has(&DataKey::ConditionalMilestones(id))); + assert!(!env.storage().instance().has(&DataKey::AttestedIds(id))); + assert!( + crate::storage::try_load_position_metadata(&env, id, PositionRole::Sender).is_none(), + "position metadata survived close_stream" + ); + }); +}