-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
soroban-tools#458: added new package for events provider
- Loading branch information
Showing
15 changed files
with
1,643 additions
and
1,241 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Change Log | ||
|
||
All notable changes to this project will be documented in this file. | ||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. | ||
|
||
# [4.0.0] (2023-04-25) | ||
|
||
**Note:** First release of soroban events package | ||
|
||
|
||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# @soroban-react/events | ||
|
||
See the official gitbook: https://soroban-react.gitbook.io/index/ | ||
___ | ||
|
||
```javascript | ||
import { useSorobanEvents, EventSubscription } from '@soroban-react/events' | ||
|
||
const crowdfundPledgedEventSubscription: EventSubscription = { | ||
contractId: Constants.CrowdfundId, | ||
topics: ['pledged_amount_changed'], | ||
cb: (event: SorobanClient.SorobanRpc.EventResponse): void => { | ||
let eventTokenBalance = xdr.ScVal.fromXDR(Buffer.from(event.value.xdr, 'base64')) | ||
setTokenBalance(convert.scvalToBigNumber(eventTokenBalance)) | ||
}, | ||
id: Math.random()} | ||
|
||
const crowdfundTargetReachedSubscription: EventSubscription = { | ||
contractId: Constants.CrowdfundId, | ||
topics: ['target_reached'], | ||
cb: (event: SorobanClient.SorobanRpc.EventResponse): void => { | ||
setTargetReached(true) | ||
}, | ||
id: Math.random()} | ||
|
||
const sorobanEventsContext = useSorobanEvents() | ||
React.useEffect(() => { | ||
const pledgedSubId = sorobanEventsContext.subscribe(crowdfundPledgedEventSubscription) | ||
const reachedSubId = sorobanEventsContext.subscribe(crowdfundTargetReachedSubscription) | ||
|
||
return () => { | ||
sorobanEventsContext.unsubscribe(pledgedSubId); | ||
sorobanEventsContext.unsubscribe(reachedSubId); | ||
} | ||
}, [sorobanEventsContext]); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{ | ||
"name": "@soroban-react/events", | ||
"keywords": [ | ||
"soroban-react", | ||
"freighter", | ||
"react", | ||
"react-hooks", | ||
"hooks", | ||
"stellar", | ||
"javascript", | ||
"typescript", | ||
"web3", | ||
"context", | ||
"frontend", | ||
"dapp" | ||
], | ||
"license": "Apache-2.0", | ||
"repository": "github:esteblock/soroban-react", | ||
"version": "4.0.0", | ||
"scripts": { | ||
"prebuild": "rm -rf dist", | ||
"build": "tsc", | ||
"start": "tsc --watch" | ||
}, | ||
"main": "dist/index.js", | ||
"exports": "./dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"files": [ | ||
"/dist" | ||
], | ||
"dependencies": { | ||
"@soroban-react/core": "4.1.0", | ||
"@soroban-react/types": "^4.0.0", | ||
"soroban-client": "https://github.com/stellar/js-soroban-client#main" | ||
}, | ||
"devDependencies": { | ||
"@types/react": "^18.0.25" | ||
}, | ||
"peerDependencies": { | ||
"react": ">=16.8" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import React, {createContext} from "react"; | ||
import * as SorobanClient from "soroban-client"; | ||
import { ChainMetadata } from "@soroban-react/types"; | ||
|
||
export type EventCallback = (event: SorobanClient.SorobanRpc.EventResponse) => void | ||
|
||
export interface EventSubscription { | ||
contractId: string; | ||
topics: string[]; | ||
cb: EventCallback; | ||
id: number; | ||
lastLedgerStart?: number; | ||
pagingToken?: string; | ||
} | ||
|
||
export interface SorobanEventsContextType { | ||
subscribe: (subscription: EventSubscription) => number; | ||
unsubscribe: (subscriptionId: number) => void; | ||
subscriptions: Array<EventSubscription>; | ||
} | ||
|
||
export const SorobanEventsContext = createContext<SorobanEventsContextType | undefined>(undefined) | ||
|
||
export const DefaultSorobanEventsContext: SorobanEventsContextType = { | ||
subscriptions: [], | ||
subscribe: (eventSubscription) => { | ||
for (const subscription of DefaultSorobanEventsContext.subscriptions) { | ||
if (subscription.id == eventSubscription.id) { | ||
return eventSubscription.id | ||
} | ||
} | ||
DefaultSorobanEventsContext.subscriptions.push(eventSubscription) | ||
return eventSubscription.id | ||
}, | ||
unsubscribe: (subscriptionId) => { | ||
const index = DefaultSorobanEventsContext.subscriptions.findIndex((subscription) => subscription.id == subscriptionId) | ||
if (index > -1) { | ||
DefaultSorobanEventsContext.subscriptions.splice(index, 1); | ||
} | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import React, {useEffect, useRef} from 'react'; | ||
import * as SorobanClient from 'soroban-client'; | ||
import { useSorobanReact, SorobanContextType } from '@soroban-react/core'; | ||
import { SorobanEventsContext, DefaultSorobanEventsContext} from "./SorobanEventsContext";; | ||
let xdr = SorobanClient.xdr | ||
|
||
export interface SorobanEventsProviderProps { | ||
children: React.ReactNode; | ||
} | ||
|
||
export function SorobanEventsProvider({ | ||
children, | ||
}: SorobanEventsProviderProps) { | ||
const pollInterval = 5000 | ||
const sorobanContext = useSorobanReact() | ||
|
||
useEffect(() => { | ||
let timeoutId: NodeJS.Timer | null = null | ||
let stop = false | ||
|
||
async function pollEvents(): Promise<void> { | ||
try { | ||
|
||
if (!sorobanContext.server) { | ||
console.debug("RPC events: Not connected to server") | ||
return | ||
} | ||
|
||
for (const subscription of DefaultSorobanEventsContext.subscriptions) { | ||
if (!subscription.lastLedgerStart) { | ||
let latestLedgerState = await sorobanContext.server.getLatestLedger(); | ||
subscription.lastLedgerStart = latestLedgerState.sequence | ||
} | ||
|
||
const subscriptionTopicXdrs: Array<string> = [] | ||
subscription.topics && subscription.topics.forEach( topic => { | ||
subscriptionTopicXdrs.push( xdr.ScVal.scvSymbol(topic).toXDR("base64")); | ||
}) | ||
|
||
// TODO: updated js-soroban-client to include latestLedger | ||
interface GetEventsWithLatestLedger extends SorobanClient.SorobanRpc.GetEventsResponse { | ||
latestLedger?: string; | ||
} | ||
|
||
// TODO: use rpc batch for single round trip, each subscription can be one | ||
// getEvents request in the batch, is that possible now? | ||
let response = await sorobanContext.server.getEvents({ | ||
startLedger: !subscription.pagingToken ? subscription.lastLedgerStart : undefined, | ||
cursor: subscription.pagingToken, | ||
filters: [ | ||
{ | ||
contractIds: [subscription.contractId], | ||
topics: [subscriptionTopicXdrs], | ||
type: "contract" | ||
} | ||
], | ||
limit: 10}) as GetEventsWithLatestLedger; | ||
|
||
delete subscription.pagingToken; | ||
if (response.latestLedger) { | ||
subscription.lastLedgerStart = parseInt(response.latestLedger); | ||
} | ||
response.events && response.events.forEach(event => { | ||
try { | ||
subscription.cb(event) | ||
} catch (error) { | ||
console.error("Poll Events: subscription callback had error: ", error); | ||
} finally { | ||
subscription.pagingToken = event.pagingToken | ||
} | ||
}) | ||
} | ||
} catch (error) { | ||
console.error("Poll Events: error: ", error); | ||
} finally { | ||
if (!stop) { | ||
timeoutId = setTimeout(pollEvents, pollInterval); | ||
} | ||
} | ||
} | ||
|
||
pollEvents(); | ||
|
||
return () => { | ||
if (timeoutId != null) clearTimeout(timeoutId) | ||
stop = true | ||
} | ||
}, [sorobanContext]); | ||
|
||
|
||
return ( | ||
<SorobanEventsContext.Provider value = {DefaultSorobanEventsContext}> | ||
{children} | ||
</SorobanEventsContext.Provider> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export * from "./SorobanEventsContext"; | ||
export * from "./SorobanEventsProvider"; | ||
export * from "./useSorobanEvents"; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { useContext, Context } from 'react'; | ||
import { SorobanEventsContext, SorobanEventsContextType } from "./SorobanEventsContext"; | ||
|
||
export function useSorobanEvents() { | ||
const context = useContext(SorobanEventsContext as Context<SorobanEventsContextType | undefined>) | ||
if (!context) throw Error('useWeb3React can only be used within the Web3ReactProvider component') | ||
return context | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"include": ["./src"], | ||
"compilerOptions": { | ||
"jsx": "react", | ||
"outDir": "./dist" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.