@phala/pay 0.1.2 → 0.2.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +86 -1
  2. package/README.md +129 -28
  3. package/dist/checkout.d.ts +37 -7
  4. package/dist/checkout.d.ts.map +1 -1
  5. package/dist/checkout.js +55 -11
  6. package/dist/checkout.js.map +1 -1
  7. package/dist/client.d.ts +8 -7
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +14 -8
  10. package/dist/client.js.map +1 -1
  11. package/dist/deposit-address.d.ts +47 -0
  12. package/dist/deposit-address.d.ts.map +1 -0
  13. package/dist/deposit-address.js +88 -0
  14. package/dist/deposit-address.js.map +1 -0
  15. package/dist/index.d.ts +3 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/payment.d.ts +43 -1
  20. package/dist/payment.d.ts.map +1 -1
  21. package/dist/payment.js +32 -10
  22. package/dist/payment.js.map +1 -1
  23. package/dist/quote.d.ts +7 -3
  24. package/dist/quote.d.ts.map +1 -1
  25. package/dist/quote.js +3 -1
  26. package/dist/quote.js.map +1 -1
  27. package/dist/react/Checkout.d.ts +11 -1
  28. package/dist/react/Checkout.d.ts.map +1 -1
  29. package/dist/react/Checkout.js +28 -37
  30. package/dist/react/Checkout.js.map +1 -1
  31. package/dist/react/DepositAddress.d.ts +31 -0
  32. package/dist/react/DepositAddress.d.ts.map +1 -0
  33. package/dist/react/DepositAddress.js +108 -0
  34. package/dist/react/DepositAddress.js.map +1 -0
  35. package/dist/react/Field.d.ts +7 -0
  36. package/dist/react/Field.d.ts.map +1 -0
  37. package/dist/react/Field.js +21 -0
  38. package/dist/react/Field.js.map +1 -0
  39. package/dist/react/appearance.d.ts +1 -1
  40. package/dist/react/appearance.d.ts.map +1 -1
  41. package/dist/react/appearance.js +3 -0
  42. package/dist/react/appearance.js.map +1 -1
  43. package/dist/react/index.d.ts +1 -0
  44. package/dist/react/index.d.ts.map +1 -1
  45. package/dist/react/index.js +1 -0
  46. package/dist/react/index.js.map +1 -1
  47. package/dist/react/useCheckout.d.ts +3 -1
  48. package/dist/react/useCheckout.d.ts.map +1 -1
  49. package/dist/react/useCheckout.js +4 -3
  50. package/dist/react/useCheckout.js.map +1 -1
  51. package/dist/server/addresses.d.ts +78 -0
  52. package/dist/server/addresses.d.ts.map +1 -0
  53. package/dist/server/addresses.js +118 -0
  54. package/dist/server/addresses.js.map +1 -0
  55. package/dist/server/index.d.ts +12 -0
  56. package/dist/server/index.d.ts.map +1 -0
  57. package/dist/server/index.js +12 -0
  58. package/dist/server/index.js.map +1 -0
  59. package/dist/server/sweeps.d.ts +78 -0
  60. package/dist/server/sweeps.d.ts.map +1 -0
  61. package/dist/server/sweeps.js +117 -0
  62. package/dist/server/sweeps.js.map +1 -0
  63. package/dist/server/webhook.d.ts +60 -0
  64. package/dist/server/webhook.d.ts.map +1 -0
  65. package/dist/server/webhook.js +148 -0
  66. package/dist/server/webhook.js.map +1 -0
  67. package/dist/wallet.d.ts +10 -8
  68. package/dist/wallet.d.ts.map +1 -1
  69. package/dist/wallet.js +61 -63
  70. package/dist/wallet.js.map +1 -1
  71. package/package.json +6 -1
  72. package/src/checkout.ts +89 -15
  73. package/src/client.ts +14 -8
  74. package/src/deposit-address.ts +138 -0
  75. package/src/index.ts +19 -1
  76. package/src/payment.ts +72 -10
  77. package/src/quote.ts +10 -4
  78. package/src/react/Checkout.tsx +72 -70
  79. package/src/react/DepositAddress.tsx +213 -0
  80. package/src/react/Field.tsx +46 -0
  81. package/src/react/appearance.ts +3 -0
  82. package/src/react/index.ts +1 -0
  83. package/src/react/useCheckout.ts +6 -2
  84. package/src/server/addresses.ts +223 -0
  85. package/src/server/index.ts +38 -0
  86. package/src/server/sweeps.ts +197 -0
  87. package/src/server/webhook.ts +202 -0
  88. package/src/wallet.ts +74 -68
@@ -0,0 +1,213 @@
1
+ "use client";
2
+
3
+ import { useEffect, useState } from "react";
4
+ import { formatUnits } from "viem";
5
+ import { networkName } from "../chains.js";
6
+ import {
7
+ retrieveDepositAddress,
8
+ type DepositAddressPayment,
9
+ } from "../deposit-address.js";
10
+ import { CheckoutError, pollDelay } from "../checkout.js";
11
+ import { depositAddressTransfer, type DepositAddressDetails } from "../payment.js";
12
+ import { STYLES, appearanceStyle, type Appearance } from "./appearance.js";
13
+ import { Field } from "./Field.js";
14
+ import { QrCode } from "./QrCode.js";
15
+
16
+ export interface DepositAddressProps {
17
+ /** `address` and `networks` from your backend's `POST /v1/deposit_addresses`. */
18
+ depositAddress: DepositAddressDetails;
19
+ /** The network shown first; the first of `networks` by default. */
20
+ chainId?: number;
21
+ /** The token shown first, for example `pha`; the network's first token by default. */
22
+ asset?: string;
23
+ /**
24
+ * The `client_secret` of the same response. With `apiBase`, the component follows the
25
+ * address's payments and shows each one within about a block of arriving: received with its
26
+ * confirmations, then credited. Display only; credit from your `deposit.credited` webhook.
27
+ */
28
+ clientSecret?: string;
29
+ /** The service origin, for example `https://pay.example.com`; needed with `clientSecret`. */
30
+ apiBase?: string;
31
+ /** Milliseconds between payment reads; default 3000. */
32
+ pollInterval?: number;
33
+ appearance?: Appearance;
34
+ className?: string;
35
+ }
36
+
37
+ /**
38
+ * A customer's persistent deposit address: one address for every supported token on every
39
+ * supported network. The payer picks a network and a token; the component shows a QR code of that
40
+ * EIP-681 transfer request and the address and token contract to copy. Any amount of a supported
41
+ * token sent is credited at the market rate when it arrives; follow it from your backend's
42
+ * `deposit.credited` webhook.
43
+ */
44
+ export function DepositAddress({
45
+ depositAddress,
46
+ chainId,
47
+ asset,
48
+ clientSecret,
49
+ apiBase,
50
+ pollInterval,
51
+ appearance,
52
+ className,
53
+ }: DepositAddressProps) {
54
+ const { networks } = depositAddress;
55
+ const payments = usePayments(clientSecret, apiBase, pollInterval ?? 3000);
56
+ const [selectedChain, setSelectedChain] = useState(chainId ?? networks[0]?.chain_id);
57
+ const [selectedAsset, setSelectedAsset] = useState(asset);
58
+ const network = networks.find((candidate) => candidate.chain_id === selectedChain) ?? networks[0];
59
+ if (network === undefined) {
60
+ throw new TypeError("the deposit address has no network");
61
+ }
62
+ const token =
63
+ network.assets.find((candidate) => candidate.asset === selectedAsset) ?? network.assets[0];
64
+ if (token === undefined) {
65
+ throw new TypeError(`the deposit address takes no token on chain ${network.chain_id}`);
66
+ }
67
+ const { token: contract, to } = depositAddressTransfer(network, token);
68
+ const symbol = token.asset.toUpperCase();
69
+ const name = networkName(network.chain_id);
70
+ const tokens = [...new Set(networks.flatMap((each) => each.assets.map((a) => a.asset.toUpperCase())))];
71
+ return (
72
+ <div
73
+ className={className === undefined ? "pp-root" : `pp-root ${className}`}
74
+ data-theme={appearance?.theme ?? "light"}
75
+ style={appearanceStyle(appearance)}
76
+ >
77
+ <style>{STYLES}</style>
78
+ <p className="pp-subtitle">
79
+ {depositAddress.address === null
80
+ ? "Your deposit address for every supported token; it differs on some networks"
81
+ : "One address for all supported tokens and networks"}
82
+ </p>
83
+ {networks.length > 1 && (
84
+ <div className="pp-tabs" role="tablist" aria-label="Network">
85
+ {networks.map((each) => (
86
+ <button
87
+ key={each.chain_id}
88
+ type="button"
89
+ role="tab"
90
+ className="pp-tab"
91
+ aria-selected={each.chain_id === network.chain_id}
92
+ onClick={() => {
93
+ setSelectedChain(each.chain_id);
94
+ }}
95
+ >
96
+ {networkName(each.chain_id)}
97
+ </button>
98
+ ))}
99
+ </div>
100
+ )}
101
+ {network.assets.length > 1 && (
102
+ <div className="pp-tabs" role="tablist" aria-label="Token">
103
+ {network.assets.map((each) => (
104
+ <button
105
+ key={each.asset}
106
+ type="button"
107
+ role="tab"
108
+ className="pp-tab"
109
+ aria-selected={each.asset === token.asset}
110
+ onClick={() => {
111
+ setSelectedAsset(each.asset);
112
+ }}
113
+ >
114
+ {each.asset.toUpperCase()}
115
+ </button>
116
+ ))}
117
+ </div>
118
+ )}
119
+ <div className="pp-qr-panel">
120
+ <QrCode value={token.payment_uri} label={`Deposit address for ${symbol} on ${name}`} />
121
+ </div>
122
+ <dl className="pp-fields">
123
+ <Field label="Network" value={`${name} (chain ID ${network.chain_id})`} />
124
+ <Field label={`Token (${symbol}) contract`} value={contract} copy />
125
+ <Field label="Deposit address" value={to} copy />
126
+ </dl>
127
+ {payments.length > 0 && (
128
+ <ul className="pp-payments" aria-live="polite" aria-label="Payments">
129
+ {payments.map((payment) => (
130
+ <li key={`${payment.chain_id}:${payment.tx_hash}:${payment.created}`}>
131
+ {paymentMessage(payment)}
132
+ </li>
133
+ ))}
134
+ </ul>
135
+ )}
136
+ <p className="pp-message">
137
+ Send only {tokens.join(", ")} on {networks.map((each) => networkName(each.chain_id)).join(", ")}
138
+ . Any amount is credited at the market rate when it arrives, usually in about 30 seconds.
139
+ Other tokens and networks are not credited. You can reuse this address.
140
+ </p>
141
+ </div>
142
+ );
143
+ }
144
+
145
+ /** The address's recent payments, read every `interval` while mounted; empty without a secret. */
146
+ function usePayments(
147
+ clientSecret: string | undefined,
148
+ apiBase: string | undefined,
149
+ interval: number,
150
+ ): DepositAddressPayment[] {
151
+ const key = clientSecret === undefined || apiBase === undefined ? "" : `${apiBase} ${clientSecret}`;
152
+ const [current, setCurrent] = useState<{ key: string; payments: DepositAddressPayment[] }>({
153
+ key: "",
154
+ payments: [],
155
+ });
156
+ useEffect(() => {
157
+ if (clientSecret === undefined || apiBase === undefined) {
158
+ return;
159
+ }
160
+ let stopped = false;
161
+ let timer: ReturnType<typeof setTimeout> | undefined;
162
+ let failures = 0;
163
+ const load = async () => {
164
+ let failure: CheckoutError | null = null;
165
+ try {
166
+ const view = await retrieveDepositAddress({ clientSecret, apiBase });
167
+ failures = 0;
168
+ if (!stopped) {
169
+ setCurrent({ key, payments: view.payments });
170
+ }
171
+ } catch (error) {
172
+ failures += 1;
173
+ // A secret that is not valid will not become valid: stop, keep showing the address.
174
+ if (error instanceof CheckoutError && error.code === "invalid_client_secret") {
175
+ return;
176
+ }
177
+ failure = error instanceof CheckoutError ? error : null;
178
+ }
179
+ if (!stopped) {
180
+ timer = setTimeout(() => void load(), pollDelay(interval, failures, failure));
181
+ }
182
+ };
183
+ void load();
184
+ return () => {
185
+ stopped = true;
186
+ clearTimeout(timer);
187
+ };
188
+ }, [key, clientSecret, apiBase, interval]);
189
+ // Another address starts without the previous one's payments.
190
+ return current.key === key && key !== "" ? current.payments : [];
191
+ }
192
+
193
+ function paymentMessage(payment: DepositAddressPayment): string {
194
+ const amount =
195
+ payment.asset === null || payment.decimals === null
196
+ ? "A payment"
197
+ : `${formatUnits(BigInt(payment.amount_atomic), payment.decimals)} ${payment.asset.toUpperCase()}`;
198
+ const on = `on ${networkName(payment.chain_id)}`;
199
+ switch (payment.status) {
200
+ case "seen":
201
+ return payment.confirmations === null
202
+ ? `${amount} received ${on}, crediting shortly`
203
+ : `${amount} received ${on}, ${payment.confirmations} confirmation${payment.confirmations === 1 ? "" : "s"}`;
204
+ case "confirming":
205
+ return `${amount} confirmed ${on}, crediting…`;
206
+ case "credited":
207
+ return `${amount} ${on} credited`;
208
+ case "rejected":
209
+ return `${amount} ${on} cannot be credited. Contact support with your transaction.`;
210
+ case "reversed":
211
+ return `${amount} ${on} was reversed: its transaction is no longer on the blockchain.`;
212
+ }
213
+ }
@@ -0,0 +1,46 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ /** `copy` adds a copy button, copying `value`, or the given string when it differs from it. */
4
+ export function Field({
5
+ label,
6
+ value,
7
+ copy = false,
8
+ }: {
9
+ label: string;
10
+ value: string;
11
+ copy?: boolean | string;
12
+ }) {
13
+ return (
14
+ <div className="pp-field">
15
+ <dt>{label}</dt>
16
+ <dd>
17
+ <span className={copy === false ? undefined : "pp-value"}>{value}</span>
18
+ {copy !== false && (
19
+ <CopyButton value={typeof copy === "string" ? copy : value} label={label} />
20
+ )}
21
+ </dd>
22
+ </div>
23
+ );
24
+ }
25
+
26
+ function CopyButton({ value, label }: { value: string; label: string }) {
27
+ const [copied, setCopied] = useState<boolean | null>(null);
28
+ useEffect(() => {
29
+ if (copied === null) {
30
+ return;
31
+ }
32
+ const timer = setTimeout(() => setCopied(null), 2000);
33
+ return () => clearTimeout(timer);
34
+ }, [copied]);
35
+ const onClick = () => {
36
+ navigator.clipboard.writeText(value).then(
37
+ () => setCopied(true),
38
+ () => setCopied(false),
39
+ );
40
+ };
41
+ return (
42
+ <button type="button" className="pp-copy" onClick={onClick} aria-label={`Copy ${label}`}>
43
+ <span aria-live="polite">{copied === null ? "Copy" : copied ? "Copied" : "Copy failed"}</span>
44
+ </button>
45
+ );
46
+ }
@@ -83,6 +83,9 @@ export const STYLES = `
83
83
  .pp-root *, .pp-root *::before, .pp-root *::after { box-sizing: inherit; }
84
84
  .pp-amount { margin: 0; overflow-wrap: anywhere; font-size: 22px; font-weight: 600; }
85
85
  .pp-subtitle { margin: 2px 0 16px; color: var(--pp-color-text-secondary); }
86
+ .pp-badge { font-weight: 600; }
87
+ .pp-payments { list-style: none; margin: 12px 0 0; padding: 0; }
88
+ .pp-payments li { margin: 4px 0; }
86
89
  .pp-status { display: flex; gap: 8px; align-items: baseline; justify-content: space-between;
87
90
  margin-bottom: 12px; padding: 10px 12px; border-radius: var(--pp-border-radius);
88
91
  border: 1px solid var(--pp-color-border); }
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
 
3
3
  export { Checkout, type CheckoutProps } from "./Checkout.js";
4
+ export { DepositAddress, type DepositAddressProps } from "./DepositAddress.js";
4
5
  export { useCheckout, type UseCheckoutOptions, type UseCheckoutResult } from "./useCheckout.js";
5
6
  export type { Appearance } from "./appearance.js";
@@ -3,6 +3,8 @@ import { createCheckout, type CheckoutSession, type CheckoutState } from "../che
3
3
 
4
4
  export interface UseCheckoutOptions {
5
5
  clientSecret: string;
6
+ /** The quote's address as your backend recomputed it; another one fails closed. */
7
+ expectedAddress: string;
6
8
  apiBase: string;
7
9
  pollInterval?: number;
8
10
  }
@@ -17,16 +19,18 @@ const LOADING: CheckoutState = { status: "loading", quote: null, error: null };
17
19
  /** Follows a quote's public view for as long as the component is mounted. */
18
20
  export function useCheckout({
19
21
  clientSecret,
22
+ expectedAddress,
20
23
  apiBase,
21
24
  pollInterval,
22
25
  }: UseCheckoutOptions): UseCheckoutResult {
23
26
  const [current, setCurrent] = useState({ key: "", state: LOADING });
24
27
  const checkout = useRef<CheckoutSession | null>(null);
25
- const key = `${apiBase} ${clientSecret}`;
28
+ const key = `${apiBase} ${clientSecret} ${expectedAddress}`;
26
29
 
27
30
  useEffect(() => {
28
31
  const instance = createCheckout({
29
32
  clientSecret,
33
+ expectedAddress,
30
34
  apiBase,
31
35
  ...(pollInterval === undefined ? {} : { pollInterval }),
32
36
  });
@@ -37,7 +41,7 @@ export function useCheckout({
37
41
  instance.destroy();
38
42
  checkout.current = null;
39
43
  };
40
- }, [key, clientSecret, apiBase, pollInterval]);
44
+ }, [key, clientSecret, expectedAddress, apiBase, pollInterval]);
41
45
 
42
46
  const refresh = useCallback(() => {
43
47
  void checkout.current?.refresh();
@@ -0,0 +1,223 @@
1
+ import {
2
+ encodeAbiParameters,
3
+ getAddress,
4
+ getContractAddress,
5
+ keccak256,
6
+ concat,
7
+ type Address,
8
+ type Hex,
9
+ } from "viem";
10
+
11
+ /**
12
+ * The forwarder `factory` deploys for `treasury` and `salt`: OpenZeppelin 5.x
13
+ * `Clones.predictDeterministicAddressWithImmutableArgs` with `abi.encodePacked(treasury)`, so the
14
+ * address commits to the factory, the implementation, the treasury, and the salt.
15
+ */
16
+ export function forwarderAddress(
17
+ factory: string,
18
+ implementation: string,
19
+ treasury: string,
20
+ salt: Hex,
21
+ ): Address {
22
+ const initCode = concat([
23
+ "0x61",
24
+ "0x0041", // runtime length: the 45-byte proxy and the 20 treasury bytes
25
+ "0x3d81600a3d39f3",
26
+ "0x363d3d373d3d3d363d73",
27
+ getAddress(implementation),
28
+ "0x5af43d82803e903d91602b57fd5bf3",
29
+ getAddress(treasury),
30
+ ]);
31
+ return getContractAddress({
32
+ opcode: "CREATE2",
33
+ from: getAddress(factory),
34
+ salt,
35
+ bytecodeHash: keccak256(initCode),
36
+ });
37
+ }
38
+
39
+ /** `keccak256(abi.encode(account, client_reference_id, "quote", quote_id))`: a quote's salt. */
40
+ export function quoteSalt(account: string, clientReferenceId: string, quoteId: string): Hex {
41
+ return keccak256(
42
+ encodeAbiParameters(
43
+ [{ type: "string" }, { type: "string" }, { type: "string" }, { type: "string" }],
44
+ [account, clientReferenceId, "quote", quoteId],
45
+ ),
46
+ );
47
+ }
48
+
49
+ /**
50
+ * `keccak256(abi.encode(account, livemode, client_reference_id, "deposit_address", version))`:
51
+ * a deposit address's salt, the same on every chain.
52
+ */
53
+ export function depositAddressSalt(
54
+ account: string,
55
+ livemode: boolean,
56
+ clientReferenceId: string,
57
+ version: number | bigint,
58
+ ): Hex {
59
+ return keccak256(
60
+ encodeAbiParameters(
61
+ [
62
+ { type: "string" },
63
+ { type: "bool" },
64
+ { type: "string" },
65
+ { type: "string" },
66
+ { type: "uint256" },
67
+ ],
68
+ [account, livemode, clientReferenceId, "deposit_address", BigInt(version)],
69
+ ),
70
+ );
71
+ }
72
+
73
+ export interface Forwarder {
74
+ factory: string;
75
+ implementation: string;
76
+ }
77
+
78
+ /** The address of a quote over `treasury`, which you pin yourself (see `verifyQuoteAddress`). */
79
+ export function quoteAddress(
80
+ forwarder: Forwarder,
81
+ quote: { client_reference_id: string; id: string },
82
+ treasury: string,
83
+ account: string,
84
+ ): Address {
85
+ return forwarderAddress(
86
+ forwarder.factory,
87
+ forwarder.implementation,
88
+ treasury,
89
+ quoteSalt(account, quote.client_reference_id, quote.id),
90
+ );
91
+ }
92
+
93
+ /** A deposit address on the network whose treasury is `treasury`, which you pin yourself. */
94
+ export function depositAddress(
95
+ forwarder: Forwarder,
96
+ address: { livemode: boolean; client_reference_id: string; version: number },
97
+ treasury: string,
98
+ account: string,
99
+ ): Address {
100
+ return forwarderAddress(
101
+ forwarder.factory,
102
+ forwarder.implementation,
103
+ treasury,
104
+ depositAddressSalt(account, address.livemode, address.client_reference_id, address.version),
105
+ );
106
+ }
107
+
108
+ /** An address the service returned is not the one your pins derive: show nothing to pay. */
109
+ export class AddressMismatchError extends Error {
110
+ override readonly name = "AddressMismatchError";
111
+ }
112
+
113
+ /**
114
+ * What every address is recomputed from, configured on your server and never read from the
115
+ * service: your account id (`acct_…`), the forwarder `factory` and `implementation` of the
116
+ * attested deployment, and `treasuries`, your own treasury per chain id as you proved it. A
117
+ * compromised service could return another treasury with the address that really derives from
118
+ * it, so the response's `treasury` is never trusted.
119
+ *
120
+ * Live mode requires `treasuries`: without the chain's treasury the check fails closed. In test
121
+ * mode an unpinned chain falls back to the response's treasury with a console warning.
122
+ */
123
+ export interface AddressPins extends Forwarder {
124
+ account: string;
125
+ treasuries?: Readonly<Record<number, string>> | undefined;
126
+ }
127
+
128
+ /**
129
+ * The treasury an address on `chainId` must pay: the pinned one, which the response must name.
130
+ */
131
+ function pinnedTreasury(
132
+ pins: AddressPins,
133
+ livemode: boolean,
134
+ chainId: number,
135
+ treasury: string,
136
+ where: string,
137
+ ): string {
138
+ const pinned = pins.treasuries?.[chainId];
139
+ if (pinned === undefined) {
140
+ if (livemode) {
141
+ throw new AddressMismatchError(`${where}: live mode requires your pinned treasury of chain ${chainId}`);
142
+ }
143
+ console.warn(
144
+ `${where}: no pinned treasury of chain ${chainId}; the service's ${treasury} is trusted (test mode only)`,
145
+ );
146
+ return treasury;
147
+ }
148
+ if (!sameAddress(pinned, treasury)) {
149
+ throw new AddressMismatchError(`${where} pays a treasury that is not the pinned one`);
150
+ }
151
+ return pinned;
152
+ }
153
+
154
+ function requirePins(pins: AddressPins, where: string): void {
155
+ for (const field of ["account", "factory", "implementation"] as const) {
156
+ if (typeof pins[field] !== "string" || pins[field] === "") {
157
+ throw new AddressMismatchError(`${where}: the pinned ${field} is missing`);
158
+ }
159
+ }
160
+ }
161
+
162
+ function sameAddress(a: string, b: string): boolean {
163
+ return a.toLowerCase() === b.toLowerCase();
164
+ }
165
+
166
+ /**
167
+ * Recomputes an open quote's address from your pins and returns it, the `expectedAddress` to
168
+ * pass to `<Checkout>`. Throws `AddressMismatchError` unless the quote names your pinned
169
+ * treasury of its chain and its address derives from it; in live mode also when the chain has no
170
+ * pinned treasury.
171
+ */
172
+ export function verifyQuoteAddress(
173
+ pins: AddressPins,
174
+ quote: {
175
+ id: string;
176
+ livemode: boolean;
177
+ chain_id: number;
178
+ treasury: string;
179
+ address: string;
180
+ client_reference_id: string;
181
+ },
182
+ ): Address {
183
+ const where = `quote ${quote.id}`;
184
+ requirePins(pins, where);
185
+ const treasury = pinnedTreasury(pins, quote.livemode, quote.chain_id, quote.treasury, where);
186
+ const derived = quoteAddress(pins, quote, treasury, pins.account);
187
+ if (!sameAddress(derived, quote.address)) {
188
+ throw new AddressMismatchError(`${where} has an address the account cannot derive`);
189
+ }
190
+ return derived;
191
+ }
192
+
193
+ /**
194
+ * Recomputes every network of an active deposit address from your pins and returns the address,
195
+ * the same on every network. Throws `AddressMismatchError` as `verifyQuoteAddress` does, for any
196
+ * network.
197
+ */
198
+ export function verifyDepositAddress(
199
+ pins: AddressPins,
200
+ address: {
201
+ id: string;
202
+ livemode: boolean;
203
+ client_reference_id: string;
204
+ version: number;
205
+ networks: readonly { chain_id: number; treasury: string; address: string }[];
206
+ },
207
+ ): Address {
208
+ requirePins(pins, `deposit address ${address.id}`);
209
+ let first: Address | undefined;
210
+ for (const network of address.networks) {
211
+ const where = `deposit address ${address.id} on chain ${network.chain_id}`;
212
+ const treasury = pinnedTreasury(pins, address.livemode, network.chain_id, network.treasury, where);
213
+ const derived = depositAddress(pins, address, treasury, pins.account);
214
+ if (!sameAddress(derived, network.address)) {
215
+ throw new AddressMismatchError(`${where} is not one the account can derive`);
216
+ }
217
+ first ??= derived;
218
+ }
219
+ if (first === undefined) {
220
+ throw new AddressMismatchError(`deposit address ${address.id} has no network`);
221
+ }
222
+ return first;
223
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Server-side helpers of `@phala/pay`. Nothing here needs or takes an API key: webhook
3
+ * verification uses your account's public webhook key, and the address and sweep helpers run
4
+ * offline. Call the API itself from your backend with a restricted key (the Python SDK, or any
5
+ * HTTP client with `Authorization: Bearer ppay_rk_…`); never ship a key to a browser. Recompute
6
+ * every address with `verifyQuoteAddress` or `verifyDepositAddress` from the pins you configure
7
+ * yourself before you show it.
8
+ */
9
+ export {
10
+ WebhookSignatureError,
11
+ constructEvent,
12
+ type ConstructEventOptions,
13
+ type WebhookEvent,
14
+ } from "./webhook.js";
15
+ export {
16
+ AddressMismatchError,
17
+ depositAddress,
18
+ depositAddressSalt,
19
+ forwarderAddress,
20
+ quoteSalt,
21
+ quoteAddress,
22
+ verifyDepositAddress,
23
+ verifyQuoteAddress,
24
+ type AddressPins,
25
+ type Forwarder,
26
+ } from "./addresses.js";
27
+ export {
28
+ batchChecksum,
29
+ flushTransaction,
30
+ flushTransactions,
31
+ safeBatch,
32
+ type BatchFile,
33
+ type BatchFileMeta,
34
+ type BatchTransaction,
35
+ type Call,
36
+ type ForwarderObject,
37
+ type SafeBatchOptions,
38
+ } from "./sweeps.js";