@routexcc/chain-stellar 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thalaxis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @routexcc/chain-stellar
2
+
3
+ Stellar chain adapter for Routex.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @routexcc/chain-stellar
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { createStellarAdapter } from "@routexcc/chain-stellar";
15
+ import { Horizon } from "@stellar/stellar-sdk";
16
+
17
+ const horizonClient = new Horizon.Server("https://horizon.stellar.org");
18
+ const adapter = createStellarAdapter(horizonClient);
19
+ ```
20
+
21
+ ## Documentation
22
+
23
+ See the [main repo README](https://github.com/routexcc/routex) for full documentation.
24
+
25
+ Part of the [Routex](https://github.com/routexcc/routex) monorepo by [Thalaxis](https://thalaxis.com).
26
+
27
+ ## License
28
+
29
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,134 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULT_USDC_ISSUER: () => DEFAULT_USDC_ISSUER,
24
+ STELLAR_FINALITY_MS: () => STELLAR_FINALITY_MS,
25
+ StellarAdapter: () => StellarAdapter
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/StellarAdapter.ts
30
+ var import_core = require("@routexcc/core");
31
+ var STELLAR_FINALITY_MS = 5e3;
32
+ var DEFAULT_USDC_ISSUER = "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN";
33
+ var STELLAR_DECIMALS = 7;
34
+ var StellarAdapter = class {
35
+ chainId = "stellar";
36
+ rpcClient;
37
+ usdcAssetCode;
38
+ usdcAssetIssuer;
39
+ // BigInt: XLM price in USD (6-decimal precision)
40
+ xlmPriceUsd;
41
+ constructor(config) {
42
+ this.rpcClient = config.rpcClient;
43
+ this.usdcAssetCode = config.usdcAssetCode ?? "USDC";
44
+ this.usdcAssetIssuer = config.usdcAssetIssuer ?? DEFAULT_USDC_ISSUER;
45
+ this.xlmPriceUsd = config.xlmPriceUsd;
46
+ }
47
+ /**
48
+ * Query USDC trustline balance for a Stellar account.
49
+ */
50
+ async getBalance(address, _token) {
51
+ const account = await this.rpcClient.getAccount(address);
52
+ const usdcBalance = account.balances.find(
53
+ (b) => b.asset_code === this.usdcAssetCode && b.asset_issuer === this.usdcAssetIssuer
54
+ );
55
+ const balanceStr = usdcBalance?.balance ?? "0";
56
+ const balance = stellarAmountToBigInt(balanceStr);
57
+ return {
58
+ chainId: this.chainId,
59
+ token: `${this.usdcAssetCode}:${this.usdcAssetIssuer}`,
60
+ // BigInt: token balance in smallest unit (6 decimals)
61
+ balance,
62
+ timestamp: Date.now()
63
+ };
64
+ }
65
+ /**
66
+ * Estimate fee using Stellar fee_stats endpoint.
67
+ * Uses p50 fee from fee_charged as the estimate.
68
+ */
69
+ async estimateFee(payment) {
70
+ const feeStats = await this.rpcClient.getFeeStats();
71
+ const feeStroops = BigInt(feeStats.fee_charged.p50);
72
+ const feeUsd = feeStroops * this.xlmPriceUsd / 10n ** BigInt(STELLAR_DECIMALS);
73
+ return {
74
+ chainId: payment.chainId,
75
+ // BigInt: fee in stroops
76
+ feeAmount: feeStroops,
77
+ // BigInt: fee in USD with 6-decimal precision
78
+ feeUsd,
79
+ finalityMs: STELLAR_FINALITY_MS,
80
+ confidence: "high",
81
+ timestamp: Date.now()
82
+ };
83
+ }
84
+ /**
85
+ * Construct a signed Stellar payment operation envelope.
86
+ * INV-1: Never accesses signer private keys — only calls signer.sign().
87
+ * INV-2: Recipient in payload matches payment requirement.
88
+ */
89
+ async buildPaymentPayload(payment, signer) {
90
+ const envelope = JSON.stringify({
91
+ type: "stellar_payment",
92
+ source: signer.address,
93
+ destination: payment.payTo,
94
+ // BigInt: amount serialized for Stellar
95
+ amount: payment.amount.toString(),
96
+ asset: {
97
+ code: this.usdcAssetCode,
98
+ issuer: this.usdcAssetIssuer
99
+ },
100
+ nonce: Date.now()
101
+ });
102
+ let signature;
103
+ try {
104
+ signature = await signer.sign(new TextEncoder().encode(envelope));
105
+ } catch (err) {
106
+ const detail = err instanceof Error ? err.message : "Unknown signing error";
107
+ throw new import_core.PaymentConstructionError(this.chainId, "sign", detail);
108
+ }
109
+ const signatureHex = Array.from(signature).map((b) => b.toString(16).padStart(2, "0")).join("");
110
+ return {
111
+ chainId: this.chainId,
112
+ to: payment.payTo,
113
+ // BigInt: token amount in smallest unit
114
+ amount: payment.amount,
115
+ token: `${this.usdcAssetCode}:${this.usdcAssetIssuer}`,
116
+ data: JSON.stringify({ envelope, signature: signatureHex })
117
+ };
118
+ }
119
+ /** Get expected finality time for Stellar (~5 seconds). */
120
+ getFinality() {
121
+ return STELLAR_FINALITY_MS;
122
+ }
123
+ };
124
+ function stellarAmountToBigInt(amount) {
125
+ const [whole = "0", frac = ""] = amount.split(".");
126
+ const paddedFrac = frac.padEnd(6, "0").slice(0, 6);
127
+ return BigInt(whole) * 1000000n + BigInt(paddedFrac);
128
+ }
129
+ // Annotate the CommonJS export names for ESM import in node:
130
+ 0 && (module.exports = {
131
+ DEFAULT_USDC_ISSUER,
132
+ STELLAR_FINALITY_MS,
133
+ StellarAdapter
134
+ });
@@ -0,0 +1,81 @@
1
+ import { ChainAdapter, TokenBalance, AcceptedPayment, FeeEstimate, Signer, PaymentPayload } from '@routexcc/core';
2
+
3
+ /**
4
+ * Stellar chain adapter for Routex.
5
+ * Uses a StellarRpcClient interface (compatible with @stellar/stellar-sdk).
6
+ * Finality: ~5000ms (ledger close time).
7
+ */
8
+
9
+ /** Balance entry from Stellar account query. */
10
+ interface StellarBalance {
11
+ readonly asset_type: string;
12
+ readonly asset_code?: string;
13
+ readonly asset_issuer?: string;
14
+ readonly balance: string;
15
+ }
16
+ /** Stellar account response shape. */
17
+ interface StellarAccountResponse {
18
+ readonly balances: readonly StellarBalance[];
19
+ }
20
+ /** Stellar fee stats response shape. */
21
+ interface StellarFeeStats {
22
+ readonly fee_charged: {
23
+ readonly p50: string;
24
+ };
25
+ readonly last_ledger_base_fee: string;
26
+ }
27
+ /**
28
+ * Minimal interface for Stellar RPC operations.
29
+ * Compatible with @stellar/stellar-sdk Server class.
30
+ */
31
+ interface StellarRpcClient {
32
+ getAccount(accountId: string): Promise<StellarAccountResponse>;
33
+ getFeeStats(): Promise<StellarFeeStats>;
34
+ }
35
+ /** Configuration for the Stellar adapter. */
36
+ interface StellarAdapterConfig {
37
+ /** Injected Stellar RPC client. */
38
+ readonly rpcClient: StellarRpcClient;
39
+ /** USDC asset code (default: 'USDC'). */
40
+ readonly usdcAssetCode?: string;
41
+ /** USDC asset issuer public key. */
42
+ readonly usdcAssetIssuer?: string;
43
+ /** XLM price in USD (6-decimal precision bigint). */
44
+ readonly xlmPriceUsd: bigint;
45
+ }
46
+ /** Stellar finality ~5 seconds (ledger close time). */
47
+ declare const STELLAR_FINALITY_MS = 5000;
48
+ /** Default USDC issuer on Stellar (Centre). */
49
+ declare const DEFAULT_USDC_ISSUER = "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN";
50
+ /**
51
+ * Stellar chain adapter implementation.
52
+ * Reads USDC trustline balances, estimates fees via fee_stats,
53
+ * and constructs signed payment operation envelopes.
54
+ */
55
+ declare class StellarAdapter implements ChainAdapter {
56
+ readonly chainId: "stellar";
57
+ private readonly rpcClient;
58
+ private readonly usdcAssetCode;
59
+ private readonly usdcAssetIssuer;
60
+ private readonly xlmPriceUsd;
61
+ constructor(config: StellarAdapterConfig);
62
+ /**
63
+ * Query USDC trustline balance for a Stellar account.
64
+ */
65
+ getBalance(address: string, _token: string): Promise<TokenBalance>;
66
+ /**
67
+ * Estimate fee using Stellar fee_stats endpoint.
68
+ * Uses p50 fee from fee_charged as the estimate.
69
+ */
70
+ estimateFee(payment: AcceptedPayment): Promise<FeeEstimate>;
71
+ /**
72
+ * Construct a signed Stellar payment operation envelope.
73
+ * INV-1: Never accesses signer private keys — only calls signer.sign().
74
+ * INV-2: Recipient in payload matches payment requirement.
75
+ */
76
+ buildPaymentPayload(payment: AcceptedPayment, signer: Signer): Promise<PaymentPayload>;
77
+ /** Get expected finality time for Stellar (~5 seconds). */
78
+ getFinality(): number;
79
+ }
80
+
81
+ export { DEFAULT_USDC_ISSUER, STELLAR_FINALITY_MS, type StellarAccountResponse, StellarAdapter, type StellarAdapterConfig, type StellarBalance, type StellarFeeStats, type StellarRpcClient };
@@ -0,0 +1,81 @@
1
+ import { ChainAdapter, TokenBalance, AcceptedPayment, FeeEstimate, Signer, PaymentPayload } from '@routexcc/core';
2
+
3
+ /**
4
+ * Stellar chain adapter for Routex.
5
+ * Uses a StellarRpcClient interface (compatible with @stellar/stellar-sdk).
6
+ * Finality: ~5000ms (ledger close time).
7
+ */
8
+
9
+ /** Balance entry from Stellar account query. */
10
+ interface StellarBalance {
11
+ readonly asset_type: string;
12
+ readonly asset_code?: string;
13
+ readonly asset_issuer?: string;
14
+ readonly balance: string;
15
+ }
16
+ /** Stellar account response shape. */
17
+ interface StellarAccountResponse {
18
+ readonly balances: readonly StellarBalance[];
19
+ }
20
+ /** Stellar fee stats response shape. */
21
+ interface StellarFeeStats {
22
+ readonly fee_charged: {
23
+ readonly p50: string;
24
+ };
25
+ readonly last_ledger_base_fee: string;
26
+ }
27
+ /**
28
+ * Minimal interface for Stellar RPC operations.
29
+ * Compatible with @stellar/stellar-sdk Server class.
30
+ */
31
+ interface StellarRpcClient {
32
+ getAccount(accountId: string): Promise<StellarAccountResponse>;
33
+ getFeeStats(): Promise<StellarFeeStats>;
34
+ }
35
+ /** Configuration for the Stellar adapter. */
36
+ interface StellarAdapterConfig {
37
+ /** Injected Stellar RPC client. */
38
+ readonly rpcClient: StellarRpcClient;
39
+ /** USDC asset code (default: 'USDC'). */
40
+ readonly usdcAssetCode?: string;
41
+ /** USDC asset issuer public key. */
42
+ readonly usdcAssetIssuer?: string;
43
+ /** XLM price in USD (6-decimal precision bigint). */
44
+ readonly xlmPriceUsd: bigint;
45
+ }
46
+ /** Stellar finality ~5 seconds (ledger close time). */
47
+ declare const STELLAR_FINALITY_MS = 5000;
48
+ /** Default USDC issuer on Stellar (Centre). */
49
+ declare const DEFAULT_USDC_ISSUER = "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN";
50
+ /**
51
+ * Stellar chain adapter implementation.
52
+ * Reads USDC trustline balances, estimates fees via fee_stats,
53
+ * and constructs signed payment operation envelopes.
54
+ */
55
+ declare class StellarAdapter implements ChainAdapter {
56
+ readonly chainId: "stellar";
57
+ private readonly rpcClient;
58
+ private readonly usdcAssetCode;
59
+ private readonly usdcAssetIssuer;
60
+ private readonly xlmPriceUsd;
61
+ constructor(config: StellarAdapterConfig);
62
+ /**
63
+ * Query USDC trustline balance for a Stellar account.
64
+ */
65
+ getBalance(address: string, _token: string): Promise<TokenBalance>;
66
+ /**
67
+ * Estimate fee using Stellar fee_stats endpoint.
68
+ * Uses p50 fee from fee_charged as the estimate.
69
+ */
70
+ estimateFee(payment: AcceptedPayment): Promise<FeeEstimate>;
71
+ /**
72
+ * Construct a signed Stellar payment operation envelope.
73
+ * INV-1: Never accesses signer private keys — only calls signer.sign().
74
+ * INV-2: Recipient in payload matches payment requirement.
75
+ */
76
+ buildPaymentPayload(payment: AcceptedPayment, signer: Signer): Promise<PaymentPayload>;
77
+ /** Get expected finality time for Stellar (~5 seconds). */
78
+ getFinality(): number;
79
+ }
80
+
81
+ export { DEFAULT_USDC_ISSUER, STELLAR_FINALITY_MS, type StellarAccountResponse, StellarAdapter, type StellarAdapterConfig, type StellarBalance, type StellarFeeStats, type StellarRpcClient };
package/dist/index.mjs ADDED
@@ -0,0 +1,105 @@
1
+ // src/StellarAdapter.ts
2
+ import { PaymentConstructionError } from "@routexcc/core";
3
+ var STELLAR_FINALITY_MS = 5e3;
4
+ var DEFAULT_USDC_ISSUER = "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN";
5
+ var STELLAR_DECIMALS = 7;
6
+ var StellarAdapter = class {
7
+ chainId = "stellar";
8
+ rpcClient;
9
+ usdcAssetCode;
10
+ usdcAssetIssuer;
11
+ // BigInt: XLM price in USD (6-decimal precision)
12
+ xlmPriceUsd;
13
+ constructor(config) {
14
+ this.rpcClient = config.rpcClient;
15
+ this.usdcAssetCode = config.usdcAssetCode ?? "USDC";
16
+ this.usdcAssetIssuer = config.usdcAssetIssuer ?? DEFAULT_USDC_ISSUER;
17
+ this.xlmPriceUsd = config.xlmPriceUsd;
18
+ }
19
+ /**
20
+ * Query USDC trustline balance for a Stellar account.
21
+ */
22
+ async getBalance(address, _token) {
23
+ const account = await this.rpcClient.getAccount(address);
24
+ const usdcBalance = account.balances.find(
25
+ (b) => b.asset_code === this.usdcAssetCode && b.asset_issuer === this.usdcAssetIssuer
26
+ );
27
+ const balanceStr = usdcBalance?.balance ?? "0";
28
+ const balance = stellarAmountToBigInt(balanceStr);
29
+ return {
30
+ chainId: this.chainId,
31
+ token: `${this.usdcAssetCode}:${this.usdcAssetIssuer}`,
32
+ // BigInt: token balance in smallest unit (6 decimals)
33
+ balance,
34
+ timestamp: Date.now()
35
+ };
36
+ }
37
+ /**
38
+ * Estimate fee using Stellar fee_stats endpoint.
39
+ * Uses p50 fee from fee_charged as the estimate.
40
+ */
41
+ async estimateFee(payment) {
42
+ const feeStats = await this.rpcClient.getFeeStats();
43
+ const feeStroops = BigInt(feeStats.fee_charged.p50);
44
+ const feeUsd = feeStroops * this.xlmPriceUsd / 10n ** BigInt(STELLAR_DECIMALS);
45
+ return {
46
+ chainId: payment.chainId,
47
+ // BigInt: fee in stroops
48
+ feeAmount: feeStroops,
49
+ // BigInt: fee in USD with 6-decimal precision
50
+ feeUsd,
51
+ finalityMs: STELLAR_FINALITY_MS,
52
+ confidence: "high",
53
+ timestamp: Date.now()
54
+ };
55
+ }
56
+ /**
57
+ * Construct a signed Stellar payment operation envelope.
58
+ * INV-1: Never accesses signer private keys — only calls signer.sign().
59
+ * INV-2: Recipient in payload matches payment requirement.
60
+ */
61
+ async buildPaymentPayload(payment, signer) {
62
+ const envelope = JSON.stringify({
63
+ type: "stellar_payment",
64
+ source: signer.address,
65
+ destination: payment.payTo,
66
+ // BigInt: amount serialized for Stellar
67
+ amount: payment.amount.toString(),
68
+ asset: {
69
+ code: this.usdcAssetCode,
70
+ issuer: this.usdcAssetIssuer
71
+ },
72
+ nonce: Date.now()
73
+ });
74
+ let signature;
75
+ try {
76
+ signature = await signer.sign(new TextEncoder().encode(envelope));
77
+ } catch (err) {
78
+ const detail = err instanceof Error ? err.message : "Unknown signing error";
79
+ throw new PaymentConstructionError(this.chainId, "sign", detail);
80
+ }
81
+ const signatureHex = Array.from(signature).map((b) => b.toString(16).padStart(2, "0")).join("");
82
+ return {
83
+ chainId: this.chainId,
84
+ to: payment.payTo,
85
+ // BigInt: token amount in smallest unit
86
+ amount: payment.amount,
87
+ token: `${this.usdcAssetCode}:${this.usdcAssetIssuer}`,
88
+ data: JSON.stringify({ envelope, signature: signatureHex })
89
+ };
90
+ }
91
+ /** Get expected finality time for Stellar (~5 seconds). */
92
+ getFinality() {
93
+ return STELLAR_FINALITY_MS;
94
+ }
95
+ };
96
+ function stellarAmountToBigInt(amount) {
97
+ const [whole = "0", frac = ""] = amount.split(".");
98
+ const paddedFrac = frac.padEnd(6, "0").slice(0, 6);
99
+ return BigInt(whole) * 1000000n + BigInt(paddedFrac);
100
+ }
101
+ export {
102
+ DEFAULT_USDC_ISSUER,
103
+ STELLAR_FINALITY_MS,
104
+ StellarAdapter
105
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@routexcc/chain-stellar",
3
+ "version": "1.0.0",
4
+ "description": "Stellar chain adapter for Routex",
5
+ "license": "MIT",
6
+ "author": "Thalaxis <opensource@thalaxis.com> (https://thalaxis.com)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/routexcc/routex.git",
10
+ "directory": "packages/chain-stellar"
11
+ },
12
+ "homepage": "https://github.com/routexcc/routex#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/routexcc/routex/issues"
15
+ },
16
+ "keywords": [
17
+ "x402",
18
+ "stellar",
19
+ "chain-adapter",
20
+ "routex"
21
+ ],
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.mjs",
27
+ "require": "./dist/index.cjs"
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.mjs",
32
+ "types": "./dist/index.d.ts",
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@routexcc/core": "1.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsup": "^8.4.0",
44
+ "typescript": "^5.7.0",
45
+ "vitest": "^3.0.0",
46
+ "@vitest/coverage-v8": "^3.0.0",
47
+ "@routexcc/test-utils": "0.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean --no-sourcemap",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vitest run",
53
+ "test:coverage": "vitest run --coverage",
54
+ "clean": "rm -rf dist coverage"
55
+ }
56
+ }