@agent402-dev/bond-client 0.0.0-stage → 0.2.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 +202 -0
- package/NOTICE +6 -0
- package/README.md +76 -2
- package/dist/index.d.ts +123 -0
- package/dist/index.js +157 -0
- package/dist/job.d.ts +68 -0
- package/dist/job.js +87 -0
- package/dist/rules.d.ts +67 -0
- package/dist/rules.js +107 -0
- package/package.json +58 -4
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/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @agent402-dev/bond-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Instruction builders for the **Agent402 Bond** Solana program (beta): a performance bond for one deal between a seller and a buyer.
|
|
4
|
+
|
|
5
|
+
Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
|
|
6
|
+
Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
|
|
7
|
+
|
|
8
|
+
> This package only builds instructions and decodes accounts. It holds no keys and sends nothing on its own. The program was reviewed internally, **not independently audited**. Not investment advice.
|
|
9
|
+
|
|
10
|
+
## The program
|
|
11
|
+
- Program id `9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK` on Solana mainnet, **no upgrade authority**.
|
|
12
|
+
- The seller locks a bond (at most 20% of the price), the buyer may lock a deposit. The outcome follows only the parties' signatures and the Solana clock. The program does not judge quality; quality disputes are resolved between the parties.
|
|
13
|
+
- Beta limits: 100 USDC locked per deal, 2,000 USDC across open deals.
|
|
14
|
+
- Source, tests and how to check the deployed code: [programs/](https://github.com/agent402-dev/agent402-toolkit/tree/main/programs). Terms and outcome table: [TERMS.md](https://github.com/agent402-dev/agent402-toolkit/blob/main/docs/bond/TERMS.md). Internal review: [INTERNAL-REVIEW.md](https://github.com/agent402-dev/agent402-toolkit/blob/main/docs/bond/INTERNAL-REVIEW.md).
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
```bash
|
|
18
|
+
npm install @agent402-dev/bond-client @solana/web3.js
|
|
19
|
+
```
|
|
20
|
+
`@solana/web3.js` (v1) is a peer dependency. `@agent402-dev/bond-client/rules` (deadlines, possible actions, settlement preview) has no dependencies at all. Node 20+.
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
```ts
|
|
24
|
+
import { Transaction } from '@solana/web3.js';
|
|
25
|
+
import * as bond from '@agent402-dev/bond-client';
|
|
26
|
+
|
|
27
|
+
const U = 1_000_000n; // USDC has 6 decimals; all amounts are in the smallest unit
|
|
28
|
+
const now = BigInt((await connection.getBlockTime(await connection.getSlot()))!); // Solana clock
|
|
29
|
+
const deal: bond.DealRef = {
|
|
30
|
+
seller, buyer, // PublicKey
|
|
31
|
+
mint: bond.MINTS.mainnet.USDC,
|
|
32
|
+
tokenProgram: bond.TOKEN_PROGRAM_ID,
|
|
33
|
+
nonce: 1n, // unique per seller + buyer pair
|
|
34
|
+
};
|
|
35
|
+
const terms: bond.Terms = {
|
|
36
|
+
price: 20n * U,
|
|
37
|
+
sellerBond: 2n * U,
|
|
38
|
+
buyerDeposit: 5n * U,
|
|
39
|
+
deliverBy: now + 3_600n, // unix seconds
|
|
40
|
+
lateWindow: 0n, // 0..=7 days
|
|
41
|
+
payWindow: 86_400n, // 1..=30 days
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// 1. Both sign: locks the bond and the deposit.
|
|
45
|
+
new Transaction().add(bond.open(deal, terms));
|
|
46
|
+
// 2. Seller marks delivery.
|
|
47
|
+
new Transaction().add(bond.markDelivered(deal));
|
|
48
|
+
// 3. Buyer confirms and pays the balance (price - deposit) straight to the seller.
|
|
49
|
+
new Transaction().add(bond.confirmReceipt(deal), bond.payBalance(deal));
|
|
50
|
+
// 4. Anyone: settle, then each side's claim (order matters).
|
|
51
|
+
new Transaction().add(...bond.settleAndClaim(deal));
|
|
52
|
+
```
|
|
53
|
+
Both sides can end a deal early with `cancelAndClaim` (both sign; each side gets its own money back). `decodeDeal(accountData)` reads a deal's state and outcome.
|
|
54
|
+
|
|
55
|
+
| Export | What it builds |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `open`, `markDelivered`, `confirmReceipt`, `payBalance`, `extend` | Deal steps |
|
|
58
|
+
| `settle`, `claimBuyer`, `claimSeller`, `settleAndClaim` | Closing a deal whose outcome is fixed |
|
|
59
|
+
| `cancel`, `cancelAndClaim` | Closing a deal by mutual agreement |
|
|
60
|
+
| `dealPda`, `vaultPda`, `counterPda`, `configPda`, `dealOf` | Addresses |
|
|
61
|
+
| `decodeDeal`, `OUTCOMES` | Reading a deal |
|
|
62
|
+
| `timeline`, `settlePreview`, `buyerDeadline`, `possibleActions`, `settleBy` | The program's settlement rules in TypeScript (also at `@agent402-dev/bond-client/rules`, no dependencies): deadlines, what each side can do, what settlement pays |
|
|
63
|
+
| `associatedTokenAddress`, `TOKEN_PROGRAM_ID`, `TOKEN_2022_PROGRAM_ID` | Token account helpers |
|
|
64
|
+
| `JOB_PROTOCOL`, `checkJobQuote`, `termsMatchQuote`, `deliverMessage`, `verifyDeliverSignature` | [Bond Job Protocol](https://github.com/agent402-dev/agent402-toolkit/blob/main/docs/bond/JOB-PROTOCOL.md) helpers shared by sellers and buyers (also at `@agent402-dev/bond-client/job`, no dependencies) |
|
|
65
|
+
| `setPaused`, `setAdmin`, `acceptAdmin`, `proposeCaps`, `observePrice`, `activatePriceMode` | Operator and price-record instructions (the operator is a Squads multisig) |
|
|
66
|
+
|
|
67
|
+
## Things to get right
|
|
68
|
+
- **Verify before you sign.** If the other side builds a transaction for you to sign, rebuild the instruction yourself from terms you accept and compare it byte for byte. The [bonded-job example](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/bond-client/examples/job) shows how.
|
|
69
|
+
- **Seller: mark before `deliverBy`.** If nothing is marked or confirmed by the deadline, the bond and the deposit go to the buyer.
|
|
70
|
+
- **Never send tokens directly to a deal vault.** Anything beyond the locked amount is paid to the buyer.
|
|
71
|
+
- If one side's token account is frozen, send `settle` and the other side's claim on their own; the frozen side can claim later into another account it owns.
|
|
72
|
+
|
|
73
|
+
## Example
|
|
74
|
+
Two agents running a bonded job end to end (seller HTTP service, buyer agent, local mainnet-fork demo with no real funds): [examples/job](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/bond-client/examples/job).
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 performance bond: instruction builders (beta).
|
|
3
|
+
*
|
|
4
|
+
* The program never judges quality. Outcomes come only from signatures and
|
|
5
|
+
* the on-chain clock. Settlement records the outcome; each side then claims
|
|
6
|
+
* its own share. `settleAndClaim` puts settle + claim_buyer + claim_seller in
|
|
7
|
+
* one transaction, which is the normal path. If one side's token account is
|
|
8
|
+
* frozen, send `settle` and the other side's claim on their own.
|
|
9
|
+
*
|
|
10
|
+
* Never send tokens straight to a deal vault. Anything beyond the locked
|
|
11
|
+
* amount is returned to the buyer.
|
|
12
|
+
*/
|
|
13
|
+
import { PublicKey, TransactionInstruction } from '@solana/web3.js';
|
|
14
|
+
/** Same program id on devnet and mainnet. */
|
|
15
|
+
export declare const BOND_PROGRAM_ID: PublicKey;
|
|
16
|
+
export declare const MINTS: {
|
|
17
|
+
readonly mainnet: {
|
|
18
|
+
readonly USDC: PublicKey;
|
|
19
|
+
readonly WSOL: PublicKey;
|
|
20
|
+
readonly PREQ: PublicKey;
|
|
21
|
+
};
|
|
22
|
+
readonly devnet: {
|
|
23
|
+
readonly USDC: PublicKey;
|
|
24
|
+
readonly WSOL: PublicKey;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export declare const PREQ_POOL: PublicKey;
|
|
28
|
+
/** sha256("global:<name>")[..8], checked in test/discriminators.test.ts. */
|
|
29
|
+
export declare const DISC: {
|
|
30
|
+
readonly init_counter: readonly [247, 168, 146, 45, 125, 26, 142, 80];
|
|
31
|
+
readonly init_config: readonly [23, 235, 115, 232, 168, 96, 1, 231];
|
|
32
|
+
readonly set_paused: readonly [91, 60, 125, 192, 176, 225, 166, 218];
|
|
33
|
+
readonly set_admin: readonly [251, 163, 0, 52, 91, 194, 187, 92];
|
|
34
|
+
readonly accept_admin: readonly [112, 42, 45, 90, 116, 181, 13, 170];
|
|
35
|
+
readonly propose_caps: readonly [63, 24, 101, 104, 86, 149, 67, 243];
|
|
36
|
+
readonly observe_price: readonly [147, 178, 4, 21, 14, 213, 81, 159];
|
|
37
|
+
readonly activate_price_mode: readonly [181, 205, 243, 174, 176, 192, 111, 71];
|
|
38
|
+
readonly open: readonly [228, 220, 155, 71, 199, 189, 60, 45];
|
|
39
|
+
readonly mark_delivered: readonly [240, 118, 188, 142, 64, 85, 107, 18];
|
|
40
|
+
readonly confirm_receipt: readonly [203, 36, 80, 115, 249, 12, 141, 170];
|
|
41
|
+
readonly pay_balance: readonly [121, 220, 140, 105, 242, 163, 148, 24];
|
|
42
|
+
readonly extend: readonly [228, 127, 0, 1, 227, 154, 54, 168];
|
|
43
|
+
readonly cancel: readonly [232, 219, 223, 41, 219, 236, 220, 190];
|
|
44
|
+
readonly settle: readonly [175, 42, 185, 87, 144, 131, 102, 212];
|
|
45
|
+
readonly claim_seller: readonly [238, 218, 144, 171, 49, 203, 29, 50];
|
|
46
|
+
readonly claim_buyer: readonly [13, 61, 90, 109, 208, 223, 195, 211];
|
|
47
|
+
};
|
|
48
|
+
export declare const configPda: (programId?: PublicKey) => PublicKey;
|
|
49
|
+
export declare const counterPda: (mint: PublicKey, programId?: PublicKey) => PublicKey;
|
|
50
|
+
export declare const dealPda: (seller: PublicKey, buyer: PublicKey, nonce: bigint, programId?: PublicKey) => PublicKey;
|
|
51
|
+
export declare const vaultPda: (deal: PublicKey, programId?: PublicKey) => PublicKey;
|
|
52
|
+
export declare const initConfig: (payer: PublicKey) => TransactionInstruction;
|
|
53
|
+
export declare const initCounter: (payer: PublicKey, mint: PublicKey) => TransactionInstruction;
|
|
54
|
+
export declare const setPaused: (admin: PublicKey, paused: boolean) => TransactionInstruction;
|
|
55
|
+
export declare const setAdmin: (admin: PublicKey, next: PublicKey) => TransactionInstruction;
|
|
56
|
+
export declare const acceptAdmin: (next: PublicKey) => TransactionInstruction;
|
|
57
|
+
export declare const proposeCaps: (admin: PublicKey, mint: PublicKey, perDeal: bigint, total: bigint) => TransactionInstruction;
|
|
58
|
+
export declare const observePrice: (preqMint: PublicKey, quoteVault: PublicKey) => TransactionInstruction;
|
|
59
|
+
export declare const activatePriceMode: (preqMint: PublicKey, quoteVault: PublicKey) => TransactionInstruction;
|
|
60
|
+
export interface Terms {
|
|
61
|
+
/** All amounts in the mint's smallest unit. */
|
|
62
|
+
price: bigint;
|
|
63
|
+
sellerBond: bigint;
|
|
64
|
+
buyerDeposit: bigint;
|
|
65
|
+
/** Unix seconds. */
|
|
66
|
+
deliverBy: bigint;
|
|
67
|
+
/** Seconds, 0..=7 days. */
|
|
68
|
+
lateWindow: bigint;
|
|
69
|
+
/** Seconds, 1..=30 days. */
|
|
70
|
+
payWindow: bigint;
|
|
71
|
+
}
|
|
72
|
+
export interface DealRef {
|
|
73
|
+
seller: PublicKey;
|
|
74
|
+
buyer: PublicKey;
|
|
75
|
+
mint: PublicKey;
|
|
76
|
+
/** SPL Token or Token-2022, matching the mint. */
|
|
77
|
+
tokenProgram: PublicKey;
|
|
78
|
+
nonce: bigint;
|
|
79
|
+
}
|
|
80
|
+
export declare const dealOf: (d: DealRef) => PublicKey;
|
|
81
|
+
/** SPL Token and Token-2022 program ids (so you do not need @solana/spl-token for these). */
|
|
82
|
+
export declare const TOKEN_PROGRAM_ID: PublicKey;
|
|
83
|
+
export declare const TOKEN_2022_PROGRAM_ID: PublicKey;
|
|
84
|
+
/** Associated token account program (same derivation as @solana/spl-token getAssociatedTokenAddressSync; checked in tests). */
|
|
85
|
+
export declare const ATA_PROGRAM_ID: PublicKey;
|
|
86
|
+
/** The owner's associated token account for a mint under a token program (SPL Token or Token-2022). */
|
|
87
|
+
export declare const associatedTokenAddress: (owner: PublicKey, mint: PublicKey, tokenProgram: PublicKey) => PublicKey;
|
|
88
|
+
/** Both seller and buyer must sign. Locks the bond and the deposit. */
|
|
89
|
+
export declare function open(d: DealRef, t: Terms, sellerToken?: PublicKey, buyerToken?: PublicKey): TransactionInstruction;
|
|
90
|
+
export declare const markDelivered: (d: DealRef) => TransactionInstruction;
|
|
91
|
+
export declare const confirmReceipt: (d: DealRef) => TransactionInstruction;
|
|
92
|
+
/** Pays price - deposit straight from buyer to seller. */
|
|
93
|
+
export declare const payBalance: (d: DealRef, buyerToken?: PublicKey, sellerToken?: PublicKey) => TransactionInstruction;
|
|
94
|
+
/** Both sign. The whole term must stay within 180 days of opening. */
|
|
95
|
+
export declare const extend: (d: DealRef, deliverBy: bigint, lateWindow: bigint, payWindow: bigint) => TransactionInstruction;
|
|
96
|
+
export declare const settle: (d: DealRef) => TransactionInstruction;
|
|
97
|
+
export declare const cancel: (d: DealRef) => TransactionInstruction;
|
|
98
|
+
/** Anyone. `to` must be a token account owned by the buyer. */
|
|
99
|
+
export declare const claimBuyer: (d: DealRef, to?: PublicKey) => TransactionInstruction;
|
|
100
|
+
/** Anyone. `to` must be a token account owned by the seller. Closes the deal once the vault is empty. */
|
|
101
|
+
export declare const claimSeller: (d: DealRef, to?: PublicKey) => TransactionInstruction;
|
|
102
|
+
/** The normal closing transaction: settle, buyer's claim, then seller's claim (order matters). */
|
|
103
|
+
export declare const settleAndClaim: (d: DealRef) => TransactionInstruction[];
|
|
104
|
+
/** Both sign: return each side's own money. */
|
|
105
|
+
export declare const cancelAndClaim: (d: DealRef) => TransactionInstruction[];
|
|
106
|
+
export declare const OUTCOMES: readonly ["open", "delivered", "buyer_default", "disputed", "seller_default", "cancelled"];
|
|
107
|
+
export interface DealState {
|
|
108
|
+
seller: PublicKey;
|
|
109
|
+
buyer: PublicKey;
|
|
110
|
+
mint: PublicKey;
|
|
111
|
+
nonce: bigint;
|
|
112
|
+
terms: Terms;
|
|
113
|
+
openedAt: bigint;
|
|
114
|
+
sellerMark: bigint | null;
|
|
115
|
+
buyerConfirm: bigint | null;
|
|
116
|
+
balancePaid: boolean;
|
|
117
|
+
outcome: (typeof OUTCOMES)[number];
|
|
118
|
+
owedSeller: bigint;
|
|
119
|
+
}
|
|
120
|
+
/** Decodes a Deal account (Anchor layout, 8-byte discriminator first). */
|
|
121
|
+
export declare function decodeDeal(raw: Uint8Array): DealState;
|
|
122
|
+
export * from './rules.js';
|
|
123
|
+
export * from './job.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 performance bond: instruction builders (beta).
|
|
3
|
+
*
|
|
4
|
+
* The program never judges quality. Outcomes come only from signatures and
|
|
5
|
+
* the on-chain clock. Settlement records the outcome; each side then claims
|
|
6
|
+
* its own share. `settleAndClaim` puts settle + claim_buyer + claim_seller in
|
|
7
|
+
* one transaction, which is the normal path. If one side's token account is
|
|
8
|
+
* frozen, send `settle` and the other side's claim on their own.
|
|
9
|
+
*
|
|
10
|
+
* Never send tokens straight to a deal vault. Anything beyond the locked
|
|
11
|
+
* amount is returned to the buyer.
|
|
12
|
+
*/
|
|
13
|
+
import { PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js';
|
|
14
|
+
/** Same program id on devnet and mainnet. */
|
|
15
|
+
export const BOND_PROGRAM_ID = new PublicKey('9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK');
|
|
16
|
+
export const MINTS = {
|
|
17
|
+
mainnet: {
|
|
18
|
+
USDC: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
|
|
19
|
+
WSOL: new PublicKey('So11111111111111111111111111111111111111112'),
|
|
20
|
+
PREQ: new PublicKey('aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX'),
|
|
21
|
+
},
|
|
22
|
+
devnet: {
|
|
23
|
+
USDC: new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'),
|
|
24
|
+
WSOL: new PublicKey('So11111111111111111111111111111111111111112'),
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
export const PREQ_POOL = new PublicKey('51F34MKDFBLr5GwKiiJMWV9HsHv63dkkP3ZMMxPN71xc');
|
|
28
|
+
/** sha256("global:<name>")[..8], checked in test/discriminators.test.ts. */
|
|
29
|
+
export const DISC = {
|
|
30
|
+
init_counter: [247, 168, 146, 45, 125, 26, 142, 80],
|
|
31
|
+
init_config: [23, 235, 115, 232, 168, 96, 1, 231],
|
|
32
|
+
set_paused: [91, 60, 125, 192, 176, 225, 166, 218],
|
|
33
|
+
set_admin: [251, 163, 0, 52, 91, 194, 187, 92],
|
|
34
|
+
accept_admin: [112, 42, 45, 90, 116, 181, 13, 170],
|
|
35
|
+
propose_caps: [63, 24, 101, 104, 86, 149, 67, 243],
|
|
36
|
+
observe_price: [147, 178, 4, 21, 14, 213, 81, 159],
|
|
37
|
+
activate_price_mode: [181, 205, 243, 174, 176, 192, 111, 71],
|
|
38
|
+
open: [228, 220, 155, 71, 199, 189, 60, 45],
|
|
39
|
+
mark_delivered: [240, 118, 188, 142, 64, 85, 107, 18],
|
|
40
|
+
confirm_receipt: [203, 36, 80, 115, 249, 12, 141, 170],
|
|
41
|
+
pay_balance: [121, 220, 140, 105, 242, 163, 148, 24],
|
|
42
|
+
extend: [228, 127, 0, 1, 227, 154, 54, 168],
|
|
43
|
+
cancel: [232, 219, 223, 41, 219, 236, 220, 190],
|
|
44
|
+
settle: [175, 42, 185, 87, 144, 131, 102, 212],
|
|
45
|
+
claim_seller: [238, 218, 144, 171, 49, 203, 29, 50],
|
|
46
|
+
claim_buyer: [13, 61, 90, 109, 208, 223, 195, 211],
|
|
47
|
+
};
|
|
48
|
+
const enc = new TextEncoder();
|
|
49
|
+
const u64 = (v) => {
|
|
50
|
+
const b = new Uint8Array(8);
|
|
51
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
52
|
+
return b;
|
|
53
|
+
};
|
|
54
|
+
const i64 = (v) => {
|
|
55
|
+
const b = new Uint8Array(8);
|
|
56
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
57
|
+
return b;
|
|
58
|
+
};
|
|
59
|
+
const data = (d, ...parts) => Buffer.concat([Buffer.from(d), ...parts.map((p) => Buffer.from(p))]);
|
|
60
|
+
const w = (pubkey, isSigner = false) => ({ pubkey, isSigner, isWritable: true });
|
|
61
|
+
const r = (pubkey, isSigner = false) => ({ pubkey, isSigner, isWritable: false });
|
|
62
|
+
const ix = (keys, d, programId = BOND_PROGRAM_ID) => new TransactionInstruction({ programId, keys, data: d });
|
|
63
|
+
// ---------------- addresses ----------------
|
|
64
|
+
export const configPda = (programId = BOND_PROGRAM_ID) => PublicKey.findProgramAddressSync([enc.encode('config')], programId)[0];
|
|
65
|
+
export const counterPda = (mint, programId = BOND_PROGRAM_ID) => PublicKey.findProgramAddressSync([enc.encode('counter'), mint.toBytes()], programId)[0];
|
|
66
|
+
export const dealPda = (seller, buyer, nonce, programId = BOND_PROGRAM_ID) => PublicKey.findProgramAddressSync([enc.encode('deal'), seller.toBytes(), buyer.toBytes(), u64(nonce)], programId)[0];
|
|
67
|
+
export const vaultPda = (deal, programId = BOND_PROGRAM_ID) => PublicKey.findProgramAddressSync([enc.encode('vault'), deal.toBytes()], programId)[0];
|
|
68
|
+
// ---------------- setup (once per cluster) ----------------
|
|
69
|
+
export const initConfig = (payer) => ix([w(payer, true), w(configPda()), r(SystemProgram.programId)], data(DISC.init_config));
|
|
70
|
+
export const initCounter = (payer, mint) => ix([w(payer, true), r(mint), w(counterPda(mint)), r(SystemProgram.programId)], data(DISC.init_counter));
|
|
71
|
+
// ---------------- admin ----------------
|
|
72
|
+
export const setPaused = (admin, paused) => ix([r(admin, true), w(configPda())], data(DISC.set_paused, Uint8Array.of(paused ? 1 : 0)));
|
|
73
|
+
export const setAdmin = (admin, next) => ix([r(admin, true), w(configPda())], data(DISC.set_admin, next.toBytes()));
|
|
74
|
+
export const acceptAdmin = (next) => ix([r(next, true), w(configPda())], data(DISC.accept_admin));
|
|
75
|
+
export const proposeCaps = (admin, mint, perDeal, total) => ix([r(admin, true), r(configPda()), w(counterPda(mint))], data(DISC.propose_caps, u64(perDeal), u64(total)));
|
|
76
|
+
// ---------------- PREQ price record (anyone) ----------------
|
|
77
|
+
export const observePrice = (preqMint, quoteVault) => ix([w(counterPda(preqMint)), r(PREQ_POOL), r(quoteVault)], data(DISC.observe_price));
|
|
78
|
+
export const activatePriceMode = (preqMint, quoteVault) => ix([w(counterPda(preqMint)), r(PREQ_POOL), r(quoteVault)], data(DISC.activate_price_mode));
|
|
79
|
+
export const dealOf = (d) => dealPda(d.seller, d.buyer, d.nonce);
|
|
80
|
+
/** SPL Token and Token-2022 program ids (so you do not need @solana/spl-token for these). */
|
|
81
|
+
export const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
|
|
82
|
+
export const TOKEN_2022_PROGRAM_ID = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
|
|
83
|
+
/** Associated token account program (same derivation as @solana/spl-token getAssociatedTokenAddressSync; checked in tests). */
|
|
84
|
+
export const ATA_PROGRAM_ID = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
|
|
85
|
+
/** The owner's associated token account for a mint under a token program (SPL Token or Token-2022). */
|
|
86
|
+
export const associatedTokenAddress = (owner, mint, tokenProgram) => PublicKey.findProgramAddressSync([owner.toBytes(), tokenProgram.toBytes(), mint.toBytes()], ATA_PROGRAM_ID)[0];
|
|
87
|
+
const ata = (owner, d) => associatedTokenAddress(owner, d.mint, d.tokenProgram);
|
|
88
|
+
/** Both seller and buyer must sign. Locks the bond and the deposit. */
|
|
89
|
+
export function open(d, t, sellerToken = ata(d.seller, d), buyerToken = ata(d.buyer, d)) {
|
|
90
|
+
const deal = dealOf(d);
|
|
91
|
+
return ix([
|
|
92
|
+
w(d.seller, true),
|
|
93
|
+
r(d.buyer, true),
|
|
94
|
+
r(d.mint),
|
|
95
|
+
w(sellerToken),
|
|
96
|
+
w(buyerToken),
|
|
97
|
+
w(deal),
|
|
98
|
+
w(vaultPda(deal)),
|
|
99
|
+
w(counterPda(d.mint)),
|
|
100
|
+
r(configPda()),
|
|
101
|
+
r(d.tokenProgram),
|
|
102
|
+
r(SystemProgram.programId),
|
|
103
|
+
], data(DISC.open, u64(d.nonce), u64(t.price), u64(t.sellerBond), u64(t.buyerDeposit), i64(t.deliverBy), i64(t.lateWindow), i64(t.payWindow)));
|
|
104
|
+
}
|
|
105
|
+
export const markDelivered = (d) => ix([r(d.seller, true), w(dealOf(d))], data(DISC.mark_delivered));
|
|
106
|
+
export const confirmReceipt = (d) => ix([r(d.buyer, true), w(dealOf(d))], data(DISC.confirm_receipt));
|
|
107
|
+
/** Pays price - deposit straight from buyer to seller. */
|
|
108
|
+
export const payBalance = (d, buyerToken = ata(d.buyer, d), sellerToken = ata(d.seller, d)) => ix([r(d.buyer, true), w(dealOf(d)), r(d.mint), w(buyerToken), w(sellerToken), r(d.tokenProgram)], data(DISC.pay_balance));
|
|
109
|
+
/** Both sign. The whole term must stay within 180 days of opening. */
|
|
110
|
+
export const extend = (d, deliverBy, lateWindow, payWindow) => ix([r(d.seller, true), r(d.buyer, true), w(dealOf(d))], data(DISC.extend, i64(deliverBy), i64(lateWindow), i64(payWindow)));
|
|
111
|
+
const decideAccounts = (d) => {
|
|
112
|
+
const deal = dealOf(d);
|
|
113
|
+
return [w(deal), r(vaultPda(deal)), w(counterPda(d.mint))];
|
|
114
|
+
};
|
|
115
|
+
export const settle = (d) => ix(decideAccounts(d), data(DISC.settle));
|
|
116
|
+
export const cancel = (d) => ix([r(d.seller, true), r(d.buyer, true), ...decideAccounts(d)], data(DISC.cancel));
|
|
117
|
+
function claim(d, to, side) {
|
|
118
|
+
const deal = dealOf(d);
|
|
119
|
+
return ix([w(d.seller), w(deal), r(d.mint), w(vaultPda(deal)), w(to), r(d.tokenProgram)], data(side === 'seller' ? DISC.claim_seller : DISC.claim_buyer));
|
|
120
|
+
}
|
|
121
|
+
/** Anyone. `to` must be a token account owned by the buyer. */
|
|
122
|
+
export const claimBuyer = (d, to = ata(d.buyer, d)) => claim(d, to, 'buyer');
|
|
123
|
+
/** Anyone. `to` must be a token account owned by the seller. Closes the deal once the vault is empty. */
|
|
124
|
+
export const claimSeller = (d, to = ata(d.seller, d)) => claim(d, to, 'seller');
|
|
125
|
+
/** The normal closing transaction: settle, buyer's claim, then seller's claim (order matters). */
|
|
126
|
+
export const settleAndClaim = (d) => [settle(d), claimBuyer(d), claimSeller(d)];
|
|
127
|
+
/** Both sign: return each side's own money. */
|
|
128
|
+
export const cancelAndClaim = (d) => [cancel(d), claimBuyer(d), claimSeller(d)];
|
|
129
|
+
// ---------------- reading a deal ----------------
|
|
130
|
+
export const OUTCOMES = ['open', 'delivered', 'buyer_default', 'disputed', 'seller_default', 'cancelled'];
|
|
131
|
+
/** Decodes a Deal account (Anchor layout, 8-byte discriminator first). */
|
|
132
|
+
export function decodeDeal(raw) {
|
|
133
|
+
const v = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
134
|
+
let o = 8;
|
|
135
|
+
const key = () => new PublicKey(raw.slice(o, (o += 32)));
|
|
136
|
+
const n = () => { const x = v.getBigUint64(o, true); o += 8; return x; };
|
|
137
|
+
const s = () => { const x = v.getBigInt64(o, true); o += 8; return x; };
|
|
138
|
+
const seller = key(), buyer = key(), mint = key();
|
|
139
|
+
const nonce = n(), price = n(), sellerBond = n(), buyerDeposit = n();
|
|
140
|
+
const deliverBy = s(), lateWindow = s(), payWindow = s(), openedAt = s(), mark = s(), conf = s();
|
|
141
|
+
const balancePaid = raw[o++] === 1;
|
|
142
|
+
o += 2; // bump, vault_bump
|
|
143
|
+
const outcome = OUTCOMES[raw[o++]] ?? 'open';
|
|
144
|
+
const owedSeller = n();
|
|
145
|
+
return {
|
|
146
|
+
seller, buyer, mint, nonce,
|
|
147
|
+
terms: { price, sellerBond, buyerDeposit, deliverBy, lateWindow, payWindow },
|
|
148
|
+
openedAt,
|
|
149
|
+
sellerMark: mark === 0n ? null : mark,
|
|
150
|
+
buyerConfirm: conf === 0n ? null : conf,
|
|
151
|
+
balancePaid, outcome, owedSeller,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
// Settlement rules (deadlines, possible actions, settlement preview), ported from the program's Rust core.
|
|
155
|
+
export * from './rules.js';
|
|
156
|
+
// Bond Job Protocol v1 (shared by sellers and buyers): quote checks, deliver message, signature check.
|
|
157
|
+
export * from './job.js';
|
package/dist/job.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 Bond Job Protocol v1 — the parts both sides share (no dependencies).
|
|
3
|
+
* Spec: docs/bond/JOB-PROTOCOL.md
|
|
4
|
+
*
|
|
5
|
+
* GET {base}/quote -> JobQuote
|
|
6
|
+
* POST {base}/open { buyer, input } -> JobOpen (open transaction signed by the seller)
|
|
7
|
+
* POST {base}/deliver { deal, expires, signature } -> JobDelivery (after the work, delivery marked on chain)
|
|
8
|
+
*/
|
|
9
|
+
export declare const JOB_PROTOCOL = "agent402-bond-job/1";
|
|
10
|
+
/** Max input size in bytes (UTF-8). */
|
|
11
|
+
export declare const JOB_MAX_INPUT = 16384;
|
|
12
|
+
export interface JobQuote {
|
|
13
|
+
protocol: typeof JOB_PROTOCOL;
|
|
14
|
+
program: string;
|
|
15
|
+
seller: string;
|
|
16
|
+
mint: string;
|
|
17
|
+
tokenProgram: string;
|
|
18
|
+
/** Amounts in the mint's smallest unit, as decimal strings */
|
|
19
|
+
price: string;
|
|
20
|
+
sellerBond: string;
|
|
21
|
+
buyerDeposit: string;
|
|
22
|
+
/** Seconds after opening the seller promises to deliver */
|
|
23
|
+
deliverSeconds: string;
|
|
24
|
+
lateWindow: string;
|
|
25
|
+
payWindow: string;
|
|
26
|
+
/** Free text: what the job is (plain text, at most 500 characters) */
|
|
27
|
+
description?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface JobTerms {
|
|
30
|
+
price: string;
|
|
31
|
+
sellerBond: string;
|
|
32
|
+
buyerDeposit: string;
|
|
33
|
+
deliverBy: string;
|
|
34
|
+
lateWindow: string;
|
|
35
|
+
payWindow: string;
|
|
36
|
+
}
|
|
37
|
+
export interface JobOpen {
|
|
38
|
+
deal: string;
|
|
39
|
+
nonce: string;
|
|
40
|
+
terms: JobTerms;
|
|
41
|
+
transaction: string;
|
|
42
|
+
}
|
|
43
|
+
export interface JobDelivery {
|
|
44
|
+
deal: string;
|
|
45
|
+
result: unknown;
|
|
46
|
+
markTx: string | null;
|
|
47
|
+
}
|
|
48
|
+
/** Returns the problems with a quote (empty if it is well formed). Business rules (limits, allowlists) are the buyer's own. */
|
|
49
|
+
export declare function checkJobQuote(q: unknown): string[];
|
|
50
|
+
/** Whether the terms of an `open` match a quote (deliverBy within deliverSeconds of `now`, allowing `slack` seconds). */
|
|
51
|
+
export declare function termsMatchQuote(t: JobTerms, q: JobQuote, now: bigint, slack?: bigint): string[];
|
|
52
|
+
/** A delivery request signature is valid for at most this many seconds. */
|
|
53
|
+
export declare const JOB_DELIVER_MAX_AGE = 600;
|
|
54
|
+
/**
|
|
55
|
+
* Bytes the buyer signs to fetch a delivery: bound to the deal, to the seller's origin (scheme://host[:port]) and to an
|
|
56
|
+
* expiry (unix seconds), so a signature given to one server cannot be replayed to another or reused later.
|
|
57
|
+
* They start with 0xff so they can never be read as a Solana transaction message (same idea as Solana off-chain messages).
|
|
58
|
+
*/
|
|
59
|
+
export declare function deliverMessage(deal: string, origin: string, expires: number): Uint8Array;
|
|
60
|
+
/** Shape check for the terms in an /open response (before any arithmetic on them). */
|
|
61
|
+
export declare function checkJobTerms(t: unknown): string[];
|
|
62
|
+
export declare const toBase64: (b: Uint8Array) => string;
|
|
63
|
+
export declare const fromBase64: (s: string) => Uint8Array<ArrayBuffer>;
|
|
64
|
+
/**
|
|
65
|
+
* Verifies a delivery request with Web Crypto (Node 20+, Cloudflare Workers, browsers): ed25519 by `publicKey`
|
|
66
|
+
* (32 raw bytes) over deliverMessage(deal, origin, expires), and `expires` between now and now + JOB_DELIVER_MAX_AGE.
|
|
67
|
+
*/
|
|
68
|
+
export declare function verifyDeliverSignature(publicKey: Uint8Array, deal: string, origin: string, expires: number, signatureBase64: string, nowSeconds?: number): Promise<boolean>;
|
package/dist/job.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent402 Bond Job Protocol v1 — the parts both sides share (no dependencies).
|
|
3
|
+
* Spec: docs/bond/JOB-PROTOCOL.md
|
|
4
|
+
*
|
|
5
|
+
* GET {base}/quote -> JobQuote
|
|
6
|
+
* POST {base}/open { buyer, input } -> JobOpen (open transaction signed by the seller)
|
|
7
|
+
* POST {base}/deliver { deal, expires, signature } -> JobDelivery (after the work, delivery marked on chain)
|
|
8
|
+
*/
|
|
9
|
+
export const JOB_PROTOCOL = 'agent402-bond-job/1';
|
|
10
|
+
/** Max input size in bytes (UTF-8). */
|
|
11
|
+
export const JOB_MAX_INPUT = 16_384;
|
|
12
|
+
const DEC = /^\d{1,20}$/;
|
|
13
|
+
const B58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
14
|
+
/** Returns the problems with a quote (empty if it is well formed). Business rules (limits, allowlists) are the buyer's own. */
|
|
15
|
+
export function checkJobQuote(q) {
|
|
16
|
+
const out = [];
|
|
17
|
+
const o = (q ?? {});
|
|
18
|
+
if (o.protocol !== JOB_PROTOCOL)
|
|
19
|
+
out.push(`protocol must be ${JOB_PROTOCOL}`);
|
|
20
|
+
for (const k of ['program', 'seller', 'mint', 'tokenProgram'])
|
|
21
|
+
if (typeof o[k] !== 'string' || !B58.test(o[k]))
|
|
22
|
+
out.push(`${k} must be a base58 address`);
|
|
23
|
+
for (const k of ['price', 'sellerBond', 'buyerDeposit', 'deliverSeconds', 'lateWindow', 'payWindow'])
|
|
24
|
+
if (typeof o[k] !== 'string' || !DEC.test(o[k]))
|
|
25
|
+
out.push(`${k} must be a decimal string`);
|
|
26
|
+
if (o.description !== undefined && (typeof o.description !== 'string' || o.description.length > 500))
|
|
27
|
+
out.push('description must be text up to 500 characters');
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/** Whether the terms of an `open` match a quote (deliverBy within deliverSeconds of `now`, allowing `slack` seconds). */
|
|
31
|
+
export function termsMatchQuote(t, q, now, slack = 120n) {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const k of ['price', 'sellerBond', 'buyerDeposit', 'lateWindow', 'payWindow'])
|
|
34
|
+
if (t[k] !== q[k])
|
|
35
|
+
out.push(`${k} differs from the quote`);
|
|
36
|
+
const by = BigInt(t.deliverBy);
|
|
37
|
+
if (by <= now)
|
|
38
|
+
out.push('deliverBy is in the past');
|
|
39
|
+
if (by > now + BigInt(q.deliverSeconds) + slack)
|
|
40
|
+
out.push('deliverBy is later than the quote allows');
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
const enc = new TextEncoder();
|
|
44
|
+
/** A delivery request signature is valid for at most this many seconds. */
|
|
45
|
+
export const JOB_DELIVER_MAX_AGE = 600;
|
|
46
|
+
/**
|
|
47
|
+
* Bytes the buyer signs to fetch a delivery: bound to the deal, to the seller's origin (scheme://host[:port]) and to an
|
|
48
|
+
* expiry (unix seconds), so a signature given to one server cannot be replayed to another or reused later.
|
|
49
|
+
* They start with 0xff so they can never be read as a Solana transaction message (same idea as Solana off-chain messages).
|
|
50
|
+
*/
|
|
51
|
+
export function deliverMessage(deal, origin, expires) {
|
|
52
|
+
const body = enc.encode(`${JOB_PROTOCOL}:deliver:${deal}:${origin}:${expires}`);
|
|
53
|
+
const out = new Uint8Array(1 + body.length);
|
|
54
|
+
out[0] = 0xff;
|
|
55
|
+
out.set(body, 1);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
const DEC_TERMS = /^\d{1,20}$/;
|
|
59
|
+
/** Shape check for the terms in an /open response (before any arithmetic on them). */
|
|
60
|
+
export function checkJobTerms(t) {
|
|
61
|
+
const o = (t ?? {});
|
|
62
|
+
return ['price', 'sellerBond', 'buyerDeposit', 'deliverBy', 'lateWindow', 'payWindow']
|
|
63
|
+
.filter((k) => typeof o[k] !== 'string' || !DEC_TERMS.test(o[k]))
|
|
64
|
+
.map((k) => `terms.${k} must be a decimal string`);
|
|
65
|
+
}
|
|
66
|
+
const b64 = (b) => btoa(String.fromCharCode(...b));
|
|
67
|
+
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
68
|
+
export const toBase64 = b64;
|
|
69
|
+
export const fromBase64 = unb64;
|
|
70
|
+
/**
|
|
71
|
+
* Verifies a delivery request with Web Crypto (Node 20+, Cloudflare Workers, browsers): ed25519 by `publicKey`
|
|
72
|
+
* (32 raw bytes) over deliverMessage(deal, origin, expires), and `expires` between now and now + JOB_DELIVER_MAX_AGE.
|
|
73
|
+
*/
|
|
74
|
+
export async function verifyDeliverSignature(publicKey, deal, origin, expires, signatureBase64, nowSeconds = Math.floor(Date.now() / 1000)) {
|
|
75
|
+
try {
|
|
76
|
+
if (!Number.isSafeInteger(expires) || expires < nowSeconds || expires > nowSeconds + JOB_DELIVER_MAX_AGE)
|
|
77
|
+
return false;
|
|
78
|
+
const sig = unb64(signatureBase64);
|
|
79
|
+
if (sig.length !== 64 || publicKey.length !== 32)
|
|
80
|
+
return false;
|
|
81
|
+
const key = await crypto.subtle.importKey('raw', new Uint8Array(publicKey), { name: 'Ed25519' }, false, ['verify']);
|
|
82
|
+
return await crypto.subtle.verify('Ed25519', key, new Uint8Array(sig), new Uint8Array(deliverMessage(deal, origin, expires)));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
package/dist/rules.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Agent402 Bond settlement rules, ported one-to-one from the program's
|
|
3
|
+
* pure Rust crate (programs/agent402-bond-core). Use it to show a deal's
|
|
4
|
+
* deadlines, what each side can still do, and what settlement would pay.
|
|
5
|
+
*
|
|
6
|
+
* The program is the source of truth. These functions only predict its
|
|
7
|
+
* answers from a deal's on-chain state; times are the Solana clock (unix seconds).
|
|
8
|
+
*/
|
|
9
|
+
import type { DealState, Terms } from './index.js';
|
|
10
|
+
export declare const DAY = 86400n;
|
|
11
|
+
export declare const GRACE = 86400n;
|
|
12
|
+
export declare const MAX_TERM: bigint;
|
|
13
|
+
export declare const MAX_LATE_WINDOW: bigint;
|
|
14
|
+
export declare const MIN_PAY_WINDOW = 86400n;
|
|
15
|
+
export declare const MAX_PAY_WINDOW: bigint;
|
|
16
|
+
export declare const MAX_BOND_BPS = 2000n;
|
|
17
|
+
export type Outcome = 'delivered' | 'buyer_default' | 'disputed' | 'seller_default' | 'cancelled';
|
|
18
|
+
export interface Payout {
|
|
19
|
+
toSeller: bigint;
|
|
20
|
+
toBuyer: bigint;
|
|
21
|
+
outcome: Outcome;
|
|
22
|
+
}
|
|
23
|
+
/** The parts of a deal the rules depend on (a subset of `DealState`). */
|
|
24
|
+
export interface RuleDeal {
|
|
25
|
+
terms: Terms;
|
|
26
|
+
openedAt: bigint;
|
|
27
|
+
sellerMark: bigint | null;
|
|
28
|
+
buyerConfirm: bigint | null;
|
|
29
|
+
balancePaid: boolean;
|
|
30
|
+
}
|
|
31
|
+
export declare const balanceOf: (t: Terms) => bigint;
|
|
32
|
+
export declare const t1: (t: Terms) => bigint;
|
|
33
|
+
export declare const t2: (t: Terms) => bigint;
|
|
34
|
+
/** Delivery time once the buyer has confirmed. */
|
|
35
|
+
export declare function deliveryTime(d: RuleDeal): bigint | null;
|
|
36
|
+
/** Last moment the buyer may confirm or pay the balance. */
|
|
37
|
+
export declare function buyerDeadline(d: RuleDeal): bigint;
|
|
38
|
+
/** Pro-rata late deduction from the seller bond, paid to the buyer. */
|
|
39
|
+
export declare function lateDeduction(d: RuleDeal): bigint;
|
|
40
|
+
/** What `settle` would pay at `now`, or null if the program would refuse (not yet settleable). */
|
|
41
|
+
export declare function settlePreview(d: RuleDeal, now: bigint): Payout | null;
|
|
42
|
+
/** Latest time at which `settle` is guaranteed to succeed. */
|
|
43
|
+
export declare const settleBy: (d: RuleDeal) => bigint;
|
|
44
|
+
/** Earliest time `settle` succeeds if nobody acts again (null if it already does at `now`). */
|
|
45
|
+
export declare function settleableFrom(d: RuleDeal, now: bigint): bigint | null;
|
|
46
|
+
export interface Action {
|
|
47
|
+
action: string;
|
|
48
|
+
who: 'seller' | 'buyer' | 'both' | 'anyone';
|
|
49
|
+
until?: bigint;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* What can still be done at `now` according to the program's rules.
|
|
53
|
+
* `cancel` and `extend` need both signatures and are listed while the deal is open.
|
|
54
|
+
*/
|
|
55
|
+
export declare function possibleActions(d: RuleDeal, now: bigint): Action[];
|
|
56
|
+
/** Summary of an open deal at `now`: deadlines, possible actions and the settlement that applies now or later. */
|
|
57
|
+
export declare function timeline(d: RuleDeal | DealState, now: bigint): {
|
|
58
|
+
now: bigint;
|
|
59
|
+
deliverBy: bigint;
|
|
60
|
+
lateUntil: bigint;
|
|
61
|
+
buyerDeadline: bigint;
|
|
62
|
+
settleBy: bigint;
|
|
63
|
+
lateDeduction: bigint;
|
|
64
|
+
settleNow: Payout | null;
|
|
65
|
+
settleableFrom: bigint | null;
|
|
66
|
+
possibleActions: Action[];
|
|
67
|
+
};
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export const DAY = 86400n;
|
|
2
|
+
export const GRACE = DAY;
|
|
3
|
+
export const MAX_TERM = 180n * DAY;
|
|
4
|
+
export const MAX_LATE_WINDOW = 7n * DAY;
|
|
5
|
+
export const MIN_PAY_WINDOW = DAY;
|
|
6
|
+
export const MAX_PAY_WINDOW = 30n * DAY;
|
|
7
|
+
export const MAX_BOND_BPS = 2000n;
|
|
8
|
+
const max = (a, b) => (a > b ? a : b);
|
|
9
|
+
const min = (a, b) => (a < b ? a : b);
|
|
10
|
+
export const balanceOf = (t) => t.price - t.buyerDeposit;
|
|
11
|
+
export const t1 = (t) => t.deliverBy + GRACE;
|
|
12
|
+
export const t2 = (t) => t1(t) + t.lateWindow;
|
|
13
|
+
/** Delivery time once the buyer has confirmed. */
|
|
14
|
+
export function deliveryTime(d) {
|
|
15
|
+
if (d.buyerConfirm === null)
|
|
16
|
+
return null;
|
|
17
|
+
return d.sellerMark === null ? d.buyerConfirm : min(d.sellerMark, d.buyerConfirm);
|
|
18
|
+
}
|
|
19
|
+
/** Last moment the buyer may confirm or pay the balance. */
|
|
20
|
+
export function buyerDeadline(d) {
|
|
21
|
+
const t = d.terms;
|
|
22
|
+
const first = d.sellerMark !== null && d.buyerConfirm !== null
|
|
23
|
+
? min(d.sellerMark, d.buyerConfirm)
|
|
24
|
+
: (d.sellerMark ?? d.buyerConfirm);
|
|
25
|
+
if (first === null)
|
|
26
|
+
return t2(t);
|
|
27
|
+
const w = max(first, t1(t)) + t.payWindow + GRACE;
|
|
28
|
+
return d.buyerConfirm === null ? max(w, t2(t)) : w;
|
|
29
|
+
}
|
|
30
|
+
/** Pro-rata late deduction from the seller bond, paid to the buyer. */
|
|
31
|
+
export function lateDeduction(d) {
|
|
32
|
+
const dt = deliveryTime(d);
|
|
33
|
+
if (dt === null)
|
|
34
|
+
return 0n;
|
|
35
|
+
const start = t1(d.terms);
|
|
36
|
+
if (dt <= start || d.terms.lateWindow === 0n)
|
|
37
|
+
return 0n;
|
|
38
|
+
const late = min(dt - start, d.terms.lateWindow);
|
|
39
|
+
return (d.terms.sellerBond * late) / d.terms.lateWindow;
|
|
40
|
+
}
|
|
41
|
+
/** What `settle` would pay at `now`, or null if the program would refuse (not yet settleable). */
|
|
42
|
+
export function settlePreview(d, now) {
|
|
43
|
+
const t = d.terms;
|
|
44
|
+
if (d.buyerConfirm !== null) {
|
|
45
|
+
const deduct = lateDeduction(d);
|
|
46
|
+
let outcome;
|
|
47
|
+
if (d.balancePaid)
|
|
48
|
+
outcome = 'delivered';
|
|
49
|
+
else if (now > buyerDeadline(d))
|
|
50
|
+
outcome = 'buyer_default';
|
|
51
|
+
else
|
|
52
|
+
return null;
|
|
53
|
+
return { toSeller: t.sellerBond - deduct + t.buyerDeposit, toBuyer: deduct, outcome };
|
|
54
|
+
}
|
|
55
|
+
if (d.sellerMark !== null) {
|
|
56
|
+
if (now <= buyerDeadline(d))
|
|
57
|
+
return null;
|
|
58
|
+
return { toSeller: t.sellerBond, toBuyer: t.buyerDeposit, outcome: 'disputed' };
|
|
59
|
+
}
|
|
60
|
+
if (now <= t2(t))
|
|
61
|
+
return null;
|
|
62
|
+
return { toSeller: 0n, toBuyer: t.sellerBond + t.buyerDeposit, outcome: 'seller_default' };
|
|
63
|
+
}
|
|
64
|
+
/** Latest time at which `settle` is guaranteed to succeed. */
|
|
65
|
+
export const settleBy = (d) => t2(d.terms) + d.terms.payWindow + GRACE + 1n;
|
|
66
|
+
/** Earliest time `settle` succeeds if nobody acts again (null if it already does at `now`). */
|
|
67
|
+
export function settleableFrom(d, now) {
|
|
68
|
+
if (settlePreview(d, now) !== null)
|
|
69
|
+
return null;
|
|
70
|
+
if (d.buyerConfirm !== null || d.sellerMark !== null)
|
|
71
|
+
return buyerDeadline(d) + 1n;
|
|
72
|
+
return t2(d.terms) + 1n;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What can still be done at `now` according to the program's rules.
|
|
76
|
+
* `cancel` and `extend` need both signatures and are listed while the deal is open.
|
|
77
|
+
*/
|
|
78
|
+
export function possibleActions(d, now) {
|
|
79
|
+
const out = [];
|
|
80
|
+
const bd = buyerDeadline(d);
|
|
81
|
+
if (d.sellerMark === null && d.buyerConfirm === null && now <= t2(d.terms)) {
|
|
82
|
+
out.push({ action: 'mark_delivered', who: 'seller', until: t2(d.terms) });
|
|
83
|
+
}
|
|
84
|
+
if (d.buyerConfirm === null && now <= bd)
|
|
85
|
+
out.push({ action: 'confirm_receipt', who: 'buyer', until: bd });
|
|
86
|
+
if (d.buyerConfirm !== null && !d.balancePaid && now <= bd)
|
|
87
|
+
out.push({ action: 'pay_balance', who: 'buyer', until: bd });
|
|
88
|
+
if (settlePreview(d, now) !== null)
|
|
89
|
+
out.push({ action: 'settle_and_claim', who: 'anyone' });
|
|
90
|
+
out.push({ action: 'cancel', who: 'both' }, { action: 'extend', who: 'both' });
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
/** Summary of an open deal at `now`: deadlines, possible actions and the settlement that applies now or later. */
|
|
94
|
+
export function timeline(d, now) {
|
|
95
|
+
const r = d;
|
|
96
|
+
return {
|
|
97
|
+
now,
|
|
98
|
+
deliverBy: r.terms.deliverBy,
|
|
99
|
+
lateUntil: t2(r.terms),
|
|
100
|
+
buyerDeadline: buyerDeadline(r),
|
|
101
|
+
settleBy: settleBy(r),
|
|
102
|
+
lateDeduction: lateDeduction(r),
|
|
103
|
+
settleNow: settlePreview(r, now),
|
|
104
|
+
settleableFrom: settleableFrom(r, now),
|
|
105
|
+
possibleActions: possibleActions(r, now),
|
|
106
|
+
};
|
|
107
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent402-dev/bond-client",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
"description": "Instruction builders for the Agent402 Bond Solana program (beta): seller bond and buyer deposit for one deal, outcomes by signatures and the Solana clock. Holds no keys and sends nothing.",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"solana",
|
|
6
|
+
"escrow",
|
|
7
|
+
"bond",
|
|
8
|
+
"usdc",
|
|
9
|
+
"agent"
|
|
10
|
+
],
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./rules": {
|
|
19
|
+
"types": "./dist/rules.d.ts",
|
|
20
|
+
"default": "./dist/rules.js"
|
|
21
|
+
},
|
|
22
|
+
"./job": {
|
|
23
|
+
"types": "./dist/job.d.ts",
|
|
24
|
+
"default": "./dist/job.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@solana/web3.js": "^1.98.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"@solana/web3.js": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"version": "0.2.0",
|
|
36
|
+
"author": "Agent402",
|
|
37
|
+
"license": "Apache-2.0",
|
|
38
|
+
"type": "module",
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=20"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/agent402-dev/agent402-toolkit.git",
|
|
45
|
+
"directory": "packages/bond-client"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/bond-client#readme",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/agent402-dev/agent402-toolkit/issues"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"files": [
|
|
55
|
+
"dist",
|
|
56
|
+
"README.md",
|
|
57
|
+
"LICENSE",
|
|
58
|
+
"NOTICE"
|
|
59
|
+
]
|
|
60
|
+
}
|