Skip to content

Credits

Purpose

Credits provide a shared customer wallet per currency across products and subscriptions. Define action costs, issue credits, and consume them atomically. Unlike metered usage, credits debit a wallet rather than a per-feature period counter.

Access and initialization

Access

const credits = subscrio.credits;
var credits = subscrio.Credits;

Method catalog

Database and connection failures may propagate from any operation. Method-specific errors are listed with each method.

Method Purpose
createCurrency Defines a currency.
updateCurrency Updates currency display properties.
getCurrency Gets a currency or null.
listCurrencies Lists currencies.
setPlanGrant Configures plan credit issuance.
getPlanGrant Gets one plan grant rule.
listPlanGrants Lists active plan grant rules.
removePlanGrant Stops future issuance from a rule.
setConsumptionRule Sets a feature action cost.
getConsumptionRule Gets one currency cost.
listConsumptionRules Lists action costs.
removeConsumptionRule Removes one action cost.
grant Issues manual, promotional, or prepaid credits.
issueDuePlanGrants Reconciles one subscription's scheduled grants.
processScheduledGrants Reconciles customer credit schedules.
getBalance Reconciles and reads one wallet.
listBalances Reconciles and lists customer wallets.
canConsume Checks affordability after reconciliation.
consume Atomically debits all required currencies.
adjust Adds or removes credits with a reason.
listGrants Lists grant history.
getOperation Finds a saved operation by retry key.
listLedgerEntries Lists accounting entries.
archiveCurrency Disables currency issuance and spending.
unarchiveCurrency Restores currency use.
deleteCurrency Deletes an unused archived currency.
Method Purpose
CreateCurrencyAsync Defines a currency.
UpdateCurrencyAsync Updates currency display properties.
GetCurrencyAsync Gets a currency or null.
ListCurrenciesAsync Lists currencies.
SetPlanGrantAsync Configures plan credit issuance.
GetPlanGrantAsync Gets one plan grant rule.
ListPlanGrantsAsync Lists active plan grant rules.
RemovePlanGrantAsync Stops future issuance from a rule.
SetConsumptionRuleAsync Sets a feature action cost.
GetConsumptionRuleAsync Gets one currency cost.
ListConsumptionRulesAsync Lists action costs.
RemoveConsumptionRuleAsync Removes one action cost.
GrantAsync Issues manual, promotional, or prepaid credits.
IssueDuePlanGrantsAsync Reconciles one subscription's scheduled grants.
ProcessScheduledGrantsAsync Reconciles customer credit schedules.
GetBalanceAsync Reconciles and reads one wallet.
ListBalancesAsync Reconciles and lists customer wallets.
CanConsumeAsync Checks affordability after reconciliation.
ConsumeAsync Atomically debits all required currencies.
AdjustAsync Adds or removes credits with a reason.
ListGrantsAsync Lists grant history.
GetOperationAsync Finds a saved operation by retry key.
ListLedgerEntriesAsync Lists accounting entries.
ArchiveCurrencyAsync Disables currency issuance and spending.
UnarchiveCurrencyAsync Restores currency use.
DeleteCurrencyAsync Deletes an unused archived currency.

Method details

createCurrency

Create an active currency with a globally unique key.

createCurrency(input: { key: string; displayName: string; metadata?: Record<string, unknown>; }): Promise<CreditCurrencyDto>

Parameters

Returns CreditCurrencyDto: Saved currency.

Example

await subscrio.credits.createCurrency({ key: 'ai-credits', displayName: 'AI credits' });
Errors (2)
  • ValidationError: An amount, policy, key, or schedule is invalid.
  • ConflictError: The currency key already exists.
Task<CreditCurrencyDto> CreateCurrencyAsync(CreateCreditCurrencyDto input)

Parameters

Returns CreditCurrencyDto: Saved currency.

Example

await subscrio.Credits.CreateCurrencyAsync(new CreateCreditCurrencyDto("ai-credits", "AI credits"));
Errors (2)
  • ValidationException: An amount, policy, key, or schedule is invalid.
  • ConflictException: The currency key already exists.

updateCurrency

Update the label and metadata without changing the key. Supplied metadata replaces the entire object; an empty object clears its entries.

updateCurrency(k: string, input: { displayName?: string; metadata?: Record<string, unknown> }): Promise<CreditCurrencyDto>

Parameters

Returns CreditCurrencyDto: Updated currency.

Example

await subscrio.credits.updateCurrency('ai-credits', { displayName: 'AI tokens' });
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<CreditCurrencyDto> UpdateCurrencyAsync(string key, string? displayName, Dictionary<string, object?>? metadata)

Parameters

  • key: Currency key.
  • displayName: Optional nonblank label; null retains the current label.
  • metadata: Optional replacement metadata; null retains the current object.

Returns CreditCurrencyDto: Updated currency.

Example

await subscrio.Credits.UpdateCurrencyAsync("ai-credits", displayName: "AI tokens");
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

getCurrency

Read currency details, including archived currencies.

getCurrency(k: string): Promise<CreditCurrencyDto | null>

Parameters

  • k: Currency key.

Returns CreditCurrencyDto | null: Currency details, or null when missing.

Example

const currency = await subscrio.credits.getCurrency('ai-credits');
console.log(currency?.status);
Task<CreditCurrencyDto?> GetCurrencyAsync(string key)

