Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Sell prepaid credits

Use this guide to credit a purchase, take credits when a player starts a game, and correct the balance when a payment is disputed. Supply explains when supply becomes available and how draws and expiry work.

In the code tabs, run the HTTP tab or the SDK tab with the shared blocks. The ResourceShark SDK package is @agentpost-tools/resourceshark-sdk.

Before you start

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

1. Create a credit resource

Use key from the project that adopted ResourceShark. Keep a scope for each holder and set supplyExpiry to expiring so ResourceShark keeps the supply entries separate. Use shortage: 'deny' to prevent players from spending past their available balance. Resources lists every field a resource takes.

const prepaidBase = {
  settings: { time: 'none', identity: 'count', supplyExpiry: 'expiring' },
  scope: { places: false, holders: true },
  tracking: 'none',
  shortage: 'deny',
  tags: ['prepaid'],
};
const { resource: prepaidLoons } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    ...prepaidBase,
    key: 'loons',
    name: 'Loons',
    unit: { code: 'loon', singular: 'loon', plural: 'loons', precision: 0 },
  },
);
const prepaidAna = 'principal:external:u_ana';
const prepaidBo = 'principal:external:u_bo';

const prepaidWrite = (path: string, attempt: string, body: unknown) =>
  api('POST', `/v1/resources${path}`, key, body, {
    'Idempotency-Key': attempt,
  });

const prepaidBalance = (resourceId: string, holderRef: string) =>
  api(
    'GET',
    `/v1/resources/holders/${encodeURIComponent(holderRef)}/balances/${resourceId}`,
    key,
  );

2. Add the signup credit and the paid pack

Give Ana 4 promotional loons at signup. Set drawOrder: -1 so ResourceShark draws those loons first. When your payment provider confirms the $4.99 order, post 500 more loons. Your app’s order record keeps the price, and the supply entry’s evidence.ref points to that order. Give the order one source key so a redelivery adds nothing, even when it comes with a different Idempotency-Key. Supply requests lists every field a supply entry takes.

const { supply: prepaidSignup } = await prepaidWrite(
  '/supply',
  'credit-ana-signup',
  {
    resourceId: prepaidLoons.id,
    scope: { holderRef: prepaidAna },
    kind: 'added',
    quantity: 4,
    drawOrder: -1,
    attributes: { source: 'promo', cohort: 'launch' },
    evidence: { kind: 'signup', ref: 'u_ana' },
    sourceKey: 'signup:u_ana',
  },
);
const orders: Record<string, { priceInCents: number; currency: string }> = {
  ord_ana_pack: { priceInCents: 499, currency: 'USD' },
};
const prepaidPackSupply = {
  resourceId: prepaidLoons.id,
  scope: { holderRef: prepaidAna },
  kind: 'added',
  quantity: 500,
  attributes: { source: 'pack', cohort: 'launch' },
  evidence: { kind: 'order', ref: 'ord_ana_pack' },
  sourceKey: 'order.paid:ord_ana_pack',
};
const { supply: prepaidPack } = await prepaidWrite(
  '/supply',
  'credit-ana-pack',
  prepaidPackSupply,
);
const prepaidRedelivery = await prepaidWrite(
  '/supply',
  'redeliver-ana-pack',
  prepaidPackSupply,
);
const prepaidOpening = await prepaidBalance(prepaidLoons.id, prepaidAna);
console.log(prepaidRedelivery.duplicate, prepaidOpening.balance.onHand); // true 504

3. Hold a credit and commit it when a game starts

Hold 1 loon for 1m. Name Ana on the line’s scope and on the hold. Commit with the game as evidence. Leaving lines out of the commit takes every line on the hold. Hold requests lists every field the hold and the commit take.

const { hold: prepaidGameHold } = await prepaidWrite(
  '/holds',
  'hold-ana-game-1',
  {
    lines: [
      {
        resourceId: prepaidLoons.id,
        scope: { holderRef: prepaidAna },
        quantity: 1,
      },
    ],
    holderRef: prepaidAna,
    ttl: '1m',
    sourceKey: 'hold:ana-game-1',
  },
);
const {
  movements: [prepaidGame],
} = await prepaidWrite(
  `/holds/${prepaidGameHold.id}/commit`,
  'commit-ana-game-1',
  {
    evidence: { kind: 'game', ref: 'ana-game-1' },
    sourceKey: 'commit:ana-game-1',
  },
);
console.log(
  prepaidGame.quantity,
  prepaidGame.pegs[0].supplyId === prepaidSignup.id,
); // -1 true

4. Take back disputed credits

Spend 10 more loons to leave 493 of the paid pack. On a dispute, request the 500 loons from the original supply entry. If the request is refused with insufficient_supply, details.lines[0].available tells you what is free to take back. If that quantity is positive, ask for it with the same sourceKey and a fresh Idempotency-Key.

const prepaidUse = (
  resourceId: string,
  holderRef: string,
  quantity: number,
  ref: string,
  estimate = false,
) =>
  prepaidWrite('/consume', `consume-${ref}`, {
    lines: [{ resourceId, scope: { holderRef }, quantity }],
    evidence: { kind: 'request', ref },
    sourceKey: `use:${ref}`,
    ...(estimate ? { estimate: true } : {}),
  });
for (let run = 2; run <= 11; run += 1) {
  await prepaidUse(prepaidLoons.id, prepaidAna, 1, `ana-game-${run}`);
}

const prepaidDispute = { kind: 'dispute', ref: 'dp_ana_1' };
const prepaidTakeBack = {
  quantity: 500,
  evidence: prepaidDispute,
  sourceKey: 'dispute:dp_ana_1',
};

resourceSharkRefusal sends a request that should be refused and returns the error that api throws, so your app can read its details. Choose the SDK tab to let takeBackUpTo handle the retry and return an outcome.

async function resourceSharkRefusal(
  method: 'GET' | 'POST',
  path: string,
  credential: string,
  request?: { body: unknown; idempotencyKey: string },
) {
  try {
    await api(
      method,
      `/v1/resources${path}`,
      credential,
      request?.body,
      request ? { 'Idempotency-Key': request.idempotencyKey } : {},
    );
  } catch (thrown) {
    const { error } = thrown as { error?: any };
    if (!error) throw thrown;
    return error;
  }
  throw new Error(`Expected a refusal for ${method} ${path}`);
}
const prepaidReversePath = `/supply/${prepaidPack.id}/reverse`;
const prepaidShort = await resourceSharkRefusal(
  'POST',
  prepaidReversePath,
  key,
  {
    body: prepaidTakeBack,
    idempotencyKey: 'reverse-dp_ana_1',
  },
);
if (prepaidShort.code !== 'insufficient_supply')
  throw new Error(prepaidShort.code);
const prepaidAvailable = prepaidShort.details.lines[0].available;
console.log(prepaidShort.code, prepaidAvailable); // insufficient_supply 493
if (prepaidAvailable <= 0) throw new Error('No credits left to take back');
const prepaidReversal = await prepaidWrite(
  prepaidReversePath,
  'reverse-dp_ana_1-retry',
  {
    ...prepaidTakeBack,
    quantity: prepaidAvailable,
  },
);
import { createClient as createPrepaidClient } from '@agentpost-tools/resourceshark-sdk';
import { takeBackUpTo } from '@agentpost-tools/resourceshark-sdk/helpers';

const prepaidClient = createPrepaidClient({ token: key });
const prepaidOutcome = await takeBackUpTo(prepaidClient, prepaidPack.id, {
  ...prepaidTakeBack,
  idempotencyKey: 'reverse-dp_ana_1',
});
if (prepaidOutcome.status === 'failed') throw prepaidOutcome.error;
if (prepaidOutcome.status === 'nothing_left')
  throw new Error('No credits left to take back');
const prepaidReversal = prepaidOutcome.response;

Both tabs leave prepaidReversal ready to use. If the dispute is decided for the player and the supply hasn’t expired, reverse the movement to restore exactly what was taken. Stock adjustments lists every field an adjustment takes.

if (!prepaidReversal.movement) throw new Error('Expected a reversal movement');
const { movement: prepaidReinstatement } = await prepaidWrite(
  '/adjustments',
  'reinstate-dp_ana_1',
  {
    reverses: prepaidReversal.movement.id,
    evidence: prepaidDispute,
    sourceKey: 'dispute-won:dp_ana_1',
  },
);
console.log(prepaidReversal.taken, prepaidReinstatement.quantity); // 493 493

5. Set an expiry for promotional credits

Give Ana 100 promotional loons with an expiresAt and spend 30. Give Bo two 100-loon entries with different expiries, then spend 150. With equal draw order, ResourceShark draws first from the entry that expires first.

const prepaidDay = 86_400_000;
const prepaidPromoEnd = new Date(
  Date.parse(prepaidSignup.createdAt) + prepaidDay,
).toISOString();
const prepaidLaterEnd = new Date(
  Date.parse(prepaidSignup.createdAt) + 2 * prepaidDay,
).toISOString();
const prepaidPromo = (
  holderRef: string,
  ref: string,
  cohort: string,
  expiresAt: string,
) =>
  prepaidWrite('/supply', `grant-${ref}`, {
    resourceId: prepaidLoons.id,
    scope: { holderRef },
    kind: 'added',
    quantity: 100,
    attributes: { source: 'promo', cohort },
    expiresAt,
    evidence: { kind: 'promo', ref },
    sourceKey: `promo:${ref}`,
  });
const { supply: prepaidAnaPromo } = await prepaidPromo(
  prepaidAna,
  'ana-promo',
  'launch',
  prepaidPromoEnd,
);
await prepaidUse(prepaidLoons.id, prepaidAna, 30, 'ana-tournament');
await prepaidPromo(prepaidBo, 'bo-promo', 'returning', prepaidPromoEnd);
await prepaidPromo(prepaidBo, 'bo-promo-long', 'returning', prepaidLaterEnd);
await prepaidUse(prepaidLoons.id, prepaidBo, 150, 'bo-tournament');

const prepaidPromoRead = await api(
  'GET',
  `/v1/resources/supply/${prepaidAnaPromo.id}`,
  key,
);
const prepaidBoBalance = await prepaidBalance(prepaidLoons.id, prepaidBo);
console.log(prepaidPromoRead.supply.remaining, prepaidBoBalance.balance.onHand); // 70 50

At the first expiry only the unused 70 go away. Read both balances again after prepaidPromoEnd and before prepaidLaterEnd. With no intervening activity, Ana has 493 and Bo still has 50. Supply explains the order of draws and what happens at expiry.

6. Consume and settle a prepaid dollar balance

For a balance priced to four decimal places, credit $10 as 100,000 units and consume $0.0125 as 125. When you know only an estimate, consume it with estimate: true and settle the claim at the actual cost. This job uses 3,200 of its estimated 5,000 units. Claim requests lists every field a consume and a settle take.

const { resource: prepaidUsd } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    ...prepaidBase,
    key: 'prepaid-usd',
    name: 'Prepaid USD',
    unit: {
      code: 'usd',
      singular: 'US dollar',
      plural: 'US dollars',
      precision: 4,
    },
  },
);
const prepaidAcme = 'customer:acme';
await prepaidWrite('/supply', 'credit-acme-10usd', {
  resourceId: prepaidUsd.id,
  scope: { holderRef: prepaidAcme },
  kind: 'added',
  quantity: 100_000,
  attributes: { source: 'order' },
  evidence: { kind: 'order', ref: 'ord_acme_10usd' },
  sourceKey: 'order.paid:ord_acme_10usd',
});
await prepaidUse(prepaidUsd.id, prepaidAcme, 125, 'acme-request-1');
const {
  claims: [prepaidEstimate],
} = await prepaidUse(prepaidUsd.id, prepaidAcme, 5_000, 'acme-job-1', true);
const prepaidSettlement = await prepaidWrite('/settle', 'settle-acme-job-1', {
  lines: [{ claimId: prepaidEstimate.id, quantity: 3_200 }],
  evidence: { kind: 'request', ref: 'acme-job-1' },
  sourceKey: 'settle:acme-job-1',
});
console.log(prepaidSettlement.movements[0].quantity); // 1800

const prepaidOverBudget = await resourceSharkRefusal('POST', '/consume', key, {
  body: {
    lines: [
      {
        resourceId: prepaidUsd.id,
        scope: { holderRef: prepaidAcme },
        quantity: 96_676,
      },
    ],
    evidence: { kind: 'request', ref: 'acme-request-2' },
    sourceKey: 'use:acme-request-2',
  },
  idempotencyKey: 'consume-acme-request-2',
});
console.log(
  prepaidOverBudget.code,
  prepaidOverBudget.details.lines[0].available,
); // insufficient_supply 96675

7. Read a signed-in player’s history

For a player signed in through your app, use the server’s secret key to mint a Platform user token for the player’s ID. The token for u_ana reads records scoped to principal:external:u_ana. Send it when listing movements.

const { token: prepaidAnaToken } = await api('POST', '/v1/user-tokens', key, {
  externalId: 'u_ana',
  expiresIn: '15m',
});
const prepaidHistoryPath = `/movements?resourceId=${prepaidLoons.id}`;
const { movements: prepaidHistory } = await api(
  'GET',
  `/v1/resources${prepaidHistoryPath}`,
  prepaidAnaToken,
);
console.log(
  prepaidHistory.some(
    (movement: { id: string }) => movement.id === prepaidGame.id,
  ),
); // true

const prepaidOtherHistory = await resourceSharkRefusal(
  'GET',
  `${prepaidHistoryPath}&holderRef=${encodeURIComponent(prepaidBo)}`,
  prepaidAnaToken,
);
console.log(prepaidOtherHistory.code); // forbidden

Use the server’s secret key for project-wide totals and the change feed. Either read answers forbidden for a holder’s token.

Check it worked

Read the paid pack and the dollar balance with the server’s key. The restored pack has 493 loons left and the dollar balance has 96,675 units available.

const prepaidSavedPack = await api(
  'GET',
  `/v1/resources/supply/${prepaidPack.id}`,
  key,
);
const prepaidDollars = await prepaidBalance(prepaidUsd.id, prepaidAcme);
console.log(
  prepaidSavedPack.supply.remaining,
  prepaidDollars.balance.available,
); // 493 96675

Use the dollar balance to post recurring supply for a monthly limit.