Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/account-sdk/src/browser-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import { base } from './interface/payment/base.js';
import { CHAIN_IDS, TOKENS } from './interface/payment/constants.js';
import { getPaymentStatus } from './interface/payment/getPaymentStatus.js';
import { pay } from './interface/payment/pay.js';
import { subscribe } from './interface/payment/subscribe.js';
import type {
InfoRequest,
PayerInfo,
PaymentOptions,
PaymentResult,
PaymentStatus,
PaymentStatusOptions,
SubscriptionOptions,
SubscriptionResult,
} from './interface/payment/types.js';

// Expose to global window object
Expand All @@ -31,12 +34,14 @@ export type {
} from ':core/provider/interface.js';
export { createBaseAccountSDK } from './interface/builder/core/createBaseAccountSDK.js';
export { getCryptoKeyAccount, removeCryptoKey } from './kms/crypto-key/index.js';
export { base, CHAIN_IDS, getPaymentStatus, pay, TOKENS };
export { base, CHAIN_IDS, getPaymentStatus, pay, subscribe, TOKENS };
export type {
InfoRequest,
PayerInfo,
PaymentOptions,
PaymentResult,
PaymentStatus,
PaymentStatusOptions,
SubscriptionOptions,
SubscriptionResult,
};
77 changes: 77 additions & 0 deletions packages/account-sdk/src/core/telemetry/events/subscription.ts
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
);
}
4 changes: 3 additions & 1 deletion packages/account-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export { createBaseAccountSDK } from './interface/builder/core/createBaseAccount
export { getCryptoKeyAccount, removeCryptoKey } from './kms/crypto-key/index.js';

// Payment interface exports
export { base, getPaymentStatus, pay } from './interface/payment/index.js';
export { base, getPaymentStatus, pay, subscribe } from './interface/payment/index.js';
export type {
InfoRequest,
PayerInfo,
Expand All @@ -17,4 +17,6 @@ export type {
PaymentStatusOptions,
PaymentStatusType,
PaymentSuccess,
SubscriptionOptions,
SubscriptionResult,
} from './interface/payment/index.js';
6 changes: 6 additions & 0 deletions packages/account-sdk/src/interface/payment/base.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import { CHAIN_IDS, TOKENS } from './constants.js';
import { getPaymentStatus } from './getPaymentStatus.js';
import { pay } from './pay.js';
import { subscribe } from './subscribe.js';
import type {
PaymentOptions,
PaymentResult,
PaymentStatus,
PaymentStatusOptions,
SubscriptionOptions,
SubscriptionResult,
} from './types.js';

/**
* Base payment interface
*/
export const base = {
pay,
subscribe,
getPaymentStatus,
constants: {
CHAIN_IDS,
Expand All @@ -23,5 +27,7 @@ export const base = {
PaymentResult: PaymentResult;
PaymentStatusOptions: PaymentStatusOptions;
PaymentStatus: PaymentStatus;
SubscriptionOptions: SubscriptionOptions;
SubscriptionResult: SubscriptionResult;
},
};
3 changes: 3 additions & 0 deletions packages/account-sdk/src/interface/payment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
export { base } from './base.js';
export { getPaymentStatus } from './getPaymentStatus.js';
export { pay } from './pay.js';
export { subscribe } from './subscribe.js';
export type {
InfoRequest,
PayerInfo,
Expand All @@ -14,6 +15,8 @@ export type {
PaymentStatusOptions,
PaymentStatusType,
PaymentSuccess,
SubscriptionOptions,
SubscriptionResult,
} from './types.js';

// Export constants
Expand Down
179 changes: 179 additions & 0 deletions packages/account-sdk/src/interface/payment/subscribe.ts
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)
Comment on lines +28 to +30
Copy link
Collaborator

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?

Copy link
Collaborator Author

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.

* @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;
}
}
34 changes: 34 additions & 0 deletions packages/account-sdk/src/interface/payment/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,40 @@ export interface PaymentStatus {
reason?: string;
}

/**
* Options for creating a subscription
*/
export interface SubscriptionOptions {
/** Amount of USDC to spend per period as a string (e.g., "10.50") */
amount: string;
/** Ethereum address that will be the spender (your application's address) */
to: string;
/** The period in days for the subscription (e.g., 30 for monthly) */
periodInDays?: number;
/** Whether to use testnet (Base Sepolia). Defaults to false (mainnet) */
testnet?: boolean;
/** Optional wallet URL to use */
walletUrl?: string;
/** Whether to enable telemetry logging. Defaults to true */
telemetry?: boolean;
}

/**
* Successful subscription result
*/
export interface SubscriptionResult {
/** The subscription ID (permission hash) */
id: string;
/** The address that owns/controls the subscription (your application) */
subscriptionOwnerAddress: Address;
/** The address that will be charged (the user's wallet) */
subscriptionPayerAddress: Address;
/** The recurring charge amount (USD denoted e.g. "9.99") */
recurringCharge: string;
/** The period in days for the subscription */
periodInDays: number;
}

/**
* Internal type for payment execution result
*/
Loading