@x402/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 (35) hide show
  1. package/README.md +74 -0
  2. package/dist/cjs/exact/client/index.d.ts +29 -0
  3. package/dist/cjs/exact/client/index.js +141 -0
  4. package/dist/cjs/exact/client/index.js.map +1 -0
  5. package/dist/cjs/exact/facilitator/index.d.ts +52 -0
  6. package/dist/cjs/exact/facilitator/index.js +373 -0
  7. package/dist/cjs/exact/facilitator/index.js.map +1 -0
  8. package/dist/cjs/exact/server/index.d.ts +67 -0
  9. package/dist/cjs/exact/server/index.js +143 -0
  10. package/dist/cjs/exact/server/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +116 -0
  12. package/dist/cjs/index.js +269 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/signer-DPT9P1NX.d.ts +59 -0
  15. package/dist/cjs/signer-DfwN1I5I.d.ts +59 -0
  16. package/dist/esm/chunk-6BMAMLXJ.mjs +93 -0
  17. package/dist/esm/chunk-6BMAMLXJ.mjs.map +1 -0
  18. package/dist/esm/chunk-D4UVBSUH.mjs +53 -0
  19. package/dist/esm/chunk-D4UVBSUH.mjs.map +1 -0
  20. package/dist/esm/chunk-FG4ANPDN.mjs +46 -0
  21. package/dist/esm/chunk-FG4ANPDN.mjs.map +1 -0
  22. package/dist/esm/exact/client/index.d.mts +29 -0
  23. package/dist/esm/exact/client/index.mjs +9 -0
  24. package/dist/esm/exact/client/index.mjs.map +1 -0
  25. package/dist/esm/exact/facilitator/index.d.mts +52 -0
  26. package/dist/esm/exact/facilitator/index.mjs +294 -0
  27. package/dist/esm/exact/facilitator/index.mjs.map +1 -0
  28. package/dist/esm/exact/server/index.d.mts +67 -0
  29. package/dist/esm/exact/server/index.mjs +116 -0
  30. package/dist/esm/exact/server/index.mjs.map +1 -0
  31. package/dist/esm/index.d.mts +116 -0
  32. package/dist/esm/index.mjs +105 -0
  33. package/dist/esm/index.mjs.map +1 -0
  34. package/dist/esm/signer-DPT9P1NX.d.mts +59 -0
  35. package/package.json +95 -0
