kokio-sdk 3.2.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,13 +8,16 @@ import { AdminDeviceWalletSubPackage } from "./interface/deviceWalletClass.js";
8
8
  import { AdminESIMWalletSubPackage } from "./interface/eSIMWalletClass.js";
9
9
  import { AdminPaymentAdapterSubPackage } from "./interface/paymentAdapterClass.js";
10
10
  import { AdminCallsSubPackage } from "./interface/callsClass.js";
11
+ import { AdminUtilsSubPackage } from "./interface/utilsClass.js";
11
12
  // Re-export the typed error surface so backend consumers can `instanceof
12
13
  // KokioError` (or a subclass) and decode reverts without reaching into internal
13
14
  // module paths - mirroring `config.ts`.
14
- export { KokioError, NullOrUndefinedValueError, MissingSmartWalletError, MissingEOAWalletError, InvalidClientError, UnsupportedChainError, UnconfiguredChainError, CounterfactualMismatchError, BatchSizeOutOfRangeError, DepositOnResumeError, ESIMWalletNotLazyDeployedError, MissingBatchEventError, StalledBatchError, ContractRevertError, decodeContractRevert, } from "../logic/errors.js";
15
+ export { KokioError, NullOrUndefinedValueError, MissingSmartWalletError, MissingEOAWalletError, InvalidClientError, UnsupportedChainError, UnconfiguredChainError, CounterfactualMismatchError, BatchSizeOutOfRangeError, DepositOnResumeError, ESIMWalletNotLazyDeployedError, MissingBatchEventError, StalledBatchError, InvalidAddressError, InvalidSymbolError, TokenNotAcceptedError, NotAProtocolESIMWalletError, UnknownTransactionError, TransactionRevertedError, ReceiptNotCanonicalError, NotAnERC20TokenError, UnmatchedPaymentEventsError, PriceOutOfRangeError, InvalidPaymentReferenceError, CouponSplitOutOfRangeError, ContractRevertError, decodeContractRevert, } from "../logic/errors.js";
15
16
  // `getOperationState` answers with this, and comparing against it needs the enum
16
17
  // at runtime rather than only in the types.
17
18
  export { OperationState } from "../logic/admin/reads/protocolAdmin.reads.js";
19
+ // Passed to `utils.tagPaymentReference` and returned by `utils.parsePaymentReference`.
20
+ export { PaymentReferenceKind } from "../logic/admin/utils/paymentReference.js";
18
21
  /**
19
22
  * EOA-only entry point for the NodeJS backend.
20
23
  *
@@ -45,6 +48,8 @@ export class KokioAdmin {
45
48
  paymentAdapter;
46
49
  /** Calls for the app to sign as a user operation, built here so the backend holds the purchase logic. */
47
50
  calls;
51
+ /** Checks what a mined transaction paid, before the backend acts on it. */
52
+ utils;
48
53
  // Instance-scoped surfaces - undefined until their address is known.
49
54
  deviceWallet;
50
55
  eSIMWallet;
@@ -60,6 +65,7 @@ export class KokioAdmin {
60
65
  this.protocolAdmin = new AdminProtocolAdminSubPackage(walletClient);
61
66
  this.paymentAdapter = new AdminPaymentAdapterSubPackage(walletClient);
62
67
  this.calls = new AdminCallsSubPackage(walletClient);
68
+ this.utils = new AdminUtilsSubPackage(walletClient);
63
69
  this.deviceWallet = deviceWalletAddress ? new AdminDeviceWalletSubPackage(walletClient, deviceWalletAddress) : undefined;
64
70
  this.eSIMWallet = eSIMWalletAddress ? new AdminESIMWalletSubPackage(walletClient, eSIMWalletAddress) : undefined;
65
71
  }