Parameters

  • key: Currency key.

Returns CreditCurrencyDto?: Currency details, or null when missing.

Example

var currency = await subscrio.Credits.GetCurrencyAsync("ai-credits");
Console.WriteLine(currency?.Status);

listCurrencies

List currencies in key order, optionally filtering by status.

listCurrencies(filter?: PageFilter): Promise<CreditCurrencyDto[]>

Parameters

  • filter: Optional PageFilter; defaults to 50 rows at offset zero. Search is ignored.

Returns CreditCurrencyDto[]: Currencies, or an empty collection.

Example

const currencies = await subscrio.credits.listCurrencies({ status: 'active' });
console.log(currencies);
Errors (1)
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<List<CreditCurrencyDto>> ListCurrenciesAsync(int limit, int offset, string? status)

Parameters

  • limit: Optional page size, 1 to 500; defaults to 50.
  • offset: Optional nonnegative rows to skip; defaults to 0.
  • status: Optional active or archived filter; null includes both.

Returns List<CreditCurrencyDto>: Currencies, or an empty collection.

Example

var currencies = await subscrio.Credits.ListCurrenciesAsync(status: "active");
Console.WriteLine(currencies.Count);
Errors (1)
  • ValidationException: An amount, policy, key, or schedule is invalid.

setPlanGrant

Create or replace the plan's grant rule for one active currency. Before changing the rule, reconcile existing customer schedules under the previous configuration. This does not immediately issue the new rule's grants.

setPlanGrant(planKey: string, currencyKey: string, input: PlanCreditGrantInput): Promise<void>

Parameters

  • planKey: Plan key.
  • currencyKey: Active currency key.
  • input: PlanCreditGrantInput specifying amount and schedule.

Returns No returned value.

Example

await subscrio.credits.setPlanGrant('pro', 'ai-credits', { amount: 1000, cadence: 'monthly' });
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task SetPlanGrantAsync(string planKey, string currencyKey, PlanCreditGrantInput input)

Parameters

  • planKey: Plan key.
  • currencyKey: Active currency key.
  • input: PlanCreditGrantInput specifying amount and schedule.

Returns No returned value.

Example

await subscrio.Credits.SetPlanGrantAsync("pro", "ai-credits", new PlanCreditGrantInput(1000, "monthly"));
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

getPlanGrant

Read active grant rule without issuing or consuming credits.

getPlanGrant(planKey: string, currencyKey: string): Promise<(PlanCreditGrantInput & { currencyKey: string; }) | null>

Parameters

  • planKey: Plan key.
  • currencyKey: Currency key.

Returns (PlanCreditGrantInput & { currencyKey: string }) | null: Matching rule, or null when none exists. See the returned properties.

Example

const result = await subscrio.credits.getPlanGrant('pro', 'ai-credits');
console.log(result);
Task<PlanCreditGrantDto?> GetPlanGrantAsync(string planKey, string currencyKey)

Parameters

  • planKey: Plan key.
  • currencyKey: Currency key.

Returns PlanCreditGrantDto?: Matching rule, or null when none exists.

Example

var result = await subscrio.Credits.GetPlanGrantAsync("pro", "ai-credits");
Console.WriteLine(result);

listPlanGrants

Read active grant rules without issuing or consuming credits. Results are ordered by currency key.

listPlanGrants(p: string): Promise<(PlanCreditGrantInput & { currencyKey: string; })[]>

Parameters

  • p: Plan key.

Returns Array<PlanCreditGrantInput & { currencyKey: string }>: Matching rules, or an empty collection. See the returned properties.

Example

