@getaccord/sdk 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @getaccord/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hold money with several sellers, then pay everyone in one step or release everything. Currently test mode only, on Sui testnet. You never deal with crypto: amounts are in cents.
4
+
5
+ ```bash
6
+ npx @getaccord/cli init # agent key + $5,000 of test funds, written to .env
7
+ npm install @getaccord/sdk
8
+ ```
9
+
10
+ ```ts
11
+ import { accord } from '@getaccord/sdk';
12
+
13
+ const intent = await accord.intent({ budget: 1200_00 }); // reads ACCORD_AGENT_KEY
14
+
15
+ await Promise.all([
16
+ intent.hold('skyfare', { amount: 640_00, ref: 'SFO to JFK, Dec 18' }),
17
+ intent.hold('stayco', { amount: 420_00, ref: '2 nights' }),
18
+ intent.hold('ridenow', { amount: 85_00, ref: 'airport pickup' }),
19
+ ]);
20
+
21
+ const result = await intent.commit(); // 'committed': all three paid. Otherwise nobody is.
22
+ console.log(result.status, result.intent.proofUrl);
23
+ ```
24
+
25
+ - **Four calls:** `intent`, `hold`, `commit`, `abort`. Holds placed in the same tick go out in one transaction.
26
+ - **Modes:** `mode: 'all'` (default) pays every hold or none. `mode: 'each'` pays the holds that are ready and releases the rest.
27
+ - **Limits are enforced on chain.** Your agent key has a weekly budget, allowed sellers, an expiry, and a human-approval threshold. A compromised agent still can't spend past them.
28
+ - **What's atomic:** the money. Accord can't make a seller's own systems atomic: a seller that confirms promises to deliver once paid.
29
+
30
+ ## Sellers
31
+
32
+ ```ts
33
+ import { accord } from '@getaccord/sdk';
34
+
35
+ app.post('/accord', accord.seller.handler({
36
+ onHold: async (hold) => (await reserveSeat(hold)) ? { ready: true } : { declined: 'sold_out' },
37
+ onCommit: issueTicket,
38
+ onAbort: releaseSeat,
39
+ }));
40
+ ```
41
+
42
+ Every event carries an `eventId`, so retries are safe.
@@ -0,0 +1,130 @@
1
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
2
+ import { handler } from './seller.ts';
3
+ export type Mode = 'all' | 'each';
4
+ export type HoldType = 'reserve' | 'deliver';
5
+ export type IntentStatus = 'awaiting_approval' | 'open' | 'committed' | 'aborted' | 'expired';
6
+ export type HoldState = 'placed' | 'ready' | 'declined' | 'submitted' | 'rejected' | 'paid' | 'released';
7
+ export type IntentOptions = {
8
+ /** The agent key (suiprivkey…). Defaults to ACCORD_AGENT_KEY. */
9
+ key?: string;
10
+ /** Most this intent may spend, in cents. */
11
+ budget: number;
12
+ /** 'all': pay every hold or none (default). 'each': pay the ready holds, release the rest. */
13
+ mode?: Mode;
14
+ /** When unanswered holds are released automatically, e.g. '15m'. */
15
+ expiresIn?: string;
16
+ };
17
+ export type HoldOptions = {
18
+ amount: number;
19
+ ref?: string;
20
+ type?: HoldType;
21
+ };
22
+ export type PlacedHold = {
23
+ index: number;
24
+ seller: string;
25
+ amount: number;
26
+ status: 'placed';
27
+ };
28
+ export type IntentState = {
29
+ id: string;
30
+ status: IntentStatus;
31
+ mode: Mode;
32
+ budget: number;
33
+ held: number;
34
+ paid: number;
35
+ deadline: string;
36
+ holds: {
37
+ index: number;
38
+ seller: string;
39
+ amount: number;
40
+ type: HoldType;
41
+ state: HoldState;
42
+ }[];
43
+ timeline: {
44
+ at: string;
45
+ what: string;
46
+ digest?: string;
47
+ }[];
48
+ proofUrl: string;
49
+ };
50
+ export type CommitResult = {
51
+ status: IntentStatus;
52
+ /** Cents paid to sellers. */
53
+ paid: number;
54
+ /** Why the intent did not commit, when it didn't. */
55
+ reason?: string;
56
+ digest?: string;
57
+ intent: IntentState;
58
+ };
59
+ /** The hosted test-mode coordinator on Sui testnet. */
60
+ export declare const DEFAULT_URL = "https://accord-testnet.fly.dev";
61
+ export type Balance = {
62
+ agent: string;
63
+ name: string;
64
+ available: number;
65
+ weekly: {
66
+ budget: number;
67
+ spent: number;
68
+ held: number;
69
+ };
70
+ revoked: boolean;
71
+ };
72
+ export declare class AccordError extends Error {
73
+ code: string;
74
+ constructor(code: string, message?: string);
75
+ }
76
+ export declare class Accord {
77
+ readonly url: string;
78
+ readonly seller: {
79
+ handler: typeof handler;
80
+ };
81
+ constructor(opts?: {
82
+ url?: string;
83
+ });
84
+ /** Opens a deal within the agent key's limits. Holds placed in the same tick go out in one transaction. */
85
+ intent(opts: IntentOptions): Promise<Intent>;
86
+ get(intentId: string): Promise<IntentState>;
87
+ /** The agent's org balance and what is left of its weekly budget, in cents. */
88
+ balance(key?: string): Promise<Balance>;
89
+ /** Test mode only. */
90
+ readonly test: {
91
+ /** Makes a demo seller decline every hold from this agent key (or stop doing so). */
92
+ failSeller: (seller: string, fail?: boolean, key?: string) => Promise<{
93
+ seller: string;
94
+ failing: boolean;
95
+ }>;
96
+ };
97
+ /** @internal */
98
+ call(method: 'GET' | 'POST', path: string, body?: unknown): Promise<any>;
99
+ /** @internal Prepare → sign with the agent key → Accord co-signs gas and executes. */
100
+ signed(keypair: Ed25519Keypair, path: string, body: Record<string, unknown>): Promise<any>;
101
+ }
102
+ export declare class Intent {
103
+ id: string | undefined;
104
+ private accord;
105
+ private keypair;
106
+ private opts;
107
+ private queue;
108
+ private flushing;
109
+ private scheduled;
110
+ private awaitingApproval;
111
+ constructor(accord: Accord, keypair: Ed25519Keypair, opts: IntentOptions);
112
+ /** Locks money with a seller. Resolves once the hold is on chain. */
113
+ hold(seller: string, opts: HoldOptions): Promise<PlacedHold>;
114
+ /**
115
+ * Waits for every seller to answer, then pays everyone at once.
116
+ * In 'all' mode, a decline or a timeout aborts the intent and releases every hold.
117
+ */
118
+ commit(opts?: {
119
+ wait?: string;
120
+ }): Promise<CommitResult>;
121
+ /** Calls the deal off. Every held dollar goes back to the balance. */
122
+ abort(): Promise<CommitResult>;
123
+ state(): Promise<IntentState>;
124
+ private abortWith;
125
+ private settled;
126
+ private flush;
127
+ }
128
+ export declare const accord: Accord;
129
+ export { handler as sellerHandler };
130
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,MAAM,CAAC;AAClC,MAAM,MAAM,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;AAC7C,MAAM,MAAM,YAAY,GAAG,mBAAmB,GAAG,MAAM,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,CAAC;AAC9F,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;AAEzG,MAAM,MAAM,aAAa,GAAG;IAC1B,iEAAiE;IACjE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,4CAA4C;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,8FAA8F;IAC9F,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,oEAAoE;IACpE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,QAAQ,CAAA;CAAE,CAAC;AAC5E,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,QAAQ,CAAA;CAAE,CA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AS;gBAErB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,aAAa;IAMxE,qEAAqE;IACrE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IAY5D;;;OAGG;IACG,MAAM,CAAC,IAAI,GAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,YAAY,CAAC;IA4BjE,sEAAsE;IAChE,KAAK,IAAI,OAAO,CAAC,YAAY,CAAC;IAI9B,KAAK,IAAI,OAAO,CAAC,WAAW,CAAC;YAMrB,SAAS;YAQT,OAAO;YAOP,KAAK;CA+BpB;AAED,eAAO,MAAM,MAAM,QAAe,CAAC;AACnC,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,195 @@
1
+ // Accord buyer SDK.
2
+ //
3
+ // const intent = await accord.intent({ key, budget: 1200_00 });
4
+ // await Promise.all([intent.hold('skyfare', { amount: 640_00, ref: 'SFO to JFK' }), ...]);
5
+ // const result = await intent.commit(); // everyone paid, or nobody
6
+ //
7
+ // Amounts are whole cents. The agent key signs every action locally; Accord
8
+ // only adds its gas signature, so it can't act as the agent.
9
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
10
+ import { fromBase64 } from '@mysten/sui/utils';
11
+ import { handler } from "./seller.js";
12
+ /** The hosted test-mode coordinator on Sui testnet. */
13
+ export const DEFAULT_URL = 'https://accord-testnet.fly.dev';
14
+ function keypair(key) {
15
+ const k = key ?? process.env.ACCORD_AGENT_KEY;
16
+ if (!k)
17
+ throw new AccordError('missing_key', 'Pass key or set ACCORD_AGENT_KEY (run: npx accord init)');
18
+ return Ed25519Keypair.fromSecretKey(k);
19
+ }
20
+ export class AccordError extends Error {
21
+ code;
22
+ constructor(code, message) {
23
+ super(message ? `${code}: ${message}` : code);
24
+ this.code = code;
25
+ }
26
+ }
27
+ export class Accord {
28
+ url;
29
+ seller = { handler };
30
+ constructor(opts = {}) {
31
+ this.url = (opts.url ?? process.env.ACCORD_URL ?? DEFAULT_URL).replace(/\/$/, '');
32
+ }
33
+ /** Opens a deal within the agent key's limits. Holds placed in the same tick go out in one transaction. */
34
+ async intent(opts) {
35
+ return new Intent(this, keypair(opts.key), opts);
36
+ }
37
+ async get(intentId) {
38
+ return this.call('GET', `/v1/intents/${intentId}`);
39
+ }
40
+ /** The agent's org balance and what is left of its weekly budget, in cents. */
41
+ async balance(key) {
42
+ return this.call('POST', '/v1/balance', { agent: keypair(key).toSuiAddress() });
43
+ }
44
+ /** Test mode only. */
45
+ test = {
46
+ /** Makes a demo seller decline every hold from this agent key (or stop doing so). */
47
+ failSeller: (seller, fail = true, key) => this.call('POST', `/v1/test/sellers/${seller}/fail`, { agent: keypair(key).toSuiAddress(), fail }),
48
+ };
49
+ /** @internal */
50
+ async call(method, path, body) {
51
+ const res = await fetch(this.url + path, {
52
+ method,
53
+ headers: body ? { 'content-type': 'application/json' } : undefined,
54
+ body: body ? JSON.stringify(body) : undefined,
55
+ });
56
+ const json = await res.json().catch(() => ({}));
57
+ if (!res.ok)
58
+ throw new AccordError(json.error?.code ?? `http_${res.status}`, json.error?.message);
59
+ return json;
60
+ }
61
+ /** @internal Prepare → sign with the agent key → Accord co-signs gas and executes. */
62
+ async signed(keypair, path, body) {
63
+ const { txBytes, ...rest } = await this.call('POST', path, { ...body, agent: keypair.toSuiAddress() });
64
+ const { signature } = await keypair.signTransaction(fromBase64(txBytes));
65
+ const out = await this.call('POST', '/v1/tx/execute', { txBytes, signature });
66
+ return { ...rest, ...out };
67
+ }
68
+ }
69
+ export class Intent {
70
+ id;
71
+ accord;
72
+ keypair;
73
+ opts;
74
+ queue = [];
75
+ flushing = Promise.resolve();
76
+ scheduled = false;
77
+ awaitingApproval = false;
78
+ constructor(accord, keypair, opts) {
79
+ this.accord = accord;
80
+ this.keypair = keypair;
81
+ this.opts = opts;
82
+ }
83
+ /** Locks money with a seller. Resolves once the hold is on chain. */
84
+ hold(seller, opts) {
85
+ return new Promise((resolve, reject) => {
86
+ this.queue.push({ seller, opts, resolve, reject });
87
+ if (!this.scheduled) {
88
+ this.scheduled = true;
89
+ setTimeout(() => {
90
+ this.flushing = this.flushing.then(() => this.flush());
91
+ }, 0);
92
+ }
93
+ });
94
+ }
95
+ /**
96
+ * Waits for every seller to answer, then pays everyone at once.
97
+ * In 'all' mode, a decline or a timeout aborts the intent and releases every hold.
98
+ */
99
+ async commit(opts = {}) {
100
+ await this.settled();
101
+ if (!this.id)
102
+ throw new AccordError('no_holds', 'Place at least one hold before commit');
103
+ const until = Date.now() + ms(opts.wait ?? '60s');
104
+ const mode = this.opts.mode ?? 'all';
105
+ for (;;) {
106
+ const state = await this.accord.get(this.id);
107
+ if (state.status === 'awaiting_approval')
108
+ return { status: state.status, paid: 0, intent: state };
109
+ if (state.status !== 'open')
110
+ return { status: state.status, paid: state.paid, intent: state };
111
+ const pending = state.holds.filter((h) => h.state === 'placed' || h.state === 'submitted');
112
+ const declined = state.holds.filter((h) => h.state === 'declined' || h.state === 'rejected');
113
+ if (mode === 'all' && declined.length > 0) {
114
+ return this.abortWith(`${declined.map((h) => h.seller).join(', ')} declined`);
115
+ }
116
+ if (pending.length === 0)
117
+ break;
118
+ if (Date.now() > until) {
119
+ if (mode === 'all')
120
+ return this.abortWith(`${pending.map((h) => h.seller).join(', ')} did not confirm in time`);
121
+ break; // 'each': pay whoever is ready.
122
+ }
123
+ await sleep(400);
124
+ }
125
+ const out = await this.accord.signed(this.keypair, `/v1/intents/${this.id}/commit/prepare`, {});
126
+ const intent = await this.accord.get(this.id);
127
+ return { status: intent.status, paid: intent.paid, digest: out.digest, intent };
128
+ }
129
+ /** Calls the deal off. Every held dollar goes back to the balance. */
130
+ async abort() {
131
+ return this.abortWith('aborted by the agent');
132
+ }
133
+ async state() {
134
+ await this.settled();
135
+ if (!this.id)
136
+ throw new AccordError('not_opened');
137
+ return this.accord.get(this.id);
138
+ }
139
+ async abortWith(reason) {
140
+ await this.settled();
141
+ if (!this.id)
142
+ throw new AccordError('not_opened');
143
+ const out = await this.accord.signed(this.keypair, `/v1/intents/${this.id}/abort/prepare`, {});
144
+ const intent = await this.accord.get(this.id);
145
+ return { status: intent.status, paid: 0, reason, digest: out.digest, intent };
146
+ }
147
+ async settled() {
148
+ while (this.scheduled || this.queue.length) {
149
+ await sleep(0);
150
+ await this.flushing;
151
+ }
152
+ }
153
+ async flush() {
154
+ const batch = this.queue.splice(0);
155
+ this.scheduled = false;
156
+ if (batch.length === 0)
157
+ return;
158
+ const holds = batch.map((b) => ({ seller: b.seller, amount: b.opts.amount, ref: b.opts.ref ?? '', type: b.opts.type ?? 'reserve' }));
159
+ try {
160
+ let out;
161
+ if (!this.id) {
162
+ out = await this.accord.signed(this.keypair, '/v1/intents/prepare', {
163
+ budget: this.opts.budget,
164
+ mode: this.opts.mode ?? 'all',
165
+ ttlMs: ms(this.opts.expiresIn ?? '15m'),
166
+ holds,
167
+ });
168
+ this.id = out.intentId;
169
+ this.awaitingApproval = !!out.awaitingApproval;
170
+ }
171
+ else {
172
+ out = await this.accord.signed(this.keypair, `/v1/intents/${this.id}/holds/prepare`, { holds });
173
+ }
174
+ if (this.awaitingApproval) {
175
+ const err = new AccordError('awaiting_approval', 'The budget is over the approval threshold; holds can be placed once a human approves');
176
+ batch.forEach((b) => b.reject(err));
177
+ return;
178
+ }
179
+ batch.forEach((b, i) => b.resolve({ index: out.holds[i].index, seller: b.seller, amount: b.opts.amount, status: 'placed' }));
180
+ }
181
+ catch (e) {
182
+ batch.forEach((b) => b.reject(e));
183
+ }
184
+ }
185
+ }
186
+ export const accord = new Accord();
187
+ export { handler as sellerHandler };
188
+ function ms(s) {
189
+ const m = /^(\d+)(ms|s|m|h)$/.exec(s.trim());
190
+ if (!m)
191
+ throw new AccordError('invalid_duration', s);
192
+ return Number(m[1]) * { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[m[2]];
193
+ }
194
+ const sleep = (t) => new Promise((r) => setTimeout(r, t));
195
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,EAAE;AACF,kEAAkE;AAClE,6FAA6F;AAC7F,wEAAwE;AACxE,EAAE;AACF,4EAA4E;AAC5E,6DAA6D;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AA4CtC,uDAAuD;AACvD,MAAM,CAAC,MAAM,WAAW,GAAG,gCAAgC,CAAC;AAU5D,SAAS,OAAO,CAAC,GAAY;IAC3B,MAAM,CAAC,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC9C,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,aAAa,EAAE,yDAAyD,CAAC,CAAC;IACxG,OAAO,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,IAAI,CAAS;IACb,YAAY,IAAY,EAAE,OAAgB;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,MAAM,OAAO,MAAM;IACR,GAAG,CAAS;IACZ,MAAM,GAAG,EAAE,OAAO,EAAE,CAAC;IAE9B,YAAY,OAAyB,EAAE;QACrC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,WAAW,CAAC,CAAC,OAAO,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CAAC;IAC7C,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,kBAAkB,EAAE,CAAC,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAA2B,CAAC,CAAC;AACpG,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,40 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export type HoldEvent = {
3
+ type: 'hold.placed';
4
+ eventId: string;
5
+ intentId: string;
6
+ index: number;
7
+ /** Cents. */
8
+ amount: number;
9
+ ref: string;
10
+ /** The buyer's agent address. */
11
+ buyer: string;
12
+ holdType: 'reserve' | 'deliver';
13
+ };
14
+ export type FinalEvent = {
15
+ type: 'intent.committed' | 'intent.aborted' | 'intent.expired';
16
+ eventId: string;
17
+ intentId: string;
18
+ index: number;
19
+ amount: number;
20
+ ref: string;
21
+ /** True when this seller's hold was paid. */
22
+ paid: boolean;
23
+ };
24
+ export type HoldAnswer = {
25
+ ready: true;
26
+ } | {
27
+ declined: string;
28
+ };
29
+ export type SellerHandlers = {
30
+ /** Reserve what was asked for. Return { ready: true } or { declined: reason }. */
31
+ onHold: (hold: HoldEvent) => Promise<HoldAnswer | boolean> | HoldAnswer | boolean;
32
+ /** You were paid: fulfill (issue the ticket, ship, release the data). */
33
+ onCommit?: (event: FinalEvent) => Promise<void> | void;
34
+ /** Not paid: release what you reserved. */
35
+ onAbort?: (event: FinalEvent) => Promise<void> | void;
36
+ };
37
+ export declare function handler(h: SellerHandlers): (req: IncomingMessage & {
38
+ body?: any;
39
+ }, res: ServerResponse) => Promise<void>;
40
+ //# sourceMappingURL=seller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seller.d.ts","sourceRoot":"","sources":["../src/seller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,EAAE,aAAa,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa;IACb,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,iCAAiC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,SAAS,GAAG,SAAS,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,kBAAkB,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;IAC/D,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,6CAA6C;IAC7C,IAAI,EAAE,OAAO,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhE,MAAM,MAAM,cAAc,GAAG;IAC3B,kFAAkF;IAClF,MAAM,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,OAAO,CAAC,GAAG,UAAU,GAAG,OAAO,CAAC;IAClF,yEAAyE;IACzE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACvD,2CAA2C;IAC3C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CACvD,CAAC;AAEF,wBAAgB,OAAO,CAAC,CAAC,EAAE,cAAc,IAIzB,KAAK,eAAe,GAAG;IAAE,IAAI,CAAC,EAAE,GAAG,CAAA;CAAE,EAAE,KAAK,cAAc,mBAmBzE"}
package/dist/seller.js ADDED
@@ -0,0 +1,38 @@
1
+ export function handler(h) {
2
+ // Retries are safe: an event already handled gets the same answer again.
3
+ const seen = new Map();
4
+ return async (req, res) => {
5
+ try {
6
+ const event = req.body ?? (await readJson(req));
7
+ if (seen.has(event.eventId))
8
+ return reply(res, 200, seen.get(event.eventId));
9
+ let answer = {};
10
+ if (event.type === 'hold.placed') {
11
+ const out = await h.onHold(event);
12
+ answer = out === true ? { ready: true } : out === false ? { declined: 'declined' } : out;
13
+ }
14
+ else if (event.type === 'intent.committed' && event.paid) {
15
+ await h.onCommit?.(event);
16
+ }
17
+ else if (event.type.startsWith('intent.')) {
18
+ await h.onAbort?.(event);
19
+ }
20
+ seen.set(event.eventId, answer);
21
+ reply(res, 200, answer);
22
+ }
23
+ catch (e) {
24
+ reply(res, 500, { error: e.message });
25
+ }
26
+ };
27
+ }
28
+ async function readJson(req) {
29
+ const chunks = [];
30
+ for await (const c of req)
31
+ chunks.push(c);
32
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
33
+ }
34
+ function reply(res, status, body) {
35
+ res.writeHead(status, { 'content-type': 'application/json' });
36
+ res.end(JSON.stringify(body));
37
+ }
38
+ //# sourceMappingURL=seller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seller.js","sourceRoot":"","sources":["../src/seller.ts"],"names":[],"mappings":"AA0CA,MAAM,UAAU,OAAO,CAAC,CAAiB;IACvC,yEAAyE;IACzE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAmB,CAAC;IAExC,OAAO,KAAK,EAAE,GAAqC,E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AW,CAAC,OAAO,EAAE,CAAC,CAAC;QACnD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,GAAoB;IAC1C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,GAAG;QAAE,MAAM,CAAC,IAAI,CAAC,CAAW,CAAC,CAAC;IACpD,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,KAAK,CAAC,GAAmB,EAAE,MAAc,EAAE,IAAa;IAC/D,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAChC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@getaccord/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Hold money with several sellers, then pay everyone in one step or release everything. Test mode on Sui testnet.",
5
+ "keywords": ["agents", "payments", "escrow", "atomic", "sui"],
6
+ "type": "module",
7
+ "license": "Apache-2.0",
8
+ "exports": {
9
+ ".": {
10
+ "accord-source": "./src/index.ts",
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./seller": {
15
+ "accord-source": "./src/seller.ts",
16
+ "types": "./dist/seller.d.ts",
17
+ "default": "./dist/seller.js"
18
+ }
19
+ },
20
+ "files": ["dist", "README.md", "LICENSE"],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "dependencies": {
29
+ "@mysten/sui": "^3.0.1"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }