latch-xlayer 0.1.0 → 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.
- package/latch.mjs +43 -6
- package/package.json +1 -1
package/latch.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// latch vaults --owner 0x… an owner's vaults
|
|
10
10
|
// latch status --vault 0x… one vault: settings, balance, what the chip sees, next action
|
|
11
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
|
|
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
13
|
// latch wrap --amount 0.1 OKB → WOKB (Take Profit vaults hold WOKB)
|
|
14
14
|
// latch pause|resume --vault 0x…
|
|
15
15
|
// latch strategy --vault 0x… [--mode --base --ref --limit --every]
|
|
@@ -28,6 +28,7 @@ const MAINNET = {
|
|
|
28
28
|
usdt: '0x779Ded0c9e1022225f8E0630b35a9b54bE713736',
|
|
29
29
|
wokb: '0xe538905cf8410324e03A5A23C1c177a474D59b2b',
|
|
30
30
|
pool: '0xe3BE6A0137f1b0602Fc1a4841686f43B340a5082',
|
|
31
|
+
depositor: '0x948ea5060786167f1d9f7fdfbF3301c59893E3D4', // LatchDeposit: OKX wallets refuse plain USDT0 transfers on X Layer, but sign contract calls
|
|
31
32
|
site: 'https://okblatch.xyz'
|
|
32
33
|
};
|
|
33
34
|
const C = { ...MAINNET, ...(process.env.LATCH_CONFIG ? JSON.parse(fs.readFileSync(process.env.LATCH_CONFIG, 'utf8')) : {}) };
|
|
@@ -35,6 +36,7 @@ const C = { ...MAINNET, ...(process.env.LATCH_CONFIG ? JSON.parse(fs.readFileSyn
|
|
|
35
36
|
const FACTORY2 = parseAbi([
|
|
36
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)',
|
|
37
38
|
'function vaultsOf(address owner) view returns (address[])',
|
|
39
|
+
'function isVault(address) view returns (bool)',
|
|
38
40
|
'function treasury() view returns (address)',
|
|
39
41
|
'function hostedKeeper() view returns (address)',
|
|
40
42
|
'function minBuy() view returns (uint256)',
|
|
@@ -56,7 +58,9 @@ const VAULT2 = parseAbi([
|
|
|
56
58
|
'function withdraw(address token, address to, uint256 amount)',
|
|
57
59
|
'error NotOwner()', 'error OverCap()', 'error CapRaised()', 'error BadParam()', 'error BadSavings()', 'error BadRecipient()', 'error Underfunded()'
|
|
58
60
|
]);
|
|
59
|
-
const ERC20 = parseAbi(['function balanceOf(address) view returns (uint256)', 'function transfer(address to, uint256 amount) returns (bool)'
|
|
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)']);
|
|
60
64
|
const WOKB = parseAbi(['function deposit() payable']);
|
|
61
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[])']);
|
|
62
66
|
const PROC = parseAbi(['function eval(uint256 id, bytes inputs) view returns (bytes)']);
|
|
@@ -127,6 +131,7 @@ async function askChip(input) {
|
|
|
127
131
|
|
|
128
132
|
/* ------------------------------------------------------------------ vault reads */
|
|
129
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.`);
|
|
130
135
|
const F = ['owner', 'keeper', 'savings', 'paused', 'direction', 'mode', 'tokenIn', 'tokenOut', 'baseAmount', 'perTxCap', 'dailyCap', 'refPrice', 'limitPrice',
|
|
131
136
|
'minInterval', 'minAmount', 'nextTradeAt', 'spentTodayNow', 'volumeIn', 'totalOut', 'trades', 'feeBpsNow', 'twapPrice'];
|
|
132
137
|
const r = Object.fromEntries(await Promise.all(F.map(async (f) => [f, await read(v, VAULT2, f)])));
|
|
@@ -135,6 +140,8 @@ async function vaultInfo(v) {
|
|
|
135
140
|
r.leftover = await read(r.tokenOut, ERC20, 'balanceOf', [v]);
|
|
136
141
|
return r;
|
|
137
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;
|
|
138
145
|
async function decision(v, r, caller) {
|
|
139
146
|
const [inputs, k, amount, fee] = await read(v, VAULT2, 'preview', [caller]);
|
|
140
147
|
const x = Number(inputs);
|
|
@@ -143,13 +150,16 @@ async function decision(v, r, caller) {
|
|
|
143
150
|
if (amount > 0n) why = `the chip says ${r.dir === 0 ? 'buy' : 'sell'} ${Number(k)}× (${amtOf(amount, r.dir)})`;
|
|
144
151
|
else if (r.paused) why = 'paused by the owner';
|
|
145
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)}`;
|
|
146
155
|
else if (r.dailyCap - r.spentTodayNow < r.minAmount) why = "today's limit is used";
|
|
147
156
|
else if (r.nextTradeAt > 0n) why = `next trade possible at ${new Date(Number(r.nextTradeAt) * 1000).toISOString()}`;
|
|
148
|
-
else if (r.balance < r.minAmount) why = `the vault needs ${r.dir === 0 ? 'USDT0' : 'WOKB'}`;
|
|
149
157
|
else {
|
|
150
158
|
const [allow, kk] = await read(v, VAULT2, 'chip', [(x & 0xff80) | 0x7e]);
|
|
151
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`;
|
|
152
|
-
else why = r.dir === 0 ? 'OKB is above the ceiling, or moving too fast' : 'OKB is under the floor, or moving too fast';
|
|
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';
|
|
153
163
|
}
|
|
154
164
|
return { tradeNow: amount > 0n, multiplier: Number(k), amount: amtOf(amount, r.dir), fee: amtOf(fee, r.dir), why,
|
|
155
165
|
chipSees: { move: DEPTHS[dep], market: VOLS[vol], safetyChecksPassed: (x & 0x7f) === 0x7e, inputBits: '0x' + x.toString(16).padStart(4, '0') } };
|
|
@@ -209,15 +219,42 @@ async function run() {
|
|
|
209
219
|
if (perTx < base || daily < perTx) throw new UserError('need base ≤ per-trade ≤ daily');
|
|
210
220
|
const every = EVERY[opt.every || 'day']; if (every === undefined) throw new UserError('--every must be any, hour, day or week');
|
|
211
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;
|
|
212
226
|
const data = encodeFunctionData({ abi: FACTORY2, functionName: 'createVault',
|
|
213
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] });
|
|
214
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)],
|
|
215
|
-
next: 'After it confirms: `latch vaults --owner <the signing wallet>` to get the vault address, then `latch fund`.' });
|
|
229
|
+
warning, next: 'After it confirms: `latch vaults --owner <the signing wallet>` to get the vault address, then `latch fund`.' });
|
|
216
230
|
}
|
|
217
231
|
case 'fund': {
|
|
218
232
|
const v = addr('vault', 'vault address'); const r = await vaultInfo(v); const dec = r.dir === 0 ? 6 : 18;
|
|
219
233
|
const amount = parseUnits(need('amount', (x) => Number(x) > 0, 'amount'), dec);
|
|
220
|
-
|
|
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,
|
|
221
258
|
note: r.dir === 1 ? 'Take Profit vaults hold WOKB. If the wallet has only OKB, run `latch wrap` first.' : undefined });
|
|
222
259
|
}
|
|
223
260
|
case 'wrap': {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "latch-xlayer",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"bin": {
|