Last active
January 26, 2024 12:28
-
-
Save 1a35e1/c2fded2d2d49c39bd21574c5b8401e58 to your computer and use it in GitHub Desktop.
withFabric, STPv1 - fetchSubscriberState EthersJS
This file contains hidden or 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
/** | |
* Source: https://github.com/withfabricxyz/protocol-sdks/blob/main/src/stpv1/subscription.ts | |
*/ | |
// From https://docs.withfabric.xyz/stp/contracts/STPV1ABI | |
import stpV1ABI from './stpv1.json' | |
// Typedef for reference | |
type SubscriberState = { | |
/** The address of the account */ | |
address: `0x${string}` | |
/** The token id (0 means no subscription) */ | |
tokenId: bigint | |
/** The amount of seconds the account can refund */ | |
refundableSeconds: bigint | |
/** The amount of seconds the account has purchased */ | |
secondsPurchased: bigint | |
/** The amount of tokens the account can withdraw from rewards */ | |
rewardBalance: bigint | |
/** The amount of reward points the account has */ | |
rewardPoints: bigint | |
/** Expires at */ | |
expiresAt: Date | |
} | |
// Define this yourself | |
// getProviderByChainId(chainId) | |
export const fetchSubscriberState = async ({ contractAddress, chainId, account }) => { | |
const provider = getProviderByChainId(chainId) | |
const contract = new ethers.Contract(contractAddress, stpV1ABI, provider) | |
const state: Partial<SubscriberState> = {} | |
const calls = [ | |
{ | |
functionName: 'subscriptionOf', | |
args: [account], | |
fn: (r: [bigint, bigint, bigint, bigint]) => { | |
return { | |
tokenId: r[0], | |
secondsPurchased: r[1], | |
rewardPoints: r[2], | |
expiresAt: new Date(Number(r[3]) * 1000) | |
} | |
} | |
}, | |
{ | |
functionName: 'refundableBalanceOf', | |
args: [account], | |
fn: (r: bigint) => { | |
return { | |
refundableSeconds: r | |
} | |
} | |
}, | |
{ | |
functionName: 'rewardBalanceOf', | |
args: [account], | |
fn: (r: bigint) => { | |
return { | |
rewardBalance: r | |
} | |
} | |
} | |
] | |
for await (const call of calls) { | |
const result = await contract[call.functionName](...call.args) | |
Object.assign(state, call.fn(result)) | |
} | |
return state | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment