@t402/aptos 2.3.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 (42) hide show
  1. package/README.md +171 -0
  2. package/dist/exact-direct/client/index.d.cts +91 -0
  3. package/dist/exact-direct/client/index.d.ts +91 -0
  4. package/dist/exact-direct/client/index.js +203 -0
  5. package/dist/exact-direct/client/index.js.map +1 -0
  6. package/dist/exact-direct/client/index.mjs +175 -0
  7. package/dist/exact-direct/client/index.mjs.map +1 -0
  8. package/dist/exact-direct/facilitator/index.d.cts +110 -0
  9. package/dist/exact-direct/facilitator/index.d.ts +110 -0
  10. package/dist/exact-direct/facilitator/index.js +352 -0
  11. package/dist/exact-direct/facilitator/index.js.map +1 -0
  12. package/dist/exact-direct/facilitator/index.mjs +324 -0
  13. package/dist/exact-direct/facilitator/index.mjs.map +1 -0
  14. package/dist/exact-direct/server/index.d.cts +106 -0
  15. package/dist/exact-direct/server/index.d.ts +106 -0
  16. package/dist/exact-direct/server/index.js +220 -0
  17. package/dist/exact-direct/server/index.js.map +1 -0
  18. package/dist/exact-direct/server/index.mjs +192 -0
  19. package/dist/exact-direct/server/index.mjs.map +1 -0
  20. package/dist/index.d.cts +145 -0
  21. package/dist/index.d.ts +145 -0
  22. package/dist/index.js +759 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/index.mjs +687 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/types-kOweBf4U.d.cts +149 -0
  27. package/dist/types-kOweBf4U.d.ts +149 -0
  28. package/package.json +100 -0
  29. package/src/constants.ts +48 -0
  30. package/src/exact-direct/client/index.ts +12 -0
  31. package/src/exact-direct/client/register.ts +83 -0
  32. package/src/exact-direct/client/scheme.ts +148 -0
  33. package/src/exact-direct/facilitator/index.ts +12 -0
  34. package/src/exact-direct/facilitator/register.ts +74 -0
  35. package/src/exact-direct/facilitator/scheme.ts +300 -0
  36. package/src/exact-direct/server/index.ts +12 -0
  37. package/src/exact-direct/server/register.ts +65 -0
  38. package/src/exact-direct/server/scheme.ts +196 -0
  39. package/src/index.ts +58 -0
  40. package/src/tokens.ts +114 -0
  41. package/src/types.ts +174 -0
  42. package/src/utils.ts +240 -0