@@ -111,6 +117,7 @@ export class KokioAdmin {
111
117
  this.protocolAdmin = new AdminProtocolAdminSubPackage(walletClient);
112
118
  this.paymentAdapter = new AdminPaymentAdapterSubPackage(walletClient);
113
119
  this.calls = new AdminCallsSubPackage(walletClient);
120
+ this.utils = new AdminUtilsSubPackage(walletClient);
114
121
  this.deviceWallet = this.deviceWalletAddress ? new AdminDeviceWalletSubPackage(walletClient, this.deviceWalletAddress) : undefined;
115
122
  this.eSIMWallet = this.eSIMWalletAddress ? new AdminESIMWalletSubPackage(walletClient, this.eSIMWalletAddress) : undefined;
116
123
  return this;
@@ -24,8 +24,8 @@ export class AdminRegistrySubPackage {
24
24
  acceptAdminUpdate() {
25
25
  return _acceptAdminUpdate(this.walletClient);
26
26
  }
27
- recordSettledPurchase(eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference) {
28
- return _recordSettledPurchase(this.walletClient, eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference);
27
+ recordSettledPurchase(eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference, couponUSDCents) {
28
+ return _recordSettledPurchase(this.walletClient, eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference, couponUSDCents);
29
29
  }
30
30
  assignESIMIdentifier(eSIMWalletAddress, eSIMUniqueIdentifier) {
31
31
  return _assignESIMIdentifier(this.walletClient, eSIMWalletAddress, eSIMUniqueIdentifier);
@@ -0,0 +1,43 @@
1
+ import { _verifyERC20Transfer, _verifyProtocolPayment } from "../../logic/admin/utils/tokenTransfer.js";
2
+ import { _parsePaymentReference, _tagPaymentReference, } from "../../logic/admin/utils/paymentReference.js";
3
+ /**
4
+ * Checks what a mined transaction actually paid, and builds and reads payment
5
+ * references. Nothing is sent. Pass a hash when it came from a user: a receipt
6
+ * is used as given, so it must come from your own node.
7
+ */
8
+ export class AdminUtilsSubPackage {
9
+ walletClient;
10
+ constructor(walletClient) {
11
+ this.walletClient = walletClient;
12
+ }
13
+ /**
14
+ * The purchases `eSIMWallet` paid for through the protocol in `symbol`
15
+ * ("USDC", "USDCt"), with each one's `paymentReference` and price in cents.
16
+ * Throws if the symbol is not an onchain currency on the payment adapter.
17
+ */
18
+ verifyProtocolPayment(transaction, symbol, eSIMWallet) {
19
+ return _verifyProtocolPayment(this.walletClient, transaction, symbol, eSIMWallet);
20
+ }
21
+ /**
22
+ * What `sender` sent `destination` directly in any ERC-20. The cents count
23
+ * one token as one dollar, so they mean nothing for a token that is not.
24
+ */
25
+ verifyERC20Transfer(transaction, token, sender, destination) {
26
+ return _verifyERC20Transfer(this.walletClient, transaction, token, sender, destination);
27
+ }
28
+ /**
29
+ * Marks `reference` with how the purchase was paid for. Its high 20 bytes
30
+ * must be zero. For a split purchase, tag the same reference once as
31
+ * `CouponPart` and once as `Remainder`.
32
+ */
33
+ tagPaymentReference(reference, kind) {
34
+ return _tagPaymentReference(reference, kind);
35
+ }
36
+ /**
37
+ * How a purchase was paid for, and the untagged reference it was built
38
+ * from. Throws on a tag this SDK did not write.
39
+ */
40
+ parsePaymentReference(reference) {
41
+ return _parsePaymentReference(reference);
42
+ }
43
+ }
@@ -1,6 +1,9 @@
1
+ import { encodeAbiParameters, keccak256, publicActions, stringToHex } from "viem";
1
2
  import { _chainId, _getChainSpecificConstants } from "../constants.js";
2
- import { MissingEOAWalletError, writeContractOrThrow } from "../errors.js";
3
+ import { CouponSplitOutOfRangeError, InvalidPaymentReferenceError, MissingEOAWalletError, TransactionRevertedError, writeContractOrThrow, } from "../errors.js";
3
4
  import { Registry } from "../../abis/index.js";
5
+ import { Settlement } from "../../types.js";
6
+ import { PaymentReferenceKind, _parsePaymentReference } from "./utils/paymentReference.js";
4
7
  // Admin-EOA logic for `Registry`. Most of this is `onlyOwner`, so the `client`
5
8
  // must carry the owner EOA. `_acceptAdminUpdate` is the nominee's own call and
6
9
  // `_assignESIMIdentifier` is `onlyESIMWalletAdmin`.
@@ -207,21 +210,92 @@ export const _assignESIMIdentifier = async (client, eSIMWalletAddress, eSIMUniqu
207
210
  * never sees a transfer to prove it), and `_tokenAmount` is recorded for
208
211
  * offchain matching but never checked against `_dataBundleDetail.priceUSDCents`.
209
212
  * `_paymentReference` is spendable once per eSIM wallet.
213
+ *
214
+ * Given `[couponRef, remainderRef]` and `couponUSDCents`, records a purchase
215
+ * split between a coupon and another payment as two lines, see
216
+ * {@link _couponSplitLines}. Lines already recorded are skipped, so a retry
217
+ * after a partial failure sends only what is missing. Returns the last hash
218
+ * sent; any earlier one is already mined.
210
219
  */
211
- export const _recordSettledPurchase = async (client, eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference) => {
220
+ export const _recordSettledPurchase = async (client, eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference, couponUSDCents) => {
212
221
  const chainID = await _chainId(client);
213
222
  const rpcURL = client.transport.url;
214
223
  const values = _getChainSpecificConstants(chainID, rpcURL);
215
224
  if (!client.account)
216
225
  throw new MissingEOAWalletError();
217
- return writeContractOrThrow(client, {
226
+ const account = client.account;
227
+ const record = (line) => writeContractOrThrow(client, {
218
228
  address: values.factoryAddresses.REGISTRY,
219
229
  chain: values.chain,
220
- account: client.account,
230
+ account,
221
231
  abi: Registry,
222
232
  functionName: 'recordSettledPurchase',
223
- args: [eSIMWalletAddress, dataBundleDetail, asset, tokenAmount, paymentReference]
233
+ args: [eSIMWalletAddress, line.dataBundleDetail, line.asset, line.tokenAmount, line.paymentReference]
224
234
  });
235
+ if (typeof paymentReference === "string") {
236
+ return record({ dataBundleDetail, asset, tokenAmount, paymentReference });
237
+ }
238
+ const lines = _couponSplitLines(dataBundleDetail, asset, tokenAmount, paymentReference, couponUSDCents);
239
+ const publicClient = client.extend(publicActions);
240
+ const spent = await Promise.all(lines.map((line) => publicClient.readContract({
241
+ address: values.factoryAddresses.REGISTRY,
242
+ abi: Registry,
243
+ functionName: "usedPaymentReferences",
244
+ args: [keccak256(encodeAbiParameters([{ type: "address" }, { type: "bytes32" }], [eSIMWalletAddress, line.paymentReference]))]
245
+ })));
246
+ const missing = lines.filter((_, i) => !spent[i]);
247
+ // With both lines recorded, the remainder is sent anyway so the contract refuses it with
248
+ // `PaymentReferenceAlreadyUsed`, the same answer a retried single reference gets.
249
+ let hash;
250
+ for (const line of missing.length > 0 ? missing : [lines[0]]) {
251
+ if (hash) {
252
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
253
+ if (receipt.status !== "success")
254
+ throw new TransactionRevertedError(hash);
255
+ }
256
+ hash = await record(line);
257
+ }
258
+ return hash;
259
+ };
260
+ // Coupons are recorded as card payments in USD, whose smallest unit is a cent.
261
+ const COUPON_ASSET = stringToHex("USD", { size: 32 });
262
+ /**
263
+ * Splits one purchase into its remainder line and its coupon line, in that
264
+ * order. `dataBundleDetail` carries the full price and how the remainder was
265
+ * paid; `asset` and `tokenAmount` are what the user paid for the remainder.
266
+ * The coupon line is always `Fiat` in `USD`, with the coupon's cents as its
267
+ * token amount.
268
+ */
269
+ export const _couponSplitLines = (dataBundleDetail, asset, tokenAmount, [couponRef, remainderRef], couponUSDCents) => {
270
+ const coupon = _parsePaymentReference(couponRef);
271
+ const remainder = _parsePaymentReference(remainderRef);
272
+ if (coupon.kind !== PaymentReferenceKind.CouponPart) {
273
+ throw new InvalidPaymentReferenceError(couponRef, "is not tagged as a coupon part");
274
+ }
275
+ if (remainder.kind !== PaymentReferenceKind.Remainder) {
276
+ throw new InvalidPaymentReferenceError(remainderRef, "is not tagged as a remainder");
277
+ }
278
+ if (coupon.reference !== remainder.reference) {
279
+ throw new InvalidPaymentReferenceError(remainderRef, `belongs to a different order than ${couponRef}`);
280
+ }
281
+ const price = dataBundleDetail.priceUSDCents;
282
+ if (couponUSDCents === undefined || couponUSDCents <= 0n || couponUSDCents >= price) {
283
+ throw new CouponSplitOutOfRangeError(couponUSDCents, price);
284
+ }
285
+ return [
286
+ {
287
+ dataBundleDetail: { ...dataBundleDetail, priceUSDCents: price - couponUSDCents },
288
+ asset,
289
+ tokenAmount,
290
+ paymentReference: remainderRef,
291
+ },
292
+ {
293
+ dataBundleDetail: { id: dataBundleDetail.id, priceUSDCents: couponUSDCents, settlement: Settlement.Fiat },
294
+ asset: COUPON_ASSET,
295
+ tokenAmount: couponUSDCents,
296
+ paymentReference: couponRef,
297
+ },
298
+ ];
225
299
  };
226
300
  /**
227
301
  * Step 2 of the 2-step admin handover: the nominee accepts. The chain requires
@@ -0,0 +1,58 @@
1
+ import { concat, isHex, pad, size, slice } from "viem";
2
+ import { InvalidPaymentReferenceError } from "../../errors.js";
3
+ /** How a purchase was paid for, as written into its payment reference. */
4
+ export var PaymentReferenceKind;
5
+ (function (PaymentReferenceKind) {
6
+ /** Paid in full without a coupon. Carries no tag. */
7
+ PaymentReferenceKind["Standard"] = "Standard";
8
+ /** Paid in full by a coupon. */
9
+ PaymentReferenceKind["Coupon"] = "Coupon";
10
+ /** The coupon's share of a purchase split between a coupon and another payment. */
11
+ PaymentReferenceKind["CouponPart"] = "CouponPart";
12
+ /** What the user paid on top of the coupon in a split purchase. */
13
+ PaymentReferenceKind["Remainder"] = "Remainder";
14
+ })(PaymentReferenceKind || (PaymentReferenceKind = {}));
15
+ // The backend puts the order id in the low 12 bytes, leaving the high 20 free for a tag.
16
+ // Every coupon tag starts with 0xfee0ff ("fee off") so it stands out on an explorer.
17
+ const TAG_SIZE = 20;
18
+ const TAGS = {
19
+ [PaymentReferenceKind.Standard]: pad("0x", { size: TAG_SIZE }),
20
+ [PaymentReferenceKind.Coupon]: pad("0xfee0ff", { size: TAG_SIZE, dir: "right" }),
21
+ [PaymentReferenceKind.CouponPart]: pad("0xfee0ffc0de", { size: TAG_SIZE, dir: "right" }),
22
+ [PaymentReferenceKind.Remainder]: pad("0xfee0ffba1a5ce0", { size: TAG_SIZE, dir: "right" }),
23
+ };
24
+ // Lowercased so a checksum-style or uppercase input compares equal to the tags above.
25
+ const _splitReference = (reference) => {
26
+ if (!isHex(reference, { strict: true }) || size(reference) !== 32) {
27
+ throw new InvalidPaymentReferenceError(reference, "is not 32 bytes of hex");
28
+ }
29
+ const lower = reference.toLowerCase();
30
+ const order = slice(lower, TAG_SIZE);
31
+ // The contracts refuse a zero reference, and a tag would hide an empty order id from that check.
32
+ if (BigInt(order) === 0n)
33
+ throw new InvalidPaymentReferenceError(reference, "has an empty order part");
34
+ return { tag: slice(lower, 0, TAG_SIZE), order };
35
+ };
36
+ /**
37
+ * Writes `kind`'s tag into the high 20 bytes of `reference`, which must be zero
38
+ * there. Tag both halves of a split purchase from the same reference, so each
39
+ * spends once onchain and both still point at the same order.
40
+ */
41
+ export const _tagPaymentReference = (reference, kind) => {
42
+ const { tag, order } = _splitReference(reference);
43
+ if (tag !== TAGS[PaymentReferenceKind.Standard]) {
44
+ throw new InvalidPaymentReferenceError(reference, "is already tagged");
45
+ }
46
+ return concat([TAGS[kind], order]);
47
+ };
48
+ /**
49
+ * Reads back how a purchase was paid for, and the untagged reference it was
50
+ * built from. Throws on a tag this SDK did not write.
51
+ */
52
+ export const _parsePaymentReference = (reference) => {
53
+ const { tag, order } = _splitReference(reference);
54
+ const kind = Object.keys(TAGS).find((k) => TAGS[k] === tag);
55
+ if (!kind)
56
+ throw new InvalidPaymentReferenceError(reference, "has an unknown tag");
57
+ return { kind, reference: pad(order, { size: 32 }) };
58
+ };
@@ -0,0 +1,157 @@
1
+ import { BaseError, ContractFunctionRevertedError, ContractFunctionZeroDataError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, TransactionReceiptNotFoundError, erc20Abi, isAddress, isAddressEqual, isHash, parseEventLogs, publicActions, stringToHex, zeroAddress, } from "viem";
2
+ import { _chainId, _getChainSpecificConstants } from "../../constants.js";
3
+ import { ESIMWallet, PaymentAdapter, Registry } from "../../../abis/index.js";
4
+ import { InvalidAddressError, InvalidSymbolError, NotAProtocolESIMWalletError, NotAnERC20TokenError, PriceOutOfRangeError, ReceiptNotCanonicalError, TokenNotAcceptedError, TransactionRevertedError, UnknownTransactionError, UnmatchedPaymentEventsError, } from "../../errors.js";
5
+ // The contracts price everything in uint64 cents.
6
+ const MAX_UINT64 = 2n ** 64n - 1n;
7
+ const _checkAddress = (what, value) => {
8
+ if (!isAddress(value))
9
+ throw new InvalidAddressError(what, value, "is not a valid address");
10
+ if (isAddressEqual(value, zeroAddress))
11
+ throw new InvalidAddressError(what, value, "is the zero address");
12
+ return value;
13
+ };
14
+ // Same bytes as Solidity's `bytes32("USDC")`: the text on the left, zeros after.
15
+ const _symbolToBytes32 = (symbol) => {
16
+ if (!symbol)
17
+ throw new InvalidSymbolError(symbol);
18
+ try {
19
+ return stringToHex(symbol, { size: 32 });
20
+ }
21
+ catch {
22
+ throw new InvalidSymbolError(symbol);
23
+ }
24
+ };
25
+ const _checkTransaction = (transaction) => {
26
+ if (typeof transaction === "string" && !isHash(transaction))
27
+ throw new UnknownTransactionError(transaction);
28
+ };
29
+ // A receipt passed in is used as given, so it must come from the caller's own node.
30
+ const _receipt = async (client, transaction) => {
31
+ let receipt = transaction;
32
+ if (typeof transaction === "string") {
33
+ try {
34
+ receipt = await client.extend(publicActions).getTransactionReceipt({ hash: transaction });
35
+ }
36
+ catch (err) {
37
+ if (err instanceof TransactionReceiptNotFoundError)
38
+ throw new UnknownTransactionError(transaction);
39
+ throw err;
40
+ }
41
+ }
42
+ if (receipt.status !== "success")
43
+ throw new TransactionRevertedError(receipt.transactionHash);
44
+ return receipt;
45
+ };
46
+ // The receipt plus how far its block has settled, read alongside it. A receipt passed in
47
+ // is also checked against the chain's block at its height, since it may be from a block
48
+ // since reorged out. One fetched by hash comes from the chain as it is now.
49
+ const _receiptWithFinality = async (client, transaction) => {
50
+ const publicClient = client.extend(publicActions);
51
+ const given = typeof transaction === "string" ? undefined : transaction;
52
+ const [receipt, safe, finalized, canonical] = await Promise.all([
53
+ _receipt(client, transaction),
54
+ publicClient.getBlock({ blockTag: "safe" }),
55
+ publicClient.getBlock({ blockTag: "finalized" }),
56
+ given && publicClient.getBlock({ blockNumber: given.blockNumber }),
57
+ ]);
58
+ if (canonical && canonical.hash !== receipt.blockHash) {
59
+ throw new ReceiptNotCanonicalError(receipt.transactionHash, receipt.blockHash);
60
+ }
61
+ const finality = receipt.blockNumber <= finalized.number ? "finalized"
62
+ : receipt.blockNumber <= safe.number ? "safe"
63
+ : "latest";
64
+ return { receipt, landed: { finality, blockNumber: receipt.blockNumber, blockHash: receipt.blockHash } };
65
+ };
66
+ /**
67
+ * Every purchase `eSIMWallet` paid for in `symbol` within one transaction, read
68
+ * from the payment adapter's `PaymentSettled` and the eSIM wallet's
69
+ * `DataBundleBoughtWithToken`. Cents and references are the contracts' own.
70
+ */
71
+ export const _verifyProtocolPayment = async (client, transaction, symbol, eSIMWallet) => {
72
+ const wallet = _checkAddress("eSIM wallet", eSIMWallet);
73
+ const asset = _symbolToBytes32(symbol);
74
+ _checkTransaction(transaction);
75
+ const publicClient = client.extend(publicActions);
76
+ const reads = async () => {
77
+ const F = _getChainSpecificConstants(await _chainId(client), client.transport.url).factoryAddresses;
78
+ const [deviceWallet, entry] = await Promise.all([
79
+ publicClient.readContract({ address: F.REGISTRY, abi: Registry, functionName: "isESIMWalletValid", args: [wallet] }),
80
+ publicClient.readContract({ address: F.PAYMENT_ADAPTER, abi: PaymentAdapter, functionName: "assets", args: [asset] }),
81
+ ]);
82
+ return { adapter: F.PAYMENT_ADAPTER, deviceWallet, entry };
83
+ };
84
+ const [{ receipt, landed }, { adapter, deviceWallet, entry: [, , decimals, token] }] = await Promise.all([
85
+ _receiptWithFinality(client, transaction),
86
+ reads(),
87
+ ]);
88
+ if (deviceWallet === zeroAddress)
89
+ throw new NotAProtocolESIMWalletError(wallet);
90
+ // A registered symbol always has non-zero decimals, even once withdrawn.
91
+ if (decimals === 0)
92
+ throw new TokenNotAcceptedError(symbol, "NOT_REGISTERED");
93
+ if (token === zeroAddress)
94
+ throw new TokenNotAcceptedError(symbol, "NOT_ONCHAIN");
95
+ // Filtered on the emitting address, so a look-alike event from any other contract is ignored.
96
+ const settled = parseEventLogs({ abi: PaymentAdapter, eventName: "PaymentSettled", logs: receipt.logs })
97
+ .filter((log) => isAddressEqual(log.address, adapter) && log.args._symbol === asset && isAddressEqual(log.args._eSIMWallet, wallet));
98
+ const bought = parseEventLogs({ abi: ESIMWallet, eventName: "DataBundleBoughtWithToken", logs: receipt.logs })
99
+ .filter((log) => isAddressEqual(log.address, wallet) && log.args._asset === asset);
100
+ // The adapter settles first and the wallet emits after, once per purchase.
101
+ if (settled.length !== bought.length)
102
+ throw new UnmatchedPaymentEventsError(receipt.transactionHash);
103
+ const payments = settled.map((s, i) => {
104
+ const b = bought[i];
105
+ if (s.logIndex > b.logIndex || s.args._priceUSDCents !== b.args._priceUSDCents || s.args._spent !== b.args._amountSpent) {
106
+ throw new UnmatchedPaymentEventsError(receipt.transactionHash);
107
+ }
108
+ return {
109
+ paymentReference: b.args._paymentReference,
110
+ dataBundleId: b.args._dataBundleID,
111
+ priceUSDCents: b.args._priceUSDCents,
112
+ amountSpent: b.args._amountSpent,
113
+ vault: s.args._vault,
114
+ };
115
+ });
116
+ return { priceUSDCents: payments.reduce((sum, p) => sum + p.priceUSDCents, 0n), payments, ...landed };
117
+ };
118
+ // A revert or an empty answer means the address is not an ERC-20. Anything else, like a
119
+ // network failure, is passed on as-is.
120
+ const _erc20Read = (read, token) => read.catch((err) => {
121
+ const notAToken = err instanceof BaseError && err.walk((e) => e instanceof ContractFunctionRevertedError ||
122
+ e instanceof ContractFunctionZeroDataError ||
123
+ e instanceof AbiDecodingZeroDataError ||
124
+ e instanceof AbiDecodingDataSizeTooSmallError);
125
+ throw notAToken ? new NotAnERC20TokenError(token) : err;
126
+ });
127
+ /**
128
+ * What `sender` sent `destination` directly in `token` within one transaction.
129
+ * Cents treat one token as one dollar, the way the payment adapter prices a
130
+ * dollar currency, so they mean nothing for a token that is not.
131
+ */
132
+ export const _verifyERC20Transfer = async (client, transaction, token, sender, destination) => {
133
+ const tokenAddress = _checkAddress("Token", token);
134
+ const from = _checkAddress("Sender", sender);
135
+ const to = _checkAddress("Destination", destination);
136
+ if (isAddressEqual(from, to))
137
+ throw new InvalidAddressError("Destination", to, "is the same as the sender");
138
+ _checkTransaction(transaction);
139
+ const publicClient = client.extend(publicActions);
140
+ // decimals() is what an ERC-721 lacks, and an address with no code answers neither.
141
+ const [{ receipt, landed }, decimals] = await Promise.all([
142
+ _receiptWithFinality(client, transaction),
143
+ _erc20Read(publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "decimals" }), tokenAddress),
144
+ _erc20Read(publicClient.readContract({ address: tokenAddress, abi: erc20Abi, functionName: "totalSupply" }), tokenAddress),
145
+ ]);
146
+ // Strict parsing skips an ERC-721 Transfer, whose third topic is the token id.
147
+ const amount = parseEventLogs({ abi: erc20Abi, eventName: "Transfer", logs: receipt.logs })
148
+ .filter((log) => isAddressEqual(log.address, tokenAddress) && isAddressEqual(log.args.from, from) && isAddressEqual(log.args.to, to))
149
+ .reduce((sum, log) => sum + log.args.value, 0n);
150
+ // amount * 100 / 10^decimals, without the large intermediate.
151
+ const priceUSDCents = decimals >= 2
152
+ ? amount / 10n ** BigInt(decimals - 2)
153
+ : amount * 10n ** BigInt(2 - decimals);
154
+ if (priceUSDCents > MAX_UINT64)
155
+ throw new PriceOutOfRangeError(priceUSDCents);
156
+ return { priceUSDCents, amount, ...landed };
157
+ };
@@ -132,6 +132,126 @@ export class StalledBatchError extends KokioError {
132
132
  this.remaining = remaining;
133
133
  }
134
134
  }
135
+ /** An address argument is malformed, zero, or the same as the other side of the transfer. */
136
+ export class InvalidAddressError extends KokioError {
137
+ value;
138
+ constructor(what, value, reason) {
139
+ super("INVALID_ADDRESS", `${what} ${value} ${reason}.`);
140
+ this.value = value;
141
+ }
142
+ }
143
+ /** A currency symbol is empty or does not fit the contracts' 32-byte symbol. */
144
+ export class InvalidSymbolError extends KokioError {
145
+ symbol;
146
+ constructor(symbol) {
147
+ super("INVALID_SYMBOL", `Symbol "${symbol}" must be 1 to 32 bytes long.`);
148
+ this.symbol = symbol;
149
+ }
150
+ }
151
+ /**
152
+ * The payment adapter cannot have taken this symbol as an onchain payment:
153
+ * `NOT_REGISTERED` if it was never added, `NOT_ONCHAIN` for fiat and non-EVM
154
+ * entries, which have no token address.
155
+ */
156
+ export class TokenNotAcceptedError extends KokioError {
157
+ symbol;
158
+ reason;
159
+ constructor(symbol, reason) {
160
+ super("TOKEN_NOT_ACCEPTED", reason === "NOT_REGISTERED"
161
+ ? `Symbol "${symbol}" is not registered on the payment adapter.`
162
+ : `Symbol "${symbol}" has no token address on the payment adapter, so it cannot be paid onchain.`);
163
+ this.symbol = symbol;
164
+ this.reason = reason;
165
+ }
166
+ }
167
+ /** The registry has no record of this address as an eSIM wallet. */
168
+ export class NotAProtocolESIMWalletError extends KokioError {
169
+ address;
170
+ constructor(address) {
171
+ super("NOT_A_PROTOCOL_ESIM_WALLET", `${address} is not an eSIM wallet the registry knows.`);
172
+ this.address = address;
173
+ }
174
+ }
175
+ /** No mined transaction with this hash on the client's chain. */
176
+ export class UnknownTransactionError extends KokioError {
177
+ hash;
178
+ constructor(hash) {
179
+ super("UNKNOWN_TRANSACTION", `No mined transaction ${hash} on this chain.`);
180
+ this.hash = hash;
181
+ }
182
+ }
183
+ /** The transaction was mined but reverted, so nothing in it moved. */
184
+ export class TransactionRevertedError extends KokioError {
185
+ hash;
186
+ constructor(hash) {
187
+ super("TRANSACTION_REVERTED", `Transaction ${hash} reverted.`);
188
+ this.hash = hash;
189
+ }
190
+ }
191
+ /**
192
+ * A receipt passed in is from a block the chain no longer has at that height,
193
+ * so it was reorged out. The payment may have landed again elsewhere.
194
+ */
195
+ export class ReceiptNotCanonicalError extends KokioError {
196
+ hash;
197
+ blockHash;
198
+ constructor(hash, blockHash) {
199
+ super("RECEIPT_NOT_CANONICAL", `The receipt for ${hash} is from block ${blockHash}, which is no longer on the chain. Check again by hash.`);
200
+ this.hash = hash;
201
+ this.blockHash = blockHash;
202
+ }
203
+ }
204
+ /** The address does not answer `decimals()` and `totalSupply()` like an ERC-20. */
205
+ export class NotAnERC20TokenError extends KokioError {
206
+ token;
207
+ constructor(token) {
208
+ super("NOT_AN_ERC20_TOKEN", `${token} is not an ERC-20 token on this chain.`);
209
+ this.token = token;
210
+ }
211
+ }
212
+ /**
213
+ * A purchase's adapter event and eSIM wallet event disagree or do not pair up.
214
+ * The current contracts always emit them together, so this means they changed.
215
+ */
216
+ export class UnmatchedPaymentEventsError extends KokioError {
217
+ hash;
218
+ constructor(hash) {
219
+ super("UNMATCHED_PAYMENT_EVENTS", `Transaction ${hash} has payment events that do not pair up.`);
220
+ this.hash = hash;
221
+ }
222
+ }
223
+ /** A cent figure too large for the uint64 the contracts price in. */
224
+ export class PriceOutOfRangeError extends KokioError {
225
+ priceUSDCents;
226
+ constructor(priceUSDCents) {
227
+ super("PRICE_OUT_OF_RANGE", `${priceUSDCents} cents does not fit the contracts' uint64 price.`);
228
+ this.priceUSDCents = priceUSDCents;
229
+ }
230
+ }
231
+ /**
232
+ * A payment reference that is not 32 bytes, has an empty order part, or
233
+ * carries a tag this SDK cannot write over or read back.
234
+ */
235
+ export class InvalidPaymentReferenceError extends KokioError {
236
+ reference;
237
+ constructor(reference, reason) {
238
+ super("INVALID_PAYMENT_REFERENCE", `Payment reference "${reference}" ${reason}.`);
239
+ this.reference = reference;
240
+ }
241
+ }
242
+ /**
243
+ * A coupon that covers none or all of the price. Neither is a split: a coupon
244
+ * covering the whole price is a full-coupon order with a single reference.
245
+ */
246
+ export class CouponSplitOutOfRangeError extends KokioError {
247
+ couponUSDCents;
248
+ priceUSDCents;
249
+ constructor(couponUSDCents, priceUSDCents) {
250
+ super("COUPON_SPLIT_OUT_OF_RANGE", `A coupon of ${couponUSDCents} cents does not split a price of ${priceUSDCents} cents.`);
251
+ this.couponUSDCents = couponUSDCents;
252
+ this.priceUSDCents = priceUSDCents;
253
+ }
254
+ }
135
255
  // Every ABI that can surface a custom error from an on-chain revert. viem's
136
256
  // `decodeErrorResult` walks each ABI's `error` fragments to match the 4-byte
137
257
  // selector in the revert data.
@@ -9,9 +9,11 @@ import { AdminDeviceWalletSubPackage } from "./interface/deviceWalletClass.js";
9
9
  import { AdminESIMWalletSubPackage } from "./interface/eSIMWalletClass.js";
10
10
  import { AdminPaymentAdapterSubPackage } from "./interface/paymentAdapterClass.js";
11
11
  import { AdminCallsSubPackage } from "./interface/callsClass.js";
12
- export { KokioError, NullOrUndefinedValueError, MissingSmartWalletError, MissingEOAWalletError, InvalidClientError, UnsupportedChainError, UnconfiguredChainError, CounterfactualMismatchError, BatchSizeOutOfRangeError, DepositOnResumeError, ESIMWalletNotLazyDeployedError, MissingBatchEventError, StalledBatchError, ContractRevertError, decodeContractRevert, } from "../logic/errors.js";
12
+ import { AdminUtilsSubPackage } from "./interface/utilsClass.js";
13
+ export { KokioError, NullOrUndefinedValueError, MissingSmartWalletError, MissingEOAWalletError, InvalidClientError, UnsupportedChainError, UnconfiguredChainError, CounterfactualMismatchError, BatchSizeOutOfRangeError, DepositOnResumeError, ESIMWalletNotLazyDeployedError, MissingBatchEventError, StalledBatchError, InvalidAddressError, InvalidSymbolError, TokenNotAcceptedError, NotAProtocolESIMWalletError, UnknownTransactionError, TransactionRevertedError, ReceiptNotCanonicalError, NotAnERC20TokenError, UnmatchedPaymentEventsError, PriceOutOfRangeError, InvalidPaymentReferenceError, CouponSplitOutOfRangeError, ContractRevertError, decodeContractRevert, } from "../logic/errors.js";
13
14
  export type { DecodedRevert } from "../logic/errors.js";
14
15
  export { OperationState } from "../logic/admin/reads/protocolAdmin.reads.js";
16
+ export { PaymentReferenceKind } from "../logic/admin/utils/paymentReference.js";
15
17
  /**
16
18
  * EOA-only entry point for the NodeJS backend.
17
19
  *
@@ -41,6 +43,8 @@ export declare class KokioAdmin {
41
43
  paymentAdapter: AdminPaymentAdapterSubPackage;
42
44
  /** Calls for the app to sign as a user operation, built here so the backend holds the purchase logic. */
43
45
  calls: AdminCallsSubPackage;
46
+ /** Checks what a mined transaction paid, before the backend acts on it. */
47
+ utils: AdminUtilsSubPackage;
44
48
  deviceWallet?: AdminDeviceWalletSubPackage;
45
49
  eSIMWallet?: AdminESIMWalletSubPackage;
46
50
  constructor(walletClient: WalletClient, deviceWalletAddress?: Address, eSIMWalletAddress?: Address);
@@ -10,7 +10,19 @@ export declare class AdminRegistrySubPackage {
10
10
  disableAdmin(): Promise<`0x${string}`>;
11
11
  enableAdmin(): Promise<`0x${string}`>;
12
12
  acceptAdminUpdate(): Promise<`0x${string}`>;
13
- recordSettledPurchase(eSIMWalletAddress: Address, dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, paymentReference: Hex): Promise<`0x${string}`>;
13
+ /**
14
+ * Records a purchase paid for by card or an external wallet, or one line of
15
+ * a coupon purchase. One transaction.
16
+ */
17
+ recordSettledPurchase(eSIMWalletAddress: Address, dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, paymentReference: Hex): Promise<Hex>;
18
+ /**
19
+ * Records a purchase split between a coupon and a card or external wallet
20
+ * payment, as two lines. `dataBundleDetail` carries the full price and how
21
+ * the remainder was paid; `asset` and `tokenAmount` are what the user paid
22
+ * for the remainder. Lines already recorded are skipped. Returns the hash
23
+ * of the last transaction sent; any earlier one is already mined.
24
+ */
25
+ recordSettledPurchase(eSIMWalletAddress: Address, dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, paymentReferences: readonly [couponRef: Hex, remainderRef: Hex], couponUSDCents: bigint): Promise<Hex>;
14
26
  assignESIMIdentifier(eSIMWalletAddress: Address, eSIMUniqueIdentifier: string): Promise<`0x${string}`>;
15
27
  pause(): Promise<`0x${string}`>;
16
28
  unpause(): Promise<`0x${string}`>;
@@ -0,0 +1,36 @@
1
+ import { Address, Hash, Hex, TransactionReceipt, WalletClient } from "viem";
2
+ import { PaymentReferenceKind } from "../../logic/admin/utils/paymentReference.js";
3
+ /**
4
+ * Checks what a mined transaction actually paid, and builds and reads payment
5
+ * references. Nothing is sent. Pass a hash when it came from a user: a receipt
6
+ * is used as given, so it must come from your own node.
7
+ */
8
+ export declare class AdminUtilsSubPackage {
9
+ walletClient: WalletClient;
10
+ constructor(walletClient: WalletClient);
11
+ /**
12
+ * The purchases `eSIMWallet` paid for through the protocol in `symbol`
13
+ * ("USDC", "USDCt"), with each one's `paymentReference` and price in cents.
14
+ * Throws if the symbol is not an onchain currency on the payment adapter.
15
+ */
16
+ verifyProtocolPayment(transaction: Hash | TransactionReceipt, symbol: string, eSIMWallet: Address): Promise<import("../../types.js").ProtocolPaymentCheck>;
17
+ /**
18
+ * What `sender` sent `destination` directly in any ERC-20. The cents count
19
+ * one token as one dollar, so they mean nothing for a token that is not.
20
+ */
21
+ verifyERC20Transfer(transaction: Hash | TransactionReceipt, token: Address, sender: Address, destination: Address): Promise<import("../../types.js").ERC20TransferCheck>;
22
+ /**
23
+ * Marks `reference` with how the purchase was paid for. Its high 20 bytes
24
+ * must be zero. For a split purchase, tag the same reference once as
25
+ * `CouponPart` and once as `Remainder`.
26
+ */
27
+ tagPaymentReference(reference: Hex, kind: PaymentReferenceKind): `0x${string}`;
28
+ /**
29
+ * How a purchase was paid for, and the untagged reference it was built
30
+ * from. Throws on a tag this SDK did not write.
31
+ */
32
+ parsePaymentReference(reference: Hex): {
33
+ kind: PaymentReferenceKind;
34
+ reference: Hex;
35
+ };
36
+ }
@@ -1,5 +1,5 @@
1
1
  import { Address, Hex, WalletClient } from "viem";
2
- import type { DataBundleDetails, OwnerCall } from "../../types.js";
2
+ import { type DataBundleDetails, type OwnerCall } from "../../types.js";
3
3
  /** Wire (or rewire) the LazyWalletRegistry into the Registry. `onlyOwner`. */
4
4
  export declare const _addOrUpdateLazyWalletRegistryAddress: (client: WalletClient, lazyWalletRegistry: Address) => Promise<`0x${string}`>;
5
5
  /** Update the vault that receives eSIM payments. `onlyOwner`. */
@@ -72,8 +72,29 @@ export declare const _assignESIMIdentifier: (client: WalletClient, eSIMWalletAdd
72
72
  * never sees a transfer to prove it), and `_tokenAmount` is recorded for
73
73
  * offchain matching but never checked against `_dataBundleDetail.priceUSDCents`.
74
74
  * `_paymentReference` is spendable once per eSIM wallet.
75
+ *
76
+ * Given `[couponRef, remainderRef]` and `couponUSDCents`, records a purchase
77
+ * split between a coupon and another payment as two lines, see
78
+ * {@link _couponSplitLines}. Lines already recorded are skipped, so a retry
79
+ * after a partial failure sends only what is missing. Returns the last hash
80
+ * sent; any earlier one is already mined.
81
+ */
82
+ export declare const _recordSettledPurchase: (client: WalletClient, eSIMWalletAddress: Address, dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, paymentReference: Hex | readonly [Hex, Hex], couponUSDCents?: bigint) => Promise<Hex>;
83
+ /** One `recordSettledPurchase` call's worth of arguments, past the eSIM wallet. */
84
+ export interface SettledLine {
85
+ dataBundleDetail: DataBundleDetails;
86
+ asset: Hex;
87
+ tokenAmount: bigint;
88
+ paymentReference: Hex;
89
+ }
90
+ /**
91
+ * Splits one purchase into its remainder line and its coupon line, in that
92
+ * order. `dataBundleDetail` carries the full price and how the remainder was
93
+ * paid; `asset` and `tokenAmount` are what the user paid for the remainder.
94
+ * The coupon line is always `Fiat` in `USD`, with the coupon's cents as its
95
+ * token amount.
75
96
  */
76
- export declare const _recordSettledPurchase: (client: WalletClient, eSIMWalletAddress: Address, dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, paymentReference: Hex) => Promise<`0x${string}`>;
97
+ export declare const _couponSplitLines: (dataBundleDetail: DataBundleDetails, asset: Hex, tokenAmount: bigint, [couponRef, remainderRef]: readonly [Hex, Hex], couponUSDCents: bigint | undefined) => [remainder: SettledLine, coupon: SettledLine];
77
98
  /**
78
99
  * Step 2 of the 2-step admin handover: the nominee accepts. The chain requires
79
100
  * `msg.sender` to equal the pending admin, so the `client` here must be the
@@ -0,0 +1,26 @@
1
+ import { Hex } from "viem";
2
+ /** How a purchase was paid for, as written into its payment reference. */
3
+ export declare enum PaymentReferenceKind {
4
+ /** Paid in full without a coupon. Carries no tag. */
5
+ Standard = "Standard",
6
+ /** Paid in full by a coupon. */
7
+ Coupon = "Coupon",
8
+ /** The coupon's share of a purchase split between a coupon and another payment. */
9
+ CouponPart = "CouponPart",
10
+ /** What the user paid on top of the coupon in a split purchase. */
11
+ Remainder = "Remainder"
12
+ }
13
+ /**
14
+ * Writes `kind`'s tag into the high 20 bytes of `reference`, which must be zero
15
+ * there. Tag both halves of a split purchase from the same reference, so each
16
+ * spends once onchain and both still point at the same order.
17
+ */
18
+ export declare const _tagPaymentReference: (reference: Hex, kind: PaymentReferenceKind) => Hex;
19
+ /**
20
+ * Reads back how a purchase was paid for, and the untagged reference it was
21
+ * built from. Throws on a tag this SDK did not write.
22
+ */
23
+ export declare const _parsePaymentReference: (reference: Hex) => {
24
+ kind: PaymentReferenceKind;
25
+ reference: Hex;
26
+ };
@@ -0,0 +1,14 @@
1
+ import { Address, Hash, TransactionReceipt, WalletClient } from "viem";
2
+ import { ERC20TransferCheck, ProtocolPaymentCheck } from "../../../types.js";
3
+ /**
4
+ * Every purchase `eSIMWallet` paid for in `symbol` within one transaction, read
5
+ * from the payment adapter's `PaymentSettled` and the eSIM wallet's
6
+ * `DataBundleBoughtWithToken`. Cents and references are the contracts' own.
7
+ */
8
+ export declare const _verifyProtocolPayment: (client: WalletClient, transaction: Hash | TransactionReceipt, symbol: string, eSIMWallet: Address) => Promise<ProtocolPaymentCheck>;
9
+ /**
10
+ * What `sender` sent `destination` directly in `token` within one transaction.
11
+ * Cents treat one token as one dollar, the way the payment adapter prices a
12
+ * dollar currency, so they mean nothing for a token that is not.
13
+ */
14
+ export declare const _verifyERC20Transfer: (client: WalletClient, transaction: Hash | TransactionReceipt, token: Address, sender: Address, destination: Address) => Promise<ERC20TransferCheck>;
@@ -87,6 +87,85 @@ export declare class StalledBatchError extends KokioError {
87
87
  readonly remaining: bigint;
88
88
  constructor(hash: Hex, remaining: bigint);
89
89
  }
90
+ /** An address argument is malformed, zero, or the same as the other side of the transfer. */
91
+ export declare class InvalidAddressError extends KokioError {
92
+ readonly value: string;
93
+ constructor(what: string, value: string, reason: string);
94
+ }
95
+ /** A currency symbol is empty or does not fit the contracts' 32-byte symbol. */
96
+ export declare class InvalidSymbolError extends KokioError {
97
+ readonly symbol: string;
98
+ constructor(symbol: string);
99
+ }
100
+ /**
101
+ * The payment adapter cannot have taken this symbol as an onchain payment:
102
+ * `NOT_REGISTERED` if it was never added, `NOT_ONCHAIN` for fiat and non-EVM
103
+ * entries, which have no token address.
104
+ */
105
+ export declare class TokenNotAcceptedError extends KokioError {
106
+ readonly symbol: string;
107
+ readonly reason: "NOT_REGISTERED" | "NOT_ONCHAIN";
108
+ constructor(symbol: string, reason: "NOT_REGISTERED" | "NOT_ONCHAIN");
109
+ }
110
+ /** The registry has no record of this address as an eSIM wallet. */
111
+ export declare class NotAProtocolESIMWalletError extends KokioError {
112
+ readonly address: string;
113
+ constructor(address: string);
114
+ }
115
+ /** No mined transaction with this hash on the client's chain. */
116
+ export declare class UnknownTransactionError extends KokioError {
117
+ readonly hash: Hex;
118
+ constructor(hash: Hex);
119
+ }
120
+ /** The transaction was mined but reverted, so nothing in it moved. */
121
+ export declare class TransactionRevertedError extends KokioError {
122
+ readonly hash: Hex;
123
+ constructor(hash: Hex);
124
+ }
125
+ /**
126
+ * A receipt passed in is from a block the chain no longer has at that height,
127
+ * so it was reorged out. The payment may have landed again elsewhere.
128
+ */
129
+ export declare class ReceiptNotCanonicalError extends KokioError {
130
+ readonly hash: Hex;
131
+ readonly blockHash: Hex;
132
+ constructor(hash: Hex, blockHash: Hex);
133
+ }
134
+ /** The address does not answer `decimals()` and `totalSupply()` like an ERC-20. */
135
+ export declare class NotAnERC20TokenError extends KokioError {
136
+ readonly token: string;
137
+ constructor(token: string);
138
+ }
139
+ /**
140
+ * A purchase's adapter event and eSIM wallet event disagree or do not pair up.
141
+ * The current contracts always emit them together, so this means they changed.
142
+ */
143
+ export declare class UnmatchedPaymentEventsError extends KokioError {
144
+ readonly hash: Hex;
145
+ constructor(hash: Hex);
146
+ }
147
+ /** A cent figure too large for the uint64 the contracts price in. */
148
+ export declare class PriceOutOfRangeError extends KokioError {
149
+ readonly priceUSDCents: bigint;
150
+ constructor(priceUSDCents: bigint);
151
+ }
152
+ /**
153
+ * A payment reference that is not 32 bytes, has an empty order part, or
154
+ * carries a tag this SDK cannot write over or read back.
155
+ */
156
+ export declare class InvalidPaymentReferenceError extends KokioError {
157
+ readonly reference: string;
158
+ constructor(reference: string, reason: string);
159
+ }
160
+ /**
161
+ * A coupon that covers none or all of the price. Neither is a split: a coupon
162
+ * covering the whole price is a full-coupon order with a single reference.
163
+ */
164
+ export declare class CouponSplitOutOfRangeError extends KokioError {
165
+ readonly couponUSDCents?: bigint;
166
+ readonly priceUSDCents: bigint;
167
+ constructor(couponUSDCents: bigint | undefined, priceUSDCents: bigint);
168
+ }
90
169
  export interface DecodedRevert {
91
170
  errorName: string;
92
171
  args: readonly unknown[];
@@ -1,3 +1,3 @@
1
- export type { P256Key, Call, WebAuthnSignature, P256Credential, DataBundleDetails, Asset, SignedRequest, KokioSmartAccount, KokioSmartAccountClient, OwnerCall, OperationOptions, ScheduledOperation, ScheduledBatchOperation, LazyDeploymentBatch, LazyDeployment, LazyHistoryBatch, LazyHistoryCopy } from './types.js';
1
+ export type { P256Key, Call, WebAuthnSignature, P256Credential, DataBundleDetails, Asset, SignedRequest, KokioSmartAccount, KokioSmartAccountClient, OwnerCall, OperationOptions, ScheduledOperation, ScheduledBatchOperation, LazyDeploymentBatch, LazyDeployment, LazyHistoryBatch, LazyHistoryCopy, Finality, TransactionFinality, ProtocolPayment, ProtocolPaymentCheck, ERC20TransferCheck } from './types.js';
2
2
  export type { KokioConstants } from './interface/constantsClass.js';
3
3
  export { Settlement } from './types.js';
@@ -154,6 +154,41 @@ export type LazyHistoryCopy = {
154
154
  /** The history was already fully copied, so nothing was sent. */
155
155
  alreadyComplete: boolean;
156
156
  };
157
+ /** One data bundle an eSIM wallet paid for through the protocol. */
158
+ export type ProtocolPayment = {
159
+ /** The offchain order id the purchase spent. */
160
+ paymentReference: Hex;
161
+ dataBundleId: Hex;
162
+ /** 123456n is $1234.56. */
163
+ priceUSDCents: bigint;
164
+ /** What reached the vault, in the token's smallest unit. */
165
+ amountSpent: bigint;
166
+ vault: Address;
167
+ };
168
+ /**
169
+ * How far a block has settled. `latest` can still be reorged out, `safe` only by
170
+ * an L1 reorg, and `finalized` not at all.
171
+ */
172
+ export type Finality = "latest" | "safe" | "finalized";
173
+ /** Where a checked transaction landed, to store and check again later. */
174
+ export type TransactionFinality = {
175
+ finality: Finality;
176
+ blockNumber: bigint;
177
+ blockHash: Hex;
178
+ };
179
+ /** Every protocol purchase one eSIM wallet made in one transaction and currency. */
180
+ export type ProtocolPaymentCheck = TransactionFinality & {
181
+ /** Total across `payments`, 0n if there were none. */
182
+ priceUSDCents: bigint;
183
+ payments: readonly ProtocolPayment[];
184
+ };
185
+ /** What one address sent another directly in one ERC-20, in one transaction. */
186
+ export type ERC20TransferCheck = TransactionFinality & {
187
+ /** `amount` as cents, counting one token as one dollar and rounding down. */
188
+ priceUSDCents: bigint;
189
+ /** In the token's smallest unit, 0n if nothing was sent. */
190
+ amount: bigint;
191
+ };
157
192
  export type SignedRequest = {
158
193
  body: string;
159
194
  stamp: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kokio-sdk",
3
- "version": "3.2.1",
3
+ "version": "3.4.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/esm/config.js",