-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: direct allocation strategy & direct allocated event handler #33
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { Changeset } from "@grants-stack-indexer/repository"; | ||
import { ChainId, ProcessorEvent, StrategyEvent } from "@grants-stack-indexer/shared"; | ||
|
||
import { ProcessorDependencies, UnsupportedEventException } from "../../../internal.js"; | ||
import { BaseStrategyHandler } from "../index.js"; | ||
import { DirectAllocatedHandler } from "./handlers/index.js"; | ||
|
||
const STRATEGY_NAME = "allov2.DirectAllocationStrategy"; | ||
|
||
/** | ||
* This handler is responsible for processing events related to the | ||
* Direct Allocation strategy. | ||
* | ||
* The following events are currently handled by this strategy: | ||
* - DirectAllocated | ||
*/ | ||
export class DirectAllocationStrategyHandler extends BaseStrategyHandler { | ||
constructor( | ||
private readonly chainId: ChainId, | ||
private readonly dependencies: ProcessorDependencies, | ||
) { | ||
super(STRATEGY_NAME); | ||
} | ||
|
||
/** @inheritdoc */ | ||
async handle(event: ProcessorEvent<"Strategy", StrategyEvent>): Promise<Changeset[]> { | ||
switch (event.eventName) { | ||
case "DirectAllocated": | ||
return new DirectAllocatedHandler( | ||
event as ProcessorEvent<"Strategy", "DirectAllocated">, | ||
this.chainId, | ||
this.dependencies, | ||
).handle(); | ||
default: | ||
throw new UnsupportedEventException("Strategy", event.eventName); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we improve this error by providing strategyName as optional or maybe create a new custom error for strategies. wdyt ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i buy the first option 🫡 |
||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import { getAddress, zeroAddress } from "viem"; | ||
|
||
import { Changeset, Donation } from "@grants-stack-indexer/repository"; | ||
import { ChainId, getTokenOrThrow, ProcessorEvent } from "@grants-stack-indexer/shared"; | ||
|
||
import { getTokenAmountInUsd } from "../../../../helpers/index.js"; | ||
import { IEventHandler, ProcessorDependencies } from "../../../../internal.js"; | ||
import { getDonationId } from "../../helpers/index.js"; | ||
|
||
type Dependencies = Pick< | ||
ProcessorDependencies, | ||
"projectRepository" | "roundRepository" | "pricingProvider" | "logger" | ||
>; | ||
|
||
/** | ||
* Handles the DirectAllocated event for the Direct Allocation strategy. | ||
* | ||
* This handler processes direct allocations of funds to a project by: | ||
* - Validating that both the round and project exist | ||
* - Retrieving token price data to calculate USD amounts | ||
* - Creating a new donation record with the allocated amount | ||
* | ||
* Unlike other allocation handlers, this one does not require an application | ||
* since funds are allocated directly to projects. | ||
*/ | ||
export class DirectAllocatedHandler implements IEventHandler<"Strategy", "DirectAllocated"> { | ||
constructor( | ||
readonly event: ProcessorEvent<"Strategy", "DirectAllocated">, | ||
private readonly chainId: ChainId, | ||
private readonly dependencies: Dependencies, | ||
) {} | ||
|
||
/** | ||
* Handles the DirectAllocated event for the Direct Allocation strategy. | ||
* @returns {Changeset[]} The changeset containing an InsertDonation change | ||
* @throws {ProjectNotFound} if the project does not exist | ||
* @throws {RoundNotFound} if the round does not exist | ||
* @throws {UnknownToken} if the token does not exist | ||
* @throws {TokenPriceNotFoundError} if the token price is not found | ||
*/ | ||
async handle(): Promise<Changeset[]> { | ||
const { projectRepository, roundRepository, pricingProvider } = this.dependencies; | ||
const strategyAddress = getAddress(this.event.srcAddress); | ||
|
||
const round = await roundRepository.getRoundByStrategyAddressOrThrow( | ||
this.chainId, | ||
strategyAddress, | ||
); | ||
const project = await projectRepository.getProjectByIdOrThrow( | ||
this.chainId, | ||
this.event.params.profileId, | ||
); | ||
Comment on lines
+45
to
+52
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sweet |
||
|
||
const donationId = getDonationId(this.event.blockNumber, this.event.logIndex); | ||
|
||
const amount = BigInt(this.event.params.amount); | ||
const token = getTokenOrThrow(this.chainId, this.event.params.token); | ||
const sender = getAddress(this.event.params.sender); | ||
|
||
const { amountInUsd, timestamp: priceTimestamp } = await getTokenAmountInUsd( | ||
pricingProvider, | ||
token, | ||
amount, | ||
this.event.blockTimestamp, | ||
); | ||
|
||
const donation: Donation = { | ||
id: donationId, | ||
chainId: this.chainId, | ||
roundId: round.id, | ||
applicationId: zeroAddress, | ||
donorAddress: sender, | ||
recipientAddress: getAddress(this.event.params.profileOwner), | ||
projectId: project.id, | ||
transactionHash: this.event.transactionFields.hash, | ||
blockNumber: BigInt(this.event.blockNumber), | ||
tokenAddress: token.address, | ||
amount: amount, | ||
amountInUsd, | ||
amountInRoundMatchToken: 0n, | ||
timestamp: new Date(priceTimestamp), | ||
}; | ||
|
||
return [ | ||
{ | ||
type: "InsertDonation", | ||
args: { donation }, | ||
}, | ||
]; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from "./directAllocated.handler.js"; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from "./handlers/index.js"; | ||
export * from "./directAllocation.handler.js"; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { encodePacked, keccak256 } from "viem/utils"; | ||
|
||
/** | ||
* DONATION_ID = keccak256(abi.encodePacked(blockNumber, "-", logIndex)); | ||
*/ | ||
export const getDonationId = (blockNumber: number, logIndex: number): string => { | ||
return keccak256(encodePacked(["string"], [`${blockNumber}-${logIndex}`])); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from "./decoder.js"; | ||
export * from "./applicationStatus.js"; | ||
export * from "./allocated.js"; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
||
import { EvmProvider } from "@grants-stack-indexer/chain-providers"; | ||
import { IMetadataProvider } from "@grants-stack-indexer/metadata"; | ||
import { IPricingProvider } from "@grants-stack-indexer/pricing"; | ||
import { | ||
IApplicationReadRepository, | ||
IProjectReadRepository, | ||
IRoundReadRepository, | ||
} from "@grants-stack-indexer/repository"; | ||
import { ChainId, ILogger, ProcessorEvent, StrategyEvent } from "@grants-stack-indexer/shared"; | ||
|
||
import { UnsupportedEventException } from "../../../src/internal.js"; | ||
import { DirectAllocationStrategyHandler } from "../../../src/processors/strategy/directAllocation/directAllocation.handler.js"; | ||
import { DirectAllocatedHandler } from "../../../src/processors/strategy/directAllocation/handlers/directAllocated.handler.js"; | ||
|
||
vi.mock( | ||
"../../../src/processors/strategy/directAllocation/handlers/directAllocated.handler.js", | ||
() => { | ||
const DirectAllocatedHandler = vi.fn(); | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
DirectAllocatedHandler.prototype.handle = vi.fn(); | ||
return { DirectAllocatedHandler }; | ||
}, | ||
); | ||
|
||
describe("DirectAllocationStrategyHandler", () => { | ||
let handler: DirectAllocationStrategyHandler; | ||
let mockMetadataProvider: IMetadataProvider; | ||
let mockRoundRepository: IRoundReadRepository; | ||
let mockProjectRepository: IProjectReadRepository; | ||
let mockEVMProvider: EvmProvider; | ||
let mockPricingProvider: IPricingProvider; | ||
let mockApplicationRepository: IApplicationReadRepository; | ||
let mockLogger: ILogger; | ||
const chainId = 10 as ChainId; | ||
|
||
beforeEach(() => { | ||
mockMetadataProvider = {} as IMetadataProvider; | ||
mockRoundRepository = {} as IRoundReadRepository; | ||
mockProjectRepository = {} as IProjectReadRepository; | ||
mockEVMProvider = {} as unknown as EvmProvider; | ||
mockPricingProvider = {} as IPricingProvider; | ||
mockApplicationRepository = {} as IApplicationReadRepository; | ||
mockLogger = {} as ILogger; | ||
|
||
handler = new DirectAllocationStrategyHandler(chainId, { | ||
metadataProvider: mockMetadataProvider, | ||
roundRepository: mockRoundRepository, | ||
projectRepository: mockProjectRepository, | ||
evmProvider: mockEVMProvider, | ||
pricingProvider: mockPricingProvider, | ||
applicationRepository: mockApplicationRepository, | ||
logger: mockLogger, | ||
}); | ||
}); | ||
|
||
afterEach(() => { | ||
vi.clearAllMocks(); | ||
}); | ||
|
||
it("returns correct name", () => { | ||
expect(handler.name).toBe("allov2.DirectAllocationStrategy"); | ||
}); | ||
|
||
it("calls DirectAllocatedHandler for DirectAllocated event", async () => { | ||
const mockEvent = { | ||
eventName: "DirectAllocated", | ||
} as ProcessorEvent<"Strategy", "DirectAllocated">; | ||
|
||
vi.spyOn(DirectAllocatedHandler.prototype, "handle").mockResolvedValue([]); | ||
|
||
await handler.handle(mockEvent); | ||
|
||
expect(DirectAllocatedHandler).toHaveBeenCalledWith(mockEvent, chainId, { | ||
metadataProvider: mockMetadataProvider, | ||
roundRepository: mockRoundRepository, | ||
projectRepository: mockProjectRepository, | ||
evmProvider: mockEVMProvider, | ||
pricingProvider: mockPricingProvider, | ||
applicationRepository: mockApplicationRepository, | ||
logger: mockLogger, | ||
}); | ||
expect(DirectAllocatedHandler.prototype.handle).toHaveBeenCalled(); | ||
}); | ||
|
||
it("throws UnsupportedEventException for unknown events", async () => { | ||
const mockEvent = { | ||
eventName: "UnknownEvent", | ||
} as unknown as ProcessorEvent<"Strategy", StrategyEvent>; | ||
|
||
await expect(handler.handle(mockEvent)).rejects.toThrow(UnsupportedEventException); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
as we add more of these we should extract these into one place
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah probably, one more to go (for now)