@@ -0,0 +1,116 @@
1
+ import {
2
+ APTOS_ADDRESS_REGEX,
3
+ USDC_MAINNET_FA,
4
+ USDC_TESTNET_FA
5
+ } from "../../chunk-FG4ANPDN.mjs";
6
+
7
+ // src/exact/server/scheme.ts
8
+ var ExactAptosScheme = class {
9
+ constructor() {
10
+ this.scheme = "exact";
11
+ this.moneyParsers = [];
12
+ }
13
+ /**
14
+ * Register a custom money parser in the parser chain.
15
+ *
16
+ * @param parser - Custom function to convert amount to AssetAmount (or null to skip)
17
+ * @returns The service instance for chaining
18
+ */
19
+ registerMoneyParser(parser) {
20
+ this.moneyParsers.push(parser);
21
+ return this;
22
+ }
23
+ /**
24
+ * Parses a price into an asset amount.
25
+ *
26
+ * @param price - The price to parse
27
+ * @param network - The network to use
28
+ * @returns Promise that resolves to the parsed asset amount
29
+ */
30
+ async parsePrice(price, network) {
31
+ if (typeof price === "object" && price !== null && "amount" in price) {
32
+ if (!price.asset) {
33
+ throw new Error(`Asset address must be specified for AssetAmount on network ${network}`);
34
+ }
35
+ if (!APTOS_ADDRESS_REGEX.test(price.asset)) {
36
+ throw new Error(`Invalid asset address format: ${price.asset}`);
37
+ }
38
+ return { amount: price.amount, asset: price.asset, extra: price.extra || {} };
39
+ }
40
+ const amount = this.parseMoneyToDecimal(price);
41
+ for (const parser of this.moneyParsers) {
42
+ const result = await parser(amount, network);
43
+ if (result !== null) {
44
+ return result;
45
+ }
46
+ }
47
+ return this.defaultMoneyConversion(amount, network);
48
+ }
49
+ /**
50
+ * Build payment requirements for this scheme/network combination
51
+ *
52
+ * @param paymentRequirements - The base payment requirements
53
+ * @param supportedKind - The supported kind configuration
54
+ * @param supportedKind.x402Version - The x402 protocol version
55
+ * @param supportedKind.scheme - The payment scheme
56
+ * @param supportedKind.network - The network identifier
57
+ * @param supportedKind.extra - Extra metadata including feePayer address
58
+ * @param extensionKeys - Extension keys supported by the facilitator
59
+ * @returns Enhanced payment requirements with feePayer in extra
60
+ */
61
+ enhancePaymentRequirements(paymentRequirements, supportedKind, extensionKeys) {
62
+ void extensionKeys;
63
+ const extra = { ...paymentRequirements.extra };
64
+ if (typeof supportedKind.extra?.feePayer === "string") {
65
+ extra.feePayer = supportedKind.extra.feePayer;
66
+ }
67
+ return Promise.resolve({ ...paymentRequirements, extra });
68
+ }
69
+ /**
70
+ * Parse Money to a decimal number.
71
+ *
72
+ * @param money - The money value to parse
73
+ * @returns Decimal number
74
+ */
75
+ parseMoneyToDecimal(money) {
76
+ if (typeof money === "number") {
77
+ return money;
78
+ }
79
+ const cleanMoney = money.replace(/^\$/, "").trim();
80
+ const amount = parseFloat(cleanMoney);
81
+ if (isNaN(amount)) {
82
+ throw new Error(`Invalid money format: ${money}`);
83
+ }
84
+ return amount;
85
+ }
86
+ /**
87
+ * Default money conversion to USDC.
88
+ *
89
+ * @param amount - The decimal amount
90
+ * @param network - The network to use
91
+ * @returns The parsed asset amount in USDC
92
+ */
93
+ defaultMoneyConversion(amount, network) {
94
+ const decimals = 6;
95
+ const tokenAmount = this.convertToTokenAmount(amount.toString(), decimals);
96
+ const asset = network === "aptos:2" ? USDC_TESTNET_FA : USDC_MAINNET_FA;
97
+ return { amount: tokenAmount, asset, extra: {} };
98
+ }
99
+ /**
100
+ * Convert a decimal amount string to a token amount string.
101
+ *
102
+ * @param amount - The decimal amount
103
+ * @param decimals - Number of decimals for the token
104
+ * @returns The amount in atomic units as a string
105
+ */
106
+ convertToTokenAmount(amount, decimals) {
107
+ const parts = amount.split(".");
108
+ const wholePart = parts[0] || "0";
109
+ const fractionalPart = (parts[1] || "").padEnd(decimals, "0").slice(0, decimals);
110
+ return BigInt(wholePart + fractionalPart).toString();
111
+ }
112
+ };
113
+ export {
114
+ ExactAptosScheme
115
+ };
116
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/exact/server/scheme.ts"],"sourcesContent":["import type {\n AssetAmount,\n Money,\n MoneyParser,\n Network,\n PaymentRequirements,\n Price,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\nimport { APTOS_ADDRESS_REGEX, USDC_MAINNET_FA, USDC_TESTNET_FA } from \"../../constants\";\n\n/**\n * Aptos server implementation for the Exact payment scheme.\n */\nexport class ExactAptosScheme implements SchemeNetworkServer {\n readonly scheme = \"exact\";\n private moneyParsers: MoneyParser[] = [];\n\n /**\n * Register a custom money parser in the parser chain.\n *\n * @param parser - Custom function to convert amount to AssetAmount (or null to skip)\n * @returns The service instance for chaining\n */\n registerMoneyParser(parser: MoneyParser): ExactAptosScheme {\n this.moneyParsers.push(parser);\n return this;\n }\n\n /**\n * Parses a price into an asset amount.\n *\n * @param price - The price to parse\n * @param network - The network to use\n * @returns Promise that resolves to the parsed asset amount\n */\n async parsePrice(price: Price, network: Network): Promise<AssetAmount> {\n if (typeof price === \"object\" && price !== null && \"amount\" in price) {\n if (!price.asset) {\n throw new Error(`Asset address must be specified for AssetAmount on network ${network}`);\n }\n if (!APTOS_ADDRESS_REGEX.test(price.asset)) {\n throw new Error(`Invalid asset address format: ${price.asset}`);\n }\n return { amount: price.amount, asset: price.asset, extra: price.extra || {} };\n }\n\n const amount = this.parseMoneyToDecimal(price as Money);\n\n for (const parser of this.moneyParsers) {\n const result = await parser(amount, network);\n if (result !== null) {\n return result;\n }\n }\n\n return this.defaultMoneyConversion(amount, network);\n }\n\n /**\n * Build payment requirements for this scheme/network combination\n *\n * @param paymentRequirements - The base payment requirements\n * @param supportedKind - The supported kind configuration\n * @param supportedKind.x402Version - The x402 protocol version\n * @param supportedKind.scheme - The payment scheme\n * @param supportedKind.network - The network identifier\n * @param supportedKind.extra - Extra metadata including feePayer address\n * @param extensionKeys - Extension keys supported by the facilitator\n * @returns Enhanced payment requirements with feePayer in extra\n */\n enhancePaymentRequirements(\n paymentRequirements: PaymentRequirements,\n supportedKind: {\n x402Version: number;\n scheme: string;\n network: Network;\n extra?: Record<string, unknown>;\n },\n extensionKeys: string[],\n ): Promise<PaymentRequirements> {\n void extensionKeys;\n\n const extra: Record<string, unknown> = { ...paymentRequirements.extra };\n if (typeof supportedKind.extra?.feePayer === \"string\") {\n extra.feePayer = supportedKind.extra.feePayer;\n }\n\n return Promise.resolve({ ...paymentRequirements, extra });\n }\n\n /**\n * Parse Money to a decimal number.\n *\n * @param money - The money value to parse\n * @returns Decimal number\n */\n private parseMoneyToDecimal(money: string | number): number {\n if (typeof money === \"number\") {\n return money;\n }\n const cleanMoney = money.replace(/^\\$/, \"\").trim();\n const amount = parseFloat(cleanMoney);\n if (isNaN(amount)) {\n throw new Error(`Invalid money format: ${money}`);\n }\n return amount;\n }\n\n /**\n * Default money conversion to USDC.\n *\n * @param amount - The decimal amount\n * @param network - The network to use\n * @returns The parsed asset amount in USDC\n */\n private defaultMoneyConversion(amount: number, network: Network): AssetAmount {\n const decimals = 6;\n const tokenAmount = this.convertToTokenAmount(amount.toString(), decimals);\n const asset = network === \"aptos:2\" ? USDC_TESTNET_FA : USDC_MAINNET_FA;\n return { amount: tokenAmount, asset, extra: {} };\n }\n\n /**\n * Convert a decimal amount string to a token amount string.\n *\n * @param amount - The decimal amount\n * @param decimals - Number of decimals for the token\n * @returns The amount in atomic units as a string\n */\n private convertToTokenAmount(amount: string, decimals: number): string {\n const parts = amount.split(\".\");\n const wholePart = parts[0] || \"0\";\n const fractionalPart = (parts[1] || \"\").padEnd(decimals, \"0\").slice(0, decimals);\n return BigInt(wholePart + fractionalPart).toString();\n }\n}\n"],"mappings":";;;;;;;AAcO,IAAM,mBAAN,MAAsD;AAAA,EAAtD;AACL,SAAS,SAAS;AAClB,SAAQ,eAA8B,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvC,oBAAoB,QAAuC;AACzD,SAAK,aAAa,KAAK,MAAM;AAC7B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,WAAW,OAAc,SAAwC;AACrE,QAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;AACpE,UAAI,CAAC,MAAM,OAAO;AAChB,cAAM,IAAI,MAAM,8DAA8D,OAAO,EAAE;AAAA,MACzF;AACA,UAAI,CAAC,oBAAoB,KAAK,MAAM,KAAK,GAAG;AAC1C,cAAM,IAAI,MAAM,iCAAiC,MAAM,KAAK,EAAE;AAAA,MAChE;AACA,aAAO,EAAE,QAAQ,MAAM,QAAQ,OAAO,MAAM,OAAO,OAAO,MAAM,SAAS,CAAC,EAAE;AAAA,IAC9E;AAEA,UAAM,SAAS,KAAK,oBAAoB,KAAc;AAEtD,eAAW,UAAU,KAAK,cAAc;AACtC,YAAM,SAAS,MAAM,OAAO,QAAQ,OAAO;AAC3C,UAAI,WAAW,MAAM;AACnB,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO,KAAK,uBAAuB,QAAQ,OAAO;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,2BACE,qBACA,eAMA,eAC8B;AAC9B,SAAK;AAEL,UAAM,QAAiC,EAAE,GAAG,oBAAoB,MAAM;AACtE,QAAI,OAAO,cAAc,OAAO,aAAa,UAAU;AACrD,YAAM,WAAW,cAAc,MAAM;AAAA,IACvC;AAEA,WAAO,QAAQ,QAAQ,EAAE,GAAG,qBAAqB,MAAM,CAAC;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,oBAAoB,OAAgC;AAC1D,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;AAAA,IACT;AACA,UAAM,aAAa,MAAM,QAAQ,OAAO,EAAE,EAAE,KAAK;AACjD,UAAM,SAAS,WAAW,UAAU;AACpC,QAAI,MAAM,MAAM,GAAG;AACjB,YAAM,IAAI,MAAM,yBAAyB,KAAK,EAAE;AAAA,IAClD;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASQ,uBAAuB,QAAgB,SAA+B;AAC5E,UAAM,WAAW;AACjB,UAAM,cAAc,KAAK,qBAAqB,OAAO,SAAS,GAAG,QAAQ;AACzE,UAAM,QAAQ,YAAY,YAAY,kBAAkB;AACxD,WAAO,EAAE,QAAQ,aAAa,OAAO,OAAO,CAAC,EAAE;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASQ,qBAAqB,QAAgB,UAA0B;AACrE,UAAM,QAAQ,OAAO,MAAM,GAAG;AAC9B,UAAM,YAAY,MAAM,CAAC,KAAK;AAC9B,UAAM,kBAAkB,MAAM,CAAC,KAAK,IAAI,OAAO,UAAU,GAAG,EAAE,MAAM,GAAG,QAAQ;AAC/E,WAAO,OAAO,YAAY,cAAc,EAAE,SAAS;AAAA,EACrD;AACF;","names":[]}
@@ -0,0 +1,116 @@
1
+ export { ExactAptosScheme } from './exact/client/index.mjs';
2
+ import { Network, Aptos, SimpleTransaction, AccountAuthenticator, EntryFunction, TransactionPayload, TransactionPayloadEntryFunction } from '@aptos-labs/ts-sdk';
3
+ export { C as ClientAptosConfig, a as ClientAptosSigner, F as FacilitatorAptosSigner, c as createClientSigner, t as toFacilitatorAptosSigner } from './signer-DPT9P1NX.mjs';
4
+ import '@x402/core/types';
5
+
6
+ /**
7
+ * Exact Aptos payload structure containing a base64 encoded transaction
8
+ */
9
+ type ExactAptosPayload = {
10
+ /**
11
+ * Base64 encoded JSON containing transaction and senderAuthenticator byte arrays
12
+ */
13
+ transaction: string;
14
+ };
15
+ /**
16
+ * Decoded Aptos payment payload structure
17
+ */
18
+ type DecodedAptosPayload = {
19
+ /**
20
+ * Transaction bytes as number array
21
+ */
22
+ transaction: number[];
23
+ /**
24
+ * Sender authenticator bytes as number array
25
+ */
26
+ senderAuthenticator: number[];
27
+ };
28
+
29
+ /**
30
+ * CAIP-2 network identifier for Aptos Mainnet
31
+ */
32
+ declare const APTOS_MAINNET_CAIP2 = "aptos:1";
33
+ /**
34
+ * CAIP-2 network identifier for Aptos Testnet
35
+ */
36
+ declare const APTOS_TESTNET_CAIP2 = "aptos:2";
37
+ /**
38
+ * Regex pattern for validating Aptos addresses
39
+ * Matches 64 hex characters with 0x prefix
40
+ */
41
+ declare const APTOS_ADDRESS_REGEX: RegExp;
42
+ /**
43
+ * The primary fungible store transfer function
44
+ */
45
+ declare const TRANSFER_FUNCTION = "0x1::primary_fungible_store::transfer";
46
+ /**
47
+ * Maximum gas amount allowed for sponsored transactions to prevent gas draining attacks.
48
+ * The Aptos SDK defaults to 200000 for simple transactions, so we allow some headroom.
49
+ */
50
+ declare const MAX_GAS_AMOUNT = 500000n;
51
+ /**
52
+ * Maps CAIP-2 network identifiers to Aptos chain IDs.
53
+ *
54
+ * @param network - The CAIP-2 network identifier (e.g., "aptos:1")
55
+ * @returns The corresponding chain ID
56
+ */
57
+ declare function getAptosChainId(network: string): number;
58
+ /**
59
+ * Default USDC fungible asset metadata address on mainnet.
60
+ */
61
+ declare const USDC_MAINNET_FA = "0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b";
62
+ /**
63
+ * Default USDC fungible asset metadata address on testnet.
64
+ */
65
+ declare const USDC_TESTNET_FA = "0x69091fbab5f7d635ee7ac5098cf0c1efbe31d68fec0f2cd565e8d168daf52832";
66
+ /**
67
+ * Maps CAIP-2 network identifiers to Aptos SDK Network enum.
68
+ *
69
+ * @param network - The CAIP-2 network identifier (e.g., "aptos:1")
70
+ * @returns The corresponding Aptos SDK Network enum value
71
+ */
72
+ declare function getAptosNetwork(network: string): Network;
73
+ /**
74
+ * Gets the default RPC URL for the given Aptos network.
75
+ *
76
+ * @param network - The Aptos SDK Network enum value
77
+ * @returns The default RPC URL for the network
78
+ */
79
+ declare function getAptosRpcUrl(network: Network): string;
80
+
81
+ /**
82
+ * Deserialize an Aptos transaction and authenticator from the payment payload.
83
+ *
84
+ * @param transactionBase64 - The base64 encoded transaction payload
85
+ * @returns The deserialized transaction and authenticator
86
+ */
87
+ declare function deserializeAptosPayment(transactionBase64: string): {
88
+ transaction: SimpleTransaction;
89
+ senderAuthenticator: AccountAuthenticator;
90
+ entryFunction?: EntryFunction;
91
+ };
92
+ /**
93
+ * Checks if it's an entry function payload.
94
+ *
95
+ * @param payload - The payload to check
96
+ * @returns True if it's an entry function payload
97
+ */
98
+ declare function isEntryFunctionPayload(payload: TransactionPayload): payload is TransactionPayloadEntryFunction;
99
+ /**
100
+ * Create an Aptos SDK client for the given network
101
+ *
102
+ * @param network - CAIP-2 network identifier (e.g., "aptos:1")
103
+ * @param rpcUrl - Optional custom RPC URL
104
+ * @returns Aptos SDK client
105
+ */
106
+ declare function createAptosClient(network: string, rpcUrl?: string): Aptos;
107
+ /**
108
+ * Encode an Aptos payment payload to base64
109
+ *
110
+ * @param transactionBytes - The serialized transaction bytes
111
+ * @param authenticatorBytes - The serialized authenticator bytes
112
+ * @returns Base64 encoded payload
113
+ */
114
+ declare function encodeAptosPayload(transactionBytes: Uint8Array, authenticatorBytes: Uint8Array): string;
115
+
116
+ export { APTOS_ADDRESS_REGEX, APTOS_MAINNET_CAIP2, APTOS_TESTNET_CAIP2, type DecodedAptosPayload, type ExactAptosPayload, MAX_GAS_AMOUNT, TRANSFER_FUNCTION, USDC_MAINNET_FA, USDC_TESTNET_FA, createAptosClient, deserializeAptosPayment, encodeAptosPayload, getAptosChainId, getAptosNetwork, getAptosRpcUrl, isEntryFunctionPayload };
@@ -0,0 +1,105 @@
1
+ import {
2
+ ExactAptosScheme
3
+ } from "./chunk-6BMAMLXJ.mjs";
4
+ import {
5
+ createAptosClient,
6
+ deserializeAptosPayment,
7
+ encodeAptosPayload,
8
+ isEntryFunctionPayload
9
+ } from "./chunk-D4UVBSUH.mjs";
10
+ import {
11
+ APTOS_ADDRESS_REGEX,
12
+ APTOS_MAINNET_CAIP2,
13
+ APTOS_TESTNET_CAIP2,
14
+ MAX_GAS_AMOUNT,
15
+ TRANSFER_FUNCTION,
16
+ USDC_MAINNET_FA,
17
+ USDC_TESTNET_FA,
18
+ getAptosChainId,
19
+ getAptosNetwork,
20
+ getAptosRpcUrl
21
+ } from "./chunk-FG4ANPDN.mjs";
22
+
23
+ // src/signer.ts
24
+ import {
25
+ Account,
26
+ Ed25519PrivateKey,
27
+ Aptos,
28
+ AptosConfig,
29
+ PrivateKey,
30
+ PrivateKeyVariants
31
+ } from "@aptos-labs/ts-sdk";
32
+ async function createClientSigner(privateKey) {
33
+ const formattedKey = PrivateKey.formatPrivateKey(privateKey, PrivateKeyVariants.Ed25519);
34
+ const privateKeyBytes = new Ed25519PrivateKey(formattedKey);
35
+ return Account.fromPrivateKey({ privateKey: privateKeyBytes });
36
+ }
37
+ function toFacilitatorAptosSigner(account, rpcConfig) {
38
+ const getRpcUrl = (network) => {
39
+ if (rpcConfig) {
40
+ if ("defaultRpcUrl" in rpcConfig && rpcConfig.defaultRpcUrl) {
41
+ return rpcConfig.defaultRpcUrl;
42
+ }
43
+ if (network in rpcConfig) {
44
+ return rpcConfig[network];
45
+ }
46
+ }
47
+ return getAptosRpcUrl(getAptosNetwork(network));
48
+ };
49
+ const getAptos = (network) => {
50
+ const aptosNetwork = getAptosNetwork(network);
51
+ const rpcUrl = getRpcUrl(network);
52
+ return new Aptos(new AptosConfig({ network: aptosNetwork, fullnode: rpcUrl }));
53
+ };
54
+ return {
55
+ getAddresses: () => [account.accountAddress.toStringLong()],
56
+ signAndSubmitAsFeePayer: async (transaction, senderAuthenticator, network) => {
57
+ const aptos = getAptos(network);
58
+ transaction.feePayerAddress = account.accountAddress;
59
+ const feePayerAuthenticator = aptos.transaction.signAsFeePayer({
60
+ signer: account,
61
+ transaction
62
+ });
63
+ return aptos.transaction.submit.simple({
64
+ transaction,
65
+ senderAuthenticator,
66
+ feePayerAuthenticator
67
+ });
68
+ },
69
+ submitTransaction: async (transaction, senderAuthenticator, network) => {
70
+ const aptos = getAptos(network);
71
+ return aptos.transaction.submit.simple({ transaction, senderAuthenticator });
72
+ },
73
+ simulateTransaction: async (transaction, network) => {
74
+ const aptos = getAptos(network);
75
+ const results = await aptos.transaction.simulate.simple({ transaction });
76
+ if (results.length === 0 || !results[0].success) {
77
+ throw new Error(`Simulation failed: ${results[0]?.vm_status || "unknown error"}`);
78
+ }
79
+ },
80
+ waitForTransaction: async (txHash, network) => {
81
+ const aptos = getAptos(network);
82
+ await aptos.waitForTransaction({ transactionHash: txHash });
83
+ }
84
+ };
85
+ }
86
+ export {
87
+ APTOS_ADDRESS_REGEX,
88
+ APTOS_MAINNET_CAIP2,
89
+ APTOS_TESTNET_CAIP2,
90
+ ExactAptosScheme,
91
+ MAX_GAS_AMOUNT,
92
+ TRANSFER_FUNCTION,
93
+ USDC_MAINNET_FA,
94
+ USDC_TESTNET_FA,
95
+ createAptosClient,
96
+ createClientSigner,
97
+ deserializeAptosPayment,
98
+ encodeAptosPayload,
99
+ getAptosChainId,
100
+ getAptosNetwork,
101
+ getAptosRpcUrl,
102
+ isEntryFunctionPayload,
103
+ toFacilitatorAptosSigner
104
+ };
105
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/signer.ts"],"sourcesContent":["import {\n Account,\n Ed25519PrivateKey,\n Aptos,\n AptosConfig,\n SimpleTransaction,\n AccountAuthenticator,\n PrivateKey,\n PrivateKeyVariants,\n type PendingTransactionResponse,\n} from \"@aptos-labs/ts-sdk\";\nimport { getAptosNetwork, getAptosRpcUrl } from \"./constants\";\n\n/**\n * Client-side signer for creating and signing Aptos transactions\n */\nexport type ClientAptosSigner = Account;\n\n/**\n * Configuration for client operations\n */\nexport type ClientAptosConfig = {\n /**\n * Optional custom RPC URL for the client to use\n */\n rpcUrl?: string;\n};\n\n/**\n * Minimal facilitator signer interface for Aptos operations\n */\nexport type FacilitatorAptosSigner = {\n /**\n * Get all addresses this facilitator can use for signing\n */\n getAddresses(): readonly string[];\n\n /**\n * Sign a transaction as the fee payer and submit it\n */\n signAndSubmitAsFeePayer(\n transaction: SimpleTransaction,\n senderAuthenticator: AccountAuthenticator,\n network: string,\n ): Promise<PendingTransactionResponse>;\n\n /**\n * Submit a fully-signed transaction (non-sponsored)\n */\n submitTransaction(\n transaction: SimpleTransaction,\n senderAuthenticator: AccountAuthenticator,\n network: string,\n ): Promise<PendingTransactionResponse>;\n\n /**\n * Simulate a transaction to verify it would succeed\n */\n simulateTransaction(transaction: SimpleTransaction, network: string): Promise<void>;\n\n /**\n * Wait for transaction confirmation\n */\n waitForTransaction(txHash: string, network: string): Promise<void>;\n};\n\n/**\n * Creates a client signer from a private key\n *\n * @param privateKey - The private key as a hex string or AIP-80 format\n * @returns An Aptos Account instance\n */\nexport async function createClientSigner(privateKey: string): Promise<ClientAptosSigner> {\n const formattedKey = PrivateKey.formatPrivateKey(privateKey, PrivateKeyVariants.Ed25519);\n const privateKeyBytes = new Ed25519PrivateKey(formattedKey);\n return Account.fromPrivateKey({ privateKey: privateKeyBytes });\n}\n\n/**\n * Create a facilitator signer from an Aptos Account\n *\n * @param account - The Aptos Account that will act as fee payer\n * @param rpcConfig - Optional RPC configuration\n * @returns FacilitatorAptosSigner instance\n */\nexport function toFacilitatorAptosSigner(\n account: Account,\n rpcConfig?: { defaultRpcUrl?: string } | Record<string, string>,\n): FacilitatorAptosSigner {\n const getRpcUrl = (network: string): string => {\n if (rpcConfig) {\n if (\"defaultRpcUrl\" in rpcConfig && rpcConfig.defaultRpcUrl) {\n return rpcConfig.defaultRpcUrl;\n }\n if (network in rpcConfig) {\n return (rpcConfig as Record<string, string>)[network];\n }\n }\n return getAptosRpcUrl(getAptosNetwork(network));\n };\n\n const getAptos = (network: string): Aptos => {\n const aptosNetwork = getAptosNetwork(network);\n const rpcUrl = getRpcUrl(network);\n return new Aptos(new AptosConfig({ network: aptosNetwork, fullnode: rpcUrl }));\n };\n\n return {\n getAddresses: () => [account.accountAddress.toStringLong()],\n\n signAndSubmitAsFeePayer: async (\n transaction: SimpleTransaction,\n senderAuthenticator: AccountAuthenticator,\n network: string,\n ) => {\n const aptos = getAptos(network);\n transaction.feePayerAddress = account.accountAddress;\n const feePayerAuthenticator = aptos.transaction.signAsFeePayer({\n signer: account,\n transaction,\n });\n return aptos.transaction.submit.simple({\n transaction,\n senderAuthenticator,\n feePayerAuthenticator,\n });\n },\n\n submitTransaction: async (\n transaction: SimpleTransaction,\n senderAuthenticator: AccountAuthenticator,\n network: string,\n ) => {\n const aptos = getAptos(network);\n return aptos.transaction.submit.simple({ transaction, senderAuthenticator });\n },\n\n simulateTransaction: async (transaction: SimpleTransaction, network: string) => {\n const aptos = getAptos(network);\n const results = await aptos.transaction.simulate.simple({ transaction });\n if (results.length === 0 || !results[0].success) {\n throw new Error(`Simulation failed: ${results[0]?.vm_status || \"unknown error\"}`);\n }\n },\n\n waitForTransaction: async (txHash: string, network: string) => {\n const aptos = getAptos(network);\n await aptos.waitForTransaction({ transactionHash: txHash });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OAEK;AA8DP,eAAsB,mBAAmB,YAAgD;AACvF,QAAM,eAAe,WAAW,iBAAiB,YAAY,mBAAmB,OAAO;AACvF,QAAM,kBAAkB,IAAI,kBAAkB,YAAY;AAC1D,SAAO,QAAQ,eAAe,EAAE,YAAY,gBAAgB,CAAC;AAC/D;AASO,SAAS,yBACd,SACA,WACwB;AACxB,QAAM,YAAY,CAAC,YAA4B;AAC7C,QAAI,WAAW;AACb,UAAI,mBAAmB,aAAa,UAAU,eAAe;AAC3D,eAAO,UAAU;AAAA,MACnB;AACA,UAAI,WAAW,WAAW;AACxB,eAAQ,UAAqC,OAAO;AAAA,MACtD;AAAA,IACF;AACA,WAAO,eAAe,gBAAgB,OAAO,CAAC;AAAA,EAChD;AAEA,QAAM,WAAW,CAAC,YAA2B;AAC3C,UAAM,eAAe,gBAAgB,OAAO;AAC5C,UAAM,SAAS,UAAU,OAAO;AAChC,WAAO,IAAI,MAAM,IAAI,YAAY,EAAE,SAAS,cAAc,UAAU,OAAO,CAAC,CAAC;AAAA,EAC/E;AAEA,SAAO;AAAA,IACL,cAAc,MAAM,CAAC,QAAQ,eAAe,aAAa,CAAC;AAAA,IAE1D,yBAAyB,OACvB,aACA,qBACA,YACG;AACH,YAAM,QAAQ,SAAS,OAAO;AAC9B,kBAAY,kBAAkB,QAAQ;AACtC,YAAM,wBAAwB,MAAM,YAAY,eAAe;AAAA,QAC7D,QAAQ;AAAA,QACR;AAAA,MACF,CAAC;AACD,aAAO,MAAM,YAAY,OAAO,OAAO;AAAA,QACrC;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,mBAAmB,OACjB,aACA,qBACA,YACG;AACH,YAAM,QAAQ,SAAS,OAAO;AAC9B,aAAO,MAAM,YAAY,OAAO,OAAO,EAAE,aAAa,oBAAoB,CAAC;AAAA,IAC7E;AAAA,IAEA,qBAAqB,OAAO,aAAgC,YAAoB;AAC9E,YAAM,QAAQ,SAAS,OAAO;AAC9B,YAAM,UAAU,MAAM,MAAM,YAAY,SAAS,OAAO,EAAE,YAAY,CAAC;AACvE,UAAI,QAAQ,WAAW,KAAK,CAAC,QAAQ,CAAC,EAAE,SAAS;AAC/C,cAAM,IAAI,MAAM,sBAAsB,QAAQ,CAAC,GAAG,aAAa,eAAe,EAAE;AAAA,MAClF;AAAA,IACF;AAAA,IAEA,oBAAoB,OAAO,QAAgB,YAAoB;AAC7D,YAAM,QAAQ,SAAS,OAAO;AAC9B,YAAM,MAAM,mBAAmB,EAAE,iBAAiB,OAAO,CAAC;AAAA,IAC5D;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,59 @@
1
+ import { Account, SimpleTransaction, AccountAuthenticator, PendingTransactionResponse } from '@aptos-labs/ts-sdk';
2
+
3
+ /**
4
+ * Client-side signer for creating and signing Aptos transactions
5
+ */
6
+ type ClientAptosSigner = Account;
7
+ /**
8
+ * Configuration for client operations
9
+ */
10
+ type ClientAptosConfig = {
11
+ /**
12
+ * Optional custom RPC URL for the client to use
13
+ */
14
+ rpcUrl?: string;
15
+ };
16
+ /**
17
+ * Minimal facilitator signer interface for Aptos operations
18
+ */
19
+ type FacilitatorAptosSigner = {
20
+ /**
21
+ * Get all addresses this facilitator can use for signing
22
+ */
23
+ getAddresses(): readonly string[];
24
+ /**
25
+ * Sign a transaction as the fee payer and submit it
26
+ */
27
+ signAndSubmitAsFeePayer(transaction: SimpleTransaction, senderAuthenticator: AccountAuthenticator, network: string): Promise<PendingTransactionResponse>;
28
+ /**
29
+ * Submit a fully-signed transaction (non-sponsored)
30
+ */
31
+ submitTransaction(transaction: SimpleTransaction, senderAuthenticator: AccountAuthenticator, network: string): Promise<PendingTransactionResponse>;
32
+ /**
33
+ * Simulate a transaction to verify it would succeed
34
+ */
35
+ simulateTransaction(transaction: SimpleTransaction, network: string): Promise<void>;
36
+ /**
37
+ * Wait for transaction confirmation
38
+ */
39
+ waitForTransaction(txHash: string, network: string): Promise<void>;
40
+ };
41
+ /**
42
+ * Creates a client signer from a private key
43
+ *
44
+ * @param privateKey - The private key as a hex string or AIP-80 format
45
+ * @returns An Aptos Account instance
46
+ */
47
+ declare function createClientSigner(privateKey: string): Promise<ClientAptosSigner>;
48
+ /**
49
+ * Create a facilitator signer from an Aptos Account
50
+ *
51
+ * @param account - The Aptos Account that will act as fee payer
52
+ * @param rpcConfig - Optional RPC configuration
53
+ * @returns FacilitatorAptosSigner instance
54
+ */
55
+ declare function toFacilitatorAptosSigner(account: Account, rpcConfig?: {
56
+ defaultRpcUrl?: string;
57
+ } | Record<string, string>): FacilitatorAptosSigner;
58
+
59
+ export { type ClientAptosConfig as C, type FacilitatorAptosSigner as F, type ClientAptosSigner as a, createClientSigner as c, toFacilitatorAptosSigner as t };
package/package.json ADDED
@@ -0,0 +1,95 @@
1
+ {
2
+ "name": "@x402/aptos",
3
+ "version": "2.3.0",
4
+ "main": "./dist/cjs/index.js",
5
+ "module": "./dist/esm/index.js",
6
+ "types": "./dist/cjs/index.d.ts",
7
+ "scripts": {
8
+ "start": "tsx --env-file=.env index.ts",
9
+ "build": "tsup",
10
+ "test": "vitest run",
11
+ "test:integration": "vitest run --config vitest.integration.config.ts",
12
+ "test:watch": "vitest",
13
+ "watch": "tsc --watch",
14
+ "format": "prettier -c .prettierrc --write \"**/*.{ts,js,cjs,json,md}\"",
15
+ "format:check": "prettier -c .prettierrc --check \"**/*.{ts,js,cjs,json,md}\"",
16
+ "lint": "eslint . --ext .ts --fix",
17
+ "lint:check": "eslint . --ext .ts"
18
+ },
19
+ "keywords": [
20
+ "x402",
21
+ "payment",
22
+ "protocol",
23
+ "aptos"
24
+ ],
25
+ "license": "Apache-2.0",
26
+ "author": "Aptos Labs",
27
+ "repository": "https://github.com/coinbase/x402",
28
+ "description": "x402 Payment Protocol Aptos Implementation",
29
+ "devDependencies": {
30
+ "@eslint/js": "^9.24.0",
31
+ "@types/node": "^22.13.4",
32
+ "@typescript-eslint/eslint-plugin": "^8.29.1",
33
+ "@typescript-eslint/parser": "^8.29.1",
34
+ "eslint": "^9.24.0",
35
+ "eslint-plugin-import": "^2.31.0",
36
+ "eslint-plugin-jsdoc": "^50.6.9",
37
+ "eslint-plugin-prettier": "^5.2.6",
38
+ "prettier": "3.5.2",
39
+ "tsup": "^8.4.0",
40
+ "tsx": "^4.19.2",
41
+ "typescript": "^5.7.3",
42
+ "vite": "^6.2.6",
43
+ "vite-tsconfig-paths": "^5.1.4",
44
+ "vitest": "^3.0.5"
45
+ },
46
+ "dependencies": {
47
+ "@x402/core": "workspace:*",
48
+ "@aptos-labs/ts-sdk": "^5.2.1"
49
+ },
50
+ "exports": {
51
+ ".": {
52
+ "import": {
53
+ "types": "./dist/esm/index.d.mts",
54
+ "default": "./dist/esm/index.mjs"
55
+ },
56
+ "require": {
57
+ "types": "./dist/cjs/index.d.ts",
58
+ "default": "./dist/cjs/index.js"
59
+ }
60
+ },
61
+ "./exact/client": {
62
+ "import": {
63
+ "types": "./dist/esm/exact/client/index.d.mts",
64
+ "default": "./dist/esm/exact/client/index.mjs"
65
+ },
66
+ "require": {
67
+ "types": "./dist/cjs/exact/client/index.d.ts",
68
+ "default": "./dist/cjs/exact/client/index.js"
69
+ }
70
+ },
71
+ "./exact/server": {
72
+ "import": {
73
+ "types": "./dist/esm/exact/server/index.d.mts",
74
+ "default": "./dist/esm/exact/server/index.mjs"
75
+ },
76
+ "require": {
77
+ "types": "./dist/cjs/exact/server/index.d.ts",
78
+ "default": "./dist/cjs/exact/server/index.js"
79
+ }
80
+ },
81
+ "./exact/facilitator": {
82
+ "import": {
83
+ "types": "./dist/esm/exact/facilitator/index.d.mts",
84
+ "default": "./dist/esm/exact/facilitator/index.mjs"
85
+ },
86
+ "require": {
87
+ "types": "./dist/cjs/exact/facilitator/index.d.ts",
88
+ "default": "./dist/cjs/exact/facilitator/index.js"
89
+ }
90
+ }
91
+ },
92
+ "files": [
93
+ "dist"
94
+ ]
95
+ }