-
Notifications
You must be signed in to change notification settings - Fork 14
Add subscription functionality to payment interface #100
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
Merged
+319
−4
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
77 changes: 77 additions & 0 deletions
77
packages/account-sdk/src/core/telemetry/events/subscription.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { ActionType, AnalyticsEventImportance, ComponentType, logEvent } from '../logEvent.js'; | ||
|
||
/** | ||
* Logs when a subscription request is started | ||
*/ | ||
export function logSubscriptionStarted(data: { | ||
amount: string; | ||
periodInDays: number; | ||
testnet: boolean; | ||
correlationId: string; | ||
}) { | ||
logEvent( | ||
`subscription.subscribe.started.${data.periodInDays}days`, | ||
{ | ||
action: ActionType.process, | ||
componentType: ComponentType.unknown, | ||
method: 'subscribe', | ||
correlationId: data.correlationId, | ||
signerType: 'base-account', | ||
amount: data.amount, | ||
testnet: data.testnet, | ||
}, | ||
AnalyticsEventImportance.high | ||
); | ||
} | ||
|
||
/** | ||
* Logs when a subscription request is completed successfully | ||
*/ | ||
export function logSubscriptionCompleted(data: { | ||
amount: string; | ||
periodInDays: number; | ||
testnet: boolean; | ||
correlationId: string; | ||
permissionHash: string; | ||
}) { | ||
logEvent( | ||
`subscription.subscribe.completed.${data.periodInDays}days`, | ||
{ | ||
action: ActionType.process, | ||
componentType: ComponentType.unknown, | ||
method: 'subscribe', | ||
correlationId: data.correlationId, | ||
signerType: 'base-account', | ||
amount: data.amount, | ||
testnet: data.testnet, | ||
status: data.permissionHash, // Using status field to store permission hash | ||
}, | ||
AnalyticsEventImportance.high | ||
); | ||
} | ||
|
||
/** | ||
* Logs when a subscription request fails | ||
*/ | ||
export function logSubscriptionError(data: { | ||
amount: string; | ||
periodInDays: number; | ||
testnet: boolean; | ||
correlationId: string; | ||
errorMessage: string; | ||
}) { | ||
logEvent( | ||
`subscription.subscribe.error.${data.periodInDays}days`, | ||
{ | ||
action: ActionType.error, | ||
componentType: ComponentType.unknown, | ||
method: 'subscribe', | ||
correlationId: data.correlationId, | ||
signerType: 'base-account', | ||
amount: data.amount, | ||
testnet: data.testnet, | ||
errorMessage: data.errorMessage, | ||
}, | ||
AnalyticsEventImportance.high | ||
); | ||
} |
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
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
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
179 changes: 179 additions & 0 deletions
179
packages/account-sdk/src/interface/payment/subscribe.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
import { | ||
logSubscriptionCompleted, | ||
logSubscriptionError, | ||
logSubscriptionStarted, | ||
} from ':core/telemetry/events/subscription.js'; | ||
import { parseErrorMessageFromAny } from ':core/telemetry/utils.js'; | ||
import { parseUnits } from 'viem'; | ||
import { getHash } from '../public-utilities/spend-permission/index.js'; | ||
import { | ||
createSpendPermissionTypedData, | ||
type SpendPermissionTypedData, | ||
} from '../public-utilities/spend-permission/utils.js'; | ||
import { CHAIN_IDS, TOKENS } from './constants.js'; | ||
import type { SubscriptionOptions, SubscriptionResult } from './types.js'; | ||
import { createEphemeralSDK } from './utils/sdkManager.js'; | ||
import { normalizeAddress, validateStringAmount } from './utils/validation.js'; | ||
|
||
// Placeholder address for mutable data - will be replaced by wallet with actual account | ||
const PLACEHOLDER_ADDRESS = '0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' as const; | ||
|
||
/** | ||
* Creates a subscription using spend permissions on Base network | ||
* | ||
* @param options - Subscription options | ||
* @param options.amount - Amount of USDC to spend per period as a string (e.g., "10.50") | ||
* @param options.to - Ethereum address that will be the spender (your application's address) | ||
* @param options.periodInDays - The period in days for the subscription (default: 30) | ||
* @param options.testnet - Whether to use Base Sepolia testnet (default: false) | ||
* @param options.walletUrl - Optional wallet URL to use | ||
* @param options.telemetry - Whether to enable telemetry logging (default: true) | ||
* @returns Promise<SubscriptionResult> - Simplified result with subscription details | ||
* @throws Error if the subscription fails | ||
* | ||
* @example | ||
* ```typescript | ||
* try { | ||
* const subscription = await subscribe({ | ||
* amount: "10.50", | ||
* to: "0xFe21034794A5a574B94fE4fDfD16e005F1C96e51", // Your app's address | ||
* periodInDays: 30, // Monthly subscription | ||
* testnet: true | ||
* }); | ||
* | ||
* console.log(`Subscription created!`); | ||
* console.log(`ID: ${subscription.id}`); | ||
* console.log(`Payer: ${subscription.subscriptionPayerAddress}`); | ||
* console.log(`Owner: ${subscription.subscriptionOwnerAddress}`); | ||
* console.log(`Charge: $${subscription.recurringCharge} every ${subscription.periodInDays} days`); | ||
* } catch (error) { | ||
* console.error(`Subscription failed: ${error.message}`); | ||
* } | ||
* ``` | ||
*/ | ||
export async function subscribe(options: SubscriptionOptions): Promise<SubscriptionResult> { | ||
const { amount, to, periodInDays = 30, testnet = false, walletUrl, telemetry = true } = options; | ||
|
||
// Generate correlation ID for this subscription request | ||
const correlationId = crypto.randomUUID(); | ||
|
||
// Log subscription started | ||
if (telemetry) { | ||
logSubscriptionStarted({ amount, periodInDays, testnet, correlationId }); | ||
} | ||
|
||
try { | ||
// Validate inputs | ||
validateStringAmount(amount, 6); | ||
const spenderAddress = normalizeAddress(to); | ||
|
||
// Setup network configuration | ||
const network = testnet ? 'baseSepolia' : 'base'; | ||
const chainId = CHAIN_IDS[network]; | ||
const tokenAddress = TOKENS.USDC.addresses[network]; | ||
|
||
// Convert amount to wei (USDC has 6 decimals) | ||
const allowanceInWei = parseUnits(amount, 6); | ||
|
||
// Create the spend permission typed data using the utility | ||
// The utility handles: | ||
// - Default values for start (now) and end (ETERNITY_TIMESTAMP) | ||
// - Auto-generation of salt and extraData | ||
// - Proper formatting of all fields | ||
// We use PLACEHOLDER_ADDRESS which will be replaced by wallet with actual account | ||
const typedData = createSpendPermissionTypedData({ | ||
account: PLACEHOLDER_ADDRESS, | ||
spender: spenderAddress, | ||
token: tokenAddress, | ||
chainId: chainId, | ||
allowance: allowanceInWei, | ||
periodInDays: periodInDays, | ||
}); | ||
|
||
// Create SDK instance | ||
const sdk = createEphemeralSDK(chainId, walletUrl, telemetry); | ||
const provider = sdk.getProvider(); | ||
|
||
try { | ||
// Define the wallet_sign parameters with mutable data | ||
// This allows the wallet to replace PLACEHOLDER_ADDRESS with the actual account | ||
const signParams = { | ||
version: '1.0', | ||
request: { | ||
type: '0x01' as const, // EIP-712 Typed Data | ||
data: typedData, | ||
}, | ||
mutableData: { | ||
fields: ['message.account'], | ||
}, | ||
}; | ||
|
||
// Request signature from wallet | ||
const result = await provider.request({ | ||
method: 'wallet_sign', | ||
params: [signParams], | ||
}); | ||
|
||
// Type guard and validation for the result | ||
if (!result || typeof result !== 'object') { | ||
throw new Error('Invalid response from wallet_sign'); | ||
} | ||
|
||
// Cast to expected response type | ||
const signResult = result as { | ||
signature: `0x${string}`; | ||
signedData: SpendPermissionTypedData; | ||
}; | ||
|
||
// Extract the signed permission data | ||
const { signedData } = signResult; | ||
const { message } = signedData; | ||
|
||
// Calculate the real permission hash using the contract's getHash method | ||
const permissionHash = await getHash({ | ||
permission: message, | ||
chainId, | ||
}); | ||
|
||
// Log subscription completed | ||
if (telemetry) { | ||
logSubscriptionCompleted({ | ||
amount, | ||
periodInDays, | ||
testnet, | ||
correlationId, | ||
permissionHash, | ||
}); | ||
} | ||
|
||
// Return simplified result | ||
return { | ||
id: permissionHash, | ||
subscriptionOwnerAddress: message.spender, | ||
subscriptionPayerAddress: message.account, | ||
recurringCharge: amount, // The amount in USD as provided by the user | ||
periodInDays, | ||
}; | ||
} finally { | ||
// Clean up provider state | ||
await provider.disconnect(); | ||
} | ||
} catch (error) { | ||
// Extract error message using the utility | ||
const errorMessage = parseErrorMessageFromAny(error); | ||
|
||
// Log subscription error | ||
if (telemetry) { | ||
logSubscriptionError({ | ||
amount, | ||
periodInDays, | ||
testnet, | ||
correlationId, | ||
errorMessage, | ||
}); | ||
} | ||
|
||
// Re-throw the original error | ||
throw error; | ||
} | ||
} |
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
do you think this would make more sense in a nested param, since these are more sdk config focused rather than affecting the behavior of the subscribe functioanlity?
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.
That's a valid consideration and I don't think there's a direct right answer - but I would be inclined to leave as is for now and add a nested param if a flat call starts to feel over-encumbered as we add more configurability down the road.