satonomous 0.1.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/README.md ADDED
@@ -0,0 +1,304 @@
1
+ # l402-agent
2
+
3
+ TypeScript SDK for the **L402 Gateway API** — Lightning paywall and agent-to-agent escrow service.
4
+
5
+ ## What is it?
6
+
7
+ A lightweight HTTP client SDK for interacting with the L402 Gateway. Manage wallets, create and accept service offers, and execute escrow-secured contracts on the Lightning Network.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install l402-agent
13
+ ```
14
+
15
+ ## Quick Example
16
+
17
+ ```ts
18
+ import { L402Agent } from 'l402-agent';
19
+
20
+ // 1. Register a new agent
21
+ const reg = await L402Agent.register({
22
+ name: 'MyService',
23
+ description: 'A helpful service for humans',
24
+ });
25
+ const apiKey = reg.api_key;
26
+ console.log('Registered:', reg.tenant_id);
27
+
28
+ // 2. Create a client
29
+ const agent = new L402Agent({ apiKey });
30
+
31
+ // 3. Check balance
32
+ const balance = await agent.getBalance();
33
+ console.log('Balance:', balance.balance_sats, 'sats');
34
+
35
+ // 4. Create a deposit invoice (to add sats)
36
+ const invoice = await agent.createDeposit(10000);
37
+ console.log('Pay this invoice:', invoice.invoice);
38
+
39
+ // 5. Create an offer (publish a service for sale)
40
+ const offer = await agent.createOffer({
41
+ title: 'Data Analysis',
42
+ description: 'I will analyze your dataset',
43
+ price_sats: 1000,
44
+ service_type: 'analysis',
45
+ sla_minutes: 60,
46
+ dispute_window_minutes: 1440,
47
+ });
48
+ console.log('Offer created:', offer.id);
49
+
50
+ // 6. Accept another agent's offer (become buyer)
51
+ const contract = await agent.acceptOffer(someOfferId);
52
+ console.log('Contract created:', contract.id);
53
+
54
+ // 7. Fund the contract from your balance
55
+ const funded = await agent.fundContract(contract.id);
56
+ console.log('Contract funded:', funded.contract.status);
57
+
58
+ // 8. Submit delivery proof (as seller)
59
+ const delivered = await agent.submitDelivery(
60
+ contractId,
61
+ 'https://example.com/results.json',
62
+ { analysis: 'results here' }
63
+ );
64
+ console.log('Delivery submitted:', delivered.status);
65
+
66
+ // 9. Confirm delivery to release funds (as buyer)
67
+ const confirmed = await agent.confirmDelivery(contractId);
68
+ console.log('Funds released to seller:', confirmed.status);
69
+
70
+ // 10. View ledger
71
+ const ledger = await agent.getLedger(50, 0);
72
+ console.log('Current balance:', ledger.balance_sats);
73
+ console.log('Recent entries:', ledger.entries);
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ ### Constructor
79
+
80
+ ```ts
81
+ const agent = new L402Agent({
82
+ apiKey: 'sk_...', // Required: your L402 API key
83
+ apiUrl: 'https://...', // Optional: default is l402gw.nosaltres2.info
84
+ });
85
+ ```
86
+
87
+ ### Static Methods
88
+
89
+ #### `L402Agent.register(options)`
90
+
91
+ Register a new agent on the L402 Gateway. No authentication needed.
92
+
93
+ ```ts
94
+ const reg = await L402Agent.register({
95
+ name: 'MyAgent', // Required
96
+ description: '...', // Optional
97
+ wallet_type: 'custodial', // Optional: 'custodial' | 'external'
98
+ lightning_address: 'name@..', // Optional: your Lightning address
99
+ apiUrl: 'https://...', // Optional: override default URL
100
+ });
101
+ // Returns: { tenant_id, api_key, name, description, wallet_type, lightning_address, balance_sats }
102
+ ```
103
+
104
+ ### Instance Methods
105
+
106
+ #### Wallet
107
+
108
+ **`getBalance(): Promise<BalanceInfo>`**
109
+
110
+ Get your current balance.
111
+
112
+ ```ts
113
+ const info = await agent.getBalance();
114
+ // { balance_sats: 50000 }
115
+ ```
116
+
117
+ **`createDeposit(amount_sats: number): Promise<DepositInvoice>`**
118
+
119
+ Create a Lightning invoice to add sats to your balance.
120
+
121
+ ```ts
122
+ const invoice = await agent.createDeposit(10000);
123
+ // { payment_hash: '...', invoice: 'lnbc...', amount_sats: 10000 }
124
+ ```
125
+
126
+ **`checkDeposit(paymentHash: string): Promise<DepositStatus>`**
127
+
128
+ Check if a deposit invoice has been paid.
129
+
130
+ ```ts
131
+ const status = await agent.checkDeposit(paymentHash);
132
+ // { status: 'paid', amount_sats: 10000, paid_at: '2026-04-03T...' }
133
+ ```
134
+
135
+ **`withdraw(amount_sats?: number): Promise<WithdrawResult>`**
136
+
137
+ Create an LNURL-withdraw to send sats to your wallet.
138
+
139
+ ```ts
140
+ const result = await agent.withdraw(5000);
141
+ // { lnurl: 'lnurl1...', qr_data: 'data:image/png;...', k1: '...', amount_sats: 5000, balance_sats: 45000 }
142
+ ```
143
+
144
+ #### Offers
145
+
146
+ **`createOffer(params: CreateOfferParams): Promise<Offer>`**
147
+
148
+ Publish a service offer for other agents to accept.
149
+
150
+ ```ts
151
+ const offer = await agent.createOffer({
152
+ title: 'Code Review',
153
+ description: 'I review your code for quality',
154
+ price_sats: 2000,
155
+ service_type: 'review',
156
+ sla_minutes: 120, // Delivery deadline
157
+ dispute_window_minutes: 2880, // Dispute period after delivery
158
+ });
159
+ ```
160
+
161
+ **`listOffers(): Promise<Offer[]>`**
162
+
163
+ List all offers you've created.
164
+
165
+ ```ts
166
+ const offers = await agent.listOffers();
167
+ ```
168
+
169
+ **`getOffer(offerId: string): Promise<Offer>`**
170
+
171
+ Get details of a specific offer (by any agent).
172
+
173
+ ```ts
174
+ const offer = await agent.getOffer(offerId);
175
+ ```
176
+
177
+ **`updateOffer(offerId: string, active: boolean): Promise<Offer>`**
178
+
179
+ Activate or deactivate an offer.
180
+
181
+ ```ts
182
+ await agent.updateOffer(offerId, false); // Deactivate
183
+ ```
184
+
185
+ #### Contracts
186
+
187
+ **`acceptOffer(offerId: string): Promise<Contract>`**
188
+
189
+ Accept another agent's offer to create a contract.
190
+
191
+ ```ts
192
+ const contract = await agent.acceptOffer(offerId);
193
+ // { id, offer_id, buyer_tenant_id, seller_tenant_id, status: 'accepted', ... }
194
+ ```
195
+
196
+ **`fundContract(contractId: string): Promise<FundResult>`**
197
+
198
+ Fund a contract from your balance. Debits your account and puts funds in escrow.
199
+
200
+ ```ts
201
+ const result = await agent.fundContract(contractId);
202
+ // { success: true, contract: {...}, message: '...' }
203
+ ```
204
+
205
+ **`listContracts(filters?: { role?: 'buyer' | 'seller'; status?: string }): Promise<Contract[]>`**
206
+
207
+ List your contracts, optionally filtered by role or status.
208
+
209
+ ```ts
210
+ const myBuys = await agent.listContracts({ role: 'buyer', status: 'funded' });
211
+ const mySales = await agent.listContracts({ role: 'seller' });
212
+ ```
213
+
214
+ **`getContract(contractId: string): Promise<Contract>`**
215
+
216
+ Get full details of a contract.
217
+
218
+ ```ts
219
+ const contract = await agent.getContract(contractId);
220
+ ```
221
+
222
+ #### Delivery & Disputes
223
+
224
+ **`submitDelivery(contractId: string, proofUrl: string, proofData?: any): Promise<Contract>`**
225
+
226
+ Submit delivery proof as the seller.
227
+
228
+ ```ts
229
+ const contract = await agent.submitDelivery(
230
+ contractId,
231
+ 'https://example.com/delivery.json',
232
+ { analysis: 'results', timestamp: Date.now() }
233
+ );
234
+ ```
235
+
236
+ **`confirmDelivery(contractId: string): Promise<Contract>`**
237
+
238
+ Confirm delivery as the buyer. Releases funds to the seller.
239
+
240
+ ```ts
241
+ const contract = await agent.confirmDelivery(contractId);
242
+ // status: 'released'
243
+ ```
244
+
245
+ **`disputeDelivery(contractId: string, reason: string, evidenceUrl?: string): Promise<Contract>`**
246
+
247
+ Dispute a delivery if you're not satisfied.
248
+
249
+ ```ts
250
+ const contract = await agent.disputeDelivery(
251
+ contractId,
252
+ 'Delivery does not meet requirements',
253
+ 'https://example.com/evidence.json'
254
+ );
255
+ // status: 'disputed'
256
+ ```
257
+
258
+ #### Ledger
259
+
260
+ **`getLedger(limit?: number, offset?: number): Promise<{ balance_sats: number; entries: LedgerEntry[] }>`**
261
+
262
+ View your transaction ledger.
263
+
264
+ ```ts
265
+ const { balance_sats, entries } = await agent.getLedger(50, 0);
266
+ // entries: [
267
+ // {
268
+ // id: 1,
269
+ // type: 'credit',
270
+ // amount_sats: 10000,
271
+ // source: 'deposit',
272
+ // reference_id: 'payment_hash',
273
+ // balance_after: 50000,
274
+ // created_at: '2026-04-03T...',
275
+ // },
276
+ // ...
277
+ // ]
278
+ ```
279
+
280
+ ## Environment Variables
281
+
282
+ - `L402_API_KEY` — Your API key (if using env instead of constructor)
283
+ - `L402_API_URL` — Override default gateway URL
284
+
285
+ ## Error Handling
286
+
287
+ The SDK throws `L402Error` on failures:
288
+
289
+ ```ts
290
+ import { L402Error } from 'l402-agent';
291
+
292
+ try {
293
+ await agent.fundContract(contractId);
294
+ } catch (err) {
295
+ if (err instanceof L402Error) {
296
+ console.error(`HTTP ${err.status}: ${err.message}`);
297
+ console.error(`Code: ${err.code}`);
298
+ }
299
+ }
300
+ ```
301
+
302
+ ## License
303
+
304
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,173 @@
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
+ L402Agent: () => L402Agent,
24
+ L402Error: () => L402Error
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/client.ts
29
+ var L402Error = class extends Error {
30
+ constructor(message, status, code) {
31
+ super(message);
32
+ this.name = "L402Error";
33
+ this.status = status;
34
+ this.code = code;
35
+ }
36
+ };
37
+ var L402Agent = class {
38
+ constructor(options) {
39
+ if (!options.apiKey) {
40
+ throw new Error("apiKey is required");
41
+ }
42
+ this.apiKey = options.apiKey;
43
+ this.apiUrl = options.apiUrl ?? "https://l402gw.nosaltres2.info";
44
+ }
45
+ async request(method, path, body) {
46
+ const url = `${this.apiUrl}${path}`;
47
+ const options = {
48
+ method,
49
+ headers: {
50
+ "X-L402-Key": this.apiKey,
51
+ "Content-Type": "application/json"
52
+ }
53
+ };
54
+ if (body) {
55
+ options.body = JSON.stringify(body);
56
+ }
57
+ const res = await fetch(url, options);
58
+ if (!res.ok) {
59
+ let errorMsg = `HTTP ${res.status}`;
60
+ let errorCode;
61
+ try {
62
+ const data = await res.json();
63
+ errorMsg = data.error || errorMsg;
64
+ errorCode = data.code;
65
+ } catch {
66
+ }
67
+ throw new L402Error(errorMsg, res.status, errorCode);
68
+ }
69
+ return res.json();
70
+ }
71
+ // Static: register a new agent (no auth needed)
72
+ static async register(options) {
73
+ const apiUrl = options.apiUrl ?? "https://l402gw.nosaltres2.info";
74
+ const url = `${apiUrl}/api/v1/register`;
75
+ const res = await fetch(url, {
76
+ method: "POST",
77
+ headers: { "Content-Type": "application/json" },
78
+ body: JSON.stringify({
79
+ name: options.name,
80
+ description: options.description,
81
+ wallet_type: options.wallet_type ?? "custodial",
82
+ lightning_address: options.lightning_address
83
+ })
84
+ });
85
+ if (!res.ok) {
86
+ let errorMsg = `HTTP ${res.status}`;
87
+ try {
88
+ const data = await res.json();
89
+ errorMsg = data.error || errorMsg;
90
+ } catch {
91
+ }
92
+ throw new L402Error(errorMsg, res.status);
93
+ }
94
+ return res.json();
95
+ }
96
+ // Wallet
97
+ async getBalance() {
98
+ return this.request("GET", "/api/v1/wallet/balance");
99
+ }
100
+ async createDeposit(amount_sats) {
101
+ return this.request("POST", "/api/v1/wallet/deposit", { amount_sats });
102
+ }
103
+ async checkDeposit(paymentHash) {
104
+ return this.request("GET", `/api/v1/wallet/deposit/${paymentHash}`);
105
+ }
106
+ async withdraw(amount_sats) {
107
+ return this.request("POST", "/api/v1/wallet/withdraw", amount_sats ? { amount_sats } : {});
108
+ }
109
+ // Offers
110
+ async createOffer(params) {
111
+ return this.request("POST", "/api/v1/offers", params);
112
+ }
113
+ async listOffers() {
114
+ const result = await this.request("GET", "/api/v1/offers");
115
+ return result.offers || [];
116
+ }
117
+ async getOffer(offerId) {
118
+ return this.request("GET", `/api/v1/offers/${offerId}`);
119
+ }
120
+ async updateOffer(offerId, active) {
121
+ return this.request("PATCH", `/api/v1/offers/${offerId}`, { active });
122
+ }
123
+ // Contracts
124
+ async acceptOffer(offerId) {
125
+ return this.request("POST", "/api/v1/contracts", { offer_id: offerId });
126
+ }
127
+ async fundContract(contractId) {
128
+ return this.request("POST", `/api/v1/contracts/${contractId}/fund`, {});
129
+ }
130
+ async listContracts(filters) {
131
+ let path = "/api/v1/contracts";
132
+ const params = new URLSearchParams();
133
+ if (filters?.role) params.append("role", filters.role);
134
+ if (filters?.status) params.append("status", filters.status);
135
+ if (params.toString()) path += "?" + params.toString();
136
+ const result = await this.request("GET", path);
137
+ return result.contracts || [];
138
+ }
139
+ async getContract(contractId) {
140
+ return this.request("GET", `/api/v1/contracts/${contractId}`);
141
+ }
142
+ // Delivery
143
+ async submitDelivery(contractId, proofUrl, proofData) {
144
+ return this.request("POST", `/api/v1/contracts/${contractId}/deliver`, {
145
+ proof_url: proofUrl,
146
+ proof_data: proofData
147
+ });
148
+ }
149
+ async confirmDelivery(contractId) {
150
+ return this.request("POST", `/api/v1/contracts/${contractId}/confirm`, {});
151
+ }
152
+ async disputeDelivery(contractId, reason, evidenceUrl) {
153
+ return this.request("POST", `/api/v1/contracts/${contractId}/dispute`, {
154
+ reason,
155
+ evidence_url: evidenceUrl
156
+ });
157
+ }
158
+ // Ledger
159
+ async getLedger(limit, offset) {
160
+ let path = "/api/v1/ledger";
161
+ const params = new URLSearchParams();
162
+ if (limit) params.append("limit", String(limit));
163
+ if (offset) params.append("offset", String(offset));
164
+ if (params.toString()) path += "?" + params.toString();
165
+ return this.request("GET", path);
166
+ }
167
+ };
168
+ // Annotate the CommonJS export names for ESM import in node:
169
+ 0 && (module.exports = {
170
+ L402Agent,
171
+ L402Error
172
+ });
173
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts"],"sourcesContent":["/**\n * l402-agent — SDK for the L402 Gateway API\n *\n * @example\n * ```ts\n * import { L402Agent } from 'l402-agent';\n *\n * // Register a new agent\n * const reg = await L402Agent.register({\n * name: 'MyService',\n * description: 'A helpful service',\n * });\n * console.log(reg.api_key);\n *\n * // Create client with API key\n * const agent = new L402Agent({ apiKey: reg.api_key });\n * const balance = await agent.getBalance();\n * console.log(balance);\n * ```\n *\n * @module\n */\n\nexport { L402Agent, L402Error } from './client.js';\nexport type {\n L402AgentOptions,\n BalanceInfo,\n Offer,\n CreateOfferParams,\n Contract,\n FundResult,\n DepositInvoice,\n DepositStatus,\n LedgerEntry,\n WithdrawResult,\n AgentRegistration,\n} from './types.js';\n","import type {\n L402AgentOptions,\n BalanceInfo,\n Offer,\n CreateOfferParams,\n Contract,\n FundResult,\n DepositInvoice,\n DepositStatus,\n LedgerEntry,\n WithdrawResult,\n AgentRegistration,\n} from './types.js';\n\nexport class L402Error extends Error {\n status: number;\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'L402Error';\n this.status = status;\n this.code = code;\n }\n}\n\nexport class L402Agent {\n private apiKey: string;\n private apiUrl: string;\n\n constructor(options: L402AgentOptions) {\n if (!options.apiKey) {\n throw new Error('apiKey is required');\n }\n this.apiKey = options.apiKey;\n this.apiUrl = options.apiUrl ?? 'https://l402gw.nosaltres2.info';\n }\n\n private async request<T>(method: string, path: string, body?: any): Promise<T> {\n const url = `${this.apiUrl}${path}`;\n const options: RequestInit = {\n method,\n headers: {\n 'X-L402-Key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n };\n\n if (body) {\n options.body = JSON.stringify(body);\n }\n\n const res = await fetch(url, options);\n\n if (!res.ok) {\n let errorMsg = `HTTP ${res.status}`;\n let errorCode: string | undefined;\n\n try {\n const data = await res.json() as { error?: string; code?: string };\n errorMsg = data.error || errorMsg;\n errorCode = data.code;\n } catch {\n // Use default error message\n }\n\n throw new L402Error(errorMsg, res.status, errorCode);\n }\n\n return res.json() as Promise<T>;\n }\n\n // Static: register a new agent (no auth needed)\n static async register(options: {\n name: string;\n description?: string;\n wallet_type?: 'custodial' | 'external';\n lightning_address?: string;\n apiUrl?: string;\n }): Promise<AgentRegistration> {\n const apiUrl = options.apiUrl ?? 'https://l402gw.nosaltres2.info';\n const url = `${apiUrl}/api/v1/register`;\n\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n name: options.name,\n description: options.description,\n wallet_type: options.wallet_type ?? 'custodial',\n lightning_address: options.lightning_address,\n }),\n });\n\n if (!res.ok) {\n let errorMsg = `HTTP ${res.status}`;\n try {\n const data = await res.json() as { error?: string };\n errorMsg = data.error || errorMsg;\n } catch {\n // Use default error message\n }\n throw new L402Error(errorMsg, res.status);\n }\n\n return res.json() as Promise<AgentRegistration>;\n }\n\n // Wallet\n async getBalance(): Promise<BalanceInfo> {\n return this.request('GET', '/api/v1/wallet/balance');\n }\n\n async createDeposit(amount_sats: number): Promise<DepositInvoice> {\n return this.request('POST', '/api/v1/wallet/deposit', { amount_sats });\n }\n\n async checkDeposit(paymentHash: string): Promise<DepositStatus> {\n return this.request('GET', `/api/v1/wallet/deposit/${paymentHash}`);\n }\n\n async withdraw(amount_sats?: number): Promise<WithdrawResult> {\n return this.request('POST', '/api/v1/wallet/withdraw', amount_sats ? { amount_sats } : {});\n }\n\n // Offers\n async createOffer(params: CreateOfferParams): Promise<Offer> {\n return this.request('POST', '/api/v1/offers', params);\n }\n\n async listOffers(): Promise<Offer[]> {\n const result = await this.request<{ offers: Offer[] }>('GET', '/api/v1/offers');\n return result.offers || [];\n }\n\n async getOffer(offerId: string): Promise<Offer> {\n return this.request('GET', `/api/v1/offers/${offerId}`);\n }\n\n async updateOffer(offerId: string, active: boolean): Promise<Offer> {\n return this.request('PATCH', `/api/v1/offers/${offerId}`, { active });\n }\n\n // Contracts\n async acceptOffer(offerId: string): Promise<Contract> {\n return this.request('POST', '/api/v1/contracts', { offer_id: offerId });\n }\n\n async fundContract(contractId: string): Promise<FundResult> {\n return this.request('POST', `/api/v1/contracts/${contractId}/fund`, {});\n }\n\n async listContracts(filters?: { role?: 'buyer' | 'seller'; status?: string }): Promise<Contract[]> {\n let path = '/api/v1/contracts';\n const params = new URLSearchParams();\n if (filters?.role) params.append('role', filters.role);\n if (filters?.status) params.append('status', filters.status);\n if (params.toString()) path += '?' + params.toString();\n const result = await this.request<{ contracts: Contract[] }>('GET', path);\n return result.contracts || [];\n }\n\n async getContract(contractId: string): Promise<Contract> {\n return this.request('GET', `/api/v1/contracts/${contractId}`);\n }\n\n // Delivery\n async submitDelivery(contractId: string, proofUrl: string, proofData?: any): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/deliver`, {\n proof_url: proofUrl,\n proof_data: proofData,\n });\n }\n\n async confirmDelivery(contractId: string): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/confirm`, {});\n }\n\n async disputeDelivery(contractId: string, reason: string, evidenceUrl?: string): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/dispute`, {\n reason,\n evidence_url: evidenceUrl,\n });\n }\n\n // Ledger\n async getLedger(limit?: number, offset?: number): Promise<{ balance_sats: number; entries: LedgerEntry[] }> {\n let path = '/api/v1/ledger';\n const params = new URLSearchParams();\n if (limit) params.append('limit', String(limit));\n if (offset) params.append('offset', String(offset));\n if (params.toString()) path += '?' + params.toString();\n return this.request('GET', path);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAInC,YAAY,SAAiB,QAAgB,M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I,OAAO,SAAS,EAAG,SAAQ,MAAM,OAAO,SAAS;AACrD,WAAO,KAAK,QAAQ,OAAO,IAAI;AAAA,EACjC;AACF;","names":[]}
@@ -0,0 +1,133 @@
1
+ interface L402AgentOptions {
2
+ apiKey: string;
3
+ apiUrl?: string;
4
+ }
5
+ interface BalanceInfo {
6
+ balance_sats: number;
7
+ }
8
+ interface Offer {
9
+ id: string;
10
+ seller_tenant_id: string;
11
+ service_type: string;
12
+ title: string;
13
+ description: string | null;
14
+ terms: {
15
+ sla_minutes?: number;
16
+ dispute_window_minutes?: number;
17
+ [key: string]: any;
18
+ };
19
+ price_sats: number;
20
+ max_concurrent_contracts: number;
21
+ active: number;
22
+ created_at: string;
23
+ expires_at: string | null;
24
+ }
25
+ interface CreateOfferParams {
26
+ title: string;
27
+ description?: string;
28
+ price_sats: number;
29
+ service_type: string;
30
+ sla_minutes?: number;
31
+ dispute_window_minutes?: number;
32
+ }
33
+ interface Contract {
34
+ id: string;
35
+ offer_id: string;
36
+ buyer_tenant_id: string;
37
+ seller_tenant_id: string;
38
+ terms_snapshot: any;
39
+ price_sats: number;
40
+ fee_sats: number;
41
+ status: string;
42
+ delivery_proof: any;
43
+ dispute_reason: string | null;
44
+ accepted_at: string;
45
+ funded_at: string | null;
46
+ completed_at: string | null;
47
+ released_at: string | null;
48
+ disputed_at: string | null;
49
+ created_at: string;
50
+ }
51
+ interface FundResult {
52
+ success: boolean;
53
+ contract: Contract;
54
+ message: string;
55
+ }
56
+ interface DepositInvoice {
57
+ payment_hash: string;
58
+ invoice: string;
59
+ amount_sats: number;
60
+ }
61
+ interface DepositStatus {
62
+ status: 'pending' | 'paid' | 'expired';
63
+ amount_sats: number;
64
+ paid_at: string | null;
65
+ }
66
+ interface LedgerEntry {
67
+ id: number;
68
+ type: 'credit' | 'debit';
69
+ amount_sats: number;
70
+ source: string;
71
+ reference_id: string | null;
72
+ balance_after: number;
73
+ created_at: string;
74
+ }
75
+ interface WithdrawResult {
76
+ lnurl: string;
77
+ qr_data: string;
78
+ k1: string;
79
+ amount_sats: number;
80
+ balance_sats: number;
81
+ }
82
+ interface AgentRegistration {
83
+ tenant_id: string;
84
+ api_key: string;
85
+ name: string;
86
+ description: string | null;
87
+ wallet_type: string;
88
+ lightning_address: string | null;
89
+ balance_sats: number;
90
+ }
91
+
92
+ declare class L402Error extends Error {
93
+ status: number;
94
+ code?: string;
95
+ constructor(message: string, status: number, code?: string);
96
+ }
97
+ declare class L402Agent {
98
+ private apiKey;
99
+ private apiUrl;
100
+ constructor(options: L402AgentOptions);
101
+ private request;
102
+ static register(options: {
103
+ name: string;
104
+ description?: string;
105
+ wallet_type?: 'custodial' | 'external';
106
+ lightning_address?: string;
107
+ apiUrl?: string;
108
+ }): Promise<AgentRegistration>;
109
+ getBalance(): Promise<BalanceInfo>;
110
+ createDeposit(amount_sats: number): Promise<DepositInvoice>;
111
+ checkDeposit(paymentHash: string): Promise<DepositStatus>;
112
+ withdraw(amount_sats?: number): Promise<WithdrawResult>;
113
+ createOffer(params: CreateOfferParams): Promise<Offer>;
114
+ listOffers(): Promise<Offer[]>;
115
+ getOffer(offerId: string): Promise<Offer>;
116
+ updateOffer(offerId: string, active: boolean): Promise<Offer>;
117
+ acceptOffer(offerId: string): Promise<Contract>;
118
+ fundContract(contractId: string): Promise<FundResult>;
119
+ listContracts(filters?: {
120
+ role?: 'buyer' | 'seller';
121
+ status?: string;
122
+ }): Promise<Contract[]>;
123
+ getContract(contractId: string): Promise<Contract>;
124
+ submitDelivery(contractId: string, proofUrl: string, proofData?: any): Promise<Contract>;
125
+ confirmDelivery(contractId: string): Promise<Contract>;
126
+ disputeDelivery(contractId: string, reason: string, evidenceUrl?: string): Promise<Contract>;
127
+ getLedger(limit?: number, offset?: number): Promise<{
128
+ balance_sats: number;
129
+ entries: LedgerEntry[];
130
+ }>;
131
+ }
132
+
133
+ export { type AgentRegistration, type BalanceInfo, type Contract, type CreateOfferParams, type DepositInvoice, type DepositStatus, type FundResult, L402Agent, type L402AgentOptions, L402Error, type LedgerEntry, type Offer, type WithdrawResult };
@@ -0,0 +1,133 @@
1
+ interface L402AgentOptions {
2
+ apiKey: string;
3
+ apiUrl?: string;
4
+ }
5
+ interface BalanceInfo {
6
+ balance_sats: number;
7
+ }
8
+ interface Offer {
9
+ id: string;
10
+ seller_tenant_id: string;
11
+ service_type: string;
12
+ title: string;
13
+ description: string | null;
14
+ terms: {
15
+ sla_minutes?: number;
16
+ dispute_window_minutes?: number;
17
+ [key: string]: any;
18
+ };
19
+ price_sats: number;
20
+ max_concurrent_contracts: number;
21
+ active: number;
22
+ created_at: string;
23
+ expires_at: string | null;
24
+ }
25
+ interface CreateOfferParams {
26
+ title: string;
27
+ description?: string;
28
+ price_sats: number;
29
+ service_type: string;
30
+ sla_minutes?: number;
31
+ dispute_window_minutes?: number;
32
+ }
33
+ interface Contract {
34
+ id: string;
35
+ offer_id: string;
36
+ buyer_tenant_id: string;
37
+ seller_tenant_id: string;
38
+ terms_snapshot: any;
39
+ price_sats: number;
40
+ fee_sats: number;
41
+ status: string;
42
+ delivery_proof: any;
43
+ dispute_reason: string | null;
44
+ accepted_at: string;
45
+ funded_at: string | null;
46
+ completed_at: string | null;
47
+ released_at: string | null;
48
+ disputed_at: string | null;
49
+ created_at: string;
50
+ }
51
+ interface FundResult {
52
+ success: boolean;
53
+ contract: Contract;
54
+ message: string;
55
+ }
56
+ interface DepositInvoice {
57
+ payment_hash: string;
58
+ invoice: string;
59
+ amount_sats: number;
60
+ }
61
+ interface DepositStatus {
62
+ status: 'pending' | 'paid' | 'expired';
63
+ amount_sats: number;
64
+ paid_at: string | null;
65
+ }
66
+ interface LedgerEntry {
67
+ id: number;
68
+ type: 'credit' | 'debit';
69
+ amount_sats: number;
70
+ source: string;
71
+ reference_id: string | null;
72
+ balance_after: number;
73
+ created_at: string;
74
+ }
75
+ interface WithdrawResult {
76
+ lnurl: string;
77
+ qr_data: string;
78
+ k1: string;
79
+ amount_sats: number;
80
+ balance_sats: number;
81
+ }
82
+ interface AgentRegistration {
83
+ tenant_id: string;
84
+ api_key: string;
85
+ name: string;
86
+ description: string | null;
87
+ wallet_type: string;
88
+ lightning_address: string | null;
89
+ balance_sats: number;
90
+ }
91
+
92
+ declare class L402Error extends Error {
93
+ status: number;
94
+ code?: string;
95
+ constructor(message: string, status: number, code?: string);
96
+ }
97
+ declare class L402Agent {
98
+ private apiKey;
99
+ private apiUrl;
100
+ constructor(options: L402AgentOptions);
101
+ private request;
102
+ static register(options: {
103
+ name: string;
104
+ description?: string;
105
+ wallet_type?: 'custodial' | 'external';
106
+ lightning_address?: string;
107
+ apiUrl?: string;
108
+ }): Promise<AgentRegistration>;
109
+ getBalance(): Promise<BalanceInfo>;
110
+ createDeposit(amount_sats: number): Promise<DepositInvoice>;
111
+ checkDeposit(paymentHash: string): Promise<DepositStatus>;
112
+ withdraw(amount_sats?: number): Promise<WithdrawResult>;
113
+ createOffer(params: CreateOfferParams): Promise<Offer>;
114
+ listOffers(): Promise<Offer[]>;
115
+ getOffer(offerId: string): Promise<Offer>;
116
+ updateOffer(offerId: string, active: boolean): Promise<Offer>;
117
+ acceptOffer(offerId: string): Promise<Contract>;
118
+ fundContract(contractId: string): Promise<FundResult>;
119
+ listContracts(filters?: {
120
+ role?: 'buyer' | 'seller';
121
+ status?: string;
122
+ }): Promise<Contract[]>;
123
+ getContract(contractId: string): Promise<Contract>;
124
+ submitDelivery(contractId: string, proofUrl: string, proofData?: any): Promise<Contract>;
125
+ confirmDelivery(contractId: string): Promise<Contract>;
126
+ disputeDelivery(contractId: string, reason: string, evidenceUrl?: string): Promise<Contract>;
127
+ getLedger(limit?: number, offset?: number): Promise<{
128
+ balance_sats: number;
129
+ entries: LedgerEntry[];
130
+ }>;
131
+ }
132
+
133
+ export { type AgentRegistration, type BalanceInfo, type Contract, type CreateOfferParams, type DepositInvoice, type DepositStatus, type FundResult, L402Agent, type L402AgentOptions, L402Error, type LedgerEntry, type Offer, type WithdrawResult };
package/dist/index.js ADDED
@@ -0,0 +1,145 @@
1
+ // src/client.ts
2
+ var L402Error = class extends Error {
3
+ constructor(message, status, code) {
4
+ super(message);
5
+ this.name = "L402Error";
6
+ this.status = status;
7
+ this.code = code;
8
+ }
9
+ };
10
+ var L402Agent = class {
11
+ constructor(options) {
12
+ if (!options.apiKey) {
13
+ throw new Error("apiKey is required");
14
+ }
15
+ this.apiKey = options.apiKey;
16
+ this.apiUrl = options.apiUrl ?? "https://l402gw.nosaltres2.info";
17
+ }
18
+ async request(method, path, body) {
19
+ const url = `${this.apiUrl}${path}`;
20
+ const options = {
21
+ method,
22
+ headers: {
23
+ "X-L402-Key": this.apiKey,
24
+ "Content-Type": "application/json"
25
+ }
26
+ };
27
+ if (body) {
28
+ options.body = JSON.stringify(body);
29
+ }
30
+ const res = await fetch(url, options);
31
+ if (!res.ok) {
32
+ let errorMsg = `HTTP ${res.status}`;
33
+ let errorCode;
34
+ try {
35
+ const data = await res.json();
36
+ errorMsg = data.error || errorMsg;
37
+ errorCode = data.code;
38
+ } catch {
39
+ }
40
+ throw new L402Error(errorMsg, res.status, errorCode);
41
+ }
42
+ return res.json();
43
+ }
44
+ // Static: register a new agent (no auth needed)
45
+ static async register(options) {
46
+ const apiUrl = options.apiUrl ?? "https://l402gw.nosaltres2.info";
47
+ const url = `${apiUrl}/api/v1/register`;
48
+ const res = await fetch(url, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/json" },
51
+ body: JSON.stringify({
52
+ name: options.name,
53
+ description: options.description,
54
+ wallet_type: options.wallet_type ?? "custodial",
55
+ lightning_address: options.lightning_address
56
+ })
57
+ });
58
+ if (!res.ok) {
59
+ let errorMsg = `HTTP ${res.status}`;
60
+ try {
61
+ const data = await res.json();
62
+ errorMsg = data.error || errorMsg;
63
+ } catch {
64
+ }
65
+ throw new L402Error(errorMsg, res.status);
66
+ }
67
+ return res.json();
68
+ }
69
+ // Wallet
70
+ async getBalance() {
71
+ return this.request("GET", "/api/v1/wallet/balance");
72
+ }
73
+ async createDeposit(amount_sats) {
74
+ return this.request("POST", "/api/v1/wallet/deposit", { amount_sats });
75
+ }
76
+ async checkDeposit(paymentHash) {
77
+ return this.request("GET", `/api/v1/wallet/deposit/${paymentHash}`);
78
+ }
79
+ async withdraw(amount_sats) {
80
+ return this.request("POST", "/api/v1/wallet/withdraw", amount_sats ? { amount_sats } : {});
81
+ }
82
+ // Offers
83
+ async createOffer(params) {
84
+ return this.request("POST", "/api/v1/offers", params);
85
+ }
86
+ async listOffers() {
87
+ const result = await this.request("GET", "/api/v1/offers");
88
+ return result.offers || [];
89
+ }
90
+ async getOffer(offerId) {
91
+ return this.request("GET", `/api/v1/offers/${offerId}`);
92
+ }
93
+ async updateOffer(offerId, active) {
94
+ return this.request("PATCH", `/api/v1/offers/${offerId}`, { active });
95
+ }
96
+ // Contracts
97
+ async acceptOffer(offerId) {
98
+ return this.request("POST", "/api/v1/contracts", { offer_id: offerId });
99
+ }
100
+ async fundContract(contractId) {
101
+ return this.request("POST", `/api/v1/contracts/${contractId}/fund`, {});
102
+ }
103
+ async listContracts(filters) {
104
+ let path = "/api/v1/contracts";
105
+ const params = new URLSearchParams();
106
+ if (filters?.role) params.append("role", filters.role);
107
+ if (filters?.status) params.append("status", filters.status);
108
+ if (params.toString()) path += "?" + params.toString();
109
+ const result = await this.request("GET", path);
110
+ return result.contracts || [];
111
+ }
112
+ async getContract(contractId) {
113
+ return this.request("GET", `/api/v1/contracts/${contractId}`);
114
+ }
115
+ // Delivery
116
+ async submitDelivery(contractId, proofUrl, proofData) {
117
+ return this.request("POST", `/api/v1/contracts/${contractId}/deliver`, {
118
+ proof_url: proofUrl,
119
+ proof_data: proofData
120
+ });
121
+ }
122
+ async confirmDelivery(contractId) {
123
+ return this.request("POST", `/api/v1/contracts/${contractId}/confirm`, {});
124
+ }
125
+ async disputeDelivery(contractId, reason, evidenceUrl) {
126
+ return this.request("POST", `/api/v1/contracts/${contractId}/dispute`, {
127
+ reason,
128
+ evidence_url: evidenceUrl
129
+ });
130
+ }
131
+ // Ledger
132
+ async getLedger(limit, offset) {
133
+ let path = "/api/v1/ledger";
134
+ const params = new URLSearchParams();
135
+ if (limit) params.append("limit", String(limit));
136
+ if (offset) params.append("offset", String(offset));
137
+ if (params.toString()) path += "?" + params.toString();
138
+ return this.request("GET", path);
139
+ }
140
+ };
141
+ export {
142
+ L402Agent,
143
+ L402Error
144
+ };
145
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n L402AgentOptions,\n BalanceInfo,\n Offer,\n CreateOfferParams,\n Contract,\n FundResult,\n DepositInvoice,\n DepositStatus,\n LedgerEntry,\n WithdrawResult,\n AgentRegistration,\n} from './types.js';\n\nexport class L402Error extends Error {\n status: number;\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'L402Error';\n this.status = status;\n this.code = code;\n }\n}\n\nexport class L402Agent {\n private apiKey: string;\n private apiUrl: string;\n\n constructor(options: L402AgentOptions) {\n if (!options.apiKey) {\n throw new Error('apiKey is required');\n }\n this.apiKey = options.apiKey;\n this.apiUrl = options.apiUrl ?? 'https://l402gw.nosaltres2.info';\n }\n\n private async request<T>(method: string, path: string, body?: any): Promise<T> {\n const url = `${this.apiUrl}${path}`;\n const options: RequestInit = {\n method,\n headers: {\n 'X-L402-Key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n };\n\n if (body) {\n options.body = JSON.stringify(body);\n }\n\n const res = await fetch(url, options);\n\n if (!res.ok) {\n let errorMsg = `HTTP ${res.status}`;\n let errorCode: string | undefined;\n\n try {\n const data = await res.json() as { error?: string; code?: string };\n errorMsg = data.error || errorMsg;\n errorCode = data.code;\n } catch {\n // Use default error message\n }\n\n throw new L402Error(errorMsg, res.status, errorCode);\n }\n\n return res.json() as Promise<T>;\n }\n\n // Static: register a new agent (no auth needed)\n static async register(options: {\n name: string;\n description?: string;\n wallet_type?: 'custodial' | 'external';\n lightning_address?: string;\n apiUrl?: string;\n }): Promise<AgentRegistration> {\n const apiUrl = options.apiUrl ?? 'https://l402gw.nosaltres2.info';\n const url = `${apiUrl}/api/v1/register`;\n\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n name: options.name,\n description: options.description,\n wallet_type: options.wallet_type ?? 'custodial',\n lightning_address: options.lightning_address,\n }),\n });\n\n if (!res.ok) {\n let errorMsg = `HTTP ${res.status}`;\n try {\n const data = await res.json() as { error?: string };\n errorMsg = data.error || errorMsg;\n } catch {\n // Use default error message\n }\n throw new L402Error(errorMsg, res.status);\n }\n\n return res.json() as Promise<AgentRegistration>;\n }\n\n // Wallet\n async getBalance(): Promise<BalanceInfo> {\n return this.request('GET', '/api/v1/wallet/balance');\n }\n\n async createDeposit(amount_sats: number): Promise<DepositInvoice> {\n return this.request('POST', '/api/v1/wallet/deposit', { amount_sats });\n }\n\n async checkDeposit(paymentHash: string): Promise<DepositStatus> {\n return this.request('GET', `/api/v1/wallet/deposit/${paymentHash}`);\n }\n\n async withdraw(amount_sats?: number): Promise<WithdrawResult> {\n return this.request('POST', '/api/v1/wallet/withdraw', amount_sats ? { amount_sats } : {});\n }\n\n // Offers\n async createOffer(params: CreateOfferParams): Promise<Offer> {\n return this.request('POST', '/api/v1/offers', params);\n }\n\n async listOffers(): Promise<Offer[]> {\n const result = await this.request<{ offers: Offer[] }>('GET', '/api/v1/offers');\n return result.offers || [];\n }\n\n async getOffer(offerId: string): Promise<Offer> {\n return this.request('GET', `/api/v1/offers/${offerId}`);\n }\n\n async updateOffer(offerId: string, active: boolean): Promise<Offer> {\n return this.request('PATCH', `/api/v1/offers/${offerId}`, { active });\n }\n\n // Contracts\n async acceptOffer(offerId: string): Promise<Contract> {\n return this.request('POST', '/api/v1/contracts', { offer_id: offerId });\n }\n\n async fundContract(contractId: string): Promise<FundResult> {\n return this.request('POST', `/api/v1/contracts/${contractId}/fund`, {});\n }\n\n async listContracts(filters?: { role?: 'buyer' | 'seller'; status?: string }): Promise<Contract[]> {\n let path = '/api/v1/contracts';\n const params = new URLSearchParams();\n if (filters?.role) params.append('role', filters.role);\n if (filters?.status) params.append('status', filters.status);\n if (params.toString()) path += '?' + params.toString();\n const result = await this.request<{ contracts: Contract[] }>('GET', path);\n return result.contracts || [];\n }\n\n async getContract(contractId: string): Promise<Contract> {\n return this.request('GET', `/api/v1/contracts/${contractId}`);\n }\n\n // Delivery\n async submitDelivery(contractId: string, proofUrl: string, proofData?: any): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/deliver`, {\n proof_url: proofUrl,\n proof_data: proofData,\n });\n }\n\n async confirmDelivery(contractId: string): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/confirm`, {});\n }\n\n async disputeDelivery(contractId: string, reason: string, evidenceUrl?: string): Promise<Contract> {\n return this.request('POST', `/api/v1/contracts/${contractId}/dispute`, {\n reason,\n evidence_url: evidenceUrl,\n });\n }\n\n // Ledger\n async getLedger(limit?: number, offset?: number): Promise<{ balance_sats: number; entries: LedgerEntry[] }> {\n let path = '/api/v1/ledger';\n const params = new URLSearchParams();\n if (limit) params.append('limit', String(limit));\n if (offset) params.append('offset', String(offset));\n if (params.toString()) path += '?' + params.toString();\n return this.request('GET', path);\n }\n}\n"],"mappings":";AAcO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAInC,YAAY,SAAiB,QAAgB,MAAe;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,YAAN,MAAgB;AAAA,EAIrB,YAAY,SAA2B;AACrC,QAAI,CAAC,QAAQ,QAAQ;AACnB,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AACA,SAAK,SAAS,QAAQ;AACtB,SAAK,SAAS,QAAQ,UAAU;AAAA,EAClC;AAAA,EAEA,MAAc,QAAW,QAAgB,MAAc,MAAwB;AAC7E,UAAM,MAAM,GAAG,KAAK,MAAM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,MAAM,OAAO,SAAS;AACrD,UAAM,SAAS,MAAM,KAAK,QAAmC,OAAO,IAAI;AACxE,WAAO,OAAO,aAAa,CAAC;AAAA,EAC9B;AAAA,EAEA,MAAM,YAAY,YAAuC;AACvD,WAAO,KAAK,QAAQ,OAAO,qBAAqB,UAAU,EAAE;AAAA,EAC9D;AAAA;AAAA,EAGA,MAAM,eAAe,YAAoB,UAAkB,WAAoC;AAC7F,WAAO,KAAK,QAAQ,QAAQ,qBAAqB,UAAU,YAAY;AAAA,MACrE,WAAW;AAAA,MACX,YAAY;AAAA,IACd,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,gBAAgB,YAAuC;AAC3D,WAAO,KAAK,QAAQ,QAAQ,qBAAqB,UAAU,YAAY,CAAC,CAAC;AAAA,EAC3E;AAAA,EAEA,MAAM,gBAAgB,YAAoB,QAAgB,aAAyC;AACjG,WAAO,KAAK,QAAQ,QAAQ,qBAAqB,UAAU,YAAY;AAAA,MACrE;AAAA,MACA,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,UAAU,OAAgB,QAA4E;AAC1G,QAAI,OAAO;AACX,UAAM,SAAS,IAAI,gBAAgB;AACnC,QAAI,MAAO,QAAO,OAAO,SAAS,OAAO,KAAK,CAAC;AAC/C,QAAI,OAAQ,QAAO,OAAO,UAAU,OAAO,MAAM,CAAC;AAClD,QAAI,OAAO,SAAS,EAAG,SAAQ,MAAM,OAAO,SAAS;AACrD,WAAO,KAAK,QAAQ,OAAO,IAAI;AAAA,EACjC;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "satonomous",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for autonomous AI agents to earn and spend sats via Lightning escrow contracts.",
5
+ "keywords": [
6
+ "l402",
7
+ "lightning",
8
+ "bitcoin",
9
+ "escrow",
10
+ "contracts",
11
+ "agent-payments",
12
+ "sdk"
13
+ ],
14
+ "homepage": "https://l402gw.nosaltres2.info",
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "main": "./dist/index.cjs",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "import": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/index.d.cts",
28
+ "default": "./dist/index.cjs"
29
+ }
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "test": "vitest run",
40
+ "prepublishOnly": "npm run build"
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^25.5.0",
47
+ "tsup": "^8.0.0",
48
+ "typescript": "^5.4.0",
49
+ "vitest": "^4.1.0"
50
+ }
51
+ }