@@ -0,0 +1,175 @@
1
+ // src/constants.ts
2
+ var APTOS_CAIP2_NAMESPACE = "aptos";
3
+ var APTOS_MAINNET_CAIP2 = "aptos:1";
4
+ var APTOS_TESTNET_CAIP2 = "aptos:2";
5
+ var APTOS_DEVNET_CAIP2 = "aptos:149";
6
+ var SCHEME_EXACT_DIRECT = "exact-direct";
7
+ var PRIMARY_FUNGIBLE_STORE_MODULE = "0x1::primary_fungible_store";
8
+ var FA_TRANSFER_FUNCTION = `${PRIMARY_FUNGIBLE_STORE_MODULE}::transfer`;
9
+
10
+ // src/tokens.ts
11
+ var TOKEN_REGISTRY = {
12
+ [APTOS_MAINNET_CAIP2]: [
13
+ {
14
+ metadataAddress: "0xf73e887a8754f540ee6e1a93bdc6dde2af69fc7ca5de32013e89dd44244473cb",
15
+ symbol: "USDT",
16
+ name: "Tether USD",
17
+ decimals: 6
18
+ },
19
+ {
20
+ metadataAddress: "0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b",
21
+ symbol: "USDC",
22
+ name: "USD Coin",
23
+ decimals: 6
24
+ }
25
+ ],
26
+ [APTOS_TESTNET_CAIP2]: [
27
+ {
28
+ // Testnet USDT (may differ from mainnet)
29
+ metadataAddress: "0xf73e887a8754f540ee6e1a93bdc6dde2af69fc7ca5de32013e89dd44244473cb",
30
+ symbol: "USDT",
31
+ name: "Tether USD",
32
+ decimals: 6
33
+ }
34
+ ],
35
+ [APTOS_DEVNET_CAIP2]: []
36
+ };
37
+ function getTokenConfig(network, symbol) {
38
+ const tokens = TOKEN_REGISTRY[network];
39
+ if (!tokens) return void 0;
40
+ return tokens.find(
41
+ (t) => t.symbol.toUpperCase() === symbol.toUpperCase()
42
+ );
43
+ }
44
+
45
+ // src/utils.ts
46
+ function isValidAptosAddress(address) {
47
+ if (!address) return false;
48
+ if (!address.startsWith("0x")) return false;
49
+ const hex = address.slice(2);
50
+ if (hex.length === 0 || hex.length > 64) return false;
51
+ return /^[0-9a-fA-F]+$/.test(hex);
52
+ }
53
+ function normalizeAptosAddress(address) {
54
+ if (!address.startsWith("0x")) {
55
+ throw new Error("Aptos address must start with 0x");
56
+ }
57
+ const hex = address.slice(2).toLowerCase();
58
+ return "0x" + hex.padStart(64, "0");
59
+ }
60
+ function compareAddresses(addr1, addr2) {
61
+ try {
62
+ return normalizeAptosAddress(addr1) === normalizeAptosAddress(addr2);
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ function isAptosNetwork(network) {
68
+ return network.startsWith(`${APTOS_CAIP2_NAMESPACE}:`);
69
+ }
70
+ function parseAssetIdentifier(asset) {
71
+ const parts = asset.split("/");
72
+ if (parts.length !== 2) return null;
73
+ const network = parts[0];
74
+ if (!isAptosNetwork(network)) return null;
75
+ const [assetType, address] = parts[1].split(":");
76
+ if (assetType !== "fa" || !address) return null;
77
+ if (!isValidAptosAddress(address)) return null;
78
+ return { network, metadataAddress: address };
79
+ }
80
+
81
+ // src/exact-direct/client/scheme.ts
82
+ var ExactDirectAptosClient = class {
83
+ constructor(signer, config = {}) {
84
+ this.signer = signer;
85
+ void config;
86
+ }
87
+ scheme = SCHEME_EXACT_DIRECT;
88
+ /**
89
+ * Create a payment payload by executing the transfer
90
+ */
91
+ async createPaymentPayload(t402Version, paymentRequirements) {
92
+ this.validateRequirements(paymentRequirements);
93
+ const from = await this.signer.getAddress();
94
+ const assetInfo = parseAssetIdentifier(paymentRequirements.asset);
95
+ if (!assetInfo) {
96
+ throw new Error(`Invalid asset identifier: ${paymentRequirements.asset}`);
97
+ }
98
+ const amount = BigInt(paymentRequirements.amount);
99
+ const balance = await this.signer.getBalance(assetInfo.metadataAddress);
100
+ if (balance < amount) {
101
+ throw new Error(
102
+ `Insufficient balance: have ${balance}, need ${amount}`
103
+ );
104
+ }
105
+ const txHash = await this.signer.transfer(
106
+ paymentRequirements.payTo,
107
+ assetInfo.metadataAddress,
108
+ amount
109
+ );
110
+ const payload = {
111
+ txHash,
112
+ from,
113
+ to: paymentRequirements.payTo,
114
+ amount: paymentRequirements.amount,
115
+ metadataAddress: assetInfo.metadataAddress
116
+ };
117
+ return {
118
+ t402Version,
119
+ payload
120
+ };
121
+ }
122
+ /**
123
+ * Validate payment requirements
124
+ */
125
+ validateRequirements(requirements) {
126
+ if (requirements.scheme !== SCHEME_EXACT_DIRECT) {
127
+ throw new Error(
128
+ `Invalid scheme: expected ${SCHEME_EXACT_DIRECT}, got ${requirements.scheme}`
129
+ );
130
+ }
131
+ if (!requirements.network.startsWith(`${APTOS_CAIP2_NAMESPACE}:`)) {
132
+ throw new Error(`Invalid network: ${requirements.network}`);
133
+ }
134
+ if (!isValidAptosAddress(requirements.payTo)) {
135
+ throw new Error(`Invalid payTo address: ${requirements.payTo}`);
136
+ }
137
+ const amount = BigInt(requirements.amount);
138
+ if (amount <= 0n) {
139
+ throw new Error(`Invalid amount: ${requirements.amount}`);
140
+ }
141
+ const assetInfo = parseAssetIdentifier(requirements.asset);
142
+ if (!assetInfo) {
143
+ throw new Error(`Invalid asset: ${requirements.asset}`);
144
+ }
145
+ const tokenConfig = getTokenConfig(requirements.network, "USDT");
146
+ if (tokenConfig && !compareAddresses(tokenConfig.metadataAddress, assetInfo.metadataAddress)) {
147
+ console.warn(
148
+ `Using non-standard token: ${assetInfo.metadataAddress}`
149
+ );
150
+ }
151
+ }
152
+ };
153
+
154
+ // src/exact-direct/client/register.ts
155
+ function registerExactDirectAptosClient(client, config) {
156
+ const scheme = new ExactDirectAptosClient(config.signer, config.schemeConfig);
157
+ if (config.networks && config.networks.length > 0) {
158
+ config.networks.forEach((network) => {
159
+ client.register(network, scheme);
160
+ });
161
+ } else {
162
+ client.register("aptos:*", scheme);
163
+ }
164
+ if (config.policies) {
165
+ config.policies.forEach((policy) => {
166
+ client.registerPolicy(policy);
167
+ });
168
+ }
169
+ return client;
170
+ }
171
+ export {
172
+ ExactDirectAptosClient,
173
+ registerExactDirectAptosClient
174
+ };
175
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/constants.ts","../../../src/tokens.ts","../../../src/utils.ts","../../../src/exact-direct/client/scheme.ts","../../../src/exact-direct/client/register.ts"],"sourcesContent":["/**\n * Aptos Network Constants\n */\n\n// CAIP-2 namespace for Aptos\nexport const APTOS_CAIP2_NAMESPACE = \"aptos\";\n\n// Standard Aptos network identifiers (CAIP-2 format)\nexport const APTOS_MAINNET_CAIP2 = \"aptos:1\";\nexport const APTOS_TESTNET_CAIP2 = \"aptos:2\";\nexport const APTOS_DEVNET_CAIP2 = \"aptos:149\";\n\n// All supported Aptos networks\nexport const APTOS_NETWORKS = [\n APTOS_MAINNET_CAIP2,\n APTOS_TESTNET_CAIP2,\n APTOS_DEVNET_CAIP2,\n] as const;\n\nexport type AptosNetwork = (typeof APTOS_NETWORKS)[number];\n\n// Chain IDs\nexport const APTOS_MAINNET_CHAIN_ID = 1;\nexport const APTOS_TESTNET_CHAIN_ID = 2;\nexport const APTOS_DEVNET_CHAIN_ID = 149;\n\n// RPC endpoints\nexport const DEFAULT_MAINNET_RPC = \"https://fullnode.mainnet.aptoslabs.com/v1\";\nexport const DEFAULT_TESTNET_RPC = \"https://fullnode.testnet.aptoslabs.com/v1\";\nexport const DEFAULT_DEVNET_RPC = \"https://fullnode.devnet.aptoslabs.com/v1\";\n\n// Scheme identifier\nexport const SCHEME_EXACT_DIRECT = \"exact-direct\";\n\n// Fungible Asset module addresses\nexport const PRIMARY_FUNGIBLE_STORE_MODULE = \"0x1::primary_fungible_store\";\nexport const FUNGIBLE_ASSET_MODULE = \"0x1::fungible_asset\";\nexport const APTOS_ACCOUNT_MODULE = \"0x1::aptos_account\";\n\n// Transfer function\nexport const FA_TRANSFER_FUNCTION = `${PRIMARY_FUNGIBLE_STORE_MODULE}::transfer`;\n\n// Default gas configuration\nexport const DEFAULT_MAX_GAS_AMOUNT = 100000n;\nexport const DEFAULT_GAS_UNIT_PRICE = 100n;\n\n// Transaction expiration (in seconds)\nexport const DEFAULT_TX_EXPIRATION_SECONDS = 600; // 10 minutes\n","/**\n * Aptos Token Registry\n *\n * Token addresses for supported stablecoins on Aptos networks.\n * All tokens use the Fungible Asset (FA) standard.\n */\n\nimport {\n APTOS_MAINNET_CAIP2,\n APTOS_TESTNET_CAIP2,\n APTOS_DEVNET_CAIP2,\n} from \"./constants.js\";\n\n/**\n * Token configuration for Aptos fungible assets\n */\nexport interface TokenConfig {\n /** Fungible Asset metadata address */\n metadataAddress: string;\n /** Token symbol (e.g., \"USDT\", \"USDC\") */\n symbol: string;\n /** Token name */\n name: string;\n /** Decimal places */\n decimals: number;\n}\n\n/**\n * Token registry mapping network -> tokens\n */\nexport const TOKEN_REGISTRY: Record<string, TokenConfig[]> = {\n [APTOS_MAINNET_CAIP2]: [\n {\n metadataAddress:\n \"0xf73e887a8754f540ee6e1a93bdc6dde2af69fc7ca5de32013e89dd44244473cb\",\n symbol: \"USDT\",\n name: \"Tether USD\",\n decimals: 6,\n },\n {\n metadataAddress:\n \"0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b\",\n symbol: \"USDC\",\n name: \"USD Coin\",\n decimals: 6,\n },\n ],\n [APTOS_TESTNET_CAIP2]: [\n {\n // Testnet USDT (may differ from mainnet)\n metadataAddress:\n \"0xf73e887a8754f540ee6e1a93bdc6dde2af69fc7ca5de32013e89dd44244473cb\",\n symbol: \"USDT\",\n name: \"Tether USD\",\n decimals: 6,\n },\n ],\n [APTOS_DEVNET_CAIP2]: [],\n};\n\n/**\n * Get token configuration for a specific network and symbol\n */\nexport function getTokenConfig(\n network: string,\n symbol: string,\n): TokenConfig | undefined {\n const tokens = TOKEN_REGISTRY[network];\n if (!tokens) return undefined;\n return tokens.find(\n (t) => t.symbol.toUpperCase() === symbol.toUpperCase(),\n );\n}\n\n/**\n * Get all supported tokens for a network\n */\nexport function getSupportedTokens(network: string): TokenConfig[] {\n return TOKEN_REGISTRY[network] || [];\n}\n\n/**\n * Check if a token is supported on a network\n */\nexport function isTokenSupported(network: string, symbol: string): boolean {\n return getTokenConfig(network, symbol) !== undefined;\n}\n\n/**\n * Get token by metadata address\n */\nexport function getTokenByAddress(\n network: string,\n metadataAddress: string,\n): TokenConfig | undefined {\n const tokens = TOKEN_REGISTRY[network];\n if (!tokens) return undefined;\n const normalizedAddress = metadataAddress.toLowerCase();\n return tokens.find(\n (t) => t.metadataAddress.toLowerCase() === normalizedAddress,\n );\n}\n\n/**\n * Default token symbol for payments (USDT)\n */\nexport const DEFAULT_TOKEN_SYMBOL = \"USDT\";\n\n/**\n * Get the default token for a network\n */\nexport function getDefaultToken(network: string): TokenConfig | undefined {\n return getTokenConfig(network, DEFAULT_TOKEN_SYMBOL);\n}\n","/**\n * Aptos Utility Functions\n */\n\nimport type { Network } from \"@t402/core/types\";\nimport {\n APTOS_CAIP2_NAMESPACE,\n APTOS_MAINNET_CAIP2,\n APTOS_TESTNET_CAIP2,\n APTOS_DEVNET_CAIP2,\n DEFAULT_MAINNET_RPC,\n DEFAULT_TESTNET_RPC,\n DEFAULT_DEVNET_RPC,\n FA_TRANSFER_FUNCTION,\n} from \"./constants.js\";\nimport type {\n AptosTransactionResult,\n AptosTransactionEvent,\n ParsedFATransfer,\n} from \"./types.js\";\n\n/**\n * Validate Aptos address format\n * Aptos addresses are 64 hex characters (32 bytes) with 0x prefix\n */\nexport function isValidAptosAddress(address: string): boolean {\n if (!address) return false;\n // Must start with 0x\n if (!address.startsWith(\"0x\")) return false;\n // Remove 0x prefix and check hex\n const hex = address.slice(2);\n // Aptos addresses can be 1-64 hex chars (leading zeros may be omitted)\n if (hex.length === 0 || hex.length > 64) return false;\n return /^[0-9a-fA-F]+$/.test(hex);\n}\n\n/**\n * Normalize Aptos address to full 64-character format\n */\nexport function normalizeAptosAddress(address: string): string {\n if (!address.startsWith(\"0x\")) {\n throw new Error(\"Aptos address must start with 0x\");\n }\n const hex = address.slice(2).toLowerCase();\n // Pad to 64 characters\n return \"0x\" + hex.padStart(64, \"0\");\n}\n\n/**\n * Compare two Aptos addresses (case-insensitive, handles short addresses)\n */\nexport function compareAddresses(addr1: string, addr2: string): boolean {\n try {\n return normalizeAptosAddress(addr1) === normalizeAptosAddress(addr2);\n } catch {\n return false;\n }\n}\n\n/**\n * Validate transaction hash format\n */\nexport function isValidTxHash(txHash: string): boolean {\n if (!txHash) return false;\n if (!txHash.startsWith(\"0x\")) return false;\n const hex = txHash.slice(2);\n // Transaction hash is 64 hex characters (32 bytes)\n if (hex.length !== 64) return false;\n return /^[0-9a-fA-F]+$/.test(hex);\n}\n\n/**\n * Get default RPC URL for a network\n */\nexport function getDefaultRpcUrl(network: Network): string {\n switch (network) {\n case APTOS_MAINNET_CAIP2:\n return DEFAULT_MAINNET_RPC;\n case APTOS_TESTNET_CAIP2:\n return DEFAULT_TESTNET_RPC;\n case APTOS_DEVNET_CAIP2:\n return DEFAULT_DEVNET_RPC;\n default:\n throw new Error(`Unknown Aptos network: ${network}`);\n }\n}\n\n/**\n * Check if a network identifier is for Aptos\n */\nexport function isAptosNetwork(network: Network): boolean {\n return network.startsWith(`${APTOS_CAIP2_NAMESPACE}:`);\n}\n\n/**\n * Parse CAIP-19 asset identifier for Aptos\n * Format: aptos:1/fa:0x...\n */\nexport function parseAssetIdentifier(asset: string): {\n network: Network;\n metadataAddress: string;\n} | null {\n const parts = asset.split(\"/\");\n if (parts.length !== 2) return null;\n\n const network = parts[0] as Network;\n if (!isAptosNetwork(network)) return null;\n\n const [assetType, address] = parts[1].split(\":\");\n if (assetType !== \"fa\" || !address) return null;\n\n if (!isValidAptosAddress(address)) return null;\n\n return { network, metadataAddress: address };\n}\n\n/**\n * Create CAIP-19 asset identifier for Aptos FA\n */\nexport function createAssetIdentifier(\n network: Network,\n metadataAddress: string,\n): string {\n return `${network}/fa:${metadataAddress}`;\n}\n\n/**\n * Parse fungible asset transfer from transaction events\n */\nexport function parseFATransferFromEvents(\n events: AptosTransactionEvent[],\n): ParsedFATransfer | null {\n // Look for Withdraw and Deposit events\n const withdrawEvent = events.find(\n (e) =>\n e.type === \"0x1::fungible_asset::Withdraw\" ||\n e.type.includes(\"::fungible_asset::Withdraw\"),\n );\n const depositEvent = events.find(\n (e) =>\n e.type === \"0x1::fungible_asset::Deposit\" ||\n e.type.includes(\"::fungible_asset::Deposit\"),\n );\n\n if (!withdrawEvent || !depositEvent) {\n return null;\n }\n\n // Extract data from events\n const withdrawData = withdrawEvent.data as {\n store?: string;\n amount?: string;\n };\n const depositData = depositEvent.data as {\n store?: string;\n amount?: string;\n };\n\n if (!withdrawData.amount || !depositData.store) {\n return null;\n }\n\n // The from address is the account that owns the withdraw store\n // The to address is the account that owns the deposit store\n // For simplicity, we'll extract from the event guid\n const from = withdrawEvent.guid.accountAddress;\n const to = depositEvent.guid.accountAddress;\n const amount = BigInt(withdrawData.amount);\n\n // Metadata address would need to be extracted from state changes\n // For now, return with empty metadata (to be filled by caller)\n return {\n from,\n to,\n amount,\n metadataAddress: \"\", // Will be filled from transaction details\n };\n}\n\n/**\n * Check if transaction is a FA transfer\n */\nexport function isFATransferTransaction(tx: AptosTransactionResult): boolean {\n if (!tx.payload) return false;\n if (tx.payload.type !== \"entry_function_payload\") return false;\n return (\n tx.payload.function === FA_TRANSFER_FUNCTION ||\n tx.payload.function?.includes(\"primary_fungible_store::transfer\") ||\n false\n );\n}\n\n/**\n * Extract transfer details from transaction\n */\nexport function extractTransferDetails(\n tx: AptosTransactionResult,\n): ParsedFATransfer | null {\n if (!tx.success) return null;\n if (!tx.payload || tx.payload.type !== \"entry_function_payload\") return null;\n\n const args = tx.payload.arguments;\n if (!args || args.length < 3) return null;\n\n // Arguments for primary_fungible_store::transfer:\n // [0] - metadata object address\n // [1] - recipient address\n // [2] - amount\n\n const metadataAddress = args[0] as string;\n const to = args[1] as string;\n const amount = BigInt(args[2] as string);\n\n return {\n from: tx.sender,\n to,\n amount,\n metadataAddress,\n };\n}\n\n/**\n * Format amount with decimals for display\n */\nexport function formatAmount(amount: bigint, decimals: number): string {\n const divisor = BigInt(10 ** decimals);\n const wholePart = amount / divisor;\n const fractionalPart = amount % divisor;\n const paddedFractional = fractionalPart.toString().padStart(decimals, \"0\");\n return `${wholePart}.${paddedFractional}`;\n}\n\n/**\n * Parse amount string to bigint\n */\nexport function parseAmount(amount: string, decimals: number): bigint {\n const [whole, fractional = \"\"] = amount.split(\".\");\n const paddedFractional = fractional.padEnd(decimals, \"0\").slice(0, decimals);\n return BigInt(whole + paddedFractional);\n}\n","/**\n * Aptos Exact-Direct Client Scheme\n *\n * The client executes the FA transfer directly and provides\n * the transaction hash as proof of payment.\n */\n\nimport type {\n SchemeNetworkClient,\n PaymentPayload,\n PaymentRequirements,\n} from \"@t402/core/types\";\nimport { SCHEME_EXACT_DIRECT, APTOS_CAIP2_NAMESPACE } from \"../../constants.js\";\nimport type { ClientAptosSigner, ExactDirectAptosPayload } from \"../../types.js\";\nimport { getTokenConfig } from \"../../tokens.js\";\nimport {\n isValidAptosAddress,\n parseAssetIdentifier,\n compareAddresses,\n} from \"../../utils.js\";\n\n/**\n * Configuration for ExactDirectAptosClient\n */\nexport interface ExactDirectAptosClientConfig {\n /**\n * Whether to verify the transfer was successful before returning\n * @default true\n */\n verifyTransfer?: boolean;\n}\n\n/**\n * Aptos Exact-Direct Client\n *\n * Implements the client-side payment flow where the client:\n * 1. Receives payment requirements\n * 2. Executes the FA transfer transaction\n * 3. Returns transaction hash as proof\n */\nexport class ExactDirectAptosClient implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT_DIRECT;\n\n constructor(\n private readonly signer: ClientAptosSigner,\n config: ExactDirectAptosClientConfig = {},\n ) {\n // Config reserved for future use (e.g., verifyTransfer option)\n void config;\n }\n\n /**\n * Create a payment payload by executing the transfer\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"t402Version\" | \"payload\">> {\n // Validate requirements\n this.validateRequirements(paymentRequirements);\n\n // Get sender address\n const from = await this.signer.getAddress();\n\n // Parse asset to get metadata address\n const assetInfo = parseAssetIdentifier(paymentRequirements.asset);\n if (!assetInfo) {\n throw new Error(`Invalid asset identifier: ${paymentRequirements.asset}`);\n }\n\n // Get amount\n const amount = BigInt(paymentRequirements.amount);\n\n // Check balance\n const balance = await this.signer.getBalance(assetInfo.metadataAddress);\n if (balance < amount) {\n throw new Error(\n `Insufficient balance: have ${balance}, need ${amount}`,\n );\n }\n\n // Execute transfer\n const txHash = await this.signer.transfer(\n paymentRequirements.payTo,\n assetInfo.metadataAddress,\n amount,\n );\n\n // Create payload\n const payload: ExactDirectAptosPayload = {\n txHash,\n from,\n to: paymentRequirements.payTo,\n amount: paymentRequirements.amount,\n metadataAddress: assetInfo.metadataAddress,\n };\n\n return {\n t402Version,\n payload,\n };\n }\n\n /**\n * Validate payment requirements\n */\n private validateRequirements(requirements: PaymentRequirements): void {\n // Check scheme\n if (requirements.scheme !== SCHEME_EXACT_DIRECT) {\n throw new Error(\n `Invalid scheme: expected ${SCHEME_EXACT_DIRECT}, got ${requirements.scheme}`,\n );\n }\n\n // Check network\n if (!requirements.network.startsWith(`${APTOS_CAIP2_NAMESPACE}:`)) {\n throw new Error(`Invalid network: ${requirements.network}`);\n }\n\n // Check payTo address\n if (!isValidAptosAddress(requirements.payTo)) {\n throw new Error(`Invalid payTo address: ${requirements.payTo}`);\n }\n\n // Check amount\n const amount = BigInt(requirements.amount);\n if (amount <= 0n) {\n throw new Error(`Invalid amount: ${requirements.amount}`);\n }\n\n // Check asset\n const assetInfo = parseAssetIdentifier(requirements.asset);\n if (!assetInfo) {\n throw new Error(`Invalid asset: ${requirements.asset}`);\n }\n\n // Verify token is supported\n const tokenConfig = getTokenConfig(requirements.network, \"USDT\");\n if (tokenConfig && !compareAddresses(tokenConfig.metadataAddress, assetInfo.metadataAddress)) {\n // Allow any valid FA, but log warning for unknown tokens\n console.warn(\n `Using non-standard token: ${assetInfo.metadataAddress}`,\n );\n }\n }\n}\n\nexport default ExactDirectAptosClient;\n","/**\n * Registration function for Aptos Exact-Direct client\n */\n\nimport { t402Client, PaymentPolicy } from \"@t402/core/client\";\nimport type { Network } from \"@t402/core/types\";\nimport type { ClientAptosSigner } from \"../../types.js\";\nimport {\n ExactDirectAptosClient,\n type ExactDirectAptosClientConfig,\n} from \"./scheme.js\";\n\n/**\n * Configuration options for registering Aptos schemes to a t402Client\n */\nexport interface AptosClientConfig {\n /**\n * The Aptos signer for client operations\n */\n signer: ClientAptosSigner;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (aptos:*)\n */\n networks?: Network[];\n\n /**\n * Optional scheme configuration\n */\n schemeConfig?: ExactDirectAptosClientConfig;\n}\n\n/**\n * Registers Aptos exact-direct payment schemes to a t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for Aptos client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactDirectAptosClient } from \"@t402/aptos/exact-direct/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerExactDirectAptosClient(client, {\n * signer: myAptosSigner,\n * networks: [\"aptos:1\"]\n * });\n * ```\n */\nexport function registerExactDirectAptosClient(\n client: t402Client,\n config: AptosClientConfig,\n): t402Client {\n const scheme = new ExactDirectAptosClient(config.signer, config.schemeConfig);\n\n // Register scheme\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach((network) => {\n client.register(network, scheme);\n });\n } else {\n // Register wildcard for all Aptos networks\n client.register(\"aptos:*\", scheme);\n }\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach((policy) => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n"],"mappings":";AAKO,IAAM,wBAAwB;AAG9B,IAAM,sBAAsB;AAC5B,I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SAAS,SAAS,MAAM;AAAA,IACjC,CAAC;AAAA,EACH,OAAO;AAEL,WAAO,SAAS,WAAW,MAAM;AAAA,EACnC;AAGA,MAAI,OAAO,UAAU;AACnB,WAAO,SAAS,QAAQ,CAAC,WAAW;AAClC,aAAO,eAAe,MAAM;AAAA,IAC9B,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,110 @@
1
+ import { SchemeNetworkFacilitator, Network, PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse } from '@t402/core/types';
2
+ import { F as FacilitatorAptosSigner } from '../../types-kOweBf4U.cjs';
3
+ import { t402Facilitator } from '@t402/core/facilitator';
4
+
5
+ /**
6
+ * Aptos Exact-Direct Facilitator Scheme
7
+ *
8
+ * Verifies FA transfer transactions and manages replay protection.
9
+ */
10
+
11
+ /**
12
+ * Configuration for ExactDirectAptosFacilitator
13
+ */
14
+ interface ExactDirectAptosFacilitatorConfig {
15
+ /**
16
+ * Maximum age of transaction in seconds (default: 3600 = 1 hour)
17
+ */
18
+ maxTransactionAge?: number;
19
+ /**
20
+ * Duration to cache used transaction hashes (in milliseconds)
21
+ */
22
+ usedTxCacheDuration?: number;
23
+ }
24
+ /**
25
+ * Aptos Exact-Direct Facilitator
26
+ *
27
+ * Implements the facilitator-side verification and settlement.
28
+ * For exact-direct, settlement is a no-op since client already executed.
29
+ */
30
+ declare class ExactDirectAptosFacilitator implements SchemeNetworkFacilitator {
31
+ private readonly signer;
32
+ readonly scheme = "exact-direct";
33
+ readonly caipFamily = "aptos:*";
34
+ private readonly config;
35
+ private usedTxs;
36
+ constructor(signer: FacilitatorAptosSigner, config?: ExactDirectAptosFacilitatorConfig);
37
+ /**
38
+ * Get extra data for a supported kind
39
+ */
40
+ getExtra(network: Network): Record<string, unknown> | undefined;
41
+ /**
42
+ * Get facilitator signer addresses for a network
43
+ */
44
+ getSigners(network: Network): string[];
45
+ /**
46
+ * Verify a payment payload
47
+ */
48
+ verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
49
+ /**
50
+ * Settle a payment (no-op for exact-direct since client already executed)
51
+ */
52
+ settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
53
+ /**
54
+ * Check if a transaction has been used
55
+ */
56
+ private isTxUsed;
57
+ /**
58
+ * Mark a transaction as used
59
+ */
60
+ private markTxUsed;
61
+ /**
62
+ * Start the cleanup interval for used transactions
63
+ */
64
+ private startCleanupInterval;
65
+ }
66
+
67
+ /**
68
+ * Registration function for Aptos Exact-Direct facilitator
69
+ */
70
+
71
+ /**
72
+ * Configuration options for registering Aptos schemes to a t402Facilitator
73
+ */
74
+ interface AptosFacilitatorConfig {
75
+ /**
76
+ * The Aptos signer for facilitator operations (verify and settle)
77
+ */
78
+ signer: FacilitatorAptosSigner;
79
+ /**
80
+ * Optional specific networks to register
81
+ * If not provided, registers wildcard support (aptos:*)
82
+ */
83
+ networks?: Network[];
84
+ /**
85
+ * Optional scheme configuration
86
+ */
87
+ schemeConfig?: ExactDirectAptosFacilitatorConfig;
88
+ }
89
+ /**
90
+ * Registers Aptos exact-direct payment schemes to a t402Facilitator instance.
91
+ *
92
+ * @param facilitator - The t402Facilitator instance to register schemes to
93
+ * @param config - Configuration for Aptos facilitator registration
94
+ * @returns The facilitator instance for chaining
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * import { registerExactDirectAptosFacilitator } from "@t402/aptos/exact-direct/facilitator";
99
+ * import { t402Facilitator } from "@t402/core/facilitator";
100
+ *
101
+ * const facilitator = new t402Facilitator();
102
+ * registerExactDirectAptosFacilitator(facilitator, {
103
+ * signer: myAptosSigner,
104
+ * networks: ["aptos:1"]
105
+ * });
106
+ * ```
107
+ */
108
+ declare function registerExactDirectAptosFacilitator(facilitator: t402Facilitator, config: AptosFacilitatorConfig): t402Facilitator;
109
+
110
+ export { type AptosFacilitatorConfig, ExactDirectAptosFacilitator, type ExactDirectAptosFacilitatorConfig, registerExactDirectAptosFacilitator };
@@ -0,0 +1,110 @@
1
+ import { SchemeNetworkFacilitator, Network, PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse } from '@t402/core/types';
2
+ import { F as FacilitatorAptosSigner } from '../../types-kOweBf4U.js';
3
+ import { t402Facilitator } from '@t402/core/facilitator';
4
+
5
+ /**
6
+ * Aptos Exact-Direct Facilitator Scheme
7
+ *
8
+ * Verifies FA transfer transactions and manages replay protection.
9
+ */
10
+
11
+ /**
12
+ * Configuration for ExactDirectAptosFacilitator
13
+ */
14
+ interface ExactDirectAptosFacilitatorConfig {
15
+ /**
16
+ * Maximum age of transaction in seconds (default: 3600 = 1 hour)
17
+ */
18
+ maxTransactionAge?: number;
19
+ /**
20
+ * Duration to cache used transaction hashes (in milliseconds)
21
+ */
22
+ usedTxCacheDuration?: number;
23
+ }
24
+ /**
25
+ * Aptos Exact-Direct Facilitator
26
+ *
27
+ * Implements the facilitator-side verification and settlement.
28
+ * For exact-direct, settlement is a no-op since client already executed.
29
+ */
30
+ declare class ExactDirectAptosFacilitator implements SchemeNetworkFacilitator {
31
+ private readonly signer;
32
+ readonly scheme = "exact-direct";
33
+ readonly caipFamily = "aptos:*";
34
+ private readonly config;
35
+ private usedTxs;
36
+ constructor(signer: FacilitatorAptosSigner, config?: ExactDirectAptosFacilitatorConfig);
37
+ /**
38
+ * Get extra data for a supported kind
39
+ */
40
+ getExtra(network: Network): Record<string, unknown> | undefined;
41
+ /**
42
+ * Get facilitator signer addresses for a network
43
+ */
44
+ getSigners(network: Network): string[];
45
+ /**
46
+ * Verify a payment payload
47
+ */
48
+ verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
49
+ /**
50
+ * Settle a payment (no-op for exact-direct since client already executed)
51
+ */
52
+ settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
53
+ /**
54
+ * Check if a transaction has been used
55
+ */
56
+ private isTxUsed;
57
+ /**
58
+ * Mark a transaction as used
59
+ */
60
+ private markTxUsed;
61
+ /**
62
+ * Start the cleanup interval for used transactions
63
+ */
64
+ private startCleanupInterval;
65
+ }
66
+
67
+ /**
68
+ * Registration function for Aptos Exact-Direct facilitator
69
+ */
70
+
71
+ /**
72
+ * Configuration options for registering Aptos schemes to a t402Facilitator
73
+ */
74
+ interface AptosFacilitatorConfig {
75
+ /**
76
+ * The Aptos signer for facilitator operations (verify and settle)
77
+ */
78
+ signer: FacilitatorAptosSigner;
79
+ /**
80
+ * Optional specific networks to register
81
+ * If not provided, registers wildcard support (aptos:*)
82
+ */
83
+ networks?: Network[];
84
+ /**
85
+ * Optional scheme configuration
86
+ */
87
+ schemeConfig?: ExactDirectAptosFacilitatorConfig;
88
+ }
89
+ /**
90
+ * Registers Aptos exact-direct payment schemes to a t402Facilitator instance.
91
+ *
92
+ * @param facilitator - The t402Facilitator instance to register schemes to
93
+ * @param config - Configuration for Aptos facilitator registration
94
+ * @returns The facilitator instance for chaining
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * import { registerExactDirectAptosFacilitator } from "@t402/aptos/exact-direct/facilitator";
99
+ * import { t402Facilitator } from "@t402/core/facilitator";
100
+ *
101
+ * const facilitator = new t402Facilitator();
102
+ * registerExactDirectAptosFacilitator(facilitator, {
103
+ * signer: myAptosSigner,
104
+ * networks: ["aptos:1"]
105
+ * });
106
+ * ```
107
+ */
108
+ declare function registerExactDirectAptosFacilitator(facilitator: t402Facilitator, config: AptosFacilitatorConfig): t402Facilitator;
109
+
110
+ export { type AptosFacilitatorConfig, ExactDirectAptosFacilitator, type ExactDirectAptosFacilitatorConfig, registerExactDirectAptosFacilitator };