latch-xlayer 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +133 -0
  2. package/README.md +25 -2
  3. package/latch.mjs +300 -0
  4. package/package.json +41 -4
package/LICENSE ADDED
@@ -0,0 +1,133 @@
1
+ Latch
2
+ Copyright (C) 2026 the Latch authors
3
+
4
+ This program is free software; you can redistribute it and/or modify it under the terms of the
5
+ GNU General Public License as published by the Free Software Foundation; either version 2 of the
6
+ License, or (at your option) any later version (SPDX: GPL-2.0-or-later).
7
+
8
+ contracts/UniMath.sol is a port of Uniswap v3 libraries, which are GPL-2.0-or-later.
9
+ contracts/LatchRelay.sol (retired) carries its own MIT SPDX header.
10
+
11
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
12
+ even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
+ General Public License below for more details.
14
+
15
+ ------------------------------------------------------------------------------------------------
16
+
17
+ GNU GENERAL PUBLIC LICENSE
18
+ Version 2, June 1991
19
+
20
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
21
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22
+
23
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
24
+
25
+ Preamble
26
+
27
+ The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
28
+
29
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
30
+
31
+ To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
34
+
35
+ We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
36
+
37
+ Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
38
+
39
+ Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
40
+
41
+ The precise terms and conditions for copying, distribution and modification follow.
42
+
43
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
44
+
45
+ 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
46
+
47
+ Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
48
+
49
+ 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
50
+
51
+ You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
52
+
53
+ 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
54
+
55
+ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
56
+
57
+ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
58
+
59
+ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
60
+
61
+ These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
62
+
63
+ Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
64
+
65
+ In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
66
+
67
+ 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
68
+
69
+ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
70
+
71
+ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
72
+
73
+ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
74
+
75
+ The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
76
+
77
+ If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
78
+
79
+ 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
80
+
81
+ 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
82
+
83
+ 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
84
+
85
+ 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
86
+
87
+ If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
88
+
89
+ It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
90
+
91
+ This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
92
+
93
+ 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
94
+
95
+ 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
96
+
97
+ Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
98
+
99
+ 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
100
+
101
+ NO WARRANTY
102
+
103
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
104
+
105
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
106
+
107
+ END OF TERMS AND CONDITIONS
108
+
109
+ How to Apply These Terms to Your New Programs
110
+
111
+ If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
112
+
113
+ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
114
+
115
+ one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
116
+
117
+ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
118
+
119
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
120
+
121
+ You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
122
+
123
+ If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
124
+
125
+ Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
126
+
127
+ The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
128
+
129
+ You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
130
+
131
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
132
+
133
+ signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # latch-xlayer
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
+ The `latch` command-line tool for AI agents using **Latch** on X Layer: vaults that buy OKB on dips or take profit on rises, with every trade sized on chain by a TapeOut circuit.
4
+
5
+ It **reads** Latch on X Layer (chain 196) and **prepares** transactions. It never holds, asks for or sees a private key: each write is printed as JSON with a ready `onchainos wallet contract-call` command, so the **OKX Agentic Wallet** signs it inside OKX's TEE after the user confirms.
6
+
7
+ ```
8
+ npx latch-xlayer market # live OKB price as Latch vaults see it
9
+ npx latch-xlayer try --dir buy --mode smart --ref 95 --limit 100 --base 2
10
+ npx latch-xlayer vaults --owner 0x…
11
+ ```
12
+
13
+ Or install once and use `latch`:
14
+
15
+ ```
16
+ npm install -g latch-xlayer
17
+ latch --help
18
+ ```
19
+
20
+ Commands: `market`, `try`, `vaults`, `status`, `create`, `fund`, `wrap`, `pause`, `resume`, `strategy`, `withdraw`, `tick`. Run `latch --help` for details.
21
+
22
+ - App: https://okblatch.xyz · Agents guide: https://okblatch.xyz/#/agents
23
+ - Skill for AI agents: `npx skills add sollid-web/latch`
24
+ - Source, tests and contracts: https://github.com/sollid-web/latch
25
+
26
+ Independent project on X Layer. Not affiliated with OKX. License: GPL-2.0-or-later.
package/latch.mjs ADDED
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env node
2
+ // latch: command-line tool for AI agents (OKX Plugin Store skill "latch").
3
+ // Reads Latch on X Layer and PREPARES transactions; it never holds or asks for a private key.
4
+ // Every write is printed as JSON with a ready `onchainos wallet contract-call` command, so the
5
+ // agent's OKX Agentic Wallet signs it inside OKX's TEE.
6
+ //
7
+ // latch market live OKB price as Latch vaults see it
8
+ // latch try --dir buy --mode smart --ref 95 --limit 100 --base 2 what would a vault do right now (real chip)
9
+ // latch vaults --owner 0x… an owner's vaults
10
+ // latch status --vault 0x… one vault: settings, balance, what the chip sees, next action
11
+ // latch create --dir buy --mode smart --savings 0x… --base 2 --ref 95 --limit 100 [--per-trade 6 --daily 6 --every day --keeper 0x…]
12
+ // latch fund --vault 0x… --amount 10 [--from 0x…] add USDT0 (Buy vault) or WOKB (Take Profit vault); checks the payer's balance first; allow + deposit through Latch's helper
13
+ // latch wrap --amount 0.1 OKB → WOKB (Take Profit vaults hold WOKB)
14
+ // latch pause|resume --vault 0x…
15
+ // latch strategy --vault 0x… [--mode --base --ref --limit --every]
16
+ // latch withdraw --vault 0x… --to 0x… everything back to the owner
17
+ // latch tick --vault 0x… --as 0x… for an agent that IS the vault's bot: trade now if the chip allows
18
+ // Global: --rpc <url> (or LATCH_RPC), LATCH_CONFIG=<json file> to point at other deployments (tests).
19
+ import fs from 'node:fs';
20
+ import { createPublicClient, http, parseAbi, encodeFunctionData, parseUnits, formatUnits, getAddress, isAddress, decodeErrorResult } from 'viem';
21
+
22
+ const MAINNET = {
23
+ chainId: 196,
24
+ rpc: 'https://rpc.xlayer.tech',
25
+ factory2: '0x9C647a631fe59813c430D03330C3A4Da21df6428',
26
+ processor: '0x3728a5dfE596F6bF7309cA911e61ecaC9b0b6813',
27
+ circuit2Id: 2,
28
+ usdt: '0x779Ded0c9e1022225f8E0630b35a9b54bE713736',
29
+ wokb: '0xe538905cf8410324e03A5A23C1c177a474D59b2b',
30
+ pool: '0xe3BE6A0137f1b0602Fc1a4841686f43B340a5082',
31
+ depositor: '0x948ea5060786167f1d9f7fdfbF3301c59893E3D4', // LatchDeposit: OKX wallets refuse plain USDT0 transfers on X Layer, but sign contract calls
32
+ site: 'https://okblatch.xyz'
33
+ };
34
+ const C = { ...MAINNET, ...(process.env.LATCH_CONFIG ? JSON.parse(fs.readFileSync(process.env.LATCH_CONFIG, 'utf8')) : {}) };
35
+
36
+ const FACTORY2 = parseAbi([
37
+ 'function createVault(uint8 direction, uint8 mode, address savings, uint256 baseAmount, uint256 perTxCap, uint256 dailyCap, uint256 refPrice, uint256 limitPrice, uint256 minInterval, address keeper) returns (address)',
38
+ 'function vaultsOf(address owner) view returns (address[])',
39
+ 'function isVault(address) view returns (bool)',
40
+ 'function treasury() view returns (address)',
41
+ 'function hostedKeeper() view returns (address)',
42
+ 'function minBuy() view returns (uint256)',
43
+ 'function minSell() view returns (uint256)'
44
+ ]);
45
+ const VAULT2 = parseAbi([
46
+ 'function owner() view returns (address)', 'function keeper() view returns (address)', 'function savings() view returns (address)',
47
+ 'function paused() view returns (bool)', 'function direction() view returns (uint8)', 'function mode() view returns (uint8)',
48
+ 'function tokenIn() view returns (address)', 'function tokenOut() view returns (address)',
49
+ 'function baseAmount() view returns (uint256)', 'function perTxCap() view returns (uint256)', 'function dailyCap() view returns (uint256)',
50
+ 'function refPrice() view returns (uint256)', 'function limitPrice() view returns (uint256)', 'function minInterval() view returns (uint256)',
51
+ 'function minAmount() view returns (uint256)', 'function nextTradeAt() view returns (uint256)', 'function spentTodayNow() view returns (uint256)',
52
+ 'function volumeIn() view returns (uint256)', 'function totalOut() view returns (uint256)', 'function trades() view returns (uint256)',
53
+ 'function feeBpsNow() view returns (uint256)', 'function twapPrice() view returns (uint256)',
54
+ 'function preview(address caller) view returns (uint16 inputs, uint8 k, uint256 amount, uint256 fee, uint256 minOut, uint256 avgPrice)',
55
+ 'function chip(uint16 inputs) view returns (bool allow, uint8 k)',
56
+ 'function tick()', 'function setPaused(bool next)',
57
+ 'function setStrategy(uint256 baseAmount, uint256 perTxCap, uint256 dailyCap, uint256 refPrice, uint256 limitPrice, uint256 minInterval, uint8 mode)',
58
+ 'function withdraw(address token, address to, uint256 amount)',
59
+ 'error NotOwner()', 'error OverCap()', 'error CapRaised()', 'error BadParam()', 'error BadSavings()', 'error BadRecipient()', 'error Underfunded()'
60
+ ]);
61
+ const ERC20 = parseAbi(['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)',
62
+ 'function allowance(address owner, address spender) view returns (uint256)', 'function approve(address spender, uint256 amount) returns (bool)']);
63
+ const DEPOSIT = parseAbi(['function deposit(address token, address vault, uint256 amount)']);
64
+ const WOKB = parseAbi(['function deposit() payable']);
65
+ const POOL = parseAbi(['function slot0() view returns (uint160,int24,uint16,uint16,uint16,uint8,bool)', 'function token0() view returns (address)', 'function observe(uint32[] secondsAgos) view returns (int56[], uint160[])']);
66
+ const PROC = parseAbi(['function eval(uint256 id, bytes inputs) view returns (bytes)']);
67
+ const MAX = 2n ** 256n - 1n;
68
+ const ZERO = '0x0000000000000000000000000000000000000000';
69
+
70
+ const MODES = ['steady', 'dips', 'smart', 'ladder'];
71
+ const MODE_TEXT = [
72
+ ['Steady: the same amount every time', 'Dips only: buys only below the reference price', 'Smart: 2× or 3× more on bigger dips, 1× when the market is jumpy', 'Ladder: 1× from a 5% dip, 2× from 15%, 3× from 30%'],
73
+ ['Steady: sells the same amount every time (never under the floor)', 'Rises only: sells only above the reference price', 'Smart: 2× or 3× more on bigger rises, 1× when the market is jumpy', 'Ladder: 1× from a 5% rise, 2× from 15%, 3× from 30%']
74
+ ];
75
+ const DEPTHS = ['no move past the reference', 'under 5%', '5–10%', '10–15%', '15–20%', '20–30%', '30–40%', '40% or more'];
76
+ const VOLS = ['calm', 'a little busy', 'jumpy', 'very jumpy'];
77
+ const EVERY = { any: 0n, hour: 3600n, day: 86400n, week: 604800n };
78
+
79
+ /* ------------------------------------------------------------------ args */
80
+ const argv = process.argv.slice(2);
81
+ const cmd = argv[0];
82
+ const opt = {};
83
+ for (let i = 1; i < argv.length; i++) {
84
+ if (argv[i].startsWith('--')) { const k = argv[i].slice(2); const v = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : 'true'; opt[k] = v; }
85
+ }
86
+ const pub = createPublicClient({ transport: http(opt.rpc || process.env.LATCH_RPC || C.rpc, { timeout: 30_000 }) });
87
+ const read = (address, abi, functionName, args = []) => pub.readContract({ address, abi, functionName, args });
88
+ const out = (o) => { process.stdout.write(JSON.stringify(o, (k, v) => (typeof v === 'bigint' ? v.toString() : v), 2) + '\n'); };
89
+ class UserError extends Error {}
90
+ const need = (k, check, what) => {
91
+ const v = opt[k];
92
+ if (v === undefined || v === 'true') throw new UserError(`missing --${k} (${what})`);
93
+ if (check && !check(v)) throw new UserError(`--${k} is not valid: ${what}`);
94
+ return v;
95
+ };
96
+ const addr = (k, what) => getAddress(need(k, isAddress, what));
97
+ const dirOf = (v) => { if (v === 'buy' || v === '0') return 0; if (v === 'sell' || v === 'take-profit' || v === 'takeprofit' || v === '1') return 1; throw new UserError('--dir must be buy or sell'); };
98
+ const modeOf = (v) => { const i = MODES.indexOf(String(v).toLowerCase()); if (i < 0) throw new UserError('--mode must be steady, dips, smart or ladder'); return i; };
99
+ const usd = (v) => Number(formatUnits(v, 6));
100
+ const amtOf = (v, dir) => (dir === 0 ? `${usd(v)} USDT0` : `${Number(formatUnits(v, 18))} OKB`);
101
+
102
+ /** A transaction for the agent's OKX Agentic Wallet to sign (never signed here). */
103
+ function tx(description, to, data, value = 0n) {
104
+ return {
105
+ description, chain: C.chainId, to, inputData: data, amt: value.toString(),
106
+ onchainos: `onchainos wallet contract-call --to ${to} --chain ${C.chainId} --input-data ${data} --amt ${value}`
107
+ };
108
+ }
109
+
110
+ /* ------------------------------------------------------------------ market + chip */
111
+ async function market() {
112
+ const [s0, t0, obs] = await Promise.all([read(C.pool, POOL, 'slot0'), read(C.pool, POOL, 'token0'), read(C.pool, POOL, 'observe', [[1800, 0]])]);
113
+ const d = obs[0][1] - obs[0][0];
114
+ let avgTick = Number(d / 1800n); if (d < 0n && d % 1800n !== 0n) avgTick--;
115
+ const usdtIs0 = t0.toLowerCase() === C.usdt.toLowerCase();
116
+ const px = (t) => { const raw = Math.pow(1.0001, t); return usdtIs0 ? 1e12 / raw : raw * 1e12; };
117
+ const gap = Math.abs(Number(s0[1]) - avgTick);
118
+ return { avg30min: +px(avgTick).toFixed(4), live: +px(Number(s0[1])).toFixed(4), gapTicks: gap, market: VOLS[gap < 15 ? 0 : gap < 35 ? 1 : gap < 60 ? 2 : 3], stable: gap <= 100 };
119
+ }
120
+ function depthOf(price, ref, dir) {
121
+ const move = dir === 0 ? (ref - price) / ref : (price - ref) / ref;
122
+ if (!(move > 0)) return 0;
123
+ const bps = move * 10000;
124
+ return bps < 500 ? 1 : bps < 1000 ? 2 : bps < 1500 ? 3 : bps < 2000 ? 4 : bps < 3000 ? 5 : bps < 4000 ? 6 : 7;
125
+ }
126
+ async function askChip(input) {
127
+ const hex = '0x' + (input & 0xff).toString(16).padStart(2, '0') + ((input >> 8) & 0xff).toString(16).padStart(2, '0');
128
+ const o = parseInt((await read(C.processor, PROC, 'eval', [BigInt(C.circuit2Id), hex])).slice(2, 4), 16);
129
+ return { allow: (o & 1) === 1, k: o & 1 ? (o >> 1) & 3 : 0 };
130
+ }
131
+
132
+ /* ------------------------------------------------------------------ vault reads */
133
+ async function vaultInfo(v) {
134
+ if (!(await read(C.factory2, FACTORY2, 'isVault', [v]))) throw new UserError(`${v} is not a Latch vault on X Layer. Check the address: \`latch vaults --owner <wallet>\` lists a wallet's vaults.`);
135
+ const F = ['owner', 'keeper', 'savings', 'paused', 'direction', 'mode', 'tokenIn', 'tokenOut', 'baseAmount', 'perTxCap', 'dailyCap', 'refPrice', 'limitPrice',
136
+ 'minInterval', 'minAmount', 'nextTradeAt', 'spentTodayNow', 'volumeIn', 'totalOut', 'trades', 'feeBpsNow', 'twapPrice'];
137
+ const r = Object.fromEntries(await Promise.all(F.map(async (f) => [f, await read(v, VAULT2, f)])));
138
+ r.dir = Number(r.direction); r.modeIx = Number(r.mode);
139
+ r.balance = await read(r.tokenIn, ERC20, 'balanceOf', [v]);
140
+ r.leftover = await read(r.tokenOut, ERC20, 'balanceOf', [v]);
141
+ return r;
142
+ }
143
+ /** The vault pays the fee on top of each trade, so its smallest possible trade needs minimum × (1 + fee). */
144
+ const needToTrade = (r) => (r.minAmount * (10_000n + r.feeBpsNow) + 9_999n) / 10_000n;
145
+ async function decision(v, r, caller) {
146
+ const [inputs, k, amount, fee] = await read(v, VAULT2, 'preview', [caller]);
147
+ const x = Number(inputs);
148
+ const dep = (x >> 7) & 7, vol = (x >> 10) & 3;
149
+ let why;
150
+ if (amount > 0n) why = `the chip says ${r.dir === 0 ? 'buy' : 'sell'} ${Number(k)}× (${amtOf(amount, r.dir)})`;
151
+ else if (r.paused) why = 'paused by the owner';
152
+ else if (caller.toLowerCase() !== r.keeper.toLowerCase()) why = `only the vault's own agent (${r.keeper}) can trade`;
153
+ else if (r.balance === 0n) why = `the vault needs ${r.dir === 0 ? 'USDT0' : 'WOKB'}`;
154
+ else if (r.balance < needToTrade(r)) why = `the vault holds ${amtOf(r.balance, r.dir)}, but the smallest trade needs ${amtOf(needToTrade(r), r.dir)} (the ${amtOf(r.minAmount, r.dir)} minimum plus the ${Number(r.feeBpsNow) / 100}% fee): add at least ${amtOf(needToTrade(r) - r.balance, r.dir)}`;
155
+ else if (r.dailyCap - r.spentTodayNow < r.minAmount) why = "today's limit is used";
156
+ else if (r.nextTradeAt > 0n) why = `next trade possible at ${new Date(Number(r.nextTradeAt) * 1000).toISOString()}`;
157
+ else {
158
+ const [allow, kk] = await read(v, VAULT2, 'chip', [(x & 0xff80) | 0x7e]);
159
+ if (!allow || Number(kk) === 0) why = vol === 3 && r.modeIx >= 2 ? 'the market is very jumpy; the strategy waits' : `OKB is ${DEPTHS[dep]} ${r.dir === 0 ? 'below' : 'above'} the reference; the strategy waits`;
160
+ else if (!(x & 8)) why = r.dir === 0 ? 'OKB is above the ceiling, or moving too fast' : 'OKB is under the floor, or moving too fast';
161
+ else if (!(x & 16)) why = 'the trade size falls outside your limits';
162
+ else why = 'a safety check said no';
163
+ }
164
+ return { tradeNow: amount > 0n, multiplier: Number(k), amount: amtOf(amount, r.dir), fee: amtOf(fee, r.dir), why,
165
+ chipSees: { move: DEPTHS[dep], market: VOLS[vol], safetyChecksPassed: (x & 0x7f) === 0x7e, inputBits: '0x' + x.toString(16).padStart(4, '0') } };
166
+ }
167
+ const summary = (v, r) => ({
168
+ vault: v, job: r.dir === 0 ? 'Buy OKB' : 'Take profit', strategy: MODE_TEXT[r.dir][r.modeIx], paused: r.paused,
169
+ owner: r.owner, outputGoesTo: r.savings, bot: r.keeper,
170
+ baseAmount: amtOf(r.baseAmount, r.dir), mostPerTrade: amtOf(r.perTxCap, r.dir), mostPerDay: amtOf(r.dailyCap, r.dir), usedToday: amtOf(r.spentTodayNow, r.dir),
171
+ referencePrice: usd(r.refPrice), [r.dir === 0 ? 'ceiling' : 'floor']: usd(r.limitPrice), average30min: usd(r.twapPrice),
172
+ spacingSeconds: Number(r.minInterval), balance: amtOf(r.balance, r.dir),
173
+ [r.dir === 0 ? 'okbBought' : 'usdt0Received']: r.dir === 0 ? Number(formatUnits(r.totalOut, 18)) : usd(r.totalOut),
174
+ trades: Number(r.trades), feePercent: Number(r.feeBpsNow) / 100, page: `${C.site}/#/vaults`
175
+ });
176
+
177
+ /* ------------------------------------------------------------------ commands */
178
+ async function run() {
179
+ switch (cmd) {
180
+ case 'market': return out({ okb: await market(), note: 'Prices in USDT0 per OKB, from the Uniswap V3 pool every Latch vault uses.' });
181
+ case 'try': {
182
+ const dir = dirOf(need('dir', null, 'buy or sell')); const mode = modeOf(opt.mode || 'smart');
183
+ const ref = Number(need('ref', (v) => Number(v) > 0, 'reference price, USDT0 per OKB'));
184
+ const limit = Number(need('limit', (v) => Number(v) > 0, dir === 0 ? 'ceiling price' : 'floor price'));
185
+ const base = Number(opt.base || (dir === 0 ? 2 : 0.02));
186
+ const m = await market();
187
+ const depth = depthOf(m.avg30min, ref, dir); const vol = m.gapTicks < 15 ? 0 : m.gapTicks < 35 ? 1 : m.gapTicks < 60 ? 2 : 3;
188
+ const priceOk = (dir === 0 ? m.avg30min <= limit : m.avg30min >= limit) && m.stable;
189
+ const input = ((priceOk ? 0x7e : 0x76) | (depth << 7) | (vol << 10) | (mode << 12));
190
+ const c = await askChip(input);
191
+ return out({
192
+ answer: c.allow ? `${dir === 0 ? 'buy' : 'sell'} ${c.k}× = ${+(base * c.k).toFixed(6)} ${dir === 0 ? 'USDT0' : 'OKB'}` : 'wait',
193
+ why: !priceOk ? (dir === 0 ? 'the 30-minute average is above the ceiling (or the market is unstable)' : 'the 30-minute average is under the floor (or the market is unstable)')
194
+ : c.allow ? `OKB is ${DEPTHS[depth]} ${dir === 0 ? 'below' : 'above'} ${ref}; market ${VOLS[vol]}` : (vol === 3 && mode >= 2 ? 'very jumpy market: strategy waits' : `OKB is ${DEPTHS[depth]} ${dir === 0 ? 'below' : 'above'} ${ref}: strategy waits`),
195
+ strategy: MODE_TEXT[dir][mode], market: m, chip: { circuit: C.circuit2Id, processor: C.processor, input: '0x' + input.toString(16).padStart(4, '0') },
196
+ assumes: 'vault funded, inside its limits, not paused'
197
+ });
198
+ }
199
+ case 'vaults': {
200
+ const owner = addr('owner', 'owner address');
201
+ const list = await read(C.factory2, FACTORY2, 'vaultsOf', [owner]);
202
+ return out({ owner, vaults: await Promise.all(list.map(async (v) => summary(v, await vaultInfo(v)))) });
203
+ }
204
+ case 'status': {
205
+ const v = addr('vault', 'vault address'); const r = await vaultInfo(v);
206
+ return out({ ...summary(v, r), now: await decision(v, r, r.keeper) });
207
+ }
208
+ case 'create': {
209
+ const dir = dirOf(need('dir', null, 'buy or sell')); const mode = modeOf(opt.mode || 'smart'); const dec = dir === 0 ? 6 : 18;
210
+ const savings = addr('savings', 'wallet that receives the output');
211
+ const [treasury, hosted, minB, minS] = await Promise.all(['treasury', 'hostedKeeper', 'minBuy', 'minSell'].map((f) => read(C.factory2, FACTORY2, f)));
212
+ if (savings.toLowerCase() === treasury.toLowerCase()) throw new UserError("that address is Latch's fee wallet; choose another --savings");
213
+ const base = parseUnits(need('base', (v) => Number(v) > 0, 'amount per trade'), dec);
214
+ const maxK = mode >= 2 ? 3n : 1n;
215
+ const perTx = opt['per-trade'] ? parseUnits(opt['per-trade'], dec) : base * maxK;
216
+ const daily = opt.daily ? parseUnits(opt.daily, dec) : perTx;
217
+ const min = dir === 0 ? minB : minS;
218
+ if (base < min) throw new UserError(`--base must be at least ${amtOf(min, dir)}`);
219
+ if (perTx < base || daily < perTx) throw new UserError('need base ≤ per-trade ≤ daily');
220
+ const every = EVERY[opt.every || 'day']; if (every === undefined) throw new UserError('--every must be any, hour, day or week');
221
+ const keeper = opt.keeper ? getAddress(opt.keeper) : ZERO;
222
+ // Legal, but worth saying: a Buy ceiling under today's price (or a Take Profit floor above it) means nothing trades until OKB moves past it.
223
+ const now = (await market()).avg30min, lim = Number(opt.limit);
224
+ const warning = dir === 0 && lim < now ? `OKB is ${now} now, above your ceiling of ${lim}: this vault buys nothing until OKB falls below ${lim} (${((lim / now - 1) * 100).toFixed(0)}%). If that's not what you meant, raise --limit.`
225
+ : dir === 1 && lim > now ? `OKB is ${now} now, under your floor of ${lim}: this vault sells nothing until OKB rises above ${lim} (+${((lim / now - 1) * 100).toFixed(0)}%). If that's not what you meant, lower --limit.` : undefined;
226
+ const data = encodeFunctionData({ abi: FACTORY2, functionName: 'createVault',
227
+ args: [dir, mode, savings, base, perTx, daily, parseUnits(need('ref', (v) => Number(v) > 0, 'reference price'), 6), parseUnits(need('limit', (v) => Number(v) > 0, dir === 0 ? 'ceiling price' : 'floor price'), 6), every, keeper] });
228
+ return out({ transactions: [tx(`Create a ${dir === 0 ? 'Buy OKB' : 'Take profit'} vault (${MODES[mode]}): ${amtOf(base, dir)} per trade, up to ${amtOf(perTx, dir)} per trade and ${amtOf(daily, dir)} per day, output to ${savings}, bot: ${keeper === ZERO ? `Latch hosted (${hosted})` : keeper}`, C.factory2, data)],
229
+ warning, next: 'After it confirms: `latch vaults --owner <the signing wallet>` to get the vault address, then `latch fund`.' });
230
+ }
231
+ case 'fund': {
232
+ const v = addr('vault', 'vault address'); const r = await vaultInfo(v); const dec = r.dir === 0 ? 6 : 18;
233
+ const amount = parseUnits(need('amount', (x) => Number(x) > 0, 'amount'), dec);
234
+ // check the paying wallet first (default: the vault's owner), so the agent gets a plain answer, not a revert
235
+ const from = opt.from ? addr('from', 'paying wallet') : r.owner;
236
+ const have = await read(r.tokenIn, ERC20, 'balanceOf', [from]);
237
+ if (have < amount) {
238
+ const okb = r.dir === 1 ? await pub.getBalance({ address: from }) : 0n;
239
+ throw new UserError(`The wallet ${from} has ${amtOf(have, r.dir)} on X Layer, less than the ${amtOf(amount, r.dir)} to add. `
240
+ + (r.dir === 0 ? 'Send USDT0 (X Layer network; some wallets call it USDT) to that wallet first, then try again.'
241
+ : okb >= amount ? 'It has enough OKB: run `latch wrap --amount ' + formatUnits(amount, 18) + '` first (Take Profit vaults hold WOKB).' : 'Send OKB (X Layer) to that wallet, then `latch wrap`, then try again.'));
242
+ }
243
+ // A vault left below minimum × (1 + fee) can never trade: refuse rather than strand the money.
244
+ if (r.balance + amount < needToTrade(r)) throw new UserError(`After adding ${amtOf(amount, r.dir)} the vault would hold ${amtOf(r.balance + amount, r.dir)}, `
245
+ + `but the smallest trade needs ${amtOf(needToTrade(r), r.dir)} (the ${amtOf(r.minAmount, r.dir)} minimum plus the ${Number(r.feeBpsNow) / 100}% fee), so it could never trade. `
246
+ + `Add at least ${amtOf(needToTrade(r) - r.balance, r.dir)}.`);
247
+ // Through Latch's deposit helper (approve, then deposit), the same route as the website's Add funds button:
248
+ // OKX's wallets refuse a plain USDT0 transfer on X Layer but sign contract calls. The helper only pays Latch vaults.
249
+ const list = [];
250
+ if (C.depositor) {
251
+ const allowed = await read(r.tokenIn, ERC20, 'allowance', [from, C.depositor]);
252
+ if (allowed < amount) list.push(tx(`Allow Latch's deposit helper to move ${amtOf(amount, r.dir)} (this amount only; it can only pay into Latch vaults)`, r.tokenIn,
253
+ encodeFunctionData({ abi: ERC20, functionName: 'approve', args: [C.depositor, amount] })));
254
+ list.push(tx(`Add ${amtOf(amount, r.dir)} to the vault (through Latch's deposit helper)`, C.depositor,
255
+ encodeFunctionData({ abi: DEPOSIT, functionName: 'deposit', args: [r.tokenIn, v, amount] })));
256
+ } else list.push(tx(`Add ${amtOf(amount, r.dir)} to the vault`, r.tokenIn, encodeFunctionData({ abi: ERC20, functionName: 'transfer', args: [v, amount] })));
257
+ return out({ transactions: list, order: list.length > 1 ? 'Sign them in order and wait for the first to confirm before the second.' : undefined,
258
+ note: r.dir === 1 ? 'Take Profit vaults hold WOKB. If the wallet has only OKB, run `latch wrap` first.' : undefined });
259
+ }
260
+ case 'wrap': {
261
+ const amount = parseUnits(need('amount', (x) => Number(x) > 0, 'OKB amount'), 18);
262
+ return out({ transactions: [tx(`Wrap ${formatUnits(amount, 18)} OKB into WOKB (1:1, unwrap any time)`, C.wokb, encodeFunctionData({ abi: WOKB, functionName: 'deposit' }), amount)] });
263
+ }
264
+ case 'pause': case 'resume': {
265
+ const v = addr('vault', 'vault address');
266
+ return out({ transactions: [tx(`${cmd === 'pause' ? 'Pause' : 'Resume'} the vault (owner only)`, v, encodeFunctionData({ abi: VAULT2, functionName: 'setPaused', args: [cmd === 'pause'] }))] });
267
+ }
268
+ case 'strategy': {
269
+ const v = addr('vault', 'vault address'); const r = await vaultInfo(v); const dec = r.dir === 0 ? 6 : 18;
270
+ const base = opt.base ? parseUnits(opt.base, dec) : r.baseAmount;
271
+ if (base > r.perTxCap) throw new UserError(`--base can be at most the per-trade limit, ${amtOf(r.perTxCap, r.dir)} (limits can only go down)`);
272
+ const mode = opt.mode ? modeOf(opt.mode) : r.modeIx;
273
+ const ref = opt.ref ? parseUnits(opt.ref, 6) : r.refPrice; const limit = opt.limit ? parseUnits(opt.limit, 6) : r.limitPrice;
274
+ const every = opt.every ? EVERY[opt.every] : r.minInterval; if (every === undefined) throw new UserError('--every must be any, hour, day or week');
275
+ return out({ transactions: [tx(`Change strategy: ${MODES[mode]}, ${amtOf(base, r.dir)} per trade, reference ${usd(ref)}, ${r.dir === 0 ? 'ceiling' : 'floor'} ${usd(limit)} (owner only)`, v,
276
+ encodeFunctionData({ abi: VAULT2, functionName: 'setStrategy', args: [base, r.perTxCap, r.dailyCap, ref, limit, every, mode] }))] });
277
+ }
278
+ case 'withdraw': {
279
+ const v = addr('vault', 'vault address'); const to = addr('to', 'where the money goes'); const r = await vaultInfo(v);
280
+ const t = [];
281
+ if (r.balance > 0n) t.push(tx(`Withdraw ${amtOf(r.balance, r.dir)} (owner only)`, v, encodeFunctionData({ abi: VAULT2, functionName: 'withdraw', args: [r.tokenIn, to, MAX] })));
282
+ if (r.leftover > 0n) t.push(tx('Withdraw leftover output token (owner only)', v, encodeFunctionData({ abi: VAULT2, functionName: 'withdraw', args: [r.tokenOut, to, MAX] })));
283
+ return out({ transactions: t, note: t.length ? 'Run them in order.' : 'The vault is already empty.' });
284
+ }
285
+ case 'tick': {
286
+ const v = addr('vault', 'vault address'); const as = addr('as', "the agent wallet address (must be the vault's own agent)"); const r = await vaultInfo(v);
287
+ const d = await decision(v, r, as);
288
+ return out({ ...d, transactions: d.tradeNow ? [tx(`Trade now: ${d.why}`, v, encodeFunctionData({ abi: VAULT2, functionName: 'tick' }))] : [],
289
+ note: d.tradeNow ? 'Sign it now; the vault re-checks everything at the moment of the trade.' : 'Nothing to do now. Ask again later (Latch\u2019s agent checks about once a minute).' });
290
+ }
291
+ default:
292
+ process.stdout.write(fs.readFileSync(new URL(import.meta.url), 'utf8').split('\n').filter((l) => l.startsWith('//')).slice(0, 18).map((l) => l.slice(3)).join('\n') + '\n');
293
+ process.exit(cmd ? 1 : 0);
294
+ }
295
+ }
296
+ run().catch((e) => {
297
+ let msg = e instanceof UserError ? e.message : (e.shortMessage || e.message || String(e)).split('\n')[0];
298
+ try { const data = e?.cause?.data || e?.data; if (typeof data === 'string') msg += ' (' + decodeErrorResult({ abi: VAULT2, data }).errorName + ')'; } catch { /* */ }
299
+ out({ error: msg }); process.exit(1);
300
+ });
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "latch-xlayer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Latch on X Layer for AI agents: buy OKB on dips / take profit on rises from a vault the owner controls; a TapeOut chip sizes every trade. Prepares transactions for the OKX Agentic Wallet (onchainos wallet contract-call); never handles keys.",
5
+ "type": "module",
6
+ "bin": {
7
+ "latch": "latch.mjs"
8
+ },
9
+ "license": "GPL-2.0-or-later",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/sollid-web/latch.git",
13
+ "directory": "agent"
14
+ },
15
+ "dependencies": {
16
+ "viem": "^2.21.0"
17
+ },
18
+ "files": [
19
+ "latch.mjs",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "keywords": [
27
+ "xlayer",
28
+ "okb",
29
+ "tapeout",
30
+ "okx",
31
+ "agentic-wallet",
32
+ "onchainos",
33
+ "dca",
34
+ "take-profit",
35
+ "ai-agent"
36
+ ],
37
+ "homepage": "https://okblatch.xyz/#/agents",
38
+ "bugs": {
39
+ "url": "https://github.com/sollid-web/latch/issues"
40
+ },
41
+ "author": "sollid-web",
42
+ "main": "latch.mjs"
43
+ }