Additional Methods
These methods support subscribe and process: merchants use them to create and manage plans, and subscribers use them to see, extend and cancel their subscriptions. Read How Subscriptions Work for the terms used here.
Note: Subscription payments are currently available only on Pi Testnet, on the first version of the Subscription contract (v1). v1 will be replaced before Mainnet: the new contract gets a new address, services must be registered again, and subscribers must subscribe again.
Limits on Testnet v1
- The maximum billing period is ~180 days, so yearly plans aren't possible yet.
- An approval lasts just under 180 days, however many periods it covers, so subscribe with a periods value whose renewals fit in it: 5 for a monthly plan, 25 for a weekly one. A Developer Portal month is 2,629,746 seconds (about 30.44 days). Extending starts a new approval, so ask Pioneers to extend before theirs runs out.
Table of Contents
Before You Start
- Set up the SDK as described in Implementation: call Pi.init() and authenticate with the payments scope.
- Every method takes an optional last argument, options, with a mode. Read methods (get..., is...) default to "simulate", which needs no signature and costs nothing. Write methods default to "submit", which opens the Pi Wallet. See Execution Modes.
- After a write in "submit" mode, wait for the transaction with the waitForTransaction helper from Waiting for a Transaction before you update your UI.
- Merchant methods must be called from the Pi Browser signed in with the merchant wallet. Subscriber methods are called for the Pioneer who is signed in, with their wallet address. Pi.authenticate doesn't return it, so for now ask the Pioneer to enter it. The examples call these addresses merchantAddress and userAddress.
Merchant methods
These methods are signed by, or read for, the merchant wallet that owns the service.
registerService
Creates a new service (plan) that Pioneers can subscribe to. You usually do this once per plan.
Important: Register your plans in the Developer Portal. That is the supported flow. Open your app in the Developer Portal, go to Subscription Services and click Register New Service. Enter the service name, the price per billing period, a weekly or monthly billing cadence and a trial length (0 to 90 days), then sign with your app's connected wallet in the Pi Wallet. That wallet is the merchant wallet: it receives the payments, and it signs process.
The Developer Portal links the service to your app, so the Pi Wallet's Subscriptions page shows Pioneers your app's name and icon and the service name. Calling registerService directly from the SDK creates the service on-chain but doesn't link it to your app: Pioneers see it only as "Service #" and its ID, with limited information, in the Pi Wallet.
Pi.SmartContract.Subscription.registerService(
merchant: string, // your merchant wallet address
name: string, // display name, must not be empty
price: string | bigint, // stroops charged per period, must be > 0
periodSeconds: string | bigint, // billing period in seconds, must be > 0
trialPeriodSeconds: string | bigint, // free trial in seconds, "0" for none
approvePeriods: string | bigint, // stored on the service, must be > 0 (the Developer Portal uses 1 monthly, 4 weekly)
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>
approvePeriods is stored on the service, but the contract doesn't apply it, and apps shouldn't pass it as periods: the Developer Portal registers 1 for monthly plans and 4 for weekly. When subscribing, pass a periods value whose renewals fit in one approval instead (see subscribe).
const ONE_PI = 10_000_000n; // stroops
const MONTH = 2_629_746n; // a Developer Portal month, about 30.44 days
const SEVEN_DAYS = 7n * 24n * 60n * 60n;
const submitted = await Pi.SmartContract.Subscription.registerService(
merchantAddress,
"Premium Plan",
5n * ONE_PI, // 5 Pi per period
MONTH, // billed monthly
SEVEN_DAYS, // 7-day free trial
"1", // what the Developer Portal registers for monthly plans; apps choose periods when subscribing
);
await waitForTransaction(submitted);
To find the new service_id, list your services with getMerchantServices (below) and take the last one.
getMerchantServices
Returns every service registered by a merchant. No signature is needed.
Pi.SmartContract.Subscription.getMerchantServices(
merchant: string,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const services = await Pi.SmartContract.Subscription.getMerchantServices(merchantAddress);
// [{ service_id: "0", name: "Premium Plan", price: "50000000", is_active: true, ... }]
const premium = services[services.length - 1];
console.log(`Premium Plan id: ${premium.service_id}`);
getMerchantSubscriptions
Returns every subscription to one of your services. merchant must own the service.
Pi.SmartContract.Subscription.getMerchantSubscriptions(
merchant: string,
serviceId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const subs = await Pi.SmartContract.Subscription.getMerchantSubscriptions(merchantAddress, "0");
const now = Math.floor(Date.now() / 1000);
const live = subs.filter((sub) => Number(sub.service_end_ts) > now);
console.log(`${live.length} of ${subs.length} subscribers currently have access`);
Subscriber methods
These methods are signed by, or read for, the Pioneer who subscribes.
getService
Returns a service's details so you can show the plan before the user subscribes. txSourceAddress is only used to build the simulation; pass the current user's address.
Pi.SmartContract.Subscription.getService(
txSourceAddress: string,
serviceId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const service = await Pi.SmartContract.Subscription.getService(userAddress, "0");
const pricePi = Number(service.price) / 10_000_000;
const days = Number(service.period_secs) / 86_400;
showPlan(`${service.name}: ${pricePi} Pi every ${days} days`);
if (!service.is_active) {
showMessage("This plan is not accepting new subscribers right now.");
}
isSubscriptionActive
Returns true while the user has access to the service, meaning the current paid (or trial) period hasn't ended. Use this to decide whether to unlock paid features.
Pi.SmartContract.Subscription.isSubscriptionActive(
subscriber: string,
serviceId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const hasPremium = await Pi.SmartContract.Subscription.isSubscriptionActive(userAddress, "0");
if (hasPremium) {
unlockPremium();
} else {
showSubscribeButton();
}
A cancelled subscription stays active until the end of the period the user already paid for.
Important: For anything valuable, check this from your backend too. A modified client can fake a true result.
getSubscriberSubscriptions
Returns the user's subscriptions, including cancelled and expired ones, but only the latest one per service: subscribing to a service again replaces the old record. Use it to build a "My subscriptions" page.
Pi.SmartContract.Subscription.getSubscriberSubscriptions(
subscriber: string,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const subs = await Pi.SmartContract.Subscription.getSubscriberSubscriptions(userAddress);
const now = Math.floor(Date.now() / 1000);
for (const sub of subs) {
const endsAt = new Date(Number(sub.service_end_ts) * 1000).toLocaleDateString();
let status;
if (Number(sub.service_end_ts) <= now) status = "Expired";
else if (sub.auto_renew) status = `Renews on ${endsAt}`;
else status = `Ends on ${endsAt}`;
console.log(`Subscription #${sub.sub_id} to service #${sub.service_id}: ${status}`);
}
getSubscription
Returns one subscription by its sub_id. The caller must be either the subscriber or the merchant that owns the service.
Pi.SmartContract.Subscription.getSubscription(
caller: string,
subscriptionId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const sub = await Pi.SmartContract.Subscription.getSubscription(userAddress, "3");
console.log(sub.auto_renew, sub.next_charge_ts);
getSubscriptionReservation
Returns how much allowance (in stroops) is still pre-approved for one subscription. Divide by the subscription's price to get how many renewals are left before the user has to extend.
Pi.SmartContract.Subscription.getSubscriptionReservation(
subscriber: string, // used only to build the simulation
subscriptionId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "simulate" }
): Promise<unknown>
const sub = await Pi.SmartContract.Subscription.getSubscription(userAddress, subId);
const reserved = await Pi.SmartContract.Subscription.getSubscriptionReservation(userAddress, subId);
const renewalsLeft = BigInt(reserved) / BigInt(sub.price);
if (sub.auto_renew && renewalsLeft < 2n) {
showMessage(`Only ${renewalsLeft} renewal(s) left. Extend your subscription to keep access.`);
}
It returns "0" once the subscription is cancelled, the user turns auto-renew off, or every pre-approved period has been charged. It can stay above 0 with auto-renew off in two cases, and that Pi is never charged: after a failed renewal (it's released when the user subscribes to that service again), and for a subscription made with autoRenew false and no trial, which reserves 1 × price.
extendSubscription
Pre-approves more periods for a subscription that is still active and turns auto-renew on. Nothing is paid now and the current end date doesn't change; the new periods are added on top of what is left.
Pi.SmartContract.Subscription.extendSubscription(
subscriber: string,
subscriptionId: string | bigint,
periods: string | bigint, // additional periods to pre-approve, must be > 0
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>
const submitted = await Pi.SmartContract.Subscription.extendSubscription(userAddress, subId, "5");
await waitForTransaction(submitted);
It fails with SubscriptionExpired if the current period has already ended. If auto-renew is still on, the renewal is due and is charged at the merchant's next process run, so there is nothing to do. If auto-renew is off, the user subscribes again.
Note: An approval lasts just under 180 days, however many periods it covers, and extending starts a new one. With a monthly plan and 5 approved periods, the user needs to extend after 5 renewals, and in any case before 180 days have passed since they subscribed or last extended. Track that date yourself, and use getSubscriptionReservation to prompt them in time.
toggleAutoRenew
Turns auto-renew off if it is on, or on if it is off. In "simulate" mode it resolves with the new value (true or false).
Pi.SmartContract.Subscription.toggleAutoRenew(
subscriber: string,
subscriptionId: string | bigint,
periods: string | bigint, // periods to pre-approve when turning ON; ignored when turning OFF
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>
- Turning off: renewals stop and the allowance left for this subscription is released. Pass "0" for periods. The user keeps access until the current period ends.
- Turning on: pass a positive periods. The contract pre-approves price × periods again. It fails with SubscriptionExpired if the current period has already ended.
const sub = await Pi.SmartContract.Subscription.getSubscription(userAddress, subId);
const periods = sub.auto_renew ? "0" : "5"; // "0" when turning off; when turning on, periods to approve (5 for a monthly plan)
const submitted = await Pi.SmartContract.Subscription.toggleAutoRenew(userAddress, subId, periods);
await waitForTransaction(submitted);
cancel
Cancels a subscription. Renewals stop and the allowance left for this subscription is released. There is no refund; the user keeps access until the end of the period they already paid for.
Pi.SmartContract.Subscription.cancel(
subscriber: string,
subscriptionId: string | bigint,
options?: ExecuteOptions // defaults to { mode: "submit" }
): Promise<unknown>
const submitted = await Pi.SmartContract.Subscription.cancel(userAddress, subId);
await waitForTransaction(submitted);
showMessage("Your subscription was cancelled. You keep access until the end of this period.");
Cancelling only affects this subscription. Allowance approved for the user's other subscriptions stays in place.
cancel only works while auto-renew is on. Once auto-renew is off, because the user turned it off or because process turned it off after a failed renewal, cancel fails with AlreadyCancelled. On Testnet v1 the Pi still reserved for a failed renewal stays reserved (getSubscriptionReservation can still show it) until the user subscribes to that service again, which releases it. The contract never charges a subscription whose auto-renew is off.
Data Types
Read methods return these records. Field names are snake_case, and u64/i128 numbers come back as strings; convert them with Number(...) for small values like timestamps, or BigInt(...) for amounts.
Service (returned by registerService in "simulate" mode, getService and getMerchantServices)
| Field | Description |
|---|---|
| service_id | Unique ID of the service. |
| merchant | Wallet that owns the service and receives payments. |
| name | Display name. |
| price | Amount charged per period, in stroops. |
| period_secs | Billing period in seconds. |
| trial_period_secs | Free trial in seconds ("0" means no trial). |
| approve_periods | Stored with the service (the Developer Portal registers 1 for monthly plans, 4 for weekly). The contract doesn't apply it; apps choose periods when subscribing. |
| is_active | false when the service doesn't accept new subscribers. |
| created_at | When the service was registered (Unix seconds). |
Subscription (returned by getSubscription, getSubscriberSubscriptions and getMerchantSubscriptions)
| Field | Description |
|---|---|
| sub_id | Unique ID of the subscription. |
| subscriber | Wallet that owns the subscription. |
| service_id | Service this subscription belongs to. |
| price | Price per period, copied from the service when subscribing. |
| period_secs | Billing period, copied from the service when subscribing. |
| trial_period_secs | Trial granted to this subscription ("0" if none). |
| trial_end_ts | When the trial ends ("0" if none). |
| auto_renew | true while the merchant can charge renewals. |
| service_end_ts | When the current paid (or trial) period ends. The user has access until then. |
| next_charge_ts | When process can next charge this subscription. |
| created_at | When the user subscribed (Unix seconds). |
Error Handling
The SDK checks your arguments before it builds a transaction:
- Addresses must be valid wallet (G...) or contract (C...) addresses, otherwise it throws an error such as "Invalid subscriber address".
- Prices and periods must be positive; IDs must be zero or positive; offset and limit must fit in a u32. An empty string throws an error such as "Service ID is required".
When the contract rejects a call, the error message ends with the error name and code, for example ... SubscriptionExpired (#11). Simulate a write first to catch these before the Pi Wallet opens.
Which errors each method can return
| Method | Possible errors |
|---|---|
| registerService | InvalidPrice (#1), InvalidPeriod (#2), InvalidServiceName (#10) |
| getMerchantServices | None. Returns an empty list if the merchant has no services. |
| getMerchantSubscriptions | ServiceNotFound (#5), NotServiceOwner (#9) |
| getService | ServiceNotFound (#5) |
| isSubscriptionActive | None. Returns false when there is no live subscription. |
| getSubscriberSubscriptions | None. Returns an empty list if the user has no subscriptions. |
| getSubscription | SubscriptionNotFound (#4), ServiceNotFound (#5), Unauthorized (#6) |
| getSubscriptionReservation | None. Returns "0" when nothing is approved. |
| extendSubscription | InvalidPeriod (#2), SubscriptionNotFound (#4), ServiceNotFound (#5), Unauthorized (#6), TimestampOverflow (#8), SubscriptionExpired (#11) |
| toggleAutoRenew | InvalidPeriod (#2), SubscriptionNotFound (#4), ServiceNotFound (#5), Unauthorized (#6), TimestampOverflow (#8), SubscriptionExpired (#11) |
| cancel | SubscriptionNotFound (#4), Unauthorized (#6), AlreadyCancelled (#7) |
What each error means
| Code | Name | What it means | What to do |
|---|---|---|---|
| 1 | InvalidPrice | Price is 0 or negative. | Use a positive price. |
| 2 | InvalidPeriod | A period or periods value is 0. | Use a positive value. |
| 4 | SubscriptionNotFound | The sub_id doesn't exist. | Reload the user's subscriptions. |
| 5 | ServiceNotFound | The service_id doesn't exist. | Check the ID. |
| 6 | Unauthorized | The wallet doesn't own this subscription (or, for getSubscription, isn't its merchant either). | Use the subscriber's own address. |
| 7 | AlreadyCancelled | Auto-renew is already off: the subscription was cancelled, auto-renew was turned off, or a renewal failed. | Nothing to cancel; refresh the page. |
| 8 | TimestampOverflow | A time or amount calculation overflowed. | Use smaller values. |
| 9 | NotServiceOwner | The merchant address doesn't own the service. | Use the merchant wallet that registered it. |
| 10 | InvalidServiceName | The service name is empty. | Provide a name. |
| 11 | SubscriptionExpired | The current period has already ended. | If auto-renew is still on, wait: the renewal is charged at the merchant's next process run. Otherwise ask the user to subscribe again. |
subscribe and process have their own errors (AlreadySubscribed, ServiceNotActive and more); see Error Handling on the core methods page.
If the user closes the Pi Wallet without signing, or the wallet fails to send the transaction, the promise rejects with a readable message. Always wrap calls in try/catch:
try {
const submitted = await Pi.SmartContract.Subscription.cancel(userAddress, subId);
await waitForTransaction(submitted);
} catch (err) {
console.error("Cancel failed:", err.message);
showMessage("We couldn't cancel your subscription. Please try again.");
}
Example Usage
A "My subscriptions" page: list the user's subscriptions, show their status, and let them extend or cancel.
async function loadMySubscriptions(userAddress) {
const subs = await Pi.SmartContract.Subscription.getSubscriberSubscriptions(userAddress);
const now = Math.floor(Date.now() / 1000);
const rows = [];
for (const sub of subs) {
const endsAt = Number(sub.service_end_ts);
// Ended: auto-renew off and the paid period over. Nothing can be charged, extended or cancelled
// (cancel fails with AlreadyCancelled once auto-renew is off), so there is nothing to manage.
if (endsAt <= now && !sub.auto_renew) continue;
const service = await Pi.SmartContract.Subscription.getService(userAddress, sub.service_id);
const reserved = await Pi.SmartContract.Subscription.getSubscriptionReservation(userAddress, sub.sub_id);
rows.push({
subId: sub.sub_id,
name: service.name,
endsOn: new Date(endsAt * 1000).toLocaleDateString(),
autoRenew: sub.auto_renew,
renewalsLeft: BigInt(reserved) / BigInt(sub.price),
});
}
return rows;
}
async function onExtend(userAddress, subId) {
try {
await waitForTransaction(await Pi.SmartContract.Subscription.extendSubscription(userAddress, subId, "5"));
showMessage("5 more periods approved.");
} catch (err) {
if (err.message.includes("SubscriptionExpired")) {
// The period ended. With auto-renew on, the renewal is due and is charged at the next process run;
// subscribing again would fail with AlreadySubscribed.
const sub = await Pi.SmartContract.Subscription.getSubscription(userAddress, subId);
showMessage(sub.auto_renew
? "Your renewal is due and will be charged soon."
: "This subscription has ended. Subscribe again to continue.");
} else {
showMessage(`Couldn't extend: ${err.message}`);
}
}
}
async function onCancel(userAddress, subId) {
try {
await waitForTransaction(await Pi.SmartContract.Subscription.cancel(userAddress, subId));
showMessage("Cancelled. You keep access until the end of this period.");
} catch (err) {
showMessage(`Couldn't cancel: ${err.message}`);
}
}
For each row, show the plan name and end date, a status (renews on, or ends on), an Extend button when auto-renew is on and renewalsLeft is low, and a Cancel button while auto-renew is on. Once auto-renew is off there is nothing to cancel: show when access ends instead.
Next
- How Subscriptions Work: the concepts and the flow.
- Implementation & Core Methods: subscribe, process, and collecting renewals from your server.
- For one-time purchases, see Payments.