@t402/near 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 (38) hide show
  1. package/README.md +173 -0
  2. package/dist/cjs/exact-direct/client/index.d.ts +105 -0
  3. package/dist/cjs/exact-direct/client/index.js +156 -0
  4. package/dist/cjs/exact-direct/client/index.js.map +1 -0
  5. package/dist/cjs/exact-direct/facilitator/index.d.ts +114 -0
  6. package/dist/cjs/exact-direct/facilitator/index.js +304 -0
  7. package/dist/cjs/exact-direct/facilitator/index.js.map +1 -0
  8. package/dist/cjs/exact-direct/server/index.d.ts +129 -0
  9. package/dist/cjs/exact-direct/server/index.js +253 -0
  10. package/dist/cjs/exact-direct/server/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +226 -0
  12. package/dist/cjs/index.js +711 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/types-Ca7ztL_f.d.ts +169 -0
  15. package/dist/esm/chunk-B3RHERRA.mjs +162 -0
  16. package/dist/esm/chunk-B3RHERRA.mjs.map +1 -0
  17. package/dist/esm/chunk-BU2BQECZ.mjs +206 -0
  18. package/dist/esm/chunk-BU2BQECZ.mjs.map +1 -0
  19. package/dist/esm/chunk-G35SAYZI.mjs +67 -0
  20. package/dist/esm/chunk-G35SAYZI.mjs.map +1 -0
  21. package/dist/esm/chunk-WANNPL6S.mjs +155 -0
  22. package/dist/esm/chunk-WANNPL6S.mjs.map +1 -0
  23. package/dist/esm/chunk-YXBOH4MJ.mjs +103 -0
  24. package/dist/esm/chunk-YXBOH4MJ.mjs.map +1 -0
  25. package/dist/esm/exact-direct/client/index.d.mts +105 -0
  26. package/dist/esm/exact-direct/client/index.mjs +10 -0
  27. package/dist/esm/exact-direct/client/index.mjs.map +1 -0
  28. package/dist/esm/exact-direct/facilitator/index.d.mts +114 -0
  29. package/dist/esm/exact-direct/facilitator/index.mjs +11 -0
  30. package/dist/esm/exact-direct/facilitator/index.mjs.map +1 -0
  31. package/dist/esm/exact-direct/server/index.d.mts +129 -0
  32. package/dist/esm/exact-direct/server/index.mjs +11 -0
  33. package/dist/esm/exact-direct/server/index.mjs.map +1 -0
  34. package/dist/esm/index.d.mts +226 -0
  35. package/dist/esm/index.mjs +97 -0
  36. package/dist/esm/index.mjs.map +1 -0
  37. package/dist/esm/types-Ca7ztL_f.d.mts +169 -0
  38. package/package.json +97 -0
