Skip to content

Commit

Permalink
refactor: delegation types
Browse files Browse the repository at this point in the history
  • Loading branch information
marthendalnunes committed Dec 5, 2024
1 parent 405ce0a commit 66429ae
Show file tree
Hide file tree
Showing 60 changed files with 450 additions and 1,210 deletions.
7 changes: 5 additions & 2 deletions apps/api-delegations/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { Config } from 'drizzle-kit';
import { env } from './src/env.js';

if (!process.env.DELEGATIONS_DATABASE_URL) {
throw new Error('DELEGATIONS_DATABASE_URL is not set');
}

export default {
schema: './src/db/schema.ts',
out: './src/db/migrations',
dialect: 'postgresql',
dbCredentials: {
url: env.DELEGATIONS_DATABASE_URL,
url: process.env.DELEGATIONS_DATABASE_URL,
},
} satisfies Config;
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { db } from '../../index.js';
export function getDelegationDb({ hash }: GetDelegationParams) {
return db.query.delegations.findFirst({
where: (delegations, { eq }) => eq(delegations.hash, hash),

with: {
caveats: true,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import type { GetDelegationsParams } from '../../../validation.js';
import { db } from '../../index.js';
import { delegations } from '../../schema.js';
import { sqlLower } from '../../utils.js';
import type { DelegationWithChainIdMetadata } from 'universal-types';
import type { DelegationWithMetadata } from 'universal-types';

export type GetDelegationsDbReturnType =
| DelegationWithChainIdMetadata[]
| undefined;
export type GetDelegationsDbReturnType = DelegationWithMetadata[] | undefined;

export function getDelegationsDb({
chainId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { DelegationWithChainIdMetadataHash } from 'universal-types';
import { db } from '../../index.js';
import {
caveats as caveatsDb,
delegations as delegationsDb,
type InsertDelegationDb,
type InsertCaveatDb,
} from '../../schema.js';

type InsertDelegationDbParams = DelegationWithChainIdMetadataHash;
type InsertDelegationDbParams = InsertDelegationDb & {
caveats: InsertCaveatDb[];
};

export function insertDelegationDb({
caveats,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { sqlLower } from '../../utils.js';

export function invalidateDelegationDb({ hash }: { hash: Hash }) {
return db

.update(delegationsDb)
.set({ isValid: false })
.where(eq(sqlLower(delegationsDb.hash), hash.toLowerCase()))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ALTER TABLE "caveats" ALTER COLUMN "type" DROP NOT NULL;--> statement-breakpoint
ALTER TABLE "delegations" ALTER COLUMN "type" DROP NOT NULL;--> statement-breakpoint
ALTER TABLE "delegations" ADD COLUMN "verifyingContract" varchar(42) NOT NULL;
156 changes: 156 additions & 0 deletions apps/api-delegations/src/db/migrations/meta/0006_snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
{
"id": "329f48a4-b96c-4cdf-99d6-6a84a14dd24c",
"prevId": "1f0dc50b-abed-4990-b8a2-435e9ee80874",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.caveats": {
"name": "caveats",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"type": {
"name": "type",
"type": "varchar(256)",
"primaryKey": false,
"notNull": false
},
"enforcer": {
"name": "enforcer",
"type": "varchar(42)",
"primaryKey": false,
"notNull": true
},
"terms": {
"name": "terms",
"type": "text",
"primaryKey": false,
"notNull": true
},
"args": {
"name": "args",
"type": "text",
"primaryKey": false,
"notNull": true
},
"delegationHash": {
"name": "delegationHash",
"type": "varchar(66)",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"caveats_delegationHash_delegations_hash_fk": {
"name": "caveats_delegationHash_delegations_hash_fk",
"tableFrom": "caveats",
"tableTo": "delegations",
"columnsFrom": [
"delegationHash"
],
"columnsTo": [
"hash"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.delegations": {
"name": "delegations",
"schema": "",
"columns": {
"hash": {
"name": "hash",
"type": "varchar(66)",
"primaryKey": true,
"notNull": true
},
"chainId": {
"name": "chainId",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"verifyingContract": {
"name": "verifyingContract",
"type": "varchar(42)",
"primaryKey": false,
"notNull": true
},
"type": {
"name": "type",
"type": "varchar(256)",
"primaryKey": false,
"notNull": false
},
"delegator": {
"name": "delegator",
"type": "varchar(42)",
"primaryKey": false,
"notNull": true
},
"delegate": {
"name": "delegate",
"type": "varchar(42)",
"primaryKey": false,
"notNull": true
},
"authority": {
"name": "authority",
"type": "varchar(66)",
"primaryKey": false,
"notNull": true
},
"salt": {
"name": "salt",
"type": "bigint",
"primaryKey": false,
"notNull": true
},
"signature": {
"name": "signature",
"type": "text",
"primaryKey": false,
"notNull": true
},
"isValid": {
"name": "isValid",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
7 changes: 7 additions & 0 deletions apps/api-delegations/src/db/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@
"when": 1733323390653,
"tag": "0005_lean_rhino",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1733419629547,
"tag": "0006_flimsy_harpoon",
"breakpoints": true
}
]
}
7 changes: 4 additions & 3 deletions apps/api-delegations/src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ const bigIntColumn = () => bigint({ mode: 'number' }).$type<bigint>();
// Table
export const delegations = pgTable('delegations', {
hash: bytes32Column().primaryKey(),
type: varchar({ length: 256 }).notNull(),
delegator: addressColumn().notNull(),
chainId: integer().notNull(),
verifyingContract: addressColumn().notNull(),
type: varchar({ length: 256 }),
delegator: addressColumn().notNull(),
delegate: addressColumn().notNull(),
authority: bytes32Column().notNull(),
salt: bigIntColumn().notNull(),
Expand All @@ -45,7 +46,7 @@ export const delegationsRelations = relations(delegations, ({ many }) => ({
// Table
export const caveats = pgTable('caveats', {
id: serial('id').primaryKey(),
type: varchar({ length: 256 }).notNull(),
type: varchar({ length: 256 }),
enforcer: addressColumn().notNull(),
terms: bytesColumn().notNull(),
args: bytesColumn().notNull(),
Expand Down
12 changes: 4 additions & 8 deletions apps/api-delegations/src/routes/delegations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,18 @@ import { getDelegationDb } from '../db/actions/delegations/get-delegation-db.js'
import { getDelegationsDb } from '../db/actions/delegations/get-delegations-db.js';
import { insertDelegationDb } from '../db/actions/delegations/insert-delegation-db.js';
import { invalidateDelegationDb } from '../db/actions/delegations/invalidate-delegation-db.js';
import type { SelectDelegationDb } from '../db/schema.js';
import {
getDelegationSchema,
getDelegationsSchema,
postDelegationSchema,
} from '../validation.js';
import type {
DelegationWithChainIdMetadata,
DelegationWithChainIdMetadataHash,
} from 'universal-types';
import type { DelegationWithMetadata } from 'universal-types';

const delegationsRouter = new Hono()
// Get a delegation by its hash
.get('/:hash', zValidator('param', getDelegationSchema), async (c) => {
const { hash } = c.req.valid('param');
const delegation: DelegationWithChainIdMetadataHash | undefined =
const delegation: DelegationWithMetadata | undefined =
await getDelegationDb({
hash,
});
Expand All @@ -34,7 +30,7 @@ const delegationsRouter = new Hono()
// Get a delegations by multiple parameters
.post('/get', zValidator('json', getDelegationsSchema), async (c) => {
const params = c.req.valid('json');
const delegations: DelegationWithChainIdMetadata[] | undefined =
const delegations: DelegationWithMetadata[] | undefined =
await getDelegationsDb(params);

if (delegations) {
Expand Down Expand Up @@ -73,7 +69,7 @@ const delegationsRouter = new Hono()
// TODO: Expect a signature from the delegator to invalidate the delegation
async (c) => {
const { hash } = c.req.valid('param');
const delegation: SelectDelegationDb[] | undefined =
const delegation: Omit<DelegationWithMetadata, 'caveats'>[] | undefined =
await invalidateDelegationDb({
hash,
});
Expand Down
2 changes: 1 addition & 1 deletion apps/api-delegations/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const postDelegationSchema = z.object({
signature: hexSchema,
caveats: z.array(
z.object({
enforcerType: typeSchema,
type: typeSchema,
enforcer: addressSchema,
terms: hexSchema,
args: hexSchema,
Expand Down
1 change: 1 addition & 0 deletions apps/api-universal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"delegations-indexer": "workspace:*",
"universal-credential-sdk": "workspace:*",
"universal-data": "workspace:*",
"universal-types": "workspace:*",
"universal-delegations-sdk": "workspace:*",
"universal-identity-sdk": "workspace:*",
"viem": "^2.21.41",
Expand Down
10 changes: 4 additions & 6 deletions apps/api-universal/src/routes/credit-lines/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import { zValidator } from '@hono/zod-validator';
import { Hono } from 'hono';
import { type TokenItem, findToken, getDefaultTokenList } from 'universal-data';
import {
type DelegationDb,
decodeEnforcerERC20TransferAmount,
} from 'universal-delegations-sdk';
import { decodeEnforcerERC20TransferAmount } from 'universal-delegations-sdk';
import { type Address, formatUnits } from 'viem';
import { getCredentialsByAddresses } from './utils/get-credentials-by-addresses.js';
import { getIssuedDelegations } from './utils/get-issued-delegations.js';
import { getRedeemedCreditLines } from './utils/get-redeemed-credit-Lines.js';
import { getCreditLineSchema } from './utils/validation.js';
import type { DelegationWithMetadata } from 'universal-types';

type DelegationDbWithOnchainData = DelegationDb & {
type DelegationWithOnchainData = DelegationWithMetadata & {
isRevoked: boolean;
};

type DelegationMetadata = {
data: DelegationDbWithOnchainData;
data: DelegationWithOnchainData;
metadata: {
available: {
amount: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import {
type DelegationDb,
decodeEnforcerERC20TransferAmount,
} from 'universal-delegations-sdk';
import { decodeEnforcerERC20TransferAmount } from 'universal-delegations-sdk';
import type { Delegation } from 'universal-types';
import type { Address } from 'viem';

export function calculateERC20TransferAmountEnforcerCollectionTotal(
delegations: DelegationDb[],
delegations: Delegation[],
token: Address,
): bigint {
return delegations.reduce((acc, delegation) => {
Expand Down
Loading

0 comments on commit 66429ae

Please sign in to comment.