Skip to content

Commit

Permalink
feat: update to use AlgorandClient (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
neilcampbell authored Dec 4, 2024
1 parent 7973538 commit 655552f
Show file tree
Hide file tree
Showing 32 changed files with 2,733 additions and 2,915 deletions.
2 changes: 1 addition & 1 deletion docs/code/modules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ The result of this subscription pull/poll.

#### Defined in

[subscriptions.ts:58](https://github.com/algorandfoundation/algokit-subscriber-ts/blob/main/src/subscriptions.ts#L58)
[subscriptions.ts:57](https://github.com/algorandfoundation/algokit-subscriber-ts/blob/main/src/subscriptions.ts#L57)
16 changes: 8 additions & 8 deletions docs/subscriptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,8 @@ If you ran the following code on a cron schedule of (say) every 5 seconds it wou
it would drop old records and restart notifications from the new tip.

```typescript
const algod = await algokit.getAlgoClient()
const algorand = AlgorandClient.defaultLocalNet()
// You would need to implement getLastWatermark() to retrieve from a persistence store
const watermark = await getLastWatermark()
const subscription = await getSubscribedTransactions(
Expand All @@ -357,7 +358,7 @@ const subscription = await getSubscribedTransactions(
maxRoundsToSync: 100,
onMaxRounds: 'skip-sync-newest',
},
algod,
algorand.client.algod,
)
if (transactions.subscribedTransactions.length > 0) {
// You would need to implement notifyTransactions to action the transactions
Expand All @@ -373,7 +374,7 @@ If you ran the following code on a cron schedule of (say) every 5 seconds it wou
it would pick up where it left off and catch up using algod (note: you need to connect it to a archival node).

```typescript
const algod = await algokit.getAlgoClient()
const algorand = AlgorandClient.defaultLocalNet()
// You would need to implement getLastWatermark() to retrieve from a persistence store
const watermark = await getLastWatermark()
const subscription = await getSubscribedTransactions(
Expand All @@ -390,7 +391,7 @@ const subscription = await getSubscribedTransactions(
maxRoundsToSync: 100,
onMaxRounds: 'sync-oldest-start-now',
},
algod,
algorand.client.algod,
)
if (transactions.subscribedTransactions.length > 0) {
// You would need to implement notifyTransactions to action the transactions
Expand All @@ -405,8 +406,7 @@ await saveWatermark(transactions.newWatermark)
If you ran the following code on a cron schedule of (say) every 30 - 60 seconds it would create a cached index of all assets created by the account (in this case the Data History Museum TestNet account `ER7AMZRPD5KDVFWTUUVOADSOWM4RQKEEV2EDYRVSA757UHXOIEKGMBQIVU`). Given it uses indexer to catch up you can deploy this into a fresh environment with an empty database and it will catch up in seconds rather than days.

```typescript
const algod = await algokit.getAlgoClient()
const indexer = await algokit.getAlgoIndexerClient()
const algorand = AlgorandClient.defaultLocalNet()
// You would need to implement getLastWatermark() to retrieve from a persistence store
const watermark = await getLastWatermark()
const subscription = await getSubscribedTransactions(
Expand All @@ -425,8 +425,8 @@ const subscription = await getSubscribedTransactions(
maxRoundsToSync: 1000,
onMaxRounds: 'catchup-with-indexer',
},
algod,
indexer,
algorand.client.algod,
algorand.client.indexer,
)
if (transactions.subscribedTransactions.length > 0) {
Expand Down
12 changes: 6 additions & 6 deletions examples/data-history-museum/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as algokit from '@algorandfoundation/algokit-utils'
import { AlgorandClient } from '@algorandfoundation/algokit-utils'
import { TransactionResult } from '@algorandfoundation/algokit-utils/types/indexer'
import algosdk from 'algosdk'
import fs from 'fs'
Expand All @@ -23,8 +23,8 @@ interface DHMAsset {
}

async function getDHMSubscriber() {
const algod = await algokit.getAlgoClient()
const indexer = await algokit.getAlgoIndexerClient()
const algorand = AlgorandClient.testNet()

const subscriber = new AlgorandSubscriber(
{
filters: [
Expand All @@ -33,7 +33,7 @@ async function getDHMSubscriber() {
filter: {
type: TransactionType.acfg,
// Data History Museum creator accounts
sender: (await algokit.isTestNet(algod))
sender: (await algorand.client.isTestNet())
? 'ER7AMZRPD5KDVFWTUUVOADSOWM4RQKEEV2EDYRVSA757UHXOIEKGMBQIVU'
: 'EHYQCYHUC6CIWZLBX5TDTLVJ4SSVE4RRTMKFDCG4Z4Q7QSQ2XWIQPMKBPU',
},
Expand All @@ -47,8 +47,8 @@ async function getDHMSubscriber() {
set: saveWatermark,
},
},
algod,
indexer,
algorand.client.algod,
algorand.client.indexer,
)
subscriber.onBatch('dhm-asset', async (events) => {
// eslint-disable-next-line no-console
Expand Down
6 changes: 3 additions & 3 deletions examples/usdc/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as algokit from '@algorandfoundation/algokit-utils'
import { AlgorandClient } from '@algorandfoundation/algokit-utils'
import algosdk from 'algosdk'
import fs from 'fs'
import path from 'path'
Expand All @@ -12,7 +12,7 @@ if (!fs.existsSync(path.join(__dirname, '..', '..', '.env')) && !process.env.ALG
}

;(async () => {
const algod = await algokit.getAlgoClient()
const algorand = AlgorandClient.testNet()
let watermark = 0

const subscriber = new AlgorandSubscriber(
Expand All @@ -36,7 +36,7 @@ if (!fs.existsSync(path.join(__dirname, '..', '..', '.env')) && !process.env.ALG
},
},
},
algod,
algorand.client.algod,
)
subscriber.on('usdc', (transfer) => {
// eslint-disable-next-line no-console
Expand Down
10 changes: 5 additions & 5 deletions examples/xgov-voting/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AlgorandClient } from '@algorandfoundation/algokit-utils'
import { Prisma, PrismaClient } from '@prisma/client'
import algosdk, { ABIValue } from 'algosdk'
import algosdk from 'algosdk'
import fs from 'fs'
import path from 'path'
import { AlgorandSubscriber } from '../../src/subscriber'
Expand All @@ -18,17 +18,17 @@ if (!fs.existsSync(path.join(__dirname, '..', '..', '.env')) && !process.env.ALG

const prisma = new PrismaClient()

const votingRoundId = 1821334702 // Grab from https://voting.algorand.foundation/
const votingRoundId = 1821334702n // Grab from https://voting.algorand.foundation/
const watermarkId = `voting-${votingRoundId}`

async function getXGovSubscriber() {
const algorand = AlgorandClient.fromEnvironment()

// Get voting round metadata
const appClient = algorand.client.getTypedAppClientById(VotingRoundAppClient, {
id: votingRoundId,
appId: votingRoundId,
})
const votingRoundState = await appClient.getGlobalState()
const votingRoundState = await appClient.state.global.getAll()
const votingRoundMetadata = (await (
await fetch(`https://ipfs.algonode.xyz/ipfs/${votingRoundState.metadataIpfsCid!.asString()}`)
).json()) as VotingRoundMetadata
Expand Down Expand Up @@ -147,7 +147,7 @@ async function getXGovSubscriber() {
data: poll.subscribedTransactions.flatMap((t) => {
return answerArrayType
.decode(Buffer.from(t!['application-transaction']!['application-args']![answerAppArgsIndex], 'base64'))
.map((v: ABIValue, i: number) => {
.map((v: algosdk.ABIValue, i: number) => {
if (!useWeighting) {
const questionIndex = i
const answerIndex = parseInt(v.toString())
Expand Down
1,866 changes: 885 additions & 981 deletions examples/xgov-voting/types/voting-app-client.ts

Large diffs are not rendered by default.

74 changes: 61 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,12 @@
"./package.json": "./package.json"
},
"devDependencies": {
"@prisma/client": "^5.15.1",
"@algorandfoundation/algokit-client-generator": "^4.0.2",
"@commitlint/cli": "^19.2.1",
"@commitlint/config-conventional": "^19.1.0",
"@eslint/js": "^9.16.0",
"@makerx/prettier-config": "^2.0.1",
"@prisma/client": "^5.15.1",
"@rollup/plugin-typescript": "^11.1.6",
"@vitest/coverage-v8": "^2.1.4",
"better-npm-audit": "^3.7.3",
Expand Down Expand Up @@ -100,8 +101,8 @@
"js-sha512": "^0.9.0"
},
"peerDependencies": {
"@algorandfoundation/algokit-utils": "^6.1.0",
"algosdk": "^2.7.0"
"@algorandfoundation/algokit-utils": "^7.0.0",
"algosdk": ">=2.9.0 <3.0"
},
"publishConfig": {
"access": "public"
Expand Down
12 changes: 6 additions & 6 deletions src/subscriber.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as algokit from '@algorandfoundation/algokit-utils'
import { Config } from '@algorandfoundation/algokit-utils'
import algosdk from 'algosdk'
import { getSubscribedTransactions } from './subscriptions'
import { AsyncEventEmitter, AsyncEventListener } from './types/async-event-emitter'
Expand Down Expand Up @@ -96,7 +96,7 @@ export class AlgorandSubscriber {
}
await this.eventEmitter.emitAsync('poll', pollResult)
} catch (e) {
algokit.Config.logger.error(`Error processing event emittance`, e)
Config.logger.error(`Error processing event emittance`, e)
throw e
}
await this.config.watermarkPersistence.set(pollResult.newWatermark)
Expand All @@ -122,7 +122,7 @@ export class AlgorandSubscriber {
const start = +new Date()
const result = await this.pollOnce()
const durationInSeconds = (+new Date() - start) / 1000
algokit.Config.getLogger(suppressLog).debug('Subscription poll', {
Config.getLogger(suppressLog).debug('Subscription poll', {
currentRound: result.currentRound,
startingWatermark: result.startingWatermark,
newWatermark: result.newWatermark,
Expand All @@ -132,21 +132,21 @@ export class AlgorandSubscriber {
inspect?.(result)
// eslint-disable-next-line no-console
if (result.currentRound > result.newWatermark || !this.config.waitForBlockWhenAtTip) {
algokit.Config.getLogger(suppressLog).info(
Config.getLogger(suppressLog).info(
`Subscription poll completed in ${durationInSeconds}s; sleeping for ${this.config.frequencyInSeconds ?? 1}s`,
)
await sleep((this.config.frequencyInSeconds ?? 1) * 1000, this.abortController.signal)
} else {
// Wait until the next block is published
algokit.Config.getLogger(suppressLog).info(
Config.getLogger(suppressLog).info(
`Subscription poll completed in ${durationInSeconds}s; waiting for round ${result.currentRound + 1}`,
)
const waitStart = +new Date()
// Despite what the `statusAfterBlock` method description suggests, you need to wait for the round before
// the round you are waiting for per the API description:
// https://developer.algorand.org/docs/rest-apis/algod/#get-v2statuswait-for-block-afterround
await race(this.algod.statusAfterBlock(result.currentRound).do(), this.abortController.signal)
algokit.Config.getLogger(suppressLog).info(`Waited for ${(+new Date() - waitStart) / 1000}s until next block`)
Config.getLogger(suppressLog).info(`Waited for ${(+new Date() - waitStart) / 1000}s until next block`)
}
}
this.started = false
Expand Down
Loading

0 comments on commit 655552f

Please sign in to comment.