package/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # @t402/near
2
+
3
+ NEAR Protocol implementation of the t402 payment protocol using the **exact-direct** payment scheme with NEP-141 fungible token transfers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @t402/near
9
+ # or
10
+ pnpm add @t402/near
11
+ ```
12
+
13
+ ## Overview
14
+
15
+ This package provides support for USDT/USDC payments on NEAR Protocol using the exact-direct scheme. The client executes an `ft_transfer` call directly on-chain, then provides the transaction hash as proof of payment.
16
+
17
+ Three main components:
18
+
19
+ - **Client** - For applications that make payments (have NEAR wallets)
20
+ - **Facilitator** - For payment processors that verify transactions via RPC
21
+ - **Server** - For resource servers that accept payments and build payment requirements
22
+
23
+ ## Supported Networks
24
+
25
+ | Network | CAIP-2 Identifier | USDT Contract | USDC Contract | Status |
26
+ | ------------ | ----------------- | ------------------------ | ------------------------------------------------------------------ | ---------- |
27
+ | NEAR Mainnet | `near:mainnet` | `usdt.tether-token.near` | `17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1` | Production |
28
+ | NEAR Testnet | `near:testnet` | - | `usdc.fakes.testnet` | Testnet |
29
+
30
+ ## Package Exports
31
+
32
+ ### Main Package (`@t402/near`)
33
+
34
+ **Constants:**
35
+
36
+ - `NEAR_MAINNET_CAIP2` - CAIP-2 identifier for mainnet
37
+ - `NEAR_TESTNET_CAIP2` - CAIP-2 identifier for testnet
38
+ - `NEAR_NETWORKS` - Array of supported networks
39
+ - `NETWORK_RPC_ENDPOINTS` - RPC endpoint mapping
40
+ - `SCHEME_EXACT_DIRECT` - Scheme identifier
41
+ - `DEFAULT_FT_TRANSFER_GAS` - Default gas for transfers (30 TGas)
42
+
43
+ **Tokens:**
44
+
45
+ - `TOKEN_REGISTRY` - Token configurations by network
46
+ - `getTokenConfig(network, symbol)` - Get token by symbol
47
+ - `getTokenByContract(network, contractId)` - Get token by contract
48
+ - `getDefaultToken(network)` - Get default token
49
+ - `isNetworkSupported(network)` - Check if network is supported
50
+
51
+ **Utilities:**
52
+
53
+ - `isValidAccountId(accountId)` - Validate NEAR account ID
54
+ - `normalizeNetwork(network)` - Normalize to CAIP-2 format
55
+ - `extractNetworkId(network)` - Extract network ID from CAIP-2
56
+ - `getRpcEndpoint(network)` - Get RPC endpoint for network
57
+ - `formatAmount(amount, decimals)` - Format for display
58
+ - `toTokenUnits(amount, decimals)` - Convert to smallest units
59
+ - `parseFtTransferArgs(argsBase64)` - Parse ft_transfer arguments
60
+ - `isTransactionSuccessful(status)` - Check transaction status
61
+
62
+ ### Client (`@t402/near/exact-direct/client`)
63
+
64
+ ```typescript
65
+ import { createExactDirectNearClient } from "@t402/near/exact-direct/client";
66
+
67
+ const client = createExactDirectNearClient({
68
+ signer: myNearSigner,
69
+ });
70
+ ```
71
+
72
+ ### Server (`@t402/near/exact-direct/server`)
73
+
74
+ ```typescript
75
+ import { registerExactDirectNearServer } from "@t402/near/exact-direct/server";
76
+
77
+ registerExactDirectNearServer(server);
78
+ ```
79
+
80
+ ### Facilitator (`@t402/near/exact-direct/facilitator`)
81
+
82
+ ```typescript
83
+ import { createExactDirectNearFacilitator } from "@t402/near/exact-direct/facilitator";
84
+
85
+ const facilitator = createExactDirectNearFacilitator(signer);
86
+ ```
87
+
88
+ ## Payment Flow
89
+
90
+ 1. **Client** requests protected resource
91
+ 2. **Server** responds with 402 + payment requirements (network, amount, payTo)
92
+ 3. **Client** calls `ft_transfer` on token contract with 1 yoctoNEAR deposit
93
+ 4. **Client** submits transaction hash as payment proof
94
+ 5. **Facilitator** queries NEAR RPC to verify the transaction
95
+ 6. **Facilitator** confirms payment matches requirements
96
+
97
+ ## Payload Structure
98
+
99
+ ```typescript
100
+ interface ExactDirectNearPayload {
101
+ txHash: string; // Transaction hash (Base58)
102
+ from: string; // Sender account ID
103
+ to: string; // Recipient account ID
104
+ amount: string; // Amount in smallest units
105
+ }
106
+ ```
107
+
108
+ ## Account ID Format
109
+
110
+ NEAR uses human-readable account IDs:
111
+
112
+ - 2-64 characters
113
+ - Lowercase alphanumeric, underscores, hyphens
114
+ - Can have subaccounts (e.g., `sub.account.near`)
115
+
116
+ Examples:
117
+
118
+ ```
119
+ alice.near
120
+ merchant.near
121
+ usdt.tether-token.near
122
+ ```
123
+
124
+ ## NEP-141 Token Standard
125
+
126
+ This package uses the NEP-141 fungible token standard:
127
+
128
+ - `ft_transfer(receiver_id, amount, memo?)` - Transfer tokens
129
+ - `ft_balance_of(account_id)` - Query balance
130
+ - Requires 1 yoctoNEAR deposit for security
131
+
132
+ ```typescript
133
+ // ft_transfer arguments
134
+ {
135
+ receiver_id: "merchant.near",
136
+ amount: "1000000",
137
+ memo: null
138
+ }
139
+ ```
140
+
141
+ ## Gas Configuration
142
+
143
+ Default gas amounts:
144
+
145
+ - `ft_transfer`: 30 TGas (30,000,000,000,000 gas)
146
+ - `storage_deposit`: 10 TGas
147
+
148
+ Required deposits:
149
+
150
+ - `ft_transfer`: 1 yoctoNEAR
151
+
152
+ ## Development
153
+
154
+ ```bash
155
+ # Build
156
+ pnpm build
157
+
158
+ # Test
159
+ pnpm test
160
+
161
+ # Test with coverage
162
+ pnpm test:coverage
163
+
164
+ # Lint
165
+ pnpm lint
166
+ ```
167
+
168
+ ## Related Packages
169
+
170
+ - `@t402/core` - Core protocol types and client
171
+ - `@t402/fetch` - HTTP wrapper with automatic payment handling
172
+ - `@t402/evm` - EVM chains implementation
173
+ - `@t402/aptos` - Aptos implementation
@@ -0,0 +1,105 @@
1
+ import { SchemeNetworkClient, PaymentRequirements, PaymentPayload, Network } from '@t402/core/types';
2
+ import { C as ClientNearSigner } from '../../types-Ca7ztL_f.js';
3
+ import { t402Client, PaymentPolicy } from '@t402/core/client';
4
+
5
+ /**
6
+ * NEAR Client Scheme Implementation - Exact Direct
7
+ *
8
+ * Creates payment payloads for NEAR NEP-141 transfers using the exact-direct scheme.
9
+ * In this scheme, the client executes the ft_transfer directly and provides
10
+ * the transaction hash as proof of payment.
11
+ */
12
+
13
+ /**
14
+ * Configuration for ExactDirectNearClient
15
+ */
16
+ interface ExactDirectNearClientConfig {
17
+ /** Override the gas amount for ft_transfer */
18
+ gasAmount?: string;
19
+ /** Optional memo to include in the transfer */
20
+ memo?: string;
21
+ }
22
+ /**
23
+ * NEAR client implementation for the Exact-Direct payment scheme.
24
+ *
25
+ * Executes NEP-141 ft_transfer and returns the transaction hash as proof.
26
+ */
27
+ declare class ExactDirectNearClient implements SchemeNetworkClient {
28
+ private readonly signer;
29
+ private readonly config;
30
+ readonly scheme = "exact-direct";
31
+ /**
32
+ * Creates a new ExactDirectNearScheme instance.
33
+ *
34
+ * @param signer - The NEAR signer for client operations
35
+ * @param config - Optional configuration overrides
36
+ */
37
+ constructor(signer: ClientNearSigner, config?: ExactDirectNearClientConfig);
38
+ /**
39
+ * Creates a payment payload by executing the transfer.
40
+ *
41
+ * Unlike other schemes where the client creates a signed message for
42
+ * the facilitator to execute, the exact-direct scheme has the client
43
+ * execute the transfer directly. The transaction hash is then used
44
+ * as proof of payment.
45
+ *
46
+ * @param t402Version - The t402 protocol version
47
+ * @param paymentRequirements - The payment requirements
48
+ * @returns Promise resolving to a payment payload with transaction hash
49
+ */
50
+ createPaymentPayload(t402Version: number, paymentRequirements: PaymentRequirements): Promise<Pick<PaymentPayload, "t402Version" | "payload">>;
51
+ }
52
+
53
+ /**
54
+ * Registration function for NEAR Exact-Direct client
55
+ */
56
+
57
+ /**
58
+ * Configuration options for registering NEAR schemes to a t402Client
59
+ */
60
+ interface NearClientConfig {
61
+ /**
62
+ * The NEAR signer to use for creating payment payloads
63
+ */
64
+ signer: ClientNearSigner;
65
+ /**
66
+ * Optional policies to apply to the client
67
+ */
68
+ policies?: PaymentPolicy[];
69
+ /**
70
+ * Optional specific networks to register
71
+ * If not provided, registers wildcard support (near:*)
72
+ */
73
+ networks?: Network[];
74
+ /**
75
+ * Optional scheme configuration (gas amounts, memo)
76
+ */
77
+ schemeConfig?: ExactDirectNearClientConfig;
78
+ }
79
+ /**
80
+ * Registers NEAR exact-direct payment schemes to a t402Client instance.
81
+ *
82
+ * @param client - The t402Client instance to register schemes to
83
+ * @param config - Configuration for NEAR client registration
84
+ * @returns The client instance for chaining
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * import { registerExactDirectNearClient } from "@t402/near/exact-direct/client";
89
+ * import { t402Client } from "@t402/core/client";
90
+ *
91
+ * const client = new t402Client();
92
+ * registerExactDirectNearClient(client, {
93
+ * signer: {
94
+ * accountId: "alice.near",
95
+ * signAndSendTransaction: async (receiverId, methodName, args, gas, deposit) => {
96
+ * // Sign and send using wallet
97
+ * return txHash;
98
+ * }
99
+ * }
100
+ * });
101
+ * ```
102
+ */
103
+ declare function registerExactDirectNearClient(client: t402Client, config: NearClientConfig): t402Client;
104
+
105
+ export { ExactDirectNearClient, type ExactDirectNearClientConfig, type NearClientConfig, registerExactDirectNearClient };
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/exact-direct/client/index.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ ExactDirectNearClient: () => ExactDirectNearClient,
24
+ registerExactDirectNearClient: () => registerExactDirectNearClient
25
+ });
26
+ module.exports = __toCommonJS(client_exports);
27
+
28
+ // src/constants.ts
29
+ var NEAR_MAINNET_CAIP2 = "near:mainnet";
30
+ var NEAR_TESTNET_CAIP2 = "near:testnet";
31
+ var NEAR_NETWORK_IDS = {
32
+ [NEAR_MAINNET_CAIP2]: "mainnet",
33
+ [NEAR_TESTNET_CAIP2]: "testnet"
34
+ };
35
+ var NEAR_MAINNET_RPC = "https://rpc.mainnet.near.org";
36
+ var NEAR_TESTNET_RPC = "https://rpc.testnet.near.org";
37
+ var NETWORK_RPC_ENDPOINTS = {
38
+ [NEAR_MAINNET_CAIP2]: NEAR_MAINNET_RPC,
39
+ [NEAR_TESTNET_CAIP2]: NEAR_TESTNET_RPC
40
+ };
41
+ var DEFAULT_FT_TRANSFER_GAS = "30000000000000";
42
+ var FT_TRANSFER_DEPOSIT = "1";
43
+ var SCHEME_EXACT_DIRECT = "exact-direct";
44
+ var MAX_TRANSACTION_AGE = 5 * 60 * 1e3;
45
+ var NEAR_CAIP2_NAMESPACE = "near";
46
+
47
+ // src/utils.ts
48
+ function normalizeNetwork(network) {
49
+ if (network.startsWith(`${NEAR_CAIP2_NAMESPACE}:`)) {
50
+ return network;
51
+ }
52
+ return `${NEAR_CAIP2_NAMESPACE}:${network}`;
53
+ }
54
+ function isValidAccountId(accountId) {
55
+ if (!accountId || accountId.length < 2 || accountId.length > 64) {
56
+ return false;
57
+ }
58
+ const regex = /^[a-z0-9]([a-z0-9_-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9_-]*[a-z0-9])?)*$/;
59
+ return regex.test(accountId);
60
+ }
61
+
62
+ // src/exact-direct/client/scheme.ts
63
+ var ExactDirectNearClient = class {
64
+ /**
65
+ * Creates a new ExactDirectNearScheme instance.
66
+ *
67
+ * @param signer - The NEAR signer for client operations
68
+ * @param config - Optional configuration overrides
69
+ */
70
+ constructor(signer, config = {}) {
71
+ this.signer = signer;
72
+ this.config = config;
73
+ this.scheme = SCHEME_EXACT_DIRECT;
74
+ }
75
+ /**
76
+ * Creates a payment payload by executing the transfer.
77
+ *
78
+ * Unlike other schemes where the client creates a signed message for
79
+ * the facilitator to execute, the exact-direct scheme has the client
80
+ * execute the transfer directly. The transaction hash is then used
81
+ * as proof of payment.
82
+ *
83
+ * @param t402Version - The t402 protocol version
84
+ * @param paymentRequirements - The payment requirements
85
+ * @returns Promise resolving to a payment payload with transaction hash
86
+ */
87
+ async createPaymentPayload(t402Version, paymentRequirements) {
88
+ normalizeNetwork(paymentRequirements.network);
89
+ if (!paymentRequirements.asset) {
90
+ throw new Error("Asset (token contract address) is required");
91
+ }
92
+ if (!paymentRequirements.payTo) {
93
+ throw new Error("PayTo address is required");
94
+ }
95
+ if (!paymentRequirements.amount) {
96
+ throw new Error("Amount is required");
97
+ }
98
+ if (!isValidAccountId(paymentRequirements.payTo)) {
99
+ throw new Error(`Invalid recipient account ID: ${paymentRequirements.payTo}`);
100
+ }
101
+ if (!isValidAccountId(this.signer.accountId)) {
102
+ throw new Error(`Invalid sender account ID: ${this.signer.accountId}`);
103
+ }
104
+ const tokenContract = paymentRequirements.asset;
105
+ const recipient = paymentRequirements.payTo;
106
+ const amount = paymentRequirements.amount;
107
+ const ftTransferArgs = {
108
+ receiver_id: recipient,
109
+ amount
110
+ };
111
+ if (this.config.memo) {
112
+ ftTransferArgs.memo = this.config.memo;
113
+ }
114
+ const txHash = await this.signer.signAndSendTransaction(
115
+ tokenContract,
116
+ "ft_transfer",
117
+ ftTransferArgs,
118
+ this.config.gasAmount || DEFAULT_FT_TRANSFER_GAS,
119
+ FT_TRANSFER_DEPOSIT
120
+ );
121
+ const payload = {
122
+ txHash,
123
+ from: this.signer.accountId,
124
+ to: recipient,
125
+ amount
126
+ };
127
+ return {
128
+ t402Version,
129
+ payload
130
+ };
131
+ }
132
+ };
133
+
134
+ // src/exact-direct/client/register.ts
135
+ function registerExactDirectNearClient(client, config) {
136
+ const scheme = new ExactDirectNearClient(config.signer, config.schemeConfig);
137
+ if (config.networks && config.networks.length > 0) {
138
+ config.networks.forEach((network) => {
139
+ client.register(network, scheme);
140
+ });
141
+ } else {
142
+ client.register("near:*", scheme);
143
+ }
144
+ if (config.policies) {
145
+ config.policies.forEach((policy) => {
146
+ client.registerPolicy(policy);
147
+ });
148
+ }
149
+ return client;
150
+ }
151
+ // Annotate the CommonJS export names for ESM import in node:
152
+ 0 && (module.exports = {
153
+ ExactDirectNearClient,
154
+ registerExactDirectNearClient
155
+ });
156
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/exact-direct/client/index.ts","../../../../src/constants.ts","../../../../src/utils.ts","../../../../src/exact-direct/client/scheme.ts","../../../../src/exact-direct/client/register.ts"],"sourcesContent":["/**\n * NEAR Exact-Direct Client Exports\n */\n\nexport { ExactDirectNearClient, type ExactDirectNearClientConfig } from \"./scheme.js\";\nexport { registerExactDirectNearClient, type NearClientConfig } from \"./register.js\";\n","/**\n * NEAR Network Constants\n *\n * This module provides constants for NEAR blockchain integration including:\n * - CAIP-2 network identifiers\n * - RPC endpoints\n * - NEP-141 function names\n * - Default gas amounts\n */\n\n/**\n * CAIP-2 Network Identifiers for NEAR\n */\nexport const NEAR_MAINNET_CAIP2 = \"near:mainnet\";\nexport const NEAR_TESTNET_CAIP2 = \"near:testnet\";\n\n/**\n * Supported NEAR networks\n */\nexport const NEAR_NETWORKS = [NEAR_MAINNET_CAIP2, NEAR_TESTNET_CAIP2] as const;\n\nexport type NearNetwork = (typeof NEAR_NETWORKS)[number];\n\n/**\n * NEAR network IDs (for wallet connection)\n */\nexport const NEAR_NETWORK_IDS: Record<string, string> = {\n [NEAR_MAINNET_CAIP2]: \"mainnet\",\n [NEAR_TESTNET_CAIP2]: \"testnet\",\n};\n\n/**\n * Default RPC endpoints\n */\nexport const NEAR_MAINNET_RPC = \"https://rpc.mainnet.near.org\";\nexport const NEAR_TESTNET_RPC = \"https://rpc.testnet.near.org\";\n\n/**\n * Network RPC endpoint mapping\n */\nexport const NETWORK_RPC_ENDPOINTS: Record<string, string> = {\n [NEAR_MAINNET_CAIP2]: NEAR_MAINNET_RPC,\n [NEAR_TESTNET_CAIP2]: NEAR_TESTNET_RPC,\n};\n\n/**\n * NEP-141 Fungible Token Standard function names\n * @see https://nomicon.io/Standards/Tokens/FungibleToken/Core\n */\nexport const NEP141_FT_TRANSFER = \"ft_transfer\";\nexport const NEP141_FT_BALANCE_OF = \"ft_balance_of\";\nexport const NEP141_STORAGE_DEPOSIT = \"storage_deposit\";\nexport const NEP141_STORAGE_BALANCE_OF = \"storage_balance_of\";\n\n/**\n * Default gas amounts for NEP-141 transfers\n * NEAR gas is measured in TGas (1 TGas = 10^12 gas)\n */\nexport const DEFAULT_FT_TRANSFER_GAS = \"30000000000000\"; // 30 TGas\nexport const DEFAULT_STORAGE_DEPOSIT_GAS = \"10000000000000\"; // 10 TGas\n\n/**\n * Required deposits for NEP-141 operations\n * ft_transfer requires 1 yoctoNEAR attached deposit\n */\nexport const FT_TRANSFER_DEPOSIT = \"1\"; // 1 yoctoNEAR\nexport const DEFAULT_STORAGE_DEPOSIT = \"1250000000000000000000\"; // 0.00125 NEAR\n\n/**\n * Scheme identifier for exact-direct payments\n */\nexport const SCHEME_EXACT_DIRECT = \"exact-direct\";\n\n/**\n * Default timeout for payment validity (in seconds)\n */\nexport const DEFAULT_VALIDITY_DURATION = 3600; // 1 hour\n\n/**\n * Maximum transaction age to accept (in milliseconds)\n */\nexport const MAX_TRANSACTION_AGE = 5 * 60 * 1000; // 5 minutes\n\n/**\n * CAIP-2 namespace for NEAR\n */\nexport const NEAR_CAIP2_NAMESPACE = \"near\";\n","/**\n * NEAR Utility Functions\n *\n * Helper functions for NEAR address validation, network normalization,\n * and RPC interactions.\n */\n\nimport { NEAR_CAIP2_NAMESPACE, NETWORK_RPC_ENDPOINTS, type NearNetwork } from \"./constants.js\";\nimport type {\n NearRpcRequest,\n NearRpcResponse,\n TransactionResult,\n FtTransferArgs,\n} from \"./types.js\";\n\n/**\n * Normalize a network identifier to CAIP-2 format\n * @param network - Network identifier (e.g., \"mainnet\", \"near:mainnet\")\n * @returns CAIP-2 formatted network identifier\n */\nexport function normalizeNetwork(network: string): NearNetwork {\n // Already in CAIP-2 format\n if (network.startsWith(`${NEAR_CAIP2_NAMESPACE}:`)) {\n return network as NearNetwork;\n }\n // Convert shorthand to CAIP-2\n return `${NEAR_CAIP2_NAMESPACE}:${network}` as NearNetwork;\n}\n\n/**\n * Extract network ID from CAIP-2 identifier\n * @param network - CAIP-2 network identifier\n * @returns Network ID (e.g., \"mainnet\")\n */\nexport function extractNetworkId(network: string): string {\n if (network.includes(\":\")) {\n return network.split(\":\")[1];\n }\n return network;\n}\n\n/**\n * Validate a NEAR account ID\n * NEAR account IDs must:\n * - Be 2-64 characters\n * - Contain only lowercase alphanumeric, underscores, hyphens\n * - Not start with a hyphen or underscore\n * @param accountId - Account ID to validate\n * @returns Whether the account ID is valid\n */\nexport function isValidAccountId(accountId: string): boolean {\n if (!accountId || accountId.length < 2 || accountId.length > 64) {\n return false;\n }\n // NEAR account ID regex\n const regex = /^[a-z0-9]([a-z0-9_-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9_-]*[a-z0-9])?)*$/;\n return regex.test(accountId);\n}\n\n/**\n * Get RPC endpoint for a network\n * @param network - CAIP-2 network identifier\n * @returns RPC endpoint URL\n */\nexport function getRpcEndpoint(network: string): string {\n const normalizedNetwork = normalizeNetwork(network);\n return NETWORK_RPC_ENDPOINTS[normalizedNetwork] || NETWORK_RPC_ENDPOINTS[\"near:mainnet\"];\n}\n\n/**\n * Make a JSON-RPC call to NEAR\n * @param network - CAIP-2 network identifier\n * @param method - RPC method name\n * @param params - Method parameters\n * @returns RPC response result\n */\nexport async function rpcCall<T>(\n network: string,\n method: string,\n params: NearRpcRequest[\"params\"],\n): Promise<T> {\n const endpoint = getRpcEndpoint(network);\n\n const request: NearRpcRequest = {\n jsonrpc: \"2.0\",\n id: `t402-${Date.now()}`,\n method,\n params,\n };\n\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n });\n\n const data = (await response.json()) as NearRpcResponse<T>;\n\n if (data.error) {\n throw new Error(`NEAR RPC error: ${data.error.message}`);\n }\n\n return data.result as T;\n}\n\n/**\n * Query a transaction by hash\n * @param network - CAIP-2 network identifier\n * @param txHash - Transaction hash\n * @param senderAccountId - Sender account ID\n * @returns Transaction result\n */\nexport async function queryTransaction(\n network: string,\n txHash: string,\n senderAccountId: string,\n): Promise<TransactionResult> {\n return rpcCall<TransactionResult>(network, \"tx\", [txHash, senderAccountId]);\n}\n\n/**\n * Query token balance\n * @param network - CAIP-2 network identifier\n * @param accountId - Account to query\n * @param tokenContract - Token contract address\n * @returns Balance as bigint\n */\nexport async function queryTokenBalance(\n network: string,\n accountId: string,\n tokenContract: string,\n): Promise<bigint> {\n try {\n const result = await rpcCall<{ result: number[] }>(network, \"query\", {\n request_type: \"call_function\",\n finality: \"final\",\n account_id: tokenContract,\n method_name: \"ft_balance_of\",\n args_base64: btoa(JSON.stringify({ account_id: accountId })),\n });\n\n // Result is a byte array representing the JSON response\n const bytes = new Uint8Array(result.result);\n const text = new TextDecoder().decode(bytes);\n // Remove quotes from JSON string response\n const balance = text.replace(/\"/g, \"\");\n return BigInt(balance);\n } catch (error) {\n console.error(\"Error fetching token balance:\", error);\n return 0n;\n }\n}\n\n/**\n * Parse ft_transfer args from base64 encoded string\n * @param argsBase64 - Base64 encoded JSON arguments\n * @returns Parsed ft_transfer arguments\n */\nexport function parseFtTransferArgs(argsBase64: string): FtTransferArgs | null {\n try {\n const argsJson = atob(argsBase64);\n return JSON.parse(argsJson) as FtTransferArgs;\n } catch {\n // Try parsing as raw JSON (some nodes return it differently)\n try {\n return JSON.parse(argsBase64) as FtTransferArgs;\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Check if a transaction succeeded\n * @param status - Transaction status\n * @returns Whether the transaction succeeded\n */\nexport function isTransactionSuccessful(status: {\n SuccessValue?: string;\n Failure?: unknown;\n}): boolean {\n return status.SuccessValue !== undefined && status.Failure === undefined;\n}\n\n/**\n * Format amount for display (with decimals)\n * @param amount - Amount in smallest units\n * @param decimals - Number of decimal places\n * @returns Formatted amount string\n */\nexport function formatAmount(amount: bigint, decimals: number): string {\n const divisor = BigInt(10 ** decimals);\n const whole = amount / divisor;\n const remainder = amount % divisor;\n const decimal = remainder.toString().padStart(decimals, \"0\").slice(0, 2);\n return `${whole}.${decimal}`;\n}\n\n/**\n * Convert decimal amount to token units\n * @param decimalAmount - Amount with decimals (e.g., \"1.50\")\n * @param decimals - Token decimals\n * @returns Amount in smallest units\n */\nexport function toTokenUnits(decimalAmount: string | number, decimals: number): bigint {\n const amount = typeof decimalAmount === \"string\" ? parseFloat(decimalAmount) : decimalAmount;\n if (isNaN(amount)) {\n throw new Error(`Invalid amount: ${decimalAmount}`);\n }\n const multiplier = 10 ** decimals;\n return BigInt(Math.floor(amount * multiplier));\n}\n","/**\n * NEAR Client Scheme Implementation - Exact Direct\n *\n * Creates payment payloads for NEAR NEP-141 transfers using the exact-direct scheme.\n * In this scheme, the client executes the ft_transfer directly and provides\n * the transaction hash as proof of payment.\n */\n\nimport type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@t402/core/types\";\nimport type { ClientNearSigner, ExactDirectNearPayload } from \"../../types.js\";\nimport {\n SCHEME_EXACT_DIRECT,\n DEFAULT_FT_TRANSFER_GAS,\n FT_TRANSFER_DEPOSIT,\n} from \"../../constants.js\";\nimport { normalizeNetwork, isValidAccountId } from \"../../utils.js\";\n\n/**\n * Configuration for ExactDirectNearClient\n */\nexport interface ExactDirectNearClientConfig {\n /** Override the gas amount for ft_transfer */\n gasAmount?: string;\n /** Optional memo to include in the transfer */\n memo?: string;\n}\n\n/**\n * NEAR client implementation for the Exact-Direct payment scheme.\n *\n * Executes NEP-141 ft_transfer and returns the transaction hash as proof.\n */\nexport class ExactDirectNearClient implements SchemeNetworkClient {\n readonly scheme = SCHEME_EXACT_DIRECT;\n\n /**\n * Creates a new ExactDirectNearScheme instance.\n *\n * @param signer - The NEAR signer for client operations\n * @param config - Optional configuration overrides\n */\n constructor(\n private readonly signer: ClientNearSigner,\n private readonly config: ExactDirectNearClientConfig = {},\n ) {}\n\n /**\n * Creates a payment payload by executing the transfer.\n *\n * Unlike other schemes where the client creates a signed message for\n * the facilitator to execute, the exact-direct scheme has the client\n * execute the transfer directly. The transaction hash is then used\n * as proof of payment.\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload with transaction hash\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"t402Version\" | \"payload\">> {\n // Normalize and validate network\n normalizeNetwork(paymentRequirements.network);\n\n // Validate required fields\n if (!paymentRequirements.asset) {\n throw new Error(\"Asset (token contract address) is required\");\n }\n if (!paymentRequirements.payTo) {\n throw new Error(\"PayTo address is required\");\n }\n if (!paymentRequirements.amount) {\n throw new Error(\"Amount is required\");\n }\n\n // Validate addresses\n if (!isValidAccountId(paymentRequirements.payTo)) {\n throw new Error(`Invalid recipient account ID: ${paymentRequirements.payTo}`);\n }\n if (!isValidAccountId(this.signer.accountId)) {\n throw new Error(`Invalid sender account ID: ${this.signer.accountId}`);\n }\n\n const tokenContract = paymentRequirements.asset;\n const recipient = paymentRequirements.payTo;\n const amount = paymentRequirements.amount;\n\n // Build ft_transfer arguments\n const ftTransferArgs: Record<string, unknown> = {\n receiver_id: recipient,\n amount: amount,\n };\n\n if (this.config.memo) {\n ftTransferArgs.memo = this.config.memo;\n }\n\n // Execute the transfer\n const txHash = await this.signer.signAndSendTransaction(\n tokenContract,\n \"ft_transfer\",\n ftTransferArgs,\n this.config.gasAmount || DEFAULT_FT_TRANSFER_GAS,\n FT_TRANSFER_DEPOSIT,\n );\n\n // Build the payload\n const payload: ExactDirectNearPayload = {\n txHash,\n from: this.signer.accountId,\n to: recipient,\n amount: amount,\n };\n\n return {\n t402Version,\n payload,\n };\n }\n}\n","/**\n * Registration function for NEAR Exact-Direct client\n */\n\nimport { t402Client, PaymentPolicy } from \"@t402/core/client\";\nimport { Network } from \"@t402/core/types\";\nimport type { ClientNearSigner } from \"../../types.js\";\nimport { ExactDirectNearClient, type ExactDirectNearClientConfig } from \"./scheme.js\";\n\n/**\n * Configuration options for registering NEAR schemes to a t402Client\n */\nexport interface NearClientConfig {\n /**\n * The NEAR signer to use for creating payment payloads\n */\n signer: ClientNearSigner;\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 (near:*)\n */\n networks?: Network[];\n\n /**\n * Optional scheme configuration (gas amounts, memo)\n */\n schemeConfig?: ExactDirectNearClientConfig;\n}\n\n/**\n * Registers NEAR exact-direct payment schemes to a t402Client instance.\n *\n * @param client - The t402Client instance to register schemes to\n * @param config - Configuration for NEAR client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactDirectNearClient } from \"@t402/near/exact-direct/client\";\n * import { t402Client } from \"@t402/core/client\";\n *\n * const client = new t402Client();\n * registerExactDirectNearClient(client, {\n * signer: {\n * accountId: \"alice.near\",\n * signAndSendTransaction: async (receiverId, methodName, args, gas, deposit) => {\n * // Sign and send using wallet\n * return txHash;\n * }\n * }\n * });\n * ```\n */\nexport function registerExactDirectNearClient(\n client: t402Client,\n config: NearClientConfig,\n): t402Client {\n const scheme = new ExactDirectNearClient(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 NEAR networks\n client.register(\"near:*\", 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":"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","names":[]}
@@ -0,0 +1,114 @@
1
+ import { SchemeNetworkFacilitator, Network, PaymentPayload, PaymentRequirements, VerifyResponse, SettleResponse } from '@t402/core/types';
2
+ import { f as FacilitatorNearSigner } from '../../types-Ca7ztL_f.js';
3
+ import { t402Facilitator } from '@t402/core/facilitator';
4
+
5
+ /**
6
+ * NEAR Facilitator Scheme Implementation - Exact Direct
7
+ *
8
+ * Verifies and settles NEAR NEP-141 payments using the exact-direct scheme.
9
+ * The facilitator verifies that the client's transaction was successful
10
+ * and matches the payment requirements.
11
+ */
12
+
13
+ /**
14
+ * Configuration for ExactDirectNearFacilitator
15
+ */
16
+ interface ExactDirectNearFacilitatorConfig {
17
+ /** Maximum age of a transaction to accept (in milliseconds) */
18
+ maxTransactionAge?: number;
19
+ /** Duration to cache used transaction hashes (in milliseconds) */
20
+ usedTxCacheDuration?: number;
21
+ }
22
+ /**
23
+ * NEAR facilitator implementation for the Exact-Direct payment scheme.
24
+ * Verifies transaction proofs and confirms payments.
25
+ */
26
+ declare class ExactDirectNearFacilitator implements SchemeNetworkFacilitator {
27
+ private readonly signer;
28
+ readonly scheme = "exact-direct";
29
+ readonly caipFamily = "near:*";
30
+ private readonly config;
31
+ private usedTxs;
32
+ constructor(signer: FacilitatorNearSigner, config?: ExactDirectNearFacilitatorConfig);
33
+ /**
34
+ * Get extra data for a supported kind
35
+ */
36
+ getExtra(network: Network): Record<string, unknown> | undefined;
37
+ /**
38
+ * Get signer addresses for a network
39
+ */
40
+ getSigners(network: Network): string[];
41
+ /**
42
+ * Verify a payment payload
43
+ */
44
+ verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
45
+ /**
46
+ * Settle a payment - for exact-direct, the transfer is already complete
47
+ */
48
+ settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
49
+ /**
50
+ * Check if a transaction has been used
51
+ */
52
+ private isTxUsed;
53
+ /**
54
+ * Mark a transaction as used
55
+ */
56
+ private markTxUsed;
57
+ /**
58
+ * Start the cleanup interval for used transactions
59
+ */
60
+ private startCleanupInterval;
61
+ }
62
+
63
+ /**
64
+ * Registration function for NEAR Exact-Direct facilitator
65
+ */
66
+
67
+ /**
68
+ * Configuration options for registering NEAR schemes to a t402Facilitator
69
+ */
70
+ interface NearFacilitatorConfig {
71
+ /**
72
+ * The NEAR signer for facilitator operations (verify and settle)
73
+ */
74
+ signer: FacilitatorNearSigner;
75
+ /**
76
+ * Networks to register (single network or array of networks)
77
+ * Examples: "near:mainnet", ["near:mainnet", "near:testnet"]
78
+ */
79
+ networks: Network | Network[];
80
+ /**
81
+ * Optional scheme configuration
82
+ */
83
+ schemeConfig?: ExactDirectNearFacilitatorConfig;
84
+ }
85
+ /**
86
+ * Registers NEAR exact-direct payment schemes to a t402Facilitator instance.
87
+ *
88
+ * @param facilitator - The t402Facilitator instance to register schemes to
89
+ * @param config - Configuration for NEAR facilitator registration
90
+ * @returns The facilitator instance for chaining
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { registerExactDirectNearFacilitator } from "@t402/near/exact-direct/facilitator";
95
+ * import { t402Facilitator } from "@t402/core/facilitator";
96
+ *
97
+ * const facilitator = new t402Facilitator();
98
+ *
99
+ * // Single network
100
+ * registerExactDirectNearFacilitator(facilitator, {
101
+ * signer: myNearSigner,
102
+ * networks: "near:mainnet"
103
+ * });
104
+ *
105
+ * // Multiple networks
106
+ * registerExactDirectNearFacilitator(facilitator, {
107
+ * signer: myNearSigner,
108
+ * networks: ["near:mainnet", "near:testnet"]
109
+ * });
110
+ * ```
111
+ */
112
+ declare function registerExactDirectNearFacilitator(facilitator: t402Facilitator, config: NearFacilitatorConfig): t402Facilitator;
113
+
114
+ export { ExactDirectNearFacilitator, type ExactDirectNearFacilitatorConfig, type NearFacilitatorConfig, registerExactDirectNearFacilitator };