const result = await subscrio.credits.listPlanGrants('pro');
console.log(result);
Task<PlanCreditGrantDto?> GetPlanGrantAsync(string planKey, string currencyKey) => (await ListPlanGrantsAsync(planKey)

Parameters

  • p: Plan key.

Returns List<PlanCreditGrantDto>: Matching rules, or an empty collection.

Example

var result = await subscrio.Credits.ListPlanGrantsAsync("pro");
Console.WriteLine(result);

removePlanGrant

Reconcile accrued grants, then deactivate the rule. Previously issued grants and history remain; removing an absent rule is harmless when the plan exists.

removePlanGrant(p: string, c: string): Promise<void>

Parameters

  • p: Plan key.
  • c: Currency key.

Returns No returned value.

Example

await subscrio.credits.removePlanGrant('pro', 'ai-credits');
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task RemovePlanGrantAsync(string p, string c)

Parameters

  • p: Plan key.
  • c: Currency key.

Returns No returned value.

Example

await subscrio.Credits.RemovePlanGrantAsync("pro", "ai-credits");
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

setConsumptionRule

Set or replace the credits charged per action unit for a feature and currency. A feature can charge several currencies in one action. Metered features cannot have credit consumption rules.

setConsumptionRule(featureKey: string, currencyKey: string, creditsPerUnit: number): Promise<void>

Parameters

  • featureKey: Non-metered feature key.
  • currencyKey: Active currency key.
  • creditsPerUnit: Positive integer cost per action unit.

Returns No returned value.

Example

await subscrio.credits.setConsumptionRule('render', 'ai-credits', 10);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task SetConsumptionRuleAsync(string f, string c, long creditsPerUnit)

Parameters

  • f: Non-metered feature key.
  • c: Active currency key.
  • creditsPerUnit: Positive integer cost per action unit.

Returns No returned value.

Example

await subscrio.Credits.SetConsumptionRuleAsync("render", "ai-credits", 10);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

getConsumptionRule

Read cost rule without issuing or consuming credits.

getConsumptionRule(featureKey: string, currencyKey: string): Promise<{ currencyKey: string; creditsPerUnit: number; } | null>

Parameters

  • featureKey: Feature key.
  • currencyKey: Currency key.

Returns { currencyKey: string; creditsPerUnit: number } | null: Matching rule, or null when none exists. See the returned properties.

Example

const result = await subscrio.credits.getConsumptionRule('render', 'ai-credits');
console.log(result);
Task<CreditConsumptionRuleDto?> GetConsumptionRuleAsync(string featureKey, string currencyKey)

Parameters

  • featureKey: Feature key.
  • currencyKey: Currency key.

Returns CreditConsumptionRuleDto?: Matching rule, or null when none exists.

Example

var result = await subscrio.Credits.GetConsumptionRuleAsync("render", "ai-credits");
Console.WriteLine(result);

listConsumptionRules

Read cost rules without issuing or consuming credits. Results are ordered by currency key.

listConsumptionRules(f: string): Promise<{ currencyKey: string; creditsPerUnit: number; }[]>

Parameters

  • f: Feature key.

Returns Array<{ currencyKey: string; creditsPerUnit: number }>: Matching rules, or an empty collection. See the returned properties.

Example

const result = await subscrio.credits.listConsumptionRules('render');
console.log(result);
Task<CreditConsumptionRuleDto?> GetConsumptionRuleAsync(string featureKey, string currencyKey) => (await ListConsumptionRulesAsync(featureKey)

Parameters

  • f: Feature key.

Returns List<CreditConsumptionRuleDto>: Matching rules, or an empty collection.

Example

var result = await subscrio.Credits.ListConsumptionRulesAsync("render");
Console.WriteLine(result);

removeConsumptionRule

Remove one currency cost from a feature. Missing rules are ignored; existing ledger history is unchanged.

removeConsumptionRule(f: string, c: string): Promise<void>

Parameters

  • f: Feature key.
  • c: Currency key.

Returns No returned value.

Example

await subscrio.credits.removeConsumptionRule('render', 'ai-credits');
Task RemoveConsumptionRuleAsync(string f, string c)

Parameters

  • f: Feature key.
  • c: Currency key.

Returns No returned value.

Example

await subscrio.Credits.RemoveConsumptionRuleAsync("render", "ai-credits");

grant

Issue credits as a manual, promotional, or prepaid grant in one transaction. The currency must be active, and an optional subscription must belong to the customer. Retrying an identical request with the same customer-scoped credit idempotency key returns the saved result without writing again. A changed request or another credit operation under that key fails. Before-hooks run inside the transaction; after-hooks run after commit and are not replayed.

grant(input: CreditGrantInput): Promise<CreditGrantDto>

Parameters

Returns CreditGrantDto: Issued grant, or the original grant snapshot on retry.

Example

await subscrio.credits.grant({
  customerKey: 'acme', currencyKey: 'ai-credits', amount: 500,
  grantType: 'prepaid', idempotencyKey: 'purchase-123'
});
Errors (3)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictError: The customer-scoped retry key was used for a different credit operation or request.
Task<CreditGrantDto> GrantAsync(CreditGrantInput input)

Parameters

Returns CreditGrantDto: Issued grant, or the original grant snapshot on retry.

Example

await subscrio.Credits.GrantAsync(new CreditGrantInput(
    "acme", "ai-credits", 500, "prepaid", "purchase-123"));
Errors (3)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictException: The customer-scoped retry key was used for a different credit operation or request.

issueDuePlanGrants

Reconcile scheduled grants for one subscription, catching up due periods and expiring applicable credits. Repeated calls do not issue the same scheduled grant twice. More than 240 catch-up periods in a rule fails the transaction.

issueDuePlanGrants(options: { subscriptionKey: string }): Promise<{ issued: CreditGrantDto[]; nextDueAt: string | null; hasMore: boolean; }>

Parameters

Returns { issued: CreditGrantDto[]; nextDueAt: string | null; hasMore: boolean }: Issued grants and schedule state.

Example

const result = await subscrio.credits.issueDuePlanGrants({ subscriptionKey: 'acme-pro' });
console.log(result.issued, result.nextDueAt);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<DuePlanGrantsDto> IssueDuePlanGrantsAsync(IssueDuePlanGrantsInput input)

Parameters

Returns DuePlanGrantsDto: Issued grants and schedule state.

Example

var result = await subscrio.Credits.IssueDuePlanGrantsAsync(new IssueDuePlanGrantsInput("acme-pro"));
Console.WriteLine(result.NextDueAt);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

processScheduledGrants

Reconcile due grants and expiration for one customer or every customer. Each customer runs in a separate transaction; if a later customer fails, earlier committed work remains. Schedule this helper when credits should be issued without waiting for wallet access.

processScheduledGrants(customerKey?: string): Promise<{ issued: number; customers: number; }>

Parameters

  • customerKey: Optional customer key; omit to process all customers.

Returns { issued: number; customers: number }: Processing counts.

Example

const result = await subscrio.credits.processScheduledGrants('acme');
console.log(result);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<(int Issued, int Customers)> ProcessScheduledGrantsAsync(string? customerKey)

Parameters

  • customerKey: Optional customer key; omit to process all customers.

Returns (int Issued, int Customers): Processing counts.

Example

var result = await subscrio.Credits.ProcessScheduledGrantsAsync("acme");
Console.WriteLine(result);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

getBalance

Reconcile due plan grants and expirations, then read one wallet. This operation can write grants and ledger entries; it is not a pure read.

getBalance(customerKey: string, currencyKey: string): Promise<CreditBalanceDto>

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key, including archived currencies.

Returns CreditBalanceDto: Spendable balance and unexpired grants with remaining credit.

Example

const result = await subscrio.credits.getBalance('acme', 'ai-credits');
console.log(result);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<CreditBalanceDto> GetBalanceAsync(string customerKey, string currencyKey)

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key, including archived currencies.

Returns CreditBalanceDto: Spendable balance and unexpired grants with remaining credit.

Example

var result = await subscrio.Credits.GetBalanceAsync("acme", "ai-credits");
Console.WriteLine(result);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

listBalances

Reconcile due plan grants and expirations, then read all existing wallets in currency-key order. This operation can write grants and ledger entries; it is not a pure read.

listBalances(customerKey: string): Promise<CreditBalanceDto[]>

Parameters

  • customerKey: Customer key.

Returns CreditBalanceDto[]: Spendable balance and unexpired grants with remaining credit.

Example

const result = await subscrio.credits.listBalances('acme');
console.log(result);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<List<CreditBalanceDto>> ListBalancesAsync(string customerKey)

Parameters

  • customerKey: Customer key.

Returns List<CreditBalanceDto>: Spendable balance and unexpired grants with remaining credit.

Example

var result = await subscrio.Credits.ListBalancesAsync("acme");
Console.WriteLine(result);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

canConsume

Reconcile the customer's schedules, then check whether every configured currency cost is affordable. This can issue grants and expire credits, but does not debit the action. It checks credit affordability, not product feature access or subscription eligibility; enforce those separately when required.

canConsume(action: CreditActionDto): Promise<CreditCheckDto>

Parameters

Returns CreditCheckDto: Affordability and per-currency costs; this does not reserve credits.

Example

const check = await subscrio.credits.canConsume({ customerKey: 'acme', featureKey: 'render', units: 2 });
console.log(check.hasAccess, check.costs);
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<CreditCheckDto> CanConsumeAsync(CreditActionDto action)

Parameters

Returns CreditCheckDto: Affordability and per-currency costs; this does not reserve credits.

Example

var check = await subscrio.Credits.CanConsumeAsync(new CreditActionDto("acme", "render", 2));
Console.WriteLine(check.HasAccess);
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.

consume

Reconcile schedules and debit every configured currency atomically. If any currency is archived or insufficient, no action debit commits. Grants are spent by ascending priority, earliest expiry with non-expiring grants last, then grant ID. This checks credit affordability only. Retrying an identical request with the same customer-scoped credit idempotency key returns the saved result without writing again. A changed request or another credit operation under that key fails. Before-hooks run inside the transaction; after-hooks run after commit and are not replayed.

consume(input: CreditConsumeInput): Promise<CreditConsumeDto>

Parameters

Returns CreditConsumeDto: Grant allocations and post-debit balances.

Example

const result = await subscrio.credits.consume({
  customerKey: 'acme', featureKey: 'render', units: 2, idempotencyKey: 'render-123'
});
console.log(result.allocations);
Errors (4)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictError: The customer-scoped retry key was used for a different credit operation or request.
  • InsufficientCreditsError: A required currency is archived or lacks funds; the error includes per-currency costs.
Task<CreditConsumeDto> ConsumeAsync(CreditConsumeInput input)

Parameters

Returns CreditConsumeDto: Grant allocations and post-debit balances.

Example

var result = await subscrio.Credits.ConsumeAsync(new CreditConsumeInput("acme", "render", 2, "render-123"));
Console.WriteLine(result.Allocations.Count);
Errors (4)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictException: The customer-scoped retry key was used for a different credit operation or request.
  • InsufficientCreditsException: A required currency is archived or lacks funds; the error includes per-currency costs.

adjust

Correct a balance with a signed amount and a required reason. Positive amounts create a manual grant; negative amounts spend existing grants in the normal order. The active currency cannot be driven below zero. Retrying an identical request with the same customer-scoped credit idempotency key returns the saved result without writing again. A changed request or another credit operation under that key fails. Before-hooks run inside the transaction; after-hooks run after commit and are not replayed.

adjust(input: CreditAdjustInput): Promise<{ operationId: string; idempotencyKey: string; balance: CreditBalanceDto; }>

Parameters

Returns { operationId: string; idempotencyKey: string; balance: CreditBalanceDto }: Operation identity and adjusted balance.

Example

await subscrio.credits.adjust({
  customerKey: 'acme', currencyKey: 'ai-credits', amount: 25,
  reason: 'Service credit', idempotencyKey: 'correction-123'
});
Errors (4)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ValidationError: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictError: The customer-scoped retry key was used for a different credit operation or request.
  • InsufficientCreditsError: A negative adjustment exceeds available credit.
Task<CreditAdjustmentDto> AdjustAsync(CreditAdjustInput input)

Parameters

Returns CreditAdjustmentDto: Operation identity and adjusted balance.

Example

await subscrio.Credits.AdjustAsync(new CreditAdjustInput(
    "acme", "ai-credits", 25, "Service credit", "correction-123"));
Errors (4)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ValidationException: An amount, policy, key, or schedule is invalid.
  • IdempotencyConflictException: The customer-scoped retry key was used for a different credit operation or request.
  • InsufficientCreditsException: A negative adjustment exceeds available credit.

listGrants

List all grants, including spent or expired grants, in descending grant-ID order. This does not reconcile schedules.

listGrants(customerKey: string, currencyKey: string, filter?: PageFilter): Promise<CreditGrantDto[]>

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key.
  • filter: Optional PageFilter; defaults to 50 rows at offset zero. Search and status are ignored.

Returns CreditGrantDto[]: Saved records, or an empty collection when none match.

Example

const history = await subscrio.credits.listGrants('acme', 'ai-credits', { limit: 20 });
console.log(history);
Errors (1)
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<List<CreditGrantDto>> ListGrantsAsync(string customerKey, string currencyKey, int limit, int offset)

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key.
  • limit: Optional page size, 1 to 500; defaults to 50.
  • offset: Optional nonnegative rows to skip; defaults to 0.

Returns List<CreditGrantDto>: Saved records, or an empty collection when none match.

Example

var history = await subscrio.Credits.ListGrantsAsync("acme", "ai-credits", limit: 20);
Console.WriteLine(history.Count);
Errors (1)
  • ValidationException: An amount, policy, key, or schedule is invalid.

getOperation

Retrieve the saved result of a credit operation using its idempotency key. This diagnostic does not replay or execute the operation.

getOperation(customerKey: string, k: string): Promise<{ id: string; type: string; result: unknown; createdAt: string; } | null>

Parameters

  • customerKey: Customer key.
  • k: Credit operation idempotency key.

Returns { id: string; type: string; result: unknown; createdAt: string } | null: Operation snapshot, or null when missing.

Example

const operation = await subscrio.credits.getOperation('acme', 'render-123');
console.log(operation?.result);
Task<CreditOperationDto?> GetOperationAsync(string customerKey, string key)

Parameters

  • customerKey: Customer key.
  • key: Credit operation idempotency key.

Returns CreditOperationDto?: Operation snapshot, or null when missing.

Example

var operation = await subscrio.Credits.GetOperationAsync("acme", "render-123");
Console.WriteLine(operation?.Result);

listLedgerEntries

List accounting entries in descending creation-time and ID order without reconciling schedules.

listLedgerEntries(customerKey: string, currencyKey: string, filter?: PageFilter): Promise<{ id: string; operationId: string; grantId: string; amount: number; reason: string; createdAt: string; metadata: unknown; }[]>

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key.
  • filter: Optional PageFilter; defaults to 50 rows at offset zero. Search and status are ignored.

Returns Array<{ id: string; operationId: string; grantId: string; amount: number; reason: string; createdAt: string; metadata: unknown }>: Saved records, or an empty collection when none match.

Example

const history = await subscrio.credits.listLedgerEntries('acme', 'ai-credits', { limit: 20 });
console.log(history);
Errors (1)
  • ValidationError: An amount, policy, key, or schedule is invalid.
Task<List<CreditLedgerEntryDto>> ListLedgerEntriesAsync(string customerKey, string currencyKey, int limit, int offset)

Parameters

  • customerKey: Customer key.
  • currencyKey: Currency key.
  • limit: Optional page size, 1 to 500; defaults to 50.
  • offset: Optional nonnegative rows to skip; defaults to 0.

Returns List<CreditLedgerEntryDto>: Saved records, or an empty collection when none match.

Example

var history = await subscrio.Credits.ListLedgerEntriesAsync("acme", "ai-credits", limit: 20);
Console.WriteLine(history.Count);
Errors (1)
  • ValidationException: An amount, policy, key, or schedule is invalid.

archiveCurrency

Archive the currency to block new grants and spending. Balances and history remain available.

archiveCurrency(k: string): Promise<void>

Parameters

  • k: Currency key.

Returns No returned value.

Example

await subscrio.credits.archiveCurrency('unused-credits');
Errors (1)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
Task ArchiveCurrencyAsync(string key)

Parameters

  • key: Currency key.

Returns No returned value.

Example

await subscrio.Credits.ArchiveCurrencyAsync("unused-credits");
Errors (1)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.

unarchiveCurrency

Restore the currency to active status, allowing issuance and spending again.

unarchiveCurrency(k: string): Promise<void>

Parameters

  • k: Currency key.

Returns No returned value.

Example

await subscrio.credits.unarchiveCurrency('unused-credits');
Errors (1)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
Task UnarchiveCurrencyAsync(string key)

Parameters

  • key: Currency key.

Returns No returned value.

Example

await subscrio.Credits.UnarchiveCurrencyAsync("unused-credits");
Errors (1)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.

deleteCurrency

Permanently delete an archived currency with no wallet, plan-grant, or consumption-rule references. Inactive plan-grant rules still count as references.

deleteCurrency(k: string): Promise<void>

Parameters

  • k: Currency key.

Returns No returned value.

Example

await subscrio.credits.deleteCurrency('unused-credits');
Errors (2)
  • NotFoundError: A required customer, currency, plan, or subscription is missing.
  • ConflictError: The currency is active or has references.
Task DeleteCurrencyAsync(string key)

Parameters

  • key: Currency key.

Returns No returned value.

Example

await subscrio.Credits.DeleteCurrencyAsync("unused-credits");
Errors (2)
  • NotFoundException: A required customer, currency, plan, or subscription is missing.
  • ConflictException: The currency is active or has references.

Data types

Amounts are safe integers with magnitude at most 9,007,199,254,740,991. IDs are opaque strings. Required means supplied input or a guaranteed returned property.

CreateCreditCurrencyDto

Currency creation input; an inline object in TypeScript.

Field Type Required Default Meaning
key string Yes None Unique 1-to-255-character key of letters, digits, underscores, or hyphens.
displayName string Yes None Nonblank label.
metadata Record<string, unknown> No None Optional JSON metadata.
Property Type Required Default Meaning
Key string Yes None Stable identifier.
DisplayName string Yes None Human-readable label, 1 to 255 characters.
Metadata Dictionary<string, object?>? No null Optional JSON metadata.

CreditCurrencyDto

Currency details.

Field Type Required Default Meaning
key string Yes Not applicable Stable identifier.
displayName string Yes Not applicable Human-readable label, 1 to 255 characters.
status string Yes Not applicable Current record status.
metadata Record<string, unknown> | null | undefined No Not applicable Optional JSON metadata.
createdAt string Yes Not applicable Creation time in UTC.
updatedAt string Yes Not applicable Last update time in UTC.
Property Type Required Default Meaning
Key string Yes Not applicable Stable identifier.
DisplayName string Yes Not applicable Human-readable label, 1 to 255 characters.
Status string Yes Not applicable Current record status.
Metadata Dictionary<string, object?>? Yes Not applicable Optional JSON metadata.
CreatedAt string Yes Not applicable Creation time in UTC.
UpdatedAt string Yes Not applicable Last update time in UTC.

UpdateCurrencyInput

TypeScript uses this inline object; .NET takes label and metadata as individual arguments.

Field Type Required Default Meaning
displayName string No None Nonblank replacement label.
metadata Record<string, unknown> No None Replacement metadata object.

See UpdateCurrencyAsync for individual parameters.

PlanCreditGrantInput

Plan grant configuration.

Field Type Required Default Meaning
amount number Yes None Positive integer amount.
cadence "monthly" | "yearly" | "billing_period" | "once" Yes None once, monthly, yearly, or billing_period. Monthly/yearly schedules anchor after any trial and clamp month-end dates.
expiryPolicy "none" | "grant_period_end" | undefined No none none retains credits; grant_period_end expires at the issued period end. The latter is invalid with once cadence.
cancellationPolicy "retain" | "expire" | undefined No retain retain keeps issued credit; expire removes its remaining credit when the subscription stops.
Property Type Required Default Meaning
Amount long Yes None Positive integer amount.
Cadence string Yes None once, monthly, yearly, or billing_period. Monthly/yearly schedules anchor after any trial and clamp month-end dates.
ExpiryPolicy string No none none retains credits; grant_period_end expires at the issued period end. The latter is invalid with once cadence.
CancellationPolicy string No retain retain keeps issued credit; expire removes its remaining credit when the subscription stops.

PlanCreditGrantDto

Returned plan rule; TypeScript uses PlanCreditGrantInput with a currencyKey.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
amount number Yes Not applicable Positive integer amount.
cadence "once" | "monthly" | "yearly" | "billing_period" Yes Not applicable once, monthly, yearly, or billing_period. Monthly/yearly schedules anchor after any trial and clamp month-end dates.
expiryPolicy "none" | "grant_period_end" Yes Not applicable none retains credits; grant_period_end expires at the issued period end. The latter is invalid with once cadence.
cancellationPolicy "retain" | "expire" Yes Not applicable retain keeps issued credit; expire removes its remaining credit when the subscription stops.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
Amount long Yes Not applicable Positive integer amount.
Cadence string Yes Not applicable once, monthly, yearly, or billing_period. Monthly/yearly schedules anchor after any trial and clamp month-end dates.
ExpiryPolicy string Yes Not applicable none retains credits; grant_period_end expires at the issued period end. The latter is invalid with once cadence.
CancellationPolicy string Yes Not applicable retain keeps issued credit; expire removes its remaining credit when the subscription stops.

CreditConsumptionRuleDto

Returned action cost; an inline object in TypeScript.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
creditsPerUnit number Yes Not applicable Positive credit cost per action unit.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
CreditsPerUnit long Yes Not applicable Positive credit cost per action unit.

CreditGrantInput

Manual credit issuance input.

Field Type Required Default Meaning
customerKey string Yes None Customer owning the wallet.
currencyKey string Yes None Credit currency key.
amount number Yes None Positive integer amount.
grantType "manual" | "promotional" | "prepaid" Yes None manual, promotional, or prepaid.
priority number | undefined No 0 Lower numbers are spent first. Signed integer with absolute value at most 2,147,483,647.
expiresAt string | Date | undefined No None Optional future UTC expiry.
subscriptionKey string | undefined No None Optional subscription belonging to this customer.
idempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.
metadata Record<string, unknown> | undefined No None Optional JSON metadata.
Property Type Required Default Meaning
CustomerKey string Yes None Customer owning the wallet.
CurrencyKey string Yes None Credit currency key.
Amount long Yes None Positive integer amount.
GrantType string Yes None manual, promotional, or prepaid.
IdempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.
Priority int No 0 Lower numbers are spent first. Signed integer with absolute value at most 2,147,483,647.
ExpiresAt DateTime? No null Optional future UTC expiry.
SubscriptionKey string? No null Optional subscription belonging to this customer.
Metadata Dictionary<string, object?>? No null Optional JSON metadata.

CreditGrantDto

Persisted grant properties.

Field Type Required Default Meaning
id string Yes Not applicable Opaque record identifier.
currencyKey string Yes Not applicable Credit currency key.
subscriptionKey string | null | undefined No Not applicable Optional subscription belonging to this customer.
grantType string Yes Not applicable manual, promotional, prepaid, or plan.
originalAmount number Yes Not applicable Amount originally issued.
remainingAmount number Yes Not applicable Amount not yet spent or expired.
priority number Yes Not applicable Lower numbers are spent first. Signed integer with absolute value at most 2,147,483,647.
expiresAt string | null Yes Not applicable UTC expiry, or null for no expiration.
createdAt string Yes Not applicable Creation time in UTC.
updatedAt string Yes Not applicable Last update time in UTC.
Property Type Required Default Meaning
Id string Yes Not applicable Opaque record identifier.
CurrencyKey string Yes Not applicable Credit currency key.
SubscriptionKey string? Yes Not applicable Optional subscription belonging to this customer.
GrantType string Yes Not applicable manual, promotional, prepaid, or plan.
OriginalAmount long Yes Not applicable Amount originally issued.
RemainingAmount long Yes Not applicable Amount not yet spent or expired.
Priority int Yes Not applicable Lower numbers are spent first. Signed integer with absolute value at most 2,147,483,647.
ExpiresAt string? Yes Not applicable UTC expiry, or null for no expiration.
CreatedAt string Yes Not applicable Creation time in UTC.
UpdatedAt string Yes Not applicable Last update time in UTC.

IssueDuePlanGrantsInput

Subscription selection; an inline object in TypeScript.

Field Type Required Default Meaning
subscriptionKey string Yes None Subscription to reconcile.
Property Type Required Default Meaning
SubscriptionKey string Yes None Optional subscription belonging to this customer.

DuePlanGrantsDto

Schedule result; an inline object in TypeScript.

Field Type Required Default Meaning
issued CreditGrantDto[] Yes Not applicable Grants issued during this call.
nextDueAt string | null Yes Not applicable Earliest stored next due time, or null.
hasMore boolean Yes Not applicable Currently always false; excessive catch-up throws instead of returning another page.
Property Type Required Default Meaning
Issued List<CreditGrantDto> Yes Not applicable Grants issued during this call.
NextDueAt string? Yes Not applicable Earliest stored next due time, or null.
HasMore bool Yes Not applicable Currently always false; excessive catch-up throws instead of returning another page.

ScheduledGrantResult

Processing counts; an inline object in TypeScript and a tuple in .NET.

Field Type Required Default Meaning
issued number Yes Not applicable Grants issued during processing.
customers number Yes Not applicable Customers processed.
Property Type Required Default Meaning
Issued int Yes Not applicable Grants issued during processing.
Customers int Yes Not applicable Customers processed.

CreditBalanceDto

Spendable wallet balance.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
available number Yes Not applicable Spendable credit remaining.
grants CreditGrantDto[] Yes Not applicable Unexpired grants with positive balances in spending order.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
Available long Yes Not applicable Spendable credit remaining.
Grants List<CreditGrantDto> Yes Not applicable Unexpired grants with positive balances in spending order.

CreditActionDto

An action to price.

Field Type Required Default Meaning
customerKey string Yes None Customer owning the wallet.
featureKey string Yes None Feature whose configured costs are charged.
units number Yes None Positive integer action quantity.
Property Type Required Default Meaning
CustomerKey string Yes None Customer owning the wallet.
FeatureKey string Yes None Feature whose configured costs are charged.
Units long Yes None Positive integer action quantity.

CreditCheckDto

Affordability result.

Field Type Required Default Meaning
hasAccess boolean Yes Not applicable True if all currency costs are affordable and currencies are active.
costs CreditCostDto[] Yes Not applicable Per-currency costs and available balances.
accessDeniedReason "insufficient_credits" | "currency_inactive" | undefined No Not applicable currency_inactive takes precedence over insufficient_credits; absent or null when allowed.
Property Type Required Default Meaning
HasAccess bool Yes Not applicable True if all currency costs are affordable and currencies are active.
Costs List<CreditCostDto> Yes Not applicable Per-currency costs and available balances.
AccessDeniedReason string? Yes Not applicable currency_inactive takes precedence over insufficient_credits; absent or null when allowed.

CreditConsumeInput

An action to charge.

Field Type Required Default Meaning
idempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.
metadata Record<string, unknown> | undefined No None Optional JSON metadata.
customerKey string Yes None Customer owning the wallet.
featureKey string Yes None Feature whose configured costs are charged.
units number Yes None Positive integer action quantity.
Property Type Required Default Meaning
CustomerKey string Yes None Customer owning the wallet.
FeatureKey string Yes None Feature whose configured costs are charged.
Units long Yes None Positive integer action quantity.
IdempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.
Metadata Dictionary<string, object?>? No null Optional JSON metadata.

CreditConsumeDto

Persisted consumption result.

Field Type Required Default Meaning
operationId string Yes Not applicable Saved operation identifier.
idempotencyKey string Yes Not applicable Nonblank 1-to-255-character key shared across credit operation types for this customer.
allocations CreditAllocationDto[] Yes Not applicable Amounts deducted from individual grants.
balances { currencyKey: string; available: number; }[] Yes Not applicable Post-debit available balance in each charged currency.
Property Type Required Default Meaning
OperationId string Yes Not applicable Saved operation identifier.
IdempotencyKey string Yes Not applicable Nonblank 1-to-255-character key shared across credit operation types for this customer.
Allocations List<CreditAllocationDto> Yes Not applicable Amounts deducted from individual grants.
Balances List<CreditAvailableDto> Yes Not applicable Post-debit available balance in each charged currency.

CreditAdjustInput

Signed balance correction.

Field Type Required Default Meaning
customerKey string Yes None Customer owning the wallet.
currencyKey string Yes None Credit currency key.
amount number Yes None Nonzero signed integer: positive adds credit; negative removes it.
reason string Yes None Required nonblank explanation for the correction.
idempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.
Property Type Required Default Meaning
CustomerKey string Yes None Customer owning the wallet.
CurrencyKey string Yes None Credit currency key.
Amount long Yes None Nonzero signed integer: positive adds credit; negative removes it.
Reason string Yes None Required nonblank explanation for the correction.
IdempotencyKey string Yes None Nonblank 1-to-255-character key shared across credit operation types for this customer.

CreditAdjustmentDto

Correction result; an inline object in TypeScript.

Field Type Required Default Meaning
operationId string Yes Not applicable Saved operation identifier.
idempotencyKey string Yes Not applicable Nonblank 1-to-255-character key shared across credit operation types for this customer.
balance CreditBalanceDto Yes Not applicable Saved post-adjustment balance.
Property Type Required Default Meaning
OperationId string Yes Not applicable Saved operation identifier.
IdempotencyKey string Yes Not applicable Nonblank 1-to-255-character key shared across credit operation types for this customer.
Balance CreditBalanceDto Yes Not applicable Saved post-adjustment balance.

CreditOperationDto

Saved operation; an inline object in TypeScript.

Field Type Required Default Meaning
id string Yes Not applicable Opaque record identifier.
type string Yes Not applicable Operation type, such as grant, consume, adjust, or plan_grant.
result unknown Yes Not applicable Saved result: grant, consumption, or balance snapshot according to operation type.
createdAt string Yes Not applicable Creation time in UTC.
Property Type Required Default Meaning
Id string Yes Not applicable Opaque record identifier.
Type string Yes Not applicable Operation type, such as grant, consume, adjust, or plan_grant.
Result System.Text.Json.JsonElement Yes Not applicable Saved result: grant, consumption, or balance snapshot according to operation type.
CreatedAt string Yes Not applicable Creation time in UTC.

CreditLedgerEntryDto

Immutable accounting entry; an inline object in TypeScript.

Field Type Required Default Meaning
id string Yes Not applicable Opaque record identifier.
operationId string Yes Not applicable Saved operation identifier.
grantId string Yes Not applicable Grant identifier.
amount number Yes Not applicable Signed change: positive issuance, negative consumption or expiry.
reason string Yes Not applicable Accounting reason, such as grant, consumption, adjustment, or expiry.
createdAt string Yes Not applicable Creation time in UTC.
metadata unknown Yes Not applicable Optional stored context; may be null.
Property Type Required Default Meaning
Id string Yes Not applicable Opaque record identifier.
OperationId string Yes Not applicable Saved operation identifier.
GrantId string Yes Not applicable Grant identifier.
Amount long Yes Not applicable Positive integer amount.
Reason string Yes Not applicable Required nonblank explanation for the correction.
CreatedAt string Yes Not applicable Creation time in UTC.
Metadata Dictionary<string, object?>? Yes Not applicable Optional JSON metadata.

CreditCostDto

One currency cost.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
cost number Yes Not applicable Total charge in this currency.
available number Yes Not applicable Spendable credit remaining.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
Cost long Yes Not applicable Total charge in this currency.
Available long Yes Not applicable Spendable credit remaining.

CreditAllocationDto

One deduction from a grant.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
grantId string Yes Not applicable Grant identifier.
amount number Yes Not applicable Positive integer amount.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
GrantId string Yes Not applicable Grant identifier.
Amount long Yes Not applicable Positive integer amount.

CreditAvailableDto

Post-consumption balance; an inline object in TypeScript.

Field Type Required Default Meaning
currencyKey string Yes Not applicable Credit currency key.
available number Yes Not applicable Spendable credit remaining.
Property Type Required Default Meaning
CurrencyKey string Yes Not applicable Credit currency key.
Available long Yes Not applicable Spendable credit remaining.
  • How Subscrio Works: metering versus credit wallets.
  • Plans: the plans that supply scheduled grants.
  • Feature Checker: feature access checks separate from credit affordability.
  • Hooks: grant, consumption, and adjustment events.