Browse Source

Update bounty totalFunding when withdrawing funds

Theophile Sandoz 3 years ago
parent
commit
f300ef9fa4
2 changed files with 33 additions and 0 deletions
  1. 2 0
      query-node/manifest.yml
  2. 31 0
      query-node/mappings/src/bounty.ts

+ 2 - 0
query-node/manifest.yml

@@ -867,6 +867,8 @@ mappings:
       handler: bounty_BountyFunded
     - event: bounty.BountyMaxFundingReached
       handler: bounty_BountyMaxFundingReached
+    - event: bounty.BountyFundingWithdrawal
+      handler: bounty_BountyFundingWithdrawal
   extrinsicHandlers:
     # infer defaults here
     #- extrinsic: Balances.Transfer

+ 31 - 0
query-node/mappings/src/bounty.ts

@@ -11,6 +11,7 @@ import {
   BountyFundedEvent,
   BountyFundingLimited,
   BountyFundingPerpetual,
+  BountyFundingWithdrawalEvent,
   BountyMaxFundingReachedEvent,
   BountyStage,
   BountyVetoedEvent,
@@ -33,6 +34,15 @@ async function getBounty(store: DatabaseManager, bountyId: BountyId): Promise<Bo
   return bounty
 }
 
+async function getContribution(store: DatabaseManager, bountyId: BountyId, contributor?: string): Promise<BountyContribution> {
+  const contribution = await store.get(BountyContribution, { where: { bountyId, contributor } })
+  if (!contribution) {
+    const actorType = typeof contributor === 'undefined' ? 'council' : `member id ${contributor}`
+    throw new Error(`Bounty contribution not found by contributor: ${actorType}`)
+  }
+  return contribution
+}
+
 function bountyActorToMembership(actor: BountyActor): Membership | undefined {
   if (actor.isMember) {
     return new Membership({ id: String(actor.asMember) })
@@ -249,3 +259,24 @@ export async function bounty_BountyMaxFundingReached({ event, store }: EventCont
   // Update the bounty stage
   endFundingPeriod(store, bounty)
 }
+
+export async function bounty_BountyFundingWithdrawal({ event, store }: EventContext & StoreContext): Promise<void> {
+  const fundingWithdrawalEvent = new BountyEvents.BountyFundingWithdrawalEvent(event)
+  const [bountyId, contributorActor] = fundingWithdrawalEvent.params
+  const eventTime = new Date(event.blockTimestamp)
+
+  const contributor = bountyActorToMembership(contributorActor)
+  const contribution = await getContribution(store, bountyId, contributor?.id)
+
+  // Update the bounty totalFunding
+  const bounty = await getBounty(store, bountyId)
+  bounty.updatedAt = eventTime
+  bounty.totalFunding = bounty.totalFunding.sub(contribution.amount)
+
+  await store.save<Bounty>(bounty)
+
+  // Record the event
+  const withdrawalInEvent = new BountyFundingWithdrawalEvent({ ...genericEventFields(event), contribution })
+
+  await store.save<BountyFundingWithdrawalEvent>(withdrawalInEvent